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