如何从捆绑包中访问<Application_Home>/Library/Caches?

Hex*_*omb 3 caching uiimage nsbundle ios

我的应用程序从服务器下载图像.我想将这些图像保存到Caches文件夹,然后使用UIImage(named:...内存缓存访问它们.会UIImage(named: "fileURL", in: NSBundle.mainBundle, compatibleWith: nil)找到Caches文件夹还是我需要创建一个不同的包?

Rob*_*Rob 6

您不希望将包用于缓存文件夹.您应该使用NSFileManager获取缓存文件夹的路径.例如,在Swift 2中:

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

let image = UIImage(contentsOfFile: fileURL.path!)
Run Code Online (Sandbox Code Playgroud)

或者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)
Run Code Online (Sandbox Code Playgroud)