Ios 无法将文件保存在tmp目录中
我有这个功能来保存tmp文件夹内的图像Ios 无法将文件保存在tmp目录中,ios,swift,Ios,Swift,我有这个功能来保存tmp文件夹内的图像 private func saveImageToTempFolder(image: UIImage, withName name: String) { if let data = UIImageJPEGRepresentation(image, 1) { let tempDirectoryURL = NSURL.fileURLWithPath(NSTemporaryDirectory(), isDirectory: true)
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)
}
}
但当我打开应用程序的临时文件夹时,它是空的。将图像保存在临时文件夹中有什么不对吗?
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)抛出
并检查成功或失败:
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)
}
谢谢你,我正在使用的网址只选择节省了我的很多时间。我第一次使用绝对字符串,但没有得到任何工作。密钥为路径。非常感谢!尝试将此代码应用于缓存目录时出现此错误。无法写入文件。文件“jd64q7sc5n.png”不存在