Firebase聊天问题 - 同时发送两条消息

时间:2015-12-15 05:07:25

标签: ios swift asynchronous firebase

我是新来的,我无法解决如何解决这个问题:

func sendMessage(msgText : String) {
    let defaults = NSUserDefaults.standardUserDefaults()

    let myRootRef = Firebase(url:"https://boiling-heat-3478.firebaseio.com/")
    self.messageCount = String(Int(self.messageCount)!+1)
    let messagesRef = myRootRef.childByAppendingPath("messages")
    let messageIDRef = messagesRef.childByAppendingPath(self.messageCount)
    let messageInfo = ["Text": self.messageText.text!, "SenderID": defaults.objectForKey("userID") as! String]
    messageIDRef.updateChildValues(messageInfo)
}

在视图上加载:

let myRootRef = Firebase(url:"https://boiling-heat-3478.firebaseio.com/")
    let messagesRef = myRootRef.childByAppendingPath("messages")
    let ref1 = Firebase(url: String(messagesRef))
    // Attach a closure to read the data at our posts reference
    ref1.queryOrderedByKey().queryStartingAtValue(self.messageCount).observeEventType(.ChildAdded, withBlock: { snapshot in


        dispatch_async(dispatch_get_main_queue()){

        let path = String(snapshot.ref)
        let parts = path.characters.split("/")

        if(Int(self.messageCount) < Int(String(parts.last!))){ self.messageCount = String(Int(self.messageCount)!+1) }

        let messageText = snapshot.value.objectForKey("Text") as! String
        let senderNameAge = snapshot.value.objectForKey("SenderID") as! String
        let msg = Message(nameAge: senderNameAge, image: nil, text: messageText)
        self.messages.append(msg)

        self.messageTableView.reloadData()
        }
    }, withCancelBlock: { error in
            print(error.description)
    })

嗯,这很好用。我可以和1个人聊天并实时查看回复,但是当我尝试发送像#34; aaaa&#34;从1到2人和&#34; bbbb&#34;从第2个人到第1个人:消息&#34; aaaa&#34;仅显示在人1屏幕和&#34; bbbb&#34;在人2。 另外,我可以在firebase上看到其中一条消息在同一目的地上替换了另一条消息!我该如何避免或解决这个问题?谢谢

1 个答案:

答案 0 :(得分:0)

您通过尝试使用计数来索引邮件来创建问题。

Firebase documentation explicitly warns against using arrays,因为(正如您发现的那样)很难在多个客户端之间保持消息计数同步。

您可以简单地在Firebase引用上调用childByAutoId,而不是在客户端之间保持计数同步,以生成一个新的子ID,该子ID保证是唯一的并且总是递增。

let messagesRef = myRootRef.childByAppendingPath("messages")
let messageIDRef = messagesRef.childByAutoId()
let messageInfo = ["Text": self.messageText.text!, "SenderID": defaults.objectForKey("userID") as! String]
messageIDRef.updateChildValues(messageInfo)

请参阅this section of the documentation for more information and examples

另请参阅此example of a chat app written in Swift,您可以将其用作灵感。