//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
}
在每次启动中,之前启动中存储的图像似乎都消失了。如果我尝试使用“readImage”函数,应用程序将崩溃,并且错误为“展开可选值时意外发现 nil”。
顺便说一句,两个“print(fM.fileExists(atPath:url))”的输出都是 false。
最佳答案
我已经解决了这个问题。
问题不在上面的代码中。这些代码运行良好。 我无法再找到我的图像的原因是应用程序的沙箱 URL 在每次更新时都会发生变化。由于我仍在尝试使用以前版本的 URL 来读取图像,因此发生了错误。
关于ios - swift 。 iOS。当我再次运行应用程序时,存储在沙箱中的图片消失了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42591780/