Error in the 3rd line due to the declaration of a constant, why is this happening? Error: Extensions must not contain stored properties Code:
extension UIImageView {
let imageCache = NSCache<NSString, UIImage>() //error
func imageFromServerURL(_ URLString: String, placeHolder: UIImage?) {
self.image = nil
//If imageurl's imagename has space then this line going to work for this
let imageServerUrl = URLString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
if let cachedImage = imageCache.object(forKey: NSString(string: imageServerUrl)) {
self.image = cachedImage
return
}
if let url = URL(string: imageServerUrl) {
URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
//print("RESPONSE FROM API: \(response)")
if error != nil {
print("ERROR LOADING IMAGES FROM URL: \(String(describing: error))")
DispatchQueue.main.async {
self.image = placeHolder
}
return
}
DispatchQueue.main.async {
if let data = data {
if let downloadedImage = UIImage(data: data) {
self.imageCache.setObject(downloadedImage, forKey: NSString(string: imageServerUrl))
self.image = downloadedImage
}
}
}
}).resume()
}
}
}
I used this code and don't understand why it doesn't work: Swift async load image