[英]how to get latest message from firebase database in ios
I have don't know what the problem please help me. 我不知道是什么问题,请帮助我。 When I get a particular message from firebase database then the value is getting but my app got a crash on one line.So please tell me what I do wrong in my code.below is my function.We also provide the screenshot of the error.
当我从Firebase数据库中收到一条特定消息时,该值正在获取,但我的应用程序在一行上崩溃了,所以请告诉我代码中我做错了什么。下面是我的函数。我们还提供了错误的屏幕截图。
func getLatestMessageFromFirebase(token:String,completionmessage: @escaping (_ message:String) -> Swift.Void)
{
print("getModelFromFirebase")
var message:String=""
ref.child("chatmessage/devicetoken/").child(token).queryLimited(toLast: 1).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
if value?["message"] as? String != ""
{
DispatchQueue.main.async
{
message = (value?["message"] as? String)! //My app stop on this line
completionmessage(message)
}
}
})
{ (error) in
print(error.localizedDescription)
}
}
func callAPI()
{
let response = (jsonResult.object(forKey: "chatListArr") as? NSArray)!
if response.count > 0
{
for i in 0..<response.count
{
let dict = response[i] as! NSDictionary
let chatlist = ChatList(dict: dict)
self.arr_list.append(chatlist)
}
for i in 0..<self.arr_list.count
{
let chatlist = self.arr_list[i]
self.getLatestMessageFromFirebase(token: chatlist.token, completionmessage: { (message) in
self.arr_list[i].msg = message
})
}
self.table_view.reloadData()
}
}
Please help me. 请帮我。 Thanks in Advance.
提前致谢。
First of all you should clean your code up a bit, you do a couple of things which would be considered anti patterns 首先,您应该清理一下代码,然后做几件事被认为是反模式
func getLatestMessageFromFirebase(token:String,completionmessage: @escaping (_ message:String) -> Swift.Void)
{
ref.child("chatmessage/devicetoken/").child(token).queryLimited(toLast: 1).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
for snap in snapshot.children.allObjects as [DataSnapshot] {
let value = snap.value as? [String: Any] ?? [:] // A good way to unwrap optionals in a single line
if let message = value["message"] as? String {
DispatchQueue.main.async {
completionmessage(message)
}
}
}
})
{ (error) in
print(error.localizedDescription)
}
}
With the above code your app shouldnt crash. 使用上面的代码,您的应用程序应该不会崩溃。 And if there is a message AND it is a string (which might have been your problem before) then your callback will fire.
如果有一条消息,并且它是一个字符串(以前可能是您的问题),则您的回调将触发。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.