Linked Questions

Popular Questions

How to Save & Load images from file directory - Swift 4

Asked by At

I am trying to save and load images to and from the file directory, however my writeImageToPath function prints the following error to the console and says the file does not exist.


Write image to directory

File exists Write image

Error Write image to directory File does NOT exist -- file:///Users/user/Library/Developer/CoreSimulator/Devices/70EAC77D-9F3C-4AFC-8CCA-A7B9B895BDE6/data/Containers/Data/Application/DDAF2EBD-5DDA-4EA6-95D3-6785B74A0B09/Documents/upload/ -- is available for use Write image Error Writing Image: Error Domain=NSCocoaErrorDomain Code=4 "The file “5202887448860” doesn’t exist." UserInfo={NSFilePath=/Users/user/Library/Developer/CoreSimulator/Devices/70EAC77D-9F3C-4AFC-8CCA-A7B9B895BDE6/data/Containers/Data/Application/DDAF2EBD-5DDA-4EA6-95D3-6785B74A0B09/Documents/upload/, NSUnderlyingError=0x600003b04ab0 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}

Here's my code, I am not sure where I am going wrong

// The images are loaded from the web and displayed in the cell.imageView.image

  if let thumbnail = product["thumbnail"] as? [String: Any],
     let path = thumbnail["path"] as? String,
     let fileExtension = thumbnail["extension"] as? String {

  //Save image to directory
  if image != nil {
     writeImageToPath(path, image: image!)


// Write image to directory
func writeImageToPath(_ path: String, image: UIImage) {
    print("Write image to directory")

    let uploadURL = URL.createFolder(folderName: "upload")!.appendingPathComponent(path)

    if !FileManager.default.fileExists(atPath: uploadURL.path) {
        print("File does NOT exist -- \(uploadURL) -- is available for use")

        let uploadURL = URL.createFolder(folderName: "upload")!.appendingPathComponent(path)

        if let data = UIImageJPEGRepresentation(image, 0.9) {
            do {
                print("Write image")
                try data.write(to: uploadURL)
            catch {
                print("Error Writing Image: \(error)")

        } else {
            print("Image is nil")
    } else {
        print("This file exists -- something is already placed at this location")


// load image from directory
func loadImageFromPath(_ path: String) -> UIImage? {

    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]

    let folderURL = documentsURL.appendingPathComponent("upload")

    let fileURL = folderURL.appendingPathComponent(path)

    if FileManager.default.fileExists(atPath: fileURL.path) {
        //Get Image And upload in server
        print("fileURL.path \(fileURL.path)")

            let data = try Data.init(contentsOf: fileURL)
            let image = UIImage(data: data)
            return image
            print("error getting image")
    } else {
        print("No image in directory")

    return nil

extension URL {
static func createFolder(folderName: String) -> URL? {
    let fileManager = FileManager.default
    // Get document directory for device, this should succeed
    if let documentDirectory = fileManager.urls(for: .documentDirectory,
                                                in: .userDomainMask).first {
        // Construct a URL with desired folder name
        let folderURL = documentDirectory.appendingPathComponent(folderName)
        // If folder URL does not exist, create it
        if !fileManager.fileExists(atPath: folderURL.path) {
            do {
                // Attempt to create folder
                try fileManager.createDirectory(atPath: folderURL.path,
                                                withIntermediateDirectories: true,
                                                attributes: nil)
            } catch {
                // Creation failed. Print error & return nil
                return nil
        // Folder either exists, or was created. Return URL
        return folderURL
    // Will only be called if document directory not found
    return nil

How can I correctly save and load images from the directory ?

Related Questions