2016-03-09 117 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!") 
     } 

    });