Say my app downloads an image, is it possible to save this to Images.xcassets programmatically, so that the image doesn't have to be downloaded again? Or would the best option be to keep retrieving it from the server?
You can't save it to the images.assets. However you can save it to the document directory buy doing this. (Code from here - How to convert code objective c to Swift to save image?)
let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) {
if paths.count > 0 {
if let dirPath = paths[0] as? String {
let readPath = dirPath.stringByAppendingPathComponent("Image.png")
let image = UIImage(named: readPath)
let writePath = dirPath.stringByAppendingPathComponent("Image2.png")
UIImagePNGRepresentation(image).writeToFile(writePath, atomically: true)
}
}
}
You can't save to Images.xcassets
, however you can save it to a file and access it with imageWithContentsOfFile:
.
You could also use a caching library, like JGAFImageCache or Haneke.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With