1. Design Database
  2. Use dummy datas and fetch them
  3. Save actual datas
  4. Timestamp

Design Database

What datas extactly do we need?

In MatchesMessagesController, we need matched users’ profile image url and their name

Fetching datas from here


There are only matched users. To render matched users’ profile image and name, using getDocuments().

getDocuments() returns array of dictionary, forEach makes it easier to use it.

Use dummy datas and fetch them

Put some dummy datas in firestore manually.

MatchesMessagesController is UICollectionViewController. Rendering items which is array of specific type.

Using struct, we can use more than one type.

In struct Match, Declaring initializer with dictionary. As fetching documents (array of dictionary)

struct Match {
    let name, profileImageUrl: String
    init(dictionary: [String: Any]) {
        self.name = dictionary["name"] as? String ?? ""
        self.profileImageUrl = dictionary["profileImageUrl"] as? String ?? ""

Save actual datas

Firestore is a tree structure, but don’t save datas too deep!

Everytime fetching users’ datas from firestore in HomeController, Save user to users as User type in dictionary as a global variable.

    var users = [String: User]()

Saving some datas locally or globally is really important.

If match has been occured, Update firestore using users dictionary. We can access informations so we can save datas in firestore optionally.

                guard let cardUser = self.users[cardUID] else { return }
                let cardUserData: [String: Any] = ["name": cardUser.name ?? "", "profileImageUrl": cardUser.imageUrl1 ?? "", "uid": cardUID, "timestamp": Timestamp(date: Date())]

Don’t forget to update opposite user’s database

                guard let currentUser = self.user else { return }
                let currentUserData: [String: Any] = ["name": currentUser.name ?? "", "profileImageUrl": currentUser.imageUrl1 ?? "", "uid": uid, "timestamp": Timestamp(date: Date())]


    Timestamp(date: Date())

we can sort matched users by timestamp and using query

        let query = Firestore.firestore().collection("matches_messages").document(currentUserId).collection("matches").order(by: "timestamp", descending: true)
        query.getDocuments { (querySnapshot, err) in

태그: ,