Skip to content

Instantly share code, notes, and snippets.

@anishparajuli555
Created January 6, 2016 08:15
Show Gist options
  • Save anishparajuli555/8eb72571ba2f6d5f95bf to your computer and use it in GitHub Desktop.
Save anishparajuli555/8eb72571ba2f6d5f95bf to your computer and use it in GitHub Desktop.
Cache Image Locally
//
// UIImageExtension.swift
// EddyCab
//
// Created by Anish on 1/4/16.
// Copyright © 2016 Esig. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
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 you call this class is as
let userImageUrl = "\(appUrl)\(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
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment