-
-
Save gunantosteven/93f97fff0479168015d98898bb356256 to your computer and use it in GitHub Desktop.
How to cache image for temporary use iOS Swift 5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
class ImageCache { | |
static func getImage(urlString: String) -> UIImage? { | |
if let dict = UserDefaults.standard.object(forKey: "ImageCache") as? [String:String] { | |
if let path = dict[urlString] { | |
if let data = try? Data(contentsOf: URL(fileURLWithPath: path)) { | |
let img = UIImage(data: data) | |
return img | |
} | |
} | |
} | |
return nil | |
} | |
static func storeImage(urlString: String, img: UIImage) { | |
let path = NSTemporaryDirectory().appending(UUID().uuidString) | |
let url = URL(fileURLWithPath: path) | |
let data = img.jpegData(compressionQuality: 1.0) | |
try? data?.write(to: url) | |
var dict = UserDefaults.standard.object(forKey: "ImageCache") as? [String:String] | |
if dict == nil { | |
dict = [String:String]() | |
} | |
dict![urlString] = path | |
UserDefaults.standard.set(dict, forKey: "ImageCache") | |
} | |
} | |
// Implemantion | |
// store | |
func downloadVideoCover(completion : @escaping (UIImage?)->Void) { | |
AVAsset(url: URL(string: url)!).generateThumbnail { (image) in | |
DispatchQueue.main.async { | |
guard let image = image else { return } | |
ImageCache.storeImage(urlString: self.url, img: image) | |
completion(image) | |
return | |
} | |
} | |
} | |
// show | |
if let image = ImageCache.getImage(urlString: url) { | |
imageView.image = image | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment