Skip to content

Instantly share code, notes, and snippets.

@wookiee
Created September 30, 2016 15:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wookiee/17386f6ed1019579d157e67ea016652c to your computer and use it in GitHub Desktop.
Save wookiee/17386f6ed1019579d157e67ea016652c to your computer and use it in GitHub Desktop.
ImageStore.swift to use with the Advanced iOS pre-course workbook
//
// Copyright © 2015 Big Nerd Ranch
//
import UIKit
class ImageStore {
let cache = NSCache<NSString, UIImage>()
func imageURL(forKey key: String) -> URL {
let documentsDirectories =
FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentDirectory = documentsDirectories.first!
return documentDirectory.appendingPathComponent(key)
}
func setImage(_ image: UIImage, forKey key: String) {
cache.setObject(image, forKey: key as NSString)
// Create full URL for image
let url = imageURL(forKey: key)
// Turn image into JPEG data
if let data = UIImageJPEGRepresentation(image, 0.5) {
// Write it to full URL
let _ = try? data.write(to: url, options: [.atomic])
}
}
func image(forKey key: String) -> UIImage? {
if let existingImage = cache.object(forKey: key as NSString) {
return existingImage
}
let url = imageURL(forKey: key)
guard let imageFromDisk = UIImage(contentsOfFile: url.path) else {
return nil
}
cache.setObject(imageFromDisk, forKey: key as NSString)
return imageFromDisk
}
func deleteImage(forKey key: String) {
cache.removeObject(forKey: key as NSString)
let url = imageURL(forKey: key)
do {
try FileManager.default.removeItem(at: url)
} catch let deleteError {
print("Error removing the image from disk: \(deleteError)")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment