我正在运行下面的代码,看看打开应用程序的用户是否已登录,然后检查他们是否已设置个人资料。我无法检查从配置文件检查返回的空值值
override func viewDidLoad() {
super.viewDidLoad()
//Check to see if user is already logged in
//by checking Firebase to see if authData is not nil
if ref.authData != nil {
//If user is already logged in, get their uid.
//Then check Firebase to see if the uid already has a profile set up
let uid = ref.authData.uid
ref.queryOrderedByChild("uid").queryEqualToValue(uid).observeSingleEventOfType(.Value, withBlock: { snapshot in
let profile = snapshot.value
print(profile)
})
在我打印(个人资料)的最后一行,我要么获取个人资料信息,要么
<null>
如何检查此值?
if profile == nil
不起作用
如果我这样做
let profile = snapshot.value as? String
首先,即使存在snapshot.value
,它也总是返回nil答案 0 :(得分:26)
利用exists()方法确定快照是否包含值。要使用您的示例:
let uid = ref.authData.uid
ref.queryOrderedByChild("uid").queryEqualToValue(uid)
.observeSingleEventOfType(.Value, withBlock: { snapshot in
guard snapshot.exists() else{
print("User doesn't exist")
return
}
print("User \(snapshot.value) exists")
})
。
这是另一个方便的例子,Swift4
let path = "userInfo/" + id + "/followers/" + rowId
let ref = Database.database().reference(withPath: path)
ref.observe(.value) { (snapshot) in
let following: Bool = snapshot.exists()
icon = yesWeAreFollowing ? "tick" : "cross"
}
答案 1 :(得分:3)
您可能想要探索另一个选项:因为您知道用户的uid以及该用户的路径,所以没有理由进行查询。在您知道路径的情况下,查询会增加不必要的开销。
例如
users
uid_0
name: "some name"
address: "some address"
最好通过值观察有问题的节点,如果它不存在则返回null
ref = "your-app/users/uid_0"
ref.observeEventType(.Value, withBlock: { snapshot in
if snapshot.value is NSNull {
print("This path was null!")
} else {
print("This path exists")
}
})
如果您以其他方式存储它;也许
random_node_id
uid: their_uid
name: "some name"
然后查询将按顺序排列,如此
ref.queryOrderedByChild("uid").queryEqualToValue(their_uid)
.observeEventType(.Value, withBlock: { snapshot in
if snapshot.exists() {
print("you found it!")
}
});