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!