我的数据结构是这样的:
正常情况下应该有多个用户在里面,所以我在 channel ID里面得到了更多的 map 。我想从该 channel ID 中的第一个人那里检索用户 ID。当使用我的 channel 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?
编辑:似乎我得到的唯一“ key ”是来自用户的随机 ID。我认为我需要从更深一层获取数据,但该怎么做?
最佳答案
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 ?? ""
}
})
关于ios - 如何从 child 的 Firebase 获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42589261/