Firebase检查空值(Swift)

5

我正在运行下面的代码,以查看打开应用程序的用户是否已经登录,然后检查他们是否设置了个人资料。我在检查从个人资料检查返回的空值时遇到了问题。

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)
        })

在最后一行中,当我打印(profile)时,要么会得到个人资料信息,要么会
 <null>

我该如何检查这个值?

 if profile == nil 

无法正常工作

如果我执行

let profile = snapshot.value as? String

首先,即使存在快照值,它始终返回nil。


尝试一下 if (snapshot.value != nil) { } 或者 if (snapshot.value as! NSObject != nil) { } - Shrikant Tanwade
谢谢Shrikant,但第一个还是有相同的问题。第二个建议给了我“类型“NSObject”的值永远不能为nil”的错误。 - FortuneFaded
快照的数据类型是什么? - Shrikant Tanwade
你尝试过这个吗?if profile == NSNull() - Shripada
在Swift中,如果要检查nil值,首先必须使用“?”将其变为可选项。然后,您可以执行以下操作:if let profile = snapshot.value { print(profile)} - Muhammad Zeeshan
1
看起来Shrikant和Shripada的问题的结合有所帮助。我认为snapshot.value as? NSObject != NSNull()正在按照我想要的方式工作。谢谢你们。 - FortuneFaded
2个回答

29

利用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"
        }

4
你可能想要探索另一个选项:因为你知道用户的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!")
       }

   });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接