Let's take a look at how we can improve our applications to load images asynchronously while still being able to scroll a list view. This is a common issue that iOS developers run into and I'll show you how to cache images and then check to see if the request finished on the correct cell.
!codebreak
<div class='filename'>VideoCell.swift</div>
!codebreak
!syntax-highlight
let thumbnailImageView: CustomImageView = {
let imageView = CustomImageView()
imageView.image = UIImage(named: "taylor_swift_blank_space")
imageView.contentMode = .ScaleAspectFill
imageView.clipsToBounds = true
return imageView
}()
let userProfileImageView: CustomImageView = {
let imageView = CustomImageView()
imageView.image = UIImage(named: "taylor_swift_profile")
imageView.layer.cornerRadius = 22
imageView.layer.masksToBounds = true
imageView.contentMode = .ScaleAspectFill
return imageView
}()
!codebreak
<div class='filename'>CustomImageView.swift</div>
!codebreak
!syntax-highlight
let imageCache = NSCache()
class CustomImageView: UIImageView {
var imageUrlString: String?
func loadImageUsingUrlString(urlString: String) {
imageUrlString = urlString
let url = NSURL(string: urlString)
image = nil
if let imageFromCache = imageCache.objectForKey(urlString) as? UIImage {
self.image = imageFromCache
return
}
NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, respones, error) in
if error != nil {
print(error)
return
}
dispatch_async(dispatch_get_main_queue(), {
let imageToCache = UIImage(data: data!)
if self.imageUrlString == urlString {
self.image = imageToCache
}
imageCache.setObject(imageToCache!, forKey: urlString)
})
}).resume()
}
}