Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift Firebase observeSingleEvent连续地将重复条目追加到我的数组中_Swift - Fatal编程技术网

Swift Firebase observeSingleEvent连续地将重复条目追加到我的数组中

Swift Firebase observeSingleEvent连续地将重复条目追加到我的数组中,swift,Swift,当我刷新集合视图时,数据在我的视图中以+1的比例复制。当我拉刷新此函数时,如何避免数组中的重复条目? 还使用了self.posts.removeAll仍然没有结果 var posts = [Post]() { didSet { collectionView?.reloadData() } } var following = [String]() let refreshControl = UIRefreshControl() override func view

当我刷新集合视图时,数据在我的视图中以+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
}
}


更新了解决方案。

我认为当刷新被激活时,会调用此函数并下载所有帖子。对于重复问题,您似乎一直在将数据附加到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 ...

在将数据添加到数组后,可以像self.posts.sortby:{$0.date!>$1.date!}那样使用日期对其进行排序。但当我滚动以重新加载集合视图时,仍然需要帮助以避免重复。谢谢如果我下面的回答不能解决您的问题,您需要上传整个视图控制器,因为您的一些代码缺失,因此无法完全理解。添加了完整的代码。谢谢你将数据库中的一些数据添加到你的问题中,这样我就可以测试它了。