6

My app downloads images from a server. I'd like to save those images to the Caches folder and then access them with UIImage(named:... for in-memory caching. Will UIImage(named: "fileURL", in: NSBundle.mainBundle, compatibleWith: nil) find the Caches folder or do I need to create a different bundle?

Hex Bob-omb
  • 314
  • 4
  • 10

1 Answers1

9

You don't want to use a bundle for caches folder. You should use NSFileManager to get the path for the caches folder. For example, in Swift 2:

let fileURL = try! NSFileManager.defaultManager()
    .URLForDirectory(.CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
    .URLByAppendingPathComponent("test.jpg")

let image = UIImage(contentsOfFile: fileURL.path!)

Or Swift 3:

let fileURL = try! FileManager.default
    .url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
    .appendingPathComponent("test.jpg")

let image = UIImage(contentsOfFile: fileURL.path)
Rob
  • 415,655
  • 72
  • 787
  • 1,044