Created
April 29, 2017 06:05
-
-
Save TheCodedSelf/7ff3a4fb64f8f6131925fa3e6e21efbe to your computer and use it in GitHub Desktop.
Store, retrieve, and delete images in your iOS app's local storage
This file contains 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 | |
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)") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
here in my local file path but this not showing in ImageView
file:///var/mobile/Containers/Data/Application/8421B8A7-CB60-462B-9DC1-3C0025828CE2/Documents/Fetish.png