Search code examples
ioscachinguiimagensbundle

How can I access <Application_Home>/Library/Caches from a bundle?


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?


Solution

  • 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)