UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Image stored in documents directory disappears on app relaunch/rebuild

Forums > Swift

Hello, I am relatively new to swift and completely new to FileManager, and I encountered some very strange behaviour of my app. I have a "Day" struct that can save an image provided to it by the user:

struct Day: Codable, Comparable, Equatable, Identifiable {
      /*
     some vars and inits
     */

     var dayImagePath: URL?

     var displayedDayImage: UIImage? {
        guard let dayImagePath = dayImagePath else { return nil }

        do {
            let data = try Data(contentsOf: dayImagePath)
            guard let image = UIImage(data: data) else { throw ImageProcessingError.noDayImage }
            return image
        } catch {
            print(error.localizedDescription)
            return UIImage(systemName: "questionmark.folder")
        }
    }

    mutating func addDayImage(_ image: UIImage) {

        if dayImagePath == nil {
            dayImagePath = FileManager.documentsDirectory.appendingPathComponent(id.toStringId().appending("DayImage.jpeg"))
        }

        if let data = image.jpegData(compressionQuality: 0.8) {
            do {
                try data.write(to: dayImagePath!, options: [.atomic, .completeFileProtection])
            } catch {
                print(error.localizedDescription)
            }
        }
    }

    /*
     some more code here
     */
}

The documents directory is found using this FileManager extension:

extension FileManager {

    static var documentsDirectory: URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return paths[0]
    }
}

Adding the image works well, the image is displayed and stored correctly. However, it gets lost on the next app relaunch/rebuild with the following error message: The file “20220917DayImage.jpeg” couldn’t be opened because there is no such file. What am I doing wrong? I would be very grateful for any suggestions. Thank you!

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.