无法在tmp目录中保存文件

时间:2016-09-03 18:39:02

标签: 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)
    }
}

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

1 个答案:

答案 0 :(得分:6)

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

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

更好,仅适用于网址:

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