ios FileManager在重建应用程序时丢失存储的数据
我正在尝试将图像存储在应用程序的文档文件夹中,以便用户可以在以后任何时候检索它们。这是我存储它们的代码:ios FileManager在重建应用程序时丢失存储的数据,ios,swift,nsfilemanager,Ios,Swift,Nsfilemanager,我正在尝试将图像存储在应用程序的文档文件夹中,以便用户可以在以后任何时候检索它们。这是我存储它们的代码: func store(_ image: UIImage) -> String { let imageName = "\(Date().timeIntervalSince1970)" let imagePath = "\(documentasPath)/\(imageName).png" let imageData = UIImagePNGRepresentat
func store(_ image: UIImage) -> String {
let imageName = "\(Date().timeIntervalSince1970)"
let imagePath = "\(documentasPath)/\(imageName).png"
let imageData = UIImagePNGRepresentation(image)
fileManager.createFile(atPath: imagePath, contents: imageData, attributes: nil)
return imagePath
}
这是我从存储器中检索图像的代码:
func retrieveImage(from path: String) -> UIImage? {
guard fileManager.fileExists(atPath: path) else {
return nil
}
return UIImage(contentsOfFile: path)
}
除了从xcode重建应用程序外,它似乎工作正常。然后,我存储的所有图像都消失了(尽管我存储的指向它们的所有路径仍然存在并且正确)
这是默认文件管理器的一些行为吗?有没有办法避免这种情况发生?我只希望手动或卸载应用程序时删除图像
谢谢更改此
func store(_ image: UIImage) -> String {
let imageName = "\(Date().timeIntervalSince1970)"
let documentsUrl = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
var imagePath = documentsUrl.appendingPathComponent("\(imageName).png")
let imageData = UIImagePNGRepresentation(image)
fileManager.createFile(atPath: imagePath, contents: imageData, attributes: nil)
return imagePath
}
func retrieveImage(from path: String) -> UIImage? {
guard fileManager.fileExists(atPath: path) else {
return nil
}
return UIImage(contentsOfFile: path)
}
换成这个
func store(_ image: UIImage) -> String {
let imageName = "\(Date().timeIntervalSince1970)"
let documentsUrl = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
var imagePath = documentsUrl.appendingPathComponent("\(imageName).png")
let imageData = UIImagePNGRepresentation(image)
fileManager.createFile(atPath: imagePath, contents: imageData, attributes: nil)
return imagePath
}
func retrieveImage(from path: String) -> UIImage? {
guard fileManager.fileExists(atPath: path) else {
return nil
}
return UIImage(contentsOfFile: path)
}
问题是您正在存储一个绝对路径。你不能这样做,因为你的应用程序是沙盒的,这意味着(部分)文档文件夹的URL可以更改。只存储文档名,每次要保存或写入文档时,请再次计算文档文件夹的路径,并附加文档名并将结果用作路径。问题在于您存储的是绝对路径。你不能这样做,因为你的应用程序是沙盒的,这意味着(部分)文档文件夹的URL可以更改。只存储文档名,每次要保存或写入文档时,请再次计算文档文件夹的路径,并附加文档名,并将结果用作路径