<aside> 💡 to save and retrieve data from the Firebase Cloud Firestore

</aside>

Cloud Firestorm

How to use Firestorm

  1. Create a new database

    1. go to Console - choose project - select 'FireStore database'
    2. create database - mode (test) - location (Seoul : northeast3)
  2. Set up your development environment

    pod 'Firebase/Firestore'
    
  3. Initialize Cloud 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>
    

Save Data

<aside> 💡 관계형 db와 몽고db 용어 차이 : https://javacpro.tistory.com/66

</aside>

  1. 예를들어, 메세지 모델이 다음과 같다면,

    struct Message {
        let sender: String //email addr
        let body: String
    }
    
  2. body ⇒ input data in TextField

  3. 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")
            }
        }
    }
}

Retrieve Data (되찾다, 회수하다, 가져오다)