iOS & Swift 공부 - How to Sort Data retrieved from Firestore (영)

김영채 (Kevin)·2021년 2월 6일
0

iOS & Swift

목록 보기
71/107
post-thumbnail

How to Sort Data retrieved from Firestore


  • In a chat application, we would have to sort the messages data by time, meaning we would have to add a time stamp to the documents stored in Firestore.
@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"
    }
}
  • Now, if we send a message and create a new document in Firestore, the document will look something like the below image

→ 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.

  • In order to sort the data retrieved, first take a look at the Firebase 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

profile
맛있는 iOS 프로그래밍

0개의 댓글