如果这已经得到回答,请提前道歉 - 我一直在环顾四周但找不到答案。
我目前正在创建一个消息传递应用程序,它可以从Firebase获取消息和相应的用户详细信息,并将它们加载到tableview上。我面临的问题是,一旦我开始检索用户详细信息,消息就会以错误的顺序显示,因为(我认为)与'Messages'数组相比,'Users'数组的填充顺序错误。
loadMessages功能:
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功能:
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功能:
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)
}
})
}
消息类:
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
}
}
用户类
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
}
}
打印数组时的结果
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")
提前致谢!