<aside> 💡 to save and retrieve data from the Firebase Cloud Firestore
</aside>
Create a new database
Set up your development environment
pod 'Firebase/Firestore'
//AppDelegate.swift
import Firebase
FirebaseApp.configure()
let db = Firestore.firestore()
[test db]
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FirebaseApp.configure()
let db = Firestore.firestore()
print(db)
return true
}
//print result: <FIRFirestore: 0x600000ecff40>
<aside> 💡 관계형 db와 몽고db 용어 차이 : https://javacpro.tistory.com/66
</aside>
예를들어, 메세지 모델이 다음과 같다면,
struct Message {
let sender: String //email addr
let body: String
}
body ⇒ input data in TextField
sender ⇒ currently signed in user! - Manage User
//currentUser property
if Auth.auth().currentUser != nil {
// User is signed in.
// ...
} else {
// No user is signed in.
// ...
}
// Add a new document with a generated ID
var ref: DocumentReference? = nil
ref = db.collection("users").addDocument(data: [
"first": "Ada",
"last": "Lovelace",
"born": 1815
]) { err in
if let err = err {
print("Error adding document: \\(err)")
} else {
print("Document added with ID: \\(ref!.documentID)")
}
}
[sample code]
let db = Firestore.firestore()
@IBAction func sendPressed(_ sender: UIButton) {
if let messageBody = messageTextfield.text, let messageSender = Auth.auth().currentUser?.email {
//create the data dictionary
db.collection(K.FStore.collectionName).addDocument(data: [ K.FStore.senderField: messageSender, K.FStore.bodyField: messageBody]) { (error) in
if let e = error {
print("There was an issue saving data to firestore. \\(e)")
} else {
print("Successfully save the data")
}
}
}
}