Reputation: 1555
Inside my CollectionViewController I have a method to fetch the data like this
func fetchData(){
let newsUrl = "http://api.meroschool.com/school/GetArticles?secretkey=1234&schoolCode=AA36&classId=ClassId000000011&pageNumber=1&type=Activities"
guard let url = URL(string: newsUrl) else {
return
}
URLSession.shared.dataTask(with: url){(data, response, err) in
guard let data = data else {return}
do{
let newsResponse = try JSONDecoder().decode(NewsResponse.self, from: data)
DispatchQueue.main.async {
self.newsList = newsResponse.newsList
print("count", self.newsList?.count)
}
}catch let error{
print("JSON Error", error)
}
}.resume()
}
I have setup all setup for ViewController to set the dynamic cells and it works while I set dummy data. But using the above method it is not updating the ViewController even the data are set to the newsList.
Some of the questions' answer in web says need to set the data in main thread so I setting data like.
DispatchQueue.main.async {
self.newsList = newsResponse.newsList
print("count", self.newsList?.count)
}
But not working for me. What would be the right way to set/update the data that is loaded from API so that CollectionViewController updates.
Upvotes: 1
Views: 800
Reputation: 6170
The collection view doesn't know that you're updated the underlying data source. So you need to state that explicitly by calling reloadData()
DispatchQueue.main.async { [weak self] in
self?.newsList = newsResponse.newsList
self?.yourCollectioView.reloadData()
}
Upvotes: 3