我的数据结构如下:
通常应该有多个用户,所以我在频道ID中有更多的地图。我想从该频道ID中的第一个人那里检索用户ID。当使用我的频道ID的正确路径时,我尝试检索用户ID,首先遵循正常的代码:
let firstChild = UInt(1)
self.channelRef?.queryLimited(toFirst: firstChild).observeSingleEvent
(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
})
if let newCreator = snapshot.childSnapshot(forPath: "userID").value
{
print(newCreator)
}
let newCreator = value?.["userID"] as! String
let newCreator = value?["userID"] as? String ?? ""
if snapshot.key == "userID"
{
let newCreator = snapshot.value as! String
}
没有任何作用,大多数输出只是零。这是快照的打印,然后打印值:
Snap (-KeLAUXw5juT1xBISOLA) {
"-KeLCHhN3FPZ-chOE9MF" = {
PictureVersion = 2;
readyToGo = 0;
userID = SZlQ76RLCJQpFa0CDhrgFJoYzrs2;
username = pietje;
};
}
Optional({
"-KeLCHhN3FPZ-chOE9MF" = {
PictureVersion = 2;
readyToGo = 0;
userID = SZlQ76RLCJQpFa0CDhrgFJoYzrs2;
username = pietje;
};
})
如何获取用户ID?
编辑:似乎我得到的唯一“密钥”是来自用户的随机ID。我需要从1级更深入地获取数据,但是如何做到这一点?
答案 0 :(得分:1)
let user = value.allValues.first! as! NSDictionary
let userID = user["userID"] as? String ?? ""
虽然快照中没有用户时会崩溃,但请确保为此编写支票。这样做可能会更好。
self.channelRef?.queryLimited(toFirst: firstChild).observeSingleEvent(of: .value, with: { snapshot in
let enumerator = snapshot.children
while let user = enumerator.nextObject() as? FIRDataSnapshot {
guard let userValue = user.value as? NSDictionary else {
return
}
let userID = userValue["userID"] as? String ?? ""
}
})