简体   繁体   中英

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.

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM