如何实时到达Firebase数据库中的特定节点

时间:2019-01-11 14:33:40

标签: swift firebase-realtime-database

我有一个由ChildByAutoID创建的消息密钥,我试图访问它们或使代码读取此密钥以在其他地方使用此密钥,以从Firebase数据库中使用此密钥获取一些数据

我试图观察用户的UID以获取密钥,但是我无法访问它们,如代码所示,它显示了快照是用户的UID,而我却试图读取UID下的节点

在聊天控制器中

func sendMessage() {


    let currentUserID = Auth.auth().currentUser?.uid
    let databaseRef = Database.database().reference().child("messages")
    let timestamp = Date.timeIntervalSinceReferenceDate
    let text = typingMessageText.text as AnyObject
    let receiverid = user?.userid as AnyObject
    let senderid = currentUserID as AnyObject
    let time = timestamp as AnyObject
    let value: [String:AnyObject] = ["text": text, "receiverid": receiverid, "senderid": senderid, "timestamp": time]
    let childref = databaseRef.childByAutoId()
    childref.updateChildValues(value) { (error, myRef) in
    print(myRef.key as Any)
    let messageID = myRef.key
        let mnm = [messageID : 1]
    let userMessageRef = Database.database().reference().child("usersmesssages").child(currentUserID!)
        userMessageRef.updateChildValues(mnm)

    }
}

Tableview控制器中的观察功能

func observeMessages(){
    let currentUserID = Auth.auth().currentUser?.uid
    let newDB = Database.database().reference().child("usersmesssages").child(currentUserID!)
    newDB.observe(.value) { (DataSnapshot) in
    let key = DataSnapshot.key
        print("the Key is \(DataSnapshot)")
        let dbRef = Database.database().reference().child("messages").child(key)
        dbRef.observe(.childAdded, with: { (snap) in
            print("thesnap is \(snap)")
            if let dictinoary = snap.value as? [String: AnyObject] {
                guard let receiverid = dictinoary["receiverid"] ,let senderid = dictinoary["senderid"], let text = dictinoary["text"], let time = dictinoary["timestamp"] else {
                    return
                }
                let messageValues = Message.init(text: text as? String, receiverid: receiverid as? String, senderid: senderid as? String, timestamp: time as? TimeInterval)
                self.messages.append(messageValues)
                dbRef.keepSynced(true)
                self.ChatRoomTable.reloadData()
            }
        })
    }
}

Firebase database Image

更新

print("the data is \(DataSnapshot)")

结果

the data is Snap (KxTbutCjzGQmIIb2OCGHrCyLNS53) {
"-LVx10-pBVxXTN-p88pT" = 1;
"-LVx10rtB0SL0y_mn4FU" = 1;
"-LVx4XosKZhkUDPgq0TI" = 1;
"-LVx4YT3NqYi1Tj12QFj" = 1;
"-LVx4_e8_OKwUrpAR_BM" = 1;
"-LVy2TEHGZD99ALhutbX" = 1;
"-LVy2dZB_mSIicC-qcSA" = 1;
"-LVy2xkg0oTT6bLbdC4T" = 1;
"-LVy3H6a__Tm_DKnM639" = 1;
}

如何访问自身(= 1)的节点或将其保存到变量以使用它。

0 个答案:

没有答案