OSとSWIFTラーニング-データベースの設定とデータの保存(英語)



  • We are going to use Cloud Firestore
    (There is Cloud Firestore & Realtime Databse)


  • Head to your project console, and "create database"
  • Start in test mode
  • Make sure the necessary pods are installed
  • The next step is to initialize the Cloud Firestore
  • (must write in AppDelegate.swift)

  • Now, we made our database → We are now ready to put in data

  • In my app, since I am developing a chat app, we need to tap into the "current user"online.
  • → If we check the Firebase documents, we can see that we are able to get the currently signed-in user by using the below code:
    if Auth.auth().currentUser != nil {
      // User is signed in.
      // ...
    } else {
      // No user is signed in.
      // ...
    }
    (currentUser is an optional, so we need to check if it is nil or not)
    → First, you need a reference to the DB to actually access it within the view controller
  • Now how do we add data to Firestore? → Check the documents as well

  • → We access the db using the collection (dictionary).
  • Since this is a chat app, we ultimately need the "sender"and the "body"to be saved to the DB.

  • → messageTextfield.text is the chat message that the user types, and Auth.auth().currentUser?.email is the currently signed in user's email
    → Since both are Optionals, we need to optionally bind the values into separate constants (messageBody and messageSender)
    → Once optional binding is successful, we can then tap in to the DB using the code below.
    @IBAction func sendPressed(_ sender: UIButton) {
            
            // Optional Binding -> Checking if both are not nil first
            if let messageBody = messageTextfield.text, let messageSender = Auth.auth().currentUser?.email{
                
                // Then, we send the data to the DB
                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 saved data")
                    }
                }
            }
        }

    (Constants.swift)
    → Notice we are sending the data in a Dictionary format.
  • If the data is saved successfully without errors, the DB will look like this.
  • db.collection(K.FStore.collectionName).addDocument(data: [K.FStore.senderField: messageSender, K.FStore.bodyField: messageBody])
    → Take a look at the code above.
    K.Fstore.collection name is the name of the newly created "collection"in Cloud Firestore. Then, we add a document (addDocument) within this newly created collection, with a Dictionary that we have configured.