Reputation: 903
My data structure looks like this:
Normally there should be multiple users in it, so I got more maps inside the channel ID. I want to retrieve the userID from the first person in that channel ID. When using the correct path to my channel ID, I tried this to retrieve the userID, first following the normal code:
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
}
Nothing works, mostly the output is just nil. This is a print of snapshot, followed by the print of value:
Snap (-KeLAUXw5juT1xBISOLA) {
"-KeLCHhN3FPZ-chOE9MF" = {
PictureVersion = 2;
readyToGo = 0;
userID = SZlQ76RLCJQpFa0CDhrgFJoYzrs2;
username = pietje;
};
}
Optional({
"-KeLCHhN3FPZ-chOE9MF" = {
PictureVersion = 2;
readyToGo = 0;
userID = SZlQ76RLCJQpFa0CDhrgFJoYzrs2;
username = pietje;
};
})
How to get the userID?
Edit: It seems that the only "key" I get, is the random ID from the user. I need to get data from 1 level deeper I think, but how to do that?
Upvotes: 0
Views: 277
Reputation:
let user = value.allValues.first! as! NSDictionary
let userID = user["userID"] as? String ?? ""
Though this will crash when there is no user in the snapshot so make sure you write a check for that. It might just be better to do this.
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 ?? ""
}
})
Upvotes: 1