Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am caching an image locally..That same image will be used in few screens. Steps for doing this is as follows:

  1. Get image from cache

  2. If not present in NSCache, get image from Cache directory

  3. If not present in Cache Directory, download from Internet

  4. Save downloaded image to dir

  5. Insert the image in cache

//Helper class is as

     class ImageCacheHelper:NSObject{

        static var cache = NSCache()
        static var isNotRunningDispatch:Bool = true

      class func setObjectForKey(imageData:NSData,imageKey:String){

            ImageCacheHelper.cache.setObject(imageData, forKey: imageKey)

        }

      class func getObjectForKey(imageKey:String)->NSData?{

            return ImageCacheHelper.cache.objectForKey(imageKey) as? NSData

        }

      class func getImage(imageUrl:String,completionHandler:(NSData)->()){        
            if ImageCacheHelper.isNotRunningDispatch{

                ImageCacheHelper.isNotRunningDispatch = false
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), {
                    let imgUrl = NSURL(string:imageUrl)
                    let imageData = NSData(contentsOfURL: imgUrl!)!
                    ImageCacheHelper.setObjectForKey(imageData, imageKey: "\(imageUrl.hashValue)")
                    ImageCacheHelper.isNotRunningDispatch = true
                    completionHandler(imageData)

                })
            }else{
               print("alerady started loading image")
           }
        }
      }

//How i call this from ViewController class is as

let userImageUrl = "\(appBaseUrl)\(imageUrlString)"
let fileManager = NSFileManager.defaultManager()
let diskPaths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let cacheDirectory = diskPaths[0] as NSString
let diskPath = cacheDirectory.stringByAppendingPathComponent("\(userImageUrl.hashValue)")
if let data = ImageCacheHelper.getObjectForKey("\(userImageUrl.hashValue)"){
          let userImage =  UIImage(data: data)
          self.userImgView.image = userImage

}else if fileManager.fileExistsAtPath(diskPath){

          let image =  UIImage(contentsOfFile: diskPath)
          self.userImgView.image = image
          ImageCacheHelper.setObjectForKey(UIImageJPEGRepresentation(image, 1.0)!, imageKey: "\(userImageUrl.hashValue)")

}else   {
          ImageCacheHelper.getImage(userImageUrl){ imageData in

            imageData.writeToFile(diskPath, atomically: true)
                    dispatch_async(dispatch_get_main_queue()){

                        let userImage =  UIImage(data: imageData)
                        self.userImgView.image = userImage

                    }
        }
}

Flaws That I see in my code are as follows:

  1. Creating a static variable for NSCache.

  2. Would be great if settingObject in NSCache, getting would be as of NSUserDefaults.

How to optimize this?

Here is a snippet of project that i have tried to do https://drive.google.com/file/d/0B6dTvD1JbkgBS1k3Ry1xNmZ1VHc/view?usp=sharing

share|improve this question

This question has an open bounty worth +50 reputation from anish parajuli ending tomorrow.

The question is widely applicable to a large audience. A detailed canonical answer is required to address all the concerns.

    
Where in your code is an image downloaded from the Internet? – Martin R Jan 5 at 18:21
    
@MartinR sorry that was just anothe snippet of code..please see the edited question – anish parajuli Jan 5 at 18:31

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.