【问题标题】:Firebase checking for null value (Swift)Firebase 检查空值(Swift)
【发布时间】:2016-03-09 04:00:44
【问题描述】:

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

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

【问题讨论】:

  • 尝试 if (snapshot.value != nil){ } 或 if (snapshot.value as!NSObject != nil){ }
  • 感谢 shrikant,但首先遇到了同样的问题。第二个建议给了我“'NSObject 类型的值永远不能为零”错误
  • 快照的数据类型是什么?
  • 如果 profile == NSNull() 你试过了吗?
  • 在快速检查 nil 值时,首先您必须使用 '?' 将其设为可选。然后你可以这样做 if let profile = snapshot.value { print(profile) }

标签: ios swift firebase


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您可能想探索另一种选择:由于您知道用户的 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!")
           }
    
       });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-29
      • 1970-01-01
      • 2021-11-17
      相关资源
      最近更新 更多