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

最佳答案

您不想为缓存文件夹使用捆绑包。您应该使用 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!)

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

let image = UIImage(contentsOfFile: fileURL.path)

关于ios - 如何从包中访问 <Application_Home>/Library/Caches?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38817310/

10-09 02:17