我有这个功能可以将图像保存在 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)
}
}
但是当我打开我的应用程序的临时文件夹时,它是空的。将图像保存在临时文件夹中我做错了什么?
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)
}
关于ios - 无法将文件保存在 tmp 目录中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39336698/
欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) | Powered by Discuz! X3.4 |