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?
Asked
Active
Viewed 7,564 times
3 Answers
5
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.

Lord Zsolt
- 6,492
- 9
- 46
- 76
5
you can't write to the bundle at all you need to save the data to you documents/caches folder inside your sandbox

Daij-Djan
- 49,552
- 17
- 113
- 135
5
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)
}
}
}

Community
- 1
- 1

Jesse Onolemen
- 1,277
- 1
- 15
- 32
-
Thanks! What would the code be then retrieve it? – Learnin Mar 12 '15 at 08:36
-
I believe the `image` variable stores the image so if you want to do anything with it be sure to use that :D – Jesse Onolemen Mar 12 '15 at 15:52