Last active
October 9, 2020 23:50
-
-
Save SlappyAUS/76efebedefadee753aeb7067f0c7cfbc to your computer and use it in GitHub Desktop.
FireStore #firebase
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// App Deleagate | |
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { | |
FirebaseApp.configure() | |
_ = Firestore.firestore() | |
return true | |
} | |
// Controller | |
// Init Firestore | |
let db = Firestore.firestore() | |
// Write a document | |
if let messageBody = messageTextfield.text, | |
let messageSender = Auth.auth().currentUser?.email { | |
db.collection(K.FStore.collectionName).addDocument(data: [ | |
K.FStore.senderField: messageSender, | |
K.FStore.bodyField: messageBody | |
]) { (error) in | |
if let err = error { | |
print("There was an issue saving data to Firestore: \(err)") | |
} else { | |
print("Successfully saved data") | |
} | |
} | |
} | |
// Reading a document | |
func loadMessages() { | |
messages = [] | |
db.collection(K.FStore.collectionName).getDocuments { (querySnapshot, error) in | |
if let err = error { | |
print("There was an issue retrieving from Firestore \(err)") | |
} else { | |
if let snap = querySnapshot { | |
for document in snap.documents { | |
let data = document.data() | |
if let messageSender = data[K.FStore.senderField] as? String, | |
let body = data[K.FStore.bodyField] as? String { | |
let newMessage = ChatMessage(sender: messageSender, body: body) | |
self.messages.append(newMessage) | |
} | |
} | |
DispatchQueue.main.async { | |
self.tableView.reloadData() | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment