Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically save an image to xcassets in Swift [duplicate]

Tags:

image

swift

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?

like image 941
Learnin Avatar asked Mar 10 '15 12:03

Learnin


2 Answers

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)
    }
  }
}
like image 154
Jesse Onolemen Avatar answered Sep 28 '22 16:09

Jesse Onolemen


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.

like image 36
Lord Zsolt Avatar answered Sep 28 '22 16:09

Lord Zsolt