2016-08-04 68 views
2

我試圖檢查,看看是否有鍵/值(密押/測試值)存在於一個節點,如果它做一個,如果不這樣做B.如何在Firebase快照中使用控制流中的Nil? (SWIFT)

我發現這個類似的線程關於StackOverflow的這一點,但沒有一個解決方案似乎爲我工作:Checking if Firebase snapshot is equal to nil in Swift

我有一個數據庫設置已插入TestKey/TestValue密鑰對。 這裏是我的代碼:

var ref: FIRDatabaseReference! 
    ref = FIRDatabase.database().reference() 

    ref.observeSingleEventOfType(.Value, withBlock: { (snapshot) in 

     //A print test to see stored value before control flow 
     print(snapshot.value!["TestKey"]) //returns TestValue 
     print(snapshot.value!["NilKey"]) //returns nil 

     // I change the value from TestKey <-> NilKey here to test the control flow 
     if snapshot.value!["TestKey"] != nil { 
      print("Exists currently") 
     } else { 
      print("Does not exist currently") 
     } 

    }) { (error) in 
     print(error.localizedDescription) 
    } 

的問題是,只有「A」被執行,即使打印測試顯示的結果是零。

我試圖扭轉與==零的操作,也嘗試「是NSNull」。

我似乎無法得到控制流的正常工作。也許下面的一個是罪魁禍首,但我不確定:

  1. 與observesSingleEventOfType持久的互動
  2. 不刪除觀察員(我甚至需要爲observeSingleEventType?)
  3. 事做自選
  4. 是與異步調用
  5. 事做的事實,火力店NSAnyObjects

最終目標是檢查一個鍵/值對是否存在以及它是否存在:如果它不存在,則不做任何事情:創建它。 我在做什麼錯了,我怎樣才能讓這個控制流程起作用?

回答

3

好吧,經過多次調查,我發現了一個可行的解決方案,它確實發佈爲來自先前存在的問題I(Checking if Firebase snapshot is equal to nil in Swift)的答案(https://stackoverflow.com/a/35682760/6515861)。

的方法,使其工作是輸入引用本身的密押,刪除snapshot.value(「密押」)的引用,然後使用「爲空」。

這裏是工作代碼:

// Database already exists with "TestKey"/"TestValue" 

var ref: FIRDatabaseReference! 
ref = FIRDatabase.database().reference() 

    // replace "TestKey" with another string to test for nil 
    ref.child("TestKey").observeSingleEventOfType(.Value, withBlock: { (snapshot) in 

    if snapshot.value is NSNull { 
     print("Does not exist currently") 
    } else { 
     print("Exists currently") 
    } 


    }) { (error) in 
     print(error.localizedDescription) 
    } 

我很高興,我發現這個解決辦法,但如果有人想還是回答原來的問題我很想知道爲什麼它不工作的其他方式。

相關問題