一尘不染

无法在tmp目录中保存文件

swift

我有此功能可以将图像保存在tmp文件夹中

private func saveImageToTempFolder(image: UIImage, withName name: String) {

    if let data = UIImageJPEGRepresentation(image, 1) {
        let tempDirectoryURL = NSURL.fileURLWithPath(NSTemporaryDirectory(), isDirectory: true)
        let targetURL = tempDirectoryURL.URLByAppendingPathComponent("\(name).jpg").absoluteString
        print("target: \(targetURL)")
        data.writeToFile(targetURL, atomically: true)
    }
}

但是,当我打开应用程序的temp文件夹时,它是空的。将图像保存在temp文件夹中,我做错了什么?


阅读 393

收藏
2020-07-07

共1个答案

一尘不染

absoluteString不是获取的文件路径的正确方法NSURL,请path改用:

let targetPath = tempDirectoryURL.URLByAppendingPathComponent("\(name).jpg").path!
data.writeToFile(targetPath, atomically: true)

或者 更好的是, 仅使用URL:

let targetURL = tempDirectoryURL.URLByAppendingPathComponent("\(name).jpg")
data.writeToURL(targetURL, atomically: true)

更好的是,使用writeToURL(url: options) throws 并检查成功或失败:

do {
    try data.writeToURL(targetURL, options: [])
} catch let error as NSError {
    print("Could not write file", error.localizedDescription)
}

Swift 3/4更新:

let targetURL = tempDirectoryURL.appendingPathComponent("\(name).jpg")
do {
    try data.write(to: targetURL)
} catch {
    print("Could not write file", error.localizedDescription)
}
2020-07-07