0

Apologies in advance if this has already been answered - I've been looking around but couldn't find an answer.

I'm currently creating a messaging app which grabs messages and corresponding user details from Firebase and loads them on a tableview. The issue i'm facing is that the messages are displayed in the wrong order once I start retrieving the user details because (I think) the 'Users' array is being populated in the wrong order in comparison to 'Messages' array.

loadMessages function:

func loadMessages() {

    // Grab all messages from assocated group ID from group-messages table
    Api.groupMessages.observeGroupMessages(groupId: self.groupId) { (messageId) in

        // After grabbing all message ID's, then grab the message details from the messages table
        Api.message.observeMessages(messageId: messageId, onSuccess: { (message) in

            print("1: \(message.senderId)")

            // Grab the user who sent the corresponding message based on senderId then update the message avatar
            Api.user.observeUser(withId: (message.senderId)!) { (user) in
                print("2: \(user.userId)")

                self.messages.append(message)
                self.users.append(user)

                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            }

        })
    }

}

observeMessages function:

func observeMessages(messageId: String, onSuccess: @escaping (Message) -> Void) {
    MESSAGE_REF.child(messageId).observeSingleEvent(of: .value, with: { (snapshot) in

        if let dict = snapshot.value as? [String: Any] {
            let message = Message.transformMessage(dict: dict)
            onSuccess(message)
        }

    })
}

observeUser function:

func observeUser(withId userId: String, onSuccess: @escaping (User) -> Void) {
    USER_REF.child(userId).observeSingleEvent(of: .value, with: { (snapshot) in
        if let dict = snapshot.value as? [String: Any] {
            let user = User.transformUser(dict: dict)
            onSuccess(user)
        }
    })
}

Messages class:

class Message {
    var senderId: String?
    var messageText: String?
}

extension Message {
    static func transformMessage(dict: [String: Any]) -> Message {
        let message = Message()
        message.messageText = dict["messageText"] as? String
        message.senderId = dict["senderId"] as? String
        return message
    }  
}

User class

class User {
    var userId: String?
    var avatar: String?
}

extension User {
    static func transformUser(dict: [String: Any]) -> User {
        let user = User()
        user.userId = dict["userId"] as? String
        user.avatar = dict["avatar"] as? String
        return user
    }
}

Results when I print the arrays

1: Optional("LClE82Z4msa5BwfNamCH6oBK1QI2")
1: Optional("LX6n4dL888hN5BsbPuLcFjWVWVw1")
1: Optional("LClE82Z4msa5BwfNamCH6oBK1QI2")
1: Optional("LX6n4dL888hN5BsbPuLcFjWVWVw1")
1: Optional("LX6n4dL888hN5BsbPuLcFjWVWVw1")

2: Optional("LClE82Z4msa5BwfNamCH6oBK1QI2")
2: Optional("LClE82Z4msa5BwfNamCH6oBK1QI2")
2: Optional("LX6n4dL888hN5BsbPuLcFjWVWVw1")
2: Optional("LX6n4dL888hN5BsbPuLcFjWVWVw1")
2: Optional("LX6n4dL888hN5BsbPuLcFjWVWVw1")

Thanks in advance!

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Alan Lau
  • 115
  • 9
  • What order do you want the items to be displayed in? – Frank van Puffelen Jun 17 '17 at 14:50
  • I need the 2nd print statement to display in the same order as the first print statement so that both message and user arrays match (i.e messages[0].senderID would match users[0].userID) Then I can use them in my custom table view cell to display the message detail with a matching user detail if that makes sense? =) – Alan Lau Jun 17 '17 at 17:23
  • I'm not really sure if I understand the code correctly. Requests from the same client are answered in the same order in which you fire them (see [my explanation here](http://stackoverflow.com/questions/35931526/speed-up-fetching-posts-for-my-social-network-app-by-using-query-instead-of-obse/35932786#35932786) for why that is). If they users arrive out of order, the requests must be sent out of order too. – Frank van Puffelen Jun 17 '17 at 22:26
  • Yep. I believe the problem occurs in the 'observeUser' part of the loadMessages function in which the 'message.senderId' parameter sent doesn't match the order in which 'observeMessage' returns the message details... not sure why this is though... – Alan Lau Jun 17 '17 at 23:10

0 Answers0