First of all please forgive any wrong terminology, I started to learn the escaping closures just a couple of weeks ago.
I have an API "returning" an array in an escaping closure. The function is called like this:
getAllUserMovies(username: user) { (result) in
switch result {
case .success(let movies):
// movies is an array. Do something with each element
break
case .error(let error):
// report error
break
}
}
And I need to use the elements of that array, only one per time, in this collection view method (it's actually more complex than this, since I interface with the TMDB API as well):
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
I tried to use the nested closures, in a similar fashion:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell : collectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: self.reuseIdentifierLargeBanners, for: indexPath as IndexPath) as! CollectionViewCell
getAllUserMovies(username: user){ (result) in
switch result {
case .success(let movies):
let movie = movies[indexPath.row] {
cell.imageView.image = movie.poster
}
break
case .error(let error):
print(error?.localizedDescription ?? "")
break
}
}
return cell
}
return UICollectionViewCell()
}
Basically I get two issues. First of all I consider this completely inefficient (I have to fetch the full movie list anytime I refresh a cell) and then I also get funny results, like duplicated banners, which keep refreshing, moving around or missing icons. I implemented the accepted answer of this question, but still I am unable to make it working. Whatever I do I either get duplicated images, empty cell or both.
UPDATE: It appears the missing icons were due to a limit in the number of calls per second in the API. Above that number the API fails and I didn't check the error.
I suppose a possible solution would be to store the "movies" array somewhere, and then be able to fetch the singular movies from it from the collection view method. Refreshing it if/when needed. That now has been fixed, thanks to anuraj answer!