刷新重新加载集合视图

时间:2018-05-25 23:24:51

标签: swift

我想在viewcontroller中刷新数据。我使用reloadData但它不起作用。我该怎么办?请帮帮我。我在tabbar控制器中有这个视图控制器。我试图从数组中删除所有元素e重用该函数但我有元素double。我曾尝试使用viewwillappear,但每次他返回Viewcontroller时,都会多次添加相同的项目

override func viewDidLoad() {
    super.viewDidLoad()
    refreshControl.addTarget(self, action: #selector(HomeViewController.refreshData), for: UIControlEvents.valueChanged)
    collectionview.addSubview(refreshControl)
    lodPosts()
}

@objc func refreshData() {
    refreshControl.endRefreshing()
}

func lodPosts() {
    let ref = Database.database().reference()
    ref.child("users").queryOrderedByKey().observeSingleEvent(of: .value, with: { snapshot in
        let users = snapshot.value as! [String : AnyObject]
        for(_,value) in users {
            if let uid = value["uid"] as? String {
                if uid == Auth.auth().currentUser?.uid {
                    if let followingUsers = value["following"] as? [String : String] {
                        for(_,user) in followingUsers {
                            self.following.append(user)
                        }
                    }

                    self.following.append(Auth.auth().currentUser!.uid)

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

                        let postsSnap = snap.value as! [String: AnyObject]
                        for(_,post) in postsSnap {
                            if let userID = post["uid"] as? String {
                                for each in self.following {
                                    if each == userID {
                                        let posst = Post()
                                        if let author = post["Author"] as? String, let likes = post["likes"] as? Int, let pathToImage = post["photoUrl"] as? String, let postID = post["postID"] as? String,let profileImage = post["profileImageUrl"] as? String,let caption = post["caption"] as? String {
                                            posst.author = author
                                            posst.likes = likes
                                            posst.pathToImage = pathToImage
                                            posst.postID = postID
                                            posst.userID = userID
                                            posst.userimage = profileImage
                                            posst.caption = caption
                                            self.posts.append(posst)

                                        }

                                    }
                                }
                                self.collectionview.reloadData()

                            }
                        }

                    })

                }
            }
        }

    })
}

1 个答案:

答案 0 :(得分:1)

必须在主线程上执行所有UI操作

Swift 4

DispatchQueue.main.async {
    self.collectionview.reloadData()
}