我一定错过了完全显而易见的东西。仅检查了每个SO问题,却找不到解决该问题的方法。我正在使用FileManager保存图像,将URL路径上传到Firestore,然后尝试加载图像。只要应用程序不关闭,它就可以正常加载。应用重新启动时,没有文件。
我的文档目录也不显示文件(来自Xcode Devices)。
保存代码为:
func saveImage(title: String, isFrontImage: Bool, imageData: Data, completion: @escaping (_ filepath: String?) -> Void) {
var imageLocation: String {
var location = ""
if isFrontImage {
location = "front"
} else {
location = "back"
}
return location
}
let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
let documentPath = documentsURL.path
let imageName = title + imageLocation
let fileURL = documentsURL.appendingPathComponent(imageName)
do {
let files = try fileManager.contentsOfDirectory(atPath: "\(documentPath)")
for file in files {
if "\(documentPath)/\(file)" == fileURL.path {
try fileManager.removeItem(atPath: fileURL.path)
}
}
} catch {
print("Could not remove image from document directory: " + error.localizedDescription)
}
do {
try imageData.write(to: fileURL)
print("File Saved Locally")
completion(fileURL.path)
} catch {
print("Couldn't write image: " + error.localizedDescription)
completion(nil)
}
}
检索代码为:
func retrieveImage(filePath: String, completion: @escaping (_ success: Bool, _ image: UIImage?) -> Void) {
if FileManager.default.fileExists(atPath: filePath) {
print("File Exists")
guard let contentsOfFilePath = UIImage(contentsOfFile: filePath) else {
completion(false, nil)
return
}
completion(true, contentsOfFilePath)
}
}
在关闭应用程序之前我很难理解为什么它存在,但是在关闭之后却很难。非常感谢您的帮助。