【问题标题】:Firebase child added in realtime not updating in collection view实时添加的 Firebase 子项未在集合视图中更新
【发布时间】:2016-10-06 15:49:43
【问题描述】:

在阅读了关于重新加载 Firebase observeEventType 观察者的一系列其他问题后,我很困惑。我正在将我的观察者字典添加到整个控制器中可访问的变量中。然后我将该值分配给数据源字典,它会加载所有先前添加的子项。

但是,一旦我尝试从另一个模拟器添加新值或在后端手动输入,我的全局字典会更新为新值,但我的数据源变量不会。一旦我离开控制器,它最终会更新,但它违背了使用 Firebase 的目的。

我认为一个开放的观察者应该在 viewWillAppear 中,但是网上一堆来源似乎在 viewDidLoad 中。

我正在使用分段控件来遍历每个自定义类,这可能会导致问题。设置是一个集合视图控制器,其单元格是自定义集合视图,也是单元格。

        override func viewWillAppear(animated: Bool) {
            super.viewWillAppear(animated)
            self.loadFireData()
        }

    func loadFireData() {
    if let locationId = location.locationId {

        let postQuery = ref.child("Posts").child(selectedRegion).child(locationId).queryOrderedByChild("descTime")
        postQuery.observeEventType(.ChildAdded, withBlock: { (snap) in


            if snap.exists() {
                let postQuery = snap.value! as! [String: AnyObject]

                let feedPost = FeedModel()

                feedPost.value = postQuery["value"] as? String

                feedPost.key = postQuery["key"] as? Int
                feedPost.balance = postQuery["balance"] as? Double
                self.post.append(feedPost)

                dispatch_async(dispatch_get_main_queue(), {
                    self.collectionView!.reloadData()
                })
            } 

            }

        })
    }

}

     override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    if indexPath.section == 1 {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(feedCellId, forIndexPath: indexPath) as! LocationFeedCell
        cell.location = location
         //this doesn't seem to be updating here 
        cell.posts = posts

        return cell
    }

任何帮助将不胜感激

【问题讨论】:

    标签: ios swift firebase firebase-realtime-database


    【解决方案1】:

    您只是将 footpost 添加到 post 数组中。所以在重新加载collectionview之后,你应该根据indexpath.row将最新的footpost添加到你的自定义单元格的标签中

    if indexPath.section == 1 {
                let cell = collectionView.dequeueReusableCellWithReuseIdentifier(feedCellId, forIndexPath: indexPath) as! LocationFeedCell
                cell.location = location
                 //Replace this below line: 
                cell.posts = post[indexpath.row] as! String
    
                return cell
            }
    

    【讨论】:

    • 对不起,我之前不够清楚,但这只是作为 post 字典的键值对之一的示例。所以这仍然行不通,因为它只根据使用该代码为字典分配一个值
    • @SethG 你终于弄明白了吗?
    猜你喜欢
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多