简体   繁体   English

如何从iOS中的Firebase数据库获取最新消息

[英]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.

相关问题 如何从Firebase按时间顺序获取最新帖子? - How to get chronologically latest post from Firebase? IOS:消息不会立即出现在来自 firebase 数据库的 tableview 中 - IOS : message doesn't appear immediately in tableview from firebase database 如何更新Firebase-Database树中的最新条目? - How to update latest entry from Firebase-Database tree? 如何在最新的 Firebase IOS SDK 中获取 Firebase JWT 令牌以在服务器端进行验证 - How to get Firebase JWT token to validate on server side in Latest Firebase IOS SDK 如何在iOS中从Firebase消息通知中获取主题? - How to get the topic out of a Firebase message notification in iOS? IOS:如何从 Firebase 实时数据库中的列表中获取特定的更改子项? - IOS: How to get specific changed child from list in Firebase Realtime Database? 如何从Firebase获取单个数据库参考 - How to get single dataBase reference from Firebase 如何从 Firebase 实时数据库检索嵌套节点到 iOS 应用程序 - How to retrieve nested nodes from Firebase realtime database to iOS app 如何在iOS中从sqlite3数据库中获取20条消息数据 - How to fetch 20 message Data from sqlite3 database in iOS 如何将“聊天消息”从iOS TextField发送到远程数据库 - How To Send “chat message” From iOS TextField To A Remote Database
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM