Checking if Firebase snapshot is equal to nil in Swift

时光总嘲笑我的痴心妄想 提交于 2019-11-29 00:29:52

There are a few things going on here, but the most important one is that you cannot test for the existence of children with .ChildAdded. That makes sense if you think about it: the .ChildAdded event is raised when a child is added to the location. If no child is added, the event won't be raised.

So if you want to test if a child exists at a location, you need to use .Value. Once you do that, there are various way to detect existence. Here's one:

ref.queryOrderedByChild("waiting").queryEqualToValue("1")
   .observeEventType(.Value, withBlock: { snapshot in
       print(snapshot.value)
       if !snapshot.exists() {
           print("test2")
       }
   });

Check for NSNull. This is the code for observing a node. Queries work much the same way.

Here's a complete and tested app. To use, change the string 'existing' to some path you know exists, like your users path and the 'notexisting' to some path that does not exist

    let myRootRef = Firebase(url:"https://your-app.firebaseio.com")
    let existingRef = myRootRef.childByAppendingPath("existing")
    let notExistingRef = myRootRef.childByAppendingPath("notexisting")

    existingRef.observeEventType(.Value, withBlock: { snapshot in

        if snapshot.value is NSNull {
            print("This path was null!")
        } else {
            print("This path exists")
        }

    })

    notExistingRef.observeEventType(.Value, withBlock: { snapshot in

        if snapshot.value is NSNull {
            print("This path was null!")
        } else {
            print("This path exists")
        }

    })

Please note that by using .Value, there will be a guaranteed a return result and the block will always fire. If your code used .ChildAdded then the block will only fire when a child exists.

Also, check to make sure of how your data appears in firebase.

users
   user_0
     waiting: 1

if different than

users
   user_0
     waiting: "1"

Note that "1" is not the same as 1.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!