Firestore addSnapshotListener在新对象输入时替换对象数据

时间:2018-03-20 09:12:39

标签: swift firebase object google-cloud-firestore

我有以下功能;

func observePosts() {
    let postReference = Firestore.firestore().collection("Posts").limit(to: 20).order(by: "postTimestamp", descending: true)
    postReference.addSnapshotListener { (snapshot, error) in
        if error != nil {
            print(error as Any)
            return
        } else {
            guard let snapshot = snapshot else { return }
            let models = snapshot.documents.flatMap({Post(dictionary: $0.data())})
            self.posts = models
            DispatchQueue.main.async {
                self.feedCollection.reloadData()
            }
        }
    }
}

这将返回集合下的所有文档。

然而,当我按照下面的说法添加另一个对象时;

uploadMedia { (url) in
        if url != nil {
            let postIDReference = self.postsReference.collection("Posts").document().documentID
            self.postsReference.collection("Posts").document().setData([
                "postID" : postIDReference,
                "postImageURL" : url!,
                "postTimestamp" : 1234567890
                ], completion: { (error) in
                if error != nil {
                    print(error as Any)
                    return
                } else {
                    picker.dismiss(animated: true, completion: nil)
                }
            })
        }
    }
}

这将使用新的setData对象覆盖单元格。我已经在SO上阅读了一些类似的问题,但大多数都与没有自动ID密钥

有关
self.postsReference.collection("Posts").document().setData(

给了我。

我尝试了什么:

终止应用并重新打开,即可获得Firestore中的所有对象。 Firestore仪表板包含所有对象(因此丢失数据没有问题)。

以下是我的代表&数据源方法

    extension FeedController: UICollectionViewDelegate, UICollectionViewDataSource 
{

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection 
section: Int) -> Int {
        return posts.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt 
indexPath: IndexPath) -> UICollectionViewCell {
        let feedCell = feedCollection.dequeueReusableCell(withReuseIdentifier: 
"cell", for: indexPath) as! PostCell
        let post = posts[indexPath.item]
        feedCell.post = post
        return feedCell
    }
}

CollectionView Cell

import UIKit
import SDWebImage

class PostCell: UICollectionViewCell {

    @IBOutlet weak var postImage: UIImageView!

    var post: Post? {
        didSet {
            guard let post = post else { return }
            let postImageURL: URL = URL(string: (post.postImageURL))!
            postImage.sd_setImage(with: postImageURL) { (image, error, cache, url) 
in
                self.postImage.image = image
            }
        }
    }
}

任何帮助表示赞赏 - 非常感谢。

1 个答案:

答案 0 :(得分:0)

问题是我的自定义flowLayout。我相信在检索新项目时我需要使布局无效。