简体   繁体   中英

FirebaseChat Swift4

When i send a message it is fetching data multiple times from Firebase

My chat is not working properly it is recieving messages multiple times when i send a new message and display on tableview

func getChatData(){

    //self.getData = []
    
    ref.child("Chats").observe(.value) { (snapshot) in
        
        if let snapshot = snapshot.children.allObjects as? [DataSnapshot]{
            for item in snapshot{
                if let postData = item.value as? [String: Any]{
                    let message = postData["message"]as? String
                    let orderid = postData["orderid"]as? Int
                    let receiver = postData["receiver"]as? String
                    let receiverUid = postData["receiverUid"]as? String
                    let sender = postData["sender"]as? String
                    let senderUid = postData["senderUid"]as? Int
                    let timestamp = postData["timestamp"]as? String
                    
                    if self.orderId == orderid{
                        //self.getData.removeAll()
                         self.getData.append(GetChat(message: message ?? "", orderid: orderid ?? 0, receiver: receiver ?? "", receiverUid: receiverUid ?? "", sender: sender ?? "", senderUid: senderUid ?? 0, timestamp: timestamp ?? ""))
                    }
                }
            }
            
           self.tableView.reloadData()
            //self.tableView.reloadInputViews()
        }

Given how you read from the database, the snapshot will contain the entire data under Chats each time it gets called.

You have two options to prevent showing duplicate data in the UI:

  1. Listen for .child*** events, instead of .value . Doing this means that (say a message gets added) your .childAdded observer gets invoked with a snapshot of only the new message.
  2. Alternatively you can simply empty your getData each time you get data from the database. This may lead to some flicker in the UI updates, but it's the smallest change from your current code. To do this, just add self.getData = [] right before for item in snapshot{ .

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