@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,
K.FStore.dateField: Date().timeIntervalSince1970
]) { (error) in
if let e = error{
print("There was an issue saving data to firestore, \(e)")
}
else{
print("Successfully saved data")
}
}
}
}
→ When we are sending a new message and adding it to Firestore, we are now adding a third value : K.FStore.dateField
note: K.FStore.dateField is a separate struct file (constants)
→ Used to prevent typos
struct K {
static let appName = "⚡️FlashChat"
static let cellIdentifier = "ReusableCell"
static let cellNibName = "MessageCell"
static let registerSegue = "RegisterToChat"
static let loginSegue = "LoginToChat"
struct BrandColors {
static let purple = "BrandPurple"
static let lightPurple = "BrandLightPurple"
static let blue = "BrandBlue"
static let lighBlue = "BrandLightBlue"
}
struct FStore {
static let collectionName = "messages"
static let senderField = "sender"
static let bodyField = "body"
static let dateField = "date"
}
}
→ We now have another key-value pair in our documents.
→ Now since we have a date key, we can use it to sort our messages, instead of the traditional document ID, which is the default way on how Firestore sorts documents.
→ We can see we need to add a order(by: "something") method.
func loadMessages(){
db.collection(K.FStore.collectionName)
.order(by: K.FStore.dateField)
.addSnapshotListener { (querySnapshot, err) in
.
.
.(생략)
.
.
}
→ Now, messages appear in an ordered fashion