how to load image from local path ios swift (by path) how to load image from local path ios swift (by path) swift swift

how to load image from local path ios swift (by path)


Folder /B2A1EE50- ... changes every time you run application.

../Application/B2A1EE50-D800-4BB0-B475-6C7F210C913C/Documents/..

Which works for me is to store fileName and get documents folder.

Swift 5

Create getter for directory folder

var documentsUrl: URL {    return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!}

Save image :

private func save(image: UIImage) -> String? {    let fileName = "FileName"    let fileURL = documentsUrl.appendingPathComponent(fileName)    if let imageData = image.jpegData(compressionQuality: 1.0) {       try? imageData.write(to: fileURL, options: .atomic)       return fileName // ----> Save fileName    }    print("Error saving image")    return nil}

Load image :

private func load(fileName: String) -> UIImage? {    let fileURL = documentsUrl.appendingPathComponent(fileName)    do {        let imageData = try Data(contentsOf: fileURL)        return UIImage(data: imageData)    } catch {        print("Error loading image : \(error)")    }    return nil}


Also you can try this.

  1. Check if your path exist

if NSFileManager.defaultManager().fileExistsAtPath(imageUrlPath) {}

  1. Create an URL to your path

let url = NSURL(string: imageUrlPath)

  1. Create data to you URL

let data = NSData(contentsOfURL: url!)

  1. Bind the url to your imageView

imageView.image = UIImage(data: data!)

Final code:

if NSFileManager.defaultManager().fileExistsAtPath(imageUrlPath) {    let url = NSURL(string: imageUrlPath)    let data = NSData(contentsOfURL: url!)    imageView.image = UIImage(data: data!)}


This code works for me

func getImageFromDir(_ imageName: String) -> UIImage? {    if let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {        let fileURL = documentsUrl.appendingPathComponent(imageName)        do {            let imageData = try Data(contentsOf: fileURL)            return UIImage(data: imageData)        } catch {            print("Not able to load image")        }    }    return nil}