Post

Replies

Boosts

Views

Activity

Image stored in documents directory disappears on app relaunch/rebuild
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      */      private 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
0
2.1k
Sep ’22