Reputation: 11
I want to refresh the data in viewcontroller. I use reloadData but it does not work.What can i do?Please help me. I have this view controller in tabbar controller. I have tried to remove all elements from the array e reuse the function but i have the elements double. I have tried to use viewwillappear but every time he returns to the Viewcontroller, it adds the same items a lot of times
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()
}
}
})
}
}
}
})
}
Upvotes: 1
Views: 69
Reputation: 1148
All UI operations must be performed on the main thread
DispatchQueue.main.async {
self.collectionview.reloadData()
}
Upvotes: 1