//the Path of images
public let appMainDirectory = NSHomeDirectory()+"/Documents"
public let imgDirectory = appMainDirectory+"/images"
//the UIImage comes from a UIImageView
func saveImageToLocal(_ img:UIImage)->String{
//get image's data
let imgData:Data = UIImageJPEGRepresentation(img, 1.0)!
//use time as file name
let time:Date = Date()
let timeFormat = DateFormatter()
timeFormat.dateFormat = "yyyMMddHHmmssSSS"
let imgName = timeFormat.string(from: time) as String
let imgURL:String = imgDirectory+"/"+imgName+".jpg"
//store image into sandbox
writeDataToEndOfFile(fileURL: imgURL, contentToWrite:imgData, create: true)
return imgURL
}
func writeDataToEndOfFile(fileURL url1:String,contentToWrite fileData:Data,create createOrNot:Bool){
let fM:FileManager = FileManager.default
if( !fM.fileExists(atPath:url1) && createOrNot ){
fM.createFile(atPath: url1, contents: nil, attributes: nil)
}
let fUpdater:FileHandle = FileHandle(forUpdatingAtPath: url1)!
fUpdater.seekToEndOfFile()
fUpdater.write(fileData)
fUpdater.closeFile()
}
func readImage(imageUrl url:String) -> UIImage? {
let fM:FileManager = FileManager.default
if( !fM.fileExists(atPath:url)){
print(fM.fileExists(atPath:url))
fM.createFile(atPath: url, contents: nil, attributes: nil)
print(fM.fileExists(atPath:url))
}
let fUpdater:FileHandle = FileHandle(forUpdatingAtPath: url)!
let imageData:Data = fUpdater.availableData
fUpdater.closeFile()
let image = UIImage(data:imageData)
return image
}
在每次发布中,存储在先前发射中的图像似乎都消失了。如果我尝试使用"读取"函数,则该应用将崩溃,并且错误是"未包装可选值时无意外发现的"。
顺便说一句,两个'print(fm.fileexists(atpath:url))的输出都是错误的。
我已经解决了这个。
问题不在上面的代码中。这些代码运行良好。我找不到图像的原因是因为该应用程序的Sandbox的URL将在每个更新中都会发生变化。而且由于我仍在尝试使用以前版本的URL读取图像,因此发生错误。