OSとSWIFTラーニング-データベースの設定とデータの保存(英語)
8292 ワード
We are going to use Cloud Firestore
(There is Cloud Firestore & Realtime Databse)
Head to your project console, and "create database"
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 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
→ We access the db using the collection (dictionary).
→ 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.
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.
Reference
この問題について(OSとSWIFTラーニング-データベースの設定とデータの保存(英語)), 我々は、より多くの情報をここで見つけました https://velog.io/@kevinkim2586/iOS-Swift-공부-Database-Setup-and-Saving-Data-to-Firebase-영テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol