2016-03-09 85 views
3

我正在运行下面的代码以查看打开该应用程序的用户是否已登录,然后检查他们是否设置了配置文件。我无法检查来自档检查Firebase检查空值(Swift)

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

+0

尝试,如果(snapshot.value!=无){}或者(snapshot.value作为!NSObject的!=无){} –

+0

谢谢shrikant,但第一有同样的问题。第二个建议给我“值类型'NSObject永远不可为零”错误 – FortuneFaded

+0

什么是快照的数据类型? –

回答

24

利用以确定该快照包含的值。使用你的例子:

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" 
     } 
+0

这是一个方便的提示好吧 – Fattie

3

你可能想探索另一种选择:因为您知道用户的uid,因此知道该用户的路径,所以没有理由进行查询。在知道路径的情况下,查询会增加不必要的开销。

例如

users 
    uid_0 
    name: "some name" 
    address: "some address" 

如果你存储它的事件不存在

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

它你好得多观察由值有问题的节点,这将返回null其他方式;也许

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

    });