Swift: YouTube - How to Load Images Async in UICollectionView (Ep 6)
Why Stack Overflow recommends it
Stack Overflow users link it when answering questions about wrong or flickering images in scrolling table and collection views, since it shows an async loading and caching pattern that fixes cell reuse issues.
Recommended by 1 people across 1 different months, 2018 to 2020.
What it is
Episode 6 of Lets Build That App's YouTube clone series for iOS, in Swift. Brian Voong shows how to load images asynchronously into a UICollectionView, cache them, and check that a finished request still belongs to the correct cell so scrolling stays smooth and images do not appear in the wrong place.
What people said
Recommends AfnanAhmad · 2019-03 · Stack Overflow · on “I have problems with JSON - Data is repeated”
dataTask runs in the background, so you can't expect it to run multiple times correctly. Furthermore, keep a identifier for each object and before assigning the object to array check if it already exists in the array. This video might prove helpful: [this video]
Cites user00007 · 2018-07 · Stack Overflow · on “error while loading images asynchronously from firebase”
Also , if I don't declare the lastImageUrl in extension the images keep on changing when I scroll down . I was following this video to fix this issue ( [this video] )
Cites SwiftySai · 2020-06 · Stack Overflow · on “tableView cell is displaying the wrong image sometimes?”
Swift 5 So a simple solution to your problem would be by creating a custom class which subclasses UIImageView. Add a property to store the url string. Initially set the image to your placeholder to stop flickering. While parsing and setting the image from response data compare class property url string with the url string passed through to the function and make sure they are equal. Cache your image with the key as the url string and retrieve accordingly. Note: Do not extend UIImageview as we plan to add property imageUrl . reference: [this video] let imageCache = NSCache<NSString, UIImage>() class CustomIV: UIImageView { var imageUrl: String? func loadImage(urlStr: String) { imageUrl = urlStr ima