Reputation: 87
Why I'm I getting an issue with my completion handler and how can I fix this?
func loadImageusingCacheWithUrlString(urlString: String) {
self.image = nil
if let cachedImage = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
self.image = cachedImage
return
}
let url = NSURL(string : urlString)
URLSession.shared.dataTask(with: url!,
completionHandler: { (data, response, error) in
if error != nil {
print(error!)
return
}
DispatchQueue.main.async(execute: {
if let currImage = UIImage(data: data) {
imageCache.setObject(currImage, forKey: urlString)
self.image = currImage
}
//cell.imageView?.image = UIImage(data: data)
})
}).resume()
}
Upvotes: 0
Views: 1023
Reputation: 524
Use this
let url = URL(string : urlString)
Also you may get an error "Value of optional type 'Data?' not unwrapped", so you should write:
if let currImage = UIImage(data: data!) {
imageCache.setObject(currImage, forKey: urlString)
self.image = currImage
}
Upvotes: 1