Firebase observeSingleEvent不断复制我的数组

时间:2017-05-10 17:09:40

标签: swift

当我刷新集合视图时,我的数据中的数据重复+1。当我拉动刷新此功能时,如何避免数组中的重复条目? 也使用self.posts.removeAll()仍然没有结果。

var posts = [Post]() {
    didSet {
        collectionView?.reloadData()
    }
}

var following = [String]()
let refreshControl = UIRefreshControl()

override func viewDidLoad() {
    super.viewDidLoad()

    refreshControl.tintColor = UIColor.gray
    refreshControl.addTarget(self, action: #selector(fetchPosts), for: UIControlEvents.valueChanged)
    collectionView?.addSubview(refreshControl)
    collectionView?.alwaysBounceVertical = true
    fetchPosts()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.collectionView.reloadData()
}

func fetchPosts(){
    let ref = FIRDatabase.database().reference()
    ref.child("users").queryOrderedByKey().observeSingleEvent(of: .value, with: { snapshot in
        guard let users = snapshot.value as? [String : AnyObject] else {
            return
        }
        print(snapshot.key)
        for (_,value) in users {
            if let uid = value["uid"] as? String {
                if uid == FIRAuth.auth()?.currentUser?.uid {
                    if let followingUsers = value["following"] as? [String : String]{
                        for (_,user) in followingUsers{
                            self.following.append(user)
                            print(user)
                        }
                    }
                    self.following.append(FIRAuth.auth()!.currentUser!.uid)

                    ref.child("posts").queryOrderedByKey().observeSingleEvent(of: .value, with: { (snap) in
                        for postSnapshot in snap.children.allObjects as! [FIRDataSnapshot] {
                        let post = postSnapshot.value as! [String : AnyObject]
                        print(snap.key)

                            if let userID = post["userID"] as? String {
                                for each in self.following {
                                    if each == userID {
                                        print(each)
                                        let posst = Post()

                                        if let date = post["date"] as? Int, let author = post["author"] as? String, let likes = post["likes"] as? Int, let pathToImage = post["pathToImage"] as? String, let postID = post["postID"] as? String {

                                            posst.date = Int(date)
                                            posst.author = author
                                            posst.likes = likes
                                            posst.pathToImage = pathToImage
                                            posst.postID = postID
                                            posst.userID = userID

                                            print(posst)
                                            if let people = post["peopleWhoLike"] as? [String : AnyObject] {
                                                for (_,person) in people {
                                                    posst.peopleWhoLike.append(person as! String)
                                                }
                                            }


                                            var postExist:Bool = false
                                            for post in self.posts {
                                                if post.postID == posst.postID {
                                                    postExist = true
                                                    break
                                                }
                                            }

                                            if !postExist {
                                                self.posts.append(posst)
                                            }

                                            self.posts.sort(by: {$0.date! > $1.date!})
                                            self.refreshControl.endRefreshing()
                                        }
                                    }
                                }
                                self.collectionView.reloadData()
                            }
                        }
                    })
                }
            }
        }

    })
    ref.removeAllObservers()
}

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PostCell.identifier, for: indexPath) as! PostCell

    cell.posts = posts[indexPath.row]

    let post = posts[indexPath.row]
    for person in post.peopleWhoLike {
        if person == FIRAuth.auth()!.currentUser!.uid {
            cell.like.isHidden = true
            cell.unlike.isHidden = false
            break
        }
    }
    return cell
}

}

更新了解决方案。

1 个答案:

答案 0 :(得分:1)

我认为当激活刷新时,会调用此函数并下载所有帖子。对于您的重复问题,似乎您继续将数据附加到posts数组而不删除旧数据。

ref.child("posts").queryOrderedByKey().observeSingleEvent(of: .value, with: { (snap) in

    let postsSnap = snap.value as! [String : AnyObject]

    self.posts.removeAll() // This will remove previously downloaded posts.

    // All your other code ...