Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift 3 NSCache does not work

Tags:

swift

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()
        })
    }
}
like image 765
SwiftER Avatar asked Sep 18 '16 06:09

SwiftER


1 Answers

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>()
like image 170
beeth0ven Avatar answered Nov 18 '22 14:11

beeth0ven