我在firebase上创建了下面的结构,我需要用红色下划线自动id:
我创建的用于查询值的代码:
let query = reference.queryOrdered(byChild: "receiverId").queryEqual(toValue: "LKupL7KYiedpr6uEizdCapezJ6i2") //Start process query.observe(.value, with: { (snapshot) in guard snapshot.exists() else{ print("Data doesn't exists") return } print(snapshot.key) }
我的" snapshot.value "导致:
Optional({ "-KaRVjQgfFD00GXurK9m" = { receiverId = LKupL7KYiedpr6uEizdCapezJ6i2; senderId = bS6JPkEDXIVrlYtSeQQgOjCNTii1; timestamp = 1484389589738; }; })
如何从上面的节点只获得字符串-KaRVjQgfFD00GXurK9m?
我曾尝试使用" print(snapshot.key) ",但结果是用户ID: bS6JPkEDXIVrlYtSeQQgOjCNTii1
一些想法?非常感谢你.
.value返回父节点和满足查询结果的所有子节点.在这种情况下,需要迭代子节点(可能有多个子节点与查询匹配).
snapshot.key是父节点键(bS6JPkEDXIVrlYtSeQQgOjCNTii1),值是所有子节点的快照(字典).这些孩子中的每一个都是一个关键:uid的值对:值和值是子节点的字典,receiverId,senderId等
此代码将打印每个子节点的uid以及与查询匹配的每个用户节点的值(timestamp)之一.
let usersRef = ref.child("users") let queryRef = usersRef.queryOrdered(byChild: "receiverId") .queryEqual(toValue: "LKupL7KYiedpr6uEizdCapezJ6i2") queryRef.observeSingleEvent(of: .value, with: { (snapshot) in for snap in snapshot.children { let userSnap = snap as! FIRDataSnapshot let uid = userSnap.key //the uid of each user let userDict = userSnap.value as! [String:AnyObject] let timestamp = userDict["timestamp"] as! String print("key = \(uid) and timestamp = \(timestamp)") } })