Skip to content

Instantly share code, notes, and snippets.

@TheCodedSelf
Created April 29, 2017 06:05
Show Gist options
  • Select an option

  • Save TheCodedSelf/7ff3a4fb64f8f6131925fa3e6e21efbe to your computer and use it in GitHub Desktop.

Select an option

Save TheCodedSelf/7ff3a4fb64f8f6131925fa3e6e21efbe to your computer and use it in GitHub Desktop.

Revisions

  1. TheCodedSelf created this gist Apr 29, 2017.
    38 changes: 38 additions & 0 deletions ImageStore.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    import UIKit

    struct ImageStore {

    static func delete(imageNamed name: String) {
    guard let imagePath = ImageStore.path(for: name) else {
    return
    }

    try? FileManager.default.removeItem(at: imagePath)
    }

    static func retrieve(imageNamed name: String) -> UIImage? {
    guard let imagePath = ImageStore.path(for: name) else {
    return nil
    }

    return UIImage(contentsOfFile: imagePath.path)
    }

    static func store(image: UIImage, name: String) throws {

    guard let imageData = UIImagePNGRepresentation(image) else {
    throw NSError(domain: "com.thecodedself.imagestore", code: 0, userInfo: [NSLocalizedDescriptionKey: "The image could not be created"])
    }

    guard let imagePath = ImageStore.path(for: name) else {
    throw NSError(domain: "com.thecodedself.imagestore", code: 0, userInfo: [NSLocalizedDescriptionKey: "The image path could not be retrieved"])
    }

    try imageData.write(to: imagePath)
    }

    private static func path(for imageName: String, fileExtension: String = "png") -> URL? {
    let directory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
    return directory?.appendingPathComponent("\(imageName).\(fileExtension)")
    }
    }