Search code examples
iosswiftnsfilemanager

How to retrieve a saved image using its name?


I'm currently saving an image using FileManager like this:

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)
}

How do I retrieve this very file using the name of the file along the similar line as following?

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")
}


Solution

  • Use the same URL related API like in the save code

    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")
    }