尝试将以下image
保存到本地存储。
if let imageData: Data = UIImagePNGRepresentation(self.emitterImageView.image!) {
try! imageData.write(to: savedImagePath, options: [])
}
但是由于以下错误而崩溃。
线程1:致命错误:“尝试!”表达式意外引发错误: 错误域= NSCocoaErrorDomain代码= 4“该文件 “ PHDEmitterImage1.png”不存在。” UserInfo = {NSFilePath = / private / var / mobile / Containers / Data / Application / 41D876EC-7D65-4AB1-820E-EDE46FAE8675 / tmp / PHDEmitterBackup / PHDEmitterImage1.png, NSUnderlyingError = 0x15bf21790 {Error Domain = NSPOSIXErrorDomain Code = 2 “没有这样的文件或目录”}}
问题出在哪里?
保存的图像路径为file:/private/var/mobile/Containers/Data/Application/41D876EC-7D65-4AB1-820E-EDE46FAE8675/tmp/PHDEmitterBackup/PHDEmitterImage1.png
自定义路径
func emitterBackupDirectoryPath() -> String? {
let dataPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.absoluteString
//let dataPath = URL(fileURLWithPath: documentsDir).appendingPathComponent("/PHDEmitterBackup").absoluteString
//let dataPath = documentsDir?.appendingPathComponent("/PHDEmitterBackup").absoluteString
if !FileManager.default.fileExists(atPath: dataPath!) { //if does not exist
do {
try FileManager.default.createDirectory(atPath: dataPath!, withIntermediateDirectories: false, attributes: nil) //Create folder
} catch {
}
}
return dataPath
}
答案 0 :(得分:1)
您可以将image
data
另存为,
let tempURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let savedImagePath = tempURL?.appendingPathComponent("Emitter.png")
if let path = savedImagePath, let imageData = self.emitterImageView.image?.pngData() {
do {
try imageData.write(to: path, options: [])
} catch {
print(error)
}
}
答案 1 :(得分:0)
解决上述问题有帮助的问题,我在此声明,因为它可能对某人有所帮助。问题在于dataPath变量是URL
。要以字符串形式获取路径,需要使用path
属性,而不是absoluteString
。