· 9 years ago · Oct 06, 2016, 03:48 PM
1override func viewDidLoad() {
2 super.viewDidLoad()
3 // Do any additional setup after loading the view, typically from a nib.
4
5 // Identify the app's Documents directory and build a path to "contacts.db"
6 let fileManager = NSFileManager.defaultManager()
7 let directoryPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
8 let documentsDirectory = directoryPaths[0]
9 databasePath = documentsDirectory.stringByAppendingString("contacts.db")
10
11 // Initialize (create) the database if it does not already exist
12 if !fileManager.fileExistsAtPath(databasePath as String) {
13 // Create the database
14 let contactDB = FMDatabase(path: databasePath as String)
15
16 // Verify that the database was created
17 if contactDB == nil {
18 print("Error: database not created, details: \(contactDB.lastErrorMessage)")
19 }
20
21 // Try to open the empty database and create the table structure required
22 if contactDB.open()
23 {
24 // Define teh SQL statement to be run
25 let SQL = "CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)"
26
27 // Attempt to run the SQL statement
28 if !contactDB.executeStatements(SQL)
29 {
30 print("Error: \(contactDB.lastErrorMessage())")
31 }
32
33 // Close the database connection
34 contactDB.close()
35 } else {
36 // We couldn't open the databse, throw error
37 print("Error: \(contactDB.lastErrorMessage())")
38 }
39 }
40 }
41
42 @IBAction func saveData(sender: AnyObject)
43 {
44 // Establish path to database through MFDatabase wrapper
45 let contactDB = FMDatabase(path: databasePath as String)
46
47 // We know database should exist now (since viewDidLoad ran)
48 // Now open the database and insert data from the view
49 if contactDB.open()
50 {
51 // Get data from the form fields on the view
52 guard let nameValue : String = name.text else {
53 status.text = "Hey, we need a name here"
54 return
55 }
56 guard let addressValue : String = address.text else {
57 status.text = "Hey, we need an address here"
58 return
59 }
60 guard let phoneValue : String = phone.text else {
61 status.text = "Please provide a phone number."
62 return
63 }
64
65 // Create SQL statement to insert data
66 let SQL = "INSERT INTO CONTACTS (name, address, phone) VALUES ( '\(nameValue)', '\(addressValue)', '\(phoneValue)')"
67
68 // Try to run teh statement
69 let result = contactDB.executeUpdate(SQL, withArgumentsInArray: nil)
70
71 // See what happened and react accordingly
72 if !result {
73 status.text = "Failed to add contact"
74 } else {
75 status.text = "Contact added"
76
77 // Clear form fields
78 name.text = ""
79 address.text = ""
80 phone.text = ""
81 }
82 } else {
83 // We couldn't open the database, throw an error
84 print("Error: \(contactDB.lastErrorMessage())")
85 }
86 }
87
88 @IBAction func findContact(sender: AnyObject)
89 {
90 // Establish path to database through FMDatabase wrapper
91 let contactDB = FMDatabase(path: databasePath as String)
92
93 // We know database should exist now (since viewDidLoad ran)
94 // Now open the database and insert data from the view
95 if contactDB.open()
96 {
97 // Get form field value
98 guard let nameValue : String = name.text else {
99 status.text = "Please provide a name."
100 return
101 }
102
103 // Create SQL statement to find data
104 let SQL = "SELECT address, phone FROM CONTACTS WHERE name = '\(nameValue)'"
105
106 // Run query
107 do {
108 // Try to run the query
109 let results : FMResultSet? = try contactDB.executeQuery(SQL, values: nil)
110
111 // We know databsae should exist now (since viewDidLoad runs at startup)
112 // Now, open the datbase and select data using value given for name in teh view
113 if results?.next() == true {
114 guard let addressValue : String = results?.stringForColumn("address") else {
115 print("Nil value returned from query, that's odd")
116 return
117 }
118 guard let phoneValue : String = results?.stringForColumn("phone") else {
119 print("Nil value returned from query, that's odd")
120 return
121 }
122
123 // Load the results in the view
124 address.text = addressValue
125 phone.text = phoneValue
126 status.text = "Record found!"
127 } else {
128 // Nothing was found for this query
129 status.text = "Record not found"
130 address.text = ""
131 phone.text = ""
132 }
133
134 // Close the database
135 contactDB.close()
136 } catch {
137 // Query did not run, throw error
138 print("Error: \(contactDB.lastErrorMessage())")
139 }
140 } else {
141 // Query did not run, throw error
142 print("Error: \(contactDB.lastErrorMessage())")
143 }
144 }