我有一个查找特定 UUID 并返回对象的查询。
print(snapshot)
Snap (users) {
"-KENROf9kGUPw1j6ghFo" = {
UUID = "A1166D66-31B4-4B1C-B28C-58E9E5615D16";
nickname = Craig;
};
}
我正在尝试提取 nickname
但有麻烦。
这是我的查询 let queryRef = Firebase(url:"https://<url>.firebaseio.com/users")
这是查询引用。
var handle = queryRef.queryOrderedByChild("UUID").queryEqualToValue("A1166D66-31B4-4B1C-B28C-58E9E5615D16").observeSingleEventOfType(.Value, withBlock: { snapshot in
if snapshot.value is NSNull {
print("snapshot empty")
} else {
print(snapshot) //this prints the snapshot above
self.nickname = snapshot.value.objectForKey("nickname") as! String //this returns an error
print(self.nickname)
}
})
}
self.nickname....
行返回以下错误。
fatal error: unexpectedly found nil while unwrapping an Optional value
我已经尝试了几种不同的方法来构建它,但还没有找到一种不会失败的方法。
最佳答案
您将用户存储在推送 ID 下,然后通过用户的 UID 查询他们。这是个坏主意。相反,将用户存储在其 uid(或在您的情况下为 UUID)下,如 Firebase documentation on storing user data 中的示例所示。显示:
ref.authUser("jenny@example.com", password:"correcthorsebatterystaple") {
error, authData in
if error != nil {
// Something went wrong. :(
} else {
// Authentication just completed successfully :)
// The logged in user's unique identifier
println(authData.uid)
// Create a new user dictionary accessing the user's info
// provided by the authData parameter
let newUser = [
"provider": authData.provider,
"displayName": authData.providerData["displayName"] as? NSString as? String
]
// Create a child path with a key set to the uid underneath the "users" node
// This creates a URL path like the following:
// - https://<YOUR-FIREBASE-APP>.firebaseio.com/users/<uid>
ref.childByAppendingPath("users")
.childByAppendingPath(authData.uid).setValue(newUser)
}
}
如果您坚持使用当前的数据结构,则需要处理 .Value
查询返回子级列表的事实。即使只有一项符合查询条件,它仍然是一项的列表。
var query = queryRef.queryOrderedByChild("UUID").queryEqualToValue("A1166D66-31B4-4B1C-B28C-58E9E5615D16")
query.observeSingleEventOfType(.Value, withBlock: { snapshot in
if snapshot.value is NSNull {
print("snapshot empty")
} else {
for child in snapshot.children {
self.nickname = child.value.objectForKey("nickname") as! String
print(self.nickname)
}
}
})
关于ios - 从 Firebase 检索子值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36389880/