I currently upgrade to Swift 3.0
. I'm not able to get the NSCache
to work.
Below is the code I currently have. I don't see anything I'm missing I'm not sure exactly what I'm doing wrong.
class myClass {
let imageCache = NSCache()
func downloadImageByUserId(userId:String,imageView:UIImageView){
print(userId)
fireBaseAPI().childRef("version_one/frontEnd/users/\(userId)").observeEventType(.Value, withBlock: {snapshot in
let imageUrl = snapshot.value!["profileImageUrl"] as! String
// check image cache
print(self.imageCache.objectForKey(imageUrl))
if let cacheImage = self.imageCache.objectForKey(imageUrl) as? UIImage{
print("image cache")
imageView.image = cacheImage
return
}
print("image not cache")
//retrieve image
let url = NSURL(string: imageUrl)
NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, resposn, error) in
if error != nil {
print(error)
return
}
dispatch_async(dispatch_get_main_queue(),{
if let downloadImage:UIImage = UIImage(data: data!){
self.imageCache.setObject(downloadImage, forKey: imageUrl)
imageView.image = downloadImage
}
})
}).resume()
})
}
}
NSCache
is more Swifty in Swift 3.0.
It acts like swift Dictionary
, you need to give the Type of Key
and Value
:
let imageCache = NSCache<NSString, UIImage>()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With