Skip to content

Instantly share code, notes, and snippets.

@markd2
Created November 29, 2016 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markd2/c3ff7af0e898f81c11ec86795a475114 to your computer and use it in GitHub Desktop.
Save markd2/c3ff7af0e898f81c11ec86795a475114 to your computer and use it in GitHub Desktop.
ImageStore.swift for the advanced ios bootcamp pre-reading
//
// 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
} else {
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 {
print("Error removing the image from disk: \(error)")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment