无法在tmp目录中保存文件

pab*_*ros 3 ios 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)
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*n R 6

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

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

或者更好,仅使用URL:

let targetURL = tempDirectoryURL.URLByAppendingPathComponent("\(name).jpg")
data.writeToURL(targetURL, atomically: true)
Run Code Online (Sandbox Code Playgroud)

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

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

Swift 3/4更新:

let targetURL = tempDirectoryURL.appendingPathComponent("\(name).jpg")
do {
    try data.write(to: targetURL)
} catch {
    print("Could not write file", error.localizedDescription)
}
Run Code Online (Sandbox Code Playgroud)

  • 尝试将此代码应用于缓存目录时出现此错误。“无法写入文件文件“jd64q7sc5n.png”不存在” (2认同)