我有这个功能来保存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)
但是,当我打开我的应用程序的临时文件夹时,它是空的.将图像保存在临时文件夹中我做错了什么?
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)
归档时间: |
|
查看次数: |
2410 次 |
最近记录: |