2017-02-12 31 views
0

因此,我目前正在研究像snapchat這樣的克隆,並且我正在向服務器發送拉請求,但是對於下載,它不太好。我創建了一個參考看起來像這樣的數據庫,Swift中的FirebaseDatabase查詢問題

var recievers: FIRDatabaseReference{ 
    return mainRef.child("pullRequests") 
} 

,然後我有一個分析數據(我知道是不是去了解這一點的最好方式的viewController,但我只是想得到它現在的工作),並在那裏我有這個

DataService.instance.recievers.observeSingleEvent(of: .value) {(recipients: FIRDataSnapshot) in 
     if let recipient = recipients.value as? Dictionary<String,AnyObject>{ 
      var index = 0; 
      for(key,value) in recipient{ 
       index = index+1 
       if let dict = value as? Dictionary<String,AnyObject>{ 
        if let reciever = dict["recipents"] as? Dictionary<String,AnyObject>{ 
         if let num = reciever["\(index)"] as? String{ 
          let uid = num 
          recipientsArr.append(uid) 
          } 
         } 
        } 
       } 
      } 
     } 

    for i in 0...recipientsArr.count{ 
    print(i) 
    } 

我沒有得到任何編譯錯誤,但它也沒有添加任何進入recipientsArr,任何人都可以幫助指導我在正確的方向?

我的火力地堡看起來是這樣的:

回答

0

您沒有正確解碼快照。從你的問題來看,你不清楚你想觀察什麼是有價值的事件 - 它只是一個新的收件人被添加?整個pullRequest? 在任何情況下,你觀察pullRequest參考,並因此爲了快照解碼:

if let pullRequest = recipients.value as? Dictionary<String,AnyObject>{ 
      if let recipientsList = pullRequest["recipents"] as? Dictionary<String,AnyObject>{ 
       for (_, value) in recipientsList { 
        if let uid = value as? String{ 
         recipientsArr.append(uid) 
         } 
        } 
       } 
      } 
+0

我試圖閱讀只有recipents元素「tLvt ...」,「JqIr ..」等放在recipientsArr,我也試過你的方法,它導致了相同的結果。看起來好像什麼都沒有被添加到數組 – andrewF

+0

你有沒有運行調試器來查看快照解碼失敗的位置?只是爲了確保 - ObserveSingleEvent的回調函數甚至調用了嗎?如果你想讀取收件人列表的變化,最好選擇這個作爲你的參考:mainRef.child(「pullRequests」)。child(「recipents」 ) –

0

的問題是,你正在使用的方法observeSingleEvent來更新數據庫中的值,當這種方法僅用於從數據庫中收到的數據,未更新。換句話說,它是隻讀的。

在firebase數據庫中更新記錄的方式與讀取方法不同。您可以使用setValueupdateChildValues兩種方法執行更新。他們都在數據庫引用上工作。

要使用setValue方法,您應該這樣做。我假設你已經有了一個pullRequests對象,您先前從信息創建從數據庫中取出,並把它在一個變量:

let previousRecipents = pullRequests.recipents 
let allRecipents = previousRecipents.append(newRecipent) // Assuming preivousRecipents is an array and you have the new Recipent 
recievers.child("recipents").setValue(allRecipents) 

要使用updateChildValues,它的工作原理非常相似。

let previousRecipents = pullRequests.recipents 
let allRecipents = previousRecipents.append(newRecipent) // Assuming preivousRecipents is an array and you have the new Recipent 
let parametersToUpdate = ["recipents": allRecipents] 
recievers.updateChildValues(parametersToUpdate) 

有關如何更新,查看以下鏈接的詳細信息: https://firebase.google.com/docs/database/ios/save-data

希望它能幫助!

+0

我沒有問題,更新數據庫,我試圖得到的UID的受惠人士票價陣列拉出數據庫 – andrewF