FileManager Has Saved My Images - yet I cannot see / display them whenever I close and reopen the application.

So basically I can tell that the images are being saved by the system (it shows it on the debug terminal) however whenever I close, and then reopen the app the images firstly aren't there at all but also whenever I search the address name I saved them as... I have tried diagonsing the problem by changing UUID's, changing PNGs to JPGS - no matter what I do it does not show once the application has closed. I think it might have to do with how the image are .HEIF (apple's standard) but I don't have any concrete evidence to back this up. If anyone can help it would be greatly apperciated.

import SwiftUI
import MapKit
import CoreLocation

struct ContentView: View {
    @StateObject private var mapAPI = MapAPI()
    @State private var text = ""
    @State private var locationInfo: String = ""
    @State private var showLocationInfo = false
    @State private var imageUrls = [String]() // Array to store image URLs
    
    @State private var showImagePicker = false
    @State private var showCamera = false
    @State private var selectedImage: UIImage?
    @State private var images: [UIImage] = []
    @State private var selectedImageSourceType: UIImagePickerController.SourceType?
    
    struct ImageInfo: Identifiable {
        let id = UUID()
        let address: String
        let imageUrl: URL
    }

...




// Page 2: Photo
            
            VStack {
                Spacer()
                
                Menu {
                    Button(action: {
                        showImagePicker = true
                        selectedImageSourceType = .photoLibrary
                    }) {
                        Label("Choose from Library", systemImage: "photo")
                    }
                    
                    Button(action: {
                        showImagePicker = true
                        selectedImageSourceType = .camera
                    }) {
                        Label("Take Photo", systemImage: "camera")
                    }
                } label: {
                    Text("Memories")
                        .font(.title)
                        .foregroundColor(.black)
                }
                .padding()
                .sheet(isPresented: $showImagePicker, onDismiss: loadImage) {
                    ImagePicker(sourceType: selectedImageSourceType ?? .photoLibrary) { image in
                        selectedImage = image
                    }
                }
                
                if !images.isEmpty {
                    ScrollView {
                        LazyVGrid(columns: [GridItem(.adaptive(minimum: 200, maximum: 700))], spacing: 20) {
                            ForEach(images, id: \.self) { image in
                                Image(uiImage: image)
                                    .resizable()
                                    .aspectRatio(contentMode: .fill)
                                    .frame(height: UIScreen.main.bounds.height / 5)
                                    .frame(width: UIScreen.main.bounds.width - 60)
                                    .cornerRadius(15)
                            }
                        }
                        .padding()
                    }
                } else {
                    Text("No photos available")
                        .foregroundColor(.gray)
                }
            }
            .tabItem {
                Image(systemName: "camera")
                Text("Memories")
            }
            .tag(1)
        }
        .accentColor(.black)
    }
    
    @State private var encodedAddress = ""
    
    func fetchLocationInfoFromWikipedia(for address: String) {
        guard let encodedAddress = address.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
              let url = URL(string: "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&exintro=true&explaintext=true&titles=\(encodedAddress)") else {
            self.encodedAddress = encodedAddress
            return
        }
        
        URLSession.shared.dataTask(with: url) { data, _, error in
            if let data = data {
                if let responseJSON = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
                   let query = responseJSON["query"] as? [String: Any],
                   let pages = query["pages"] as? [String: Any],
                   let page = pages.keys.first,
                   let pageData = pages[page] as? [String: Any],
                   let extract = pageData["extract"] as? String {
                    DispatchQueue.main.async {
                        self.locationInfo = extract
                    }
                }
            }
        }
        .resume()
    }
    
    func openWebsite(_ urlString: String) {
        if let encodedAddress = self.text.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
           let url = URL(string: urlString + encodedAddress) {
            UIApplication.shared.open(url)
        }
    }
    
    func loadImage() {
         guard let selectedImage = selectedImage else { return }
         images.append(selectedImage)
         saveImage(selectedImage)
         self.selectedImage = nil
     }
     
     func saveImage(_ image: UIImage) {
         let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
         let filename = UUID().uuidString
         let fileURL = documentsDirectory.appendingPathComponent(filename)
         
         if let imageData = image.jpegData(compressionQuality: 1.0) {
             do {
                 try imageData.write(to: fileURL)
                 print("Image saved at: \(fileURL)")
             } catch {
                 print("Error saving image data: \(error.localizedDescription)")
             }
         }
     }
     
     func loadSavedImages() {
         let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
         do {
             let fileURLs = try FileManager.default.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil, options: [])
             let imageFiles = fileURLs.filter { $0.pathExtension == "png" || $0.pathExtension == "png" }
             
             for fileURL in imageFiles {
                 if let imageData = try? Data(contentsOf: fileURL),
                    let image = UIImage(data: imageData) {
                     images.append(image)
                 }
             }
         } catch {
             print("Error loading saved images: \(error.localizedDescription)")
         }
     }
 }

 struct ContentView_Previews: PreviewProvider {
     static var previews: some View {
         ContentView()
     }
 }

Accepted Reply

I'm a bit confused here; is this your actual/current code?

Because if so, you're filtering out your saved images by only looking at those with the file extension .png, whereas when you save them to disk, you are saving them with no extension at all, just a UUID as the filename.

Replies

I'm a bit confused here; is this your actual/current code?

Because if so, you're filtering out your saved images by only looking at those with the file extension .png, whereas when you save them to disk, you are saving them with no extension at all, just a UUID as the filename.

This is my current code.