无法使用快速

时间:2016-10-19 00:18:19

标签: ios swift firebase firebase-realtime-database

我正在开发一个项目,我从firebase中提取数据(排队"排队等#34;)。基本上数据是用时间戳保存的,因此当它被调用时,它可以按顺序排序(先进先出)。

我面临的问题是当我在我的应用上检索数据时。根据我的研究,在Stack overflow以及firebase文档中,.Value提供了一个快照,并在添加新数据时继续监听数据。但是,当添加新数据时,它将拍摄整个集合的新快照(因此"复制数据"在我的应用程序的数组中)。

为了解决这个问题,我尝试使用.ChildAdded,它可以在将新数据添加到firebase数据库时将新数据添加到我的数组中。但是,它不会添加完整的数据集(数据库中已存在的数据),这是我需要的,除了添加新数据之外。

假设firebase节点如下:

App_Queue:
         Category1:
                        Timestamp1:
                                  Uid: User_1_uid
                         Timestamp2:
                                   Uid: User_2_uid

Swift代码(2.3):

案例1:

self.databaseRef.child("App_Queue/\(Category1)").queryLimitedToLast(15).observeEventType(.Value, withBlock: { (snapshot) in
                if let userDict = snapshot.value as? [String:AnyObject]{
                    for each in userDict{

                        let timeIdExtract = each.0 as! String 

                        self.timeIdArray.append(timeIdExtract)
                        print(self.timeIdArray)
                    }

//this gives me full snapshot of time stamps & a userId
          //but if timestamp3 and user_3_uid is added to firebase, the array is appended with a new snapshot thus, duplicating items.

情况2:

self.databaseRef.child("App_Queue/\(Category1)").queryLimitedToLast(15).observeEventType(FIRDataEventType.ChildAdded, withBlock: { (snapshot : FIRDataSnapshot) in
                if let userDict = snapshot.value as? [String:AnyObject]{
                    for each in userDict{

                        let timeIdExtract = each.0 as! String // Every follwers ID.

                        self.timeIdArray.append(timeIdExtract)
                        print(self.timeIdArray)
                    }

           //this gives me only new items added, but not already added. 
          // if timestamp3 and user_3_uid is added the array is appended with this new item. But timestamp1 & timestamp2 not added

案例3: 我尝试过Case1的混合(改为使用.observeSingleEventOfType())& Case2,在case 1中的代码之后添加self.databaseRef.removeAllObservers(),然后为case2打开.ChildAdded观察者。它几乎可以工作....通过案例1添加初始快照,然后监听,如果说最近添加了timestamp2,它​​将在调用Case2时再次追加它,从而复制数组。

所以我的问题是:如何在数据库中获取现有对象并添加新对象,而不重复数组中的数据?

修改

我很傻 - 在块之后有一些无关紧要的代码。 DOH!对于遇到问题的人,首先要检查!还。与observeEventType配对的.ChildAdded完成了这个技巧。 (获取DB +中已有的所有先前数据,在添加新数据时)。

self.databaseRef.child("App_Queue/\(Category1)").queryLimitedToLast(15).observeEventType(.ChildAdded, withBlock: { (snapshot) in
...

1 个答案:

答案 0 :(得分:0)

我很傻 - 在块之后有一些无关紧要的代码。 DOH!对于遇到问题的人,首先要检查!还。与observeEventType配对的.ChildAdded完成了这个技巧。 (获取DB +中已有的所有先前数据,在添加新数据时)。

L' ********* | ***************************** | ************ R'

   L_Margin  L           Width               R    R_Margin