我创建了一种从 Firebase 获取用户消息的方法,但是当离开DispatchGroup
应用程序崩溃时会导致此错误Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
我不确定我做错了什么。请帮助和解释我。
代码:
public func fetchMessages(for userId: String, completion: @escaping (_ result: Result<([Message], [String: Message]), Error>) -> Void) {
let group = DispatchGroup()
var messages = [Message]()
var messagesDict = [String: Message]()
group.enter()
database.child("user-messages").child(userId).observe(.childAdded, with: { [weak self] snapshot in
let messageId = snapshot.key
let messagesRef = self?.database.child("messages").child(messageId)
messagesRef?.observeSingleEvent(of: .value, with: { snapshot in
if let dict = snapshot.value as? [String: AnyObject] {
let message = Message(dict: dict)
if let chatPartnerId = message.chatPartnerId() {
messagesDict[chatPartnerId] = message
messages = Array(messagesDict.values)
messages.sort { message1, message2 in
guard let timestamp1 = message1.timestamp?.intValue, let timestamp2 = message2.timestamp?.intValue else { return false }
return timestamp1 > timestamp2
}
group.leave() // Crashes
}
}
}, withCancel: nil)
}, withCancel: nil)
group.notify(queue: .main) {
print("Array: \(messages)\nDict: \(messagesDict)")
}
}