如何使用名称检索已保存的图像?

How to retrieve a saved image using its name?

我目前正在使用 FileManager 保存图像,如下所示:

guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let fileName = imageName
let fileURL = documentsDirectory.appendingPathComponent(fileName)
guard let data = image.jpegData(compressionQuality: 0.8) else { return }

do {
    try data.write(to: fileURL)
} catch let error {
    print("error saving file with error", error)
}

如何使用类似以下行的文件名检索这个文件?

let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = NSURL(fileURLWithPath: path)
if let pathComponent = url.appendingPathComponent("fileName") {
    let filePath = pathComponent.path
    let fileManager = FileManager.default
    // ??
} else {
    print("file not available")
}

使用与 save 代码中相同的 URL 相关 API

let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileName = "fileName.jpg"
let fileURL = documentsDirectory.appendingPathComponent(fileName)

if let image = UIImage(contentsOfFile: fileURL.path) {
    // do something with the image
} else {
    print("error loading file")
}

如果你想要 UIImage 你可以使用 init(contentsOfFile:) init(data:) or init(data:scale:)