2017-02-12 32 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