Skip to content

Instantly share code, notes, and snippets.

@zntfdr
Last active March 8, 2017 10:55
Show Gist options
  • Save zntfdr/69543d864527114a6d1bc161b5d2b243 to your computer and use it in GitHub Desktop.
Save zntfdr/69543d864527114a6d1bc161b5d2b243 to your computer and use it in GitHub Desktop.
extension UIImage {
func load(image imageName: String) -> UIImage {
// declare image location
let imagePath: String = "\(NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])/\(imageName).png"
let imageUrl: URL = URL(fileURLWithPath: imagePath)
// check if the image is stored already
if FileManager.default.fileExists(atPath: imagePath),
let imageData: Data = try? Data(contentsOf: imageUrl),
let image: UIImage = UIImage(data: imageData, scale: UIScreen.main.scale) {
return image
}
// image has not been created yet: create it, store it, return it
let newImage: UIImage = // create your UIImage here
try? UIImagePNGRepresentation(newImage)?.write(to: imageUrl)
return newImage
}
}
@cgoldsby
Copy link

cgoldsby commented Mar 8, 2017

I am wondering if the load method should be static so that you can call UIImage.load(_:).

- func load(image imageName: String) -> UIImage
+ static func load(image imageName: String) -> UIImage

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment