I'm working on a functionality on my code - where it will add a flag to the map once an image is added to the app (via the second page, not shown) but it just doesn't perform how I want. (This is not all the code)

I'm working on a functionality on my code - where it will add a flag to the map once an image is added to the app (via the second page, not shown) but it just doesn't perform how I want. Basically the photo saving is working perfectly and shows via the terminal where and how something is saving and the flags or pins that are added to the map also do save however just to see the you have to go to the second page (press on it) and come back to page 1 (Map) to see them - I just want to be able to see them from the start of the app. I tried init() { loadSavedImages(for: "") loadSavedImageLocations() but this doesn't really help much - if anyone can help it would really be apperciated.


import SwiftUI
import MapKit
import CoreLocation
import UIKit

struct MapView: UIViewRepresentable {
    @Binding var region: MKCoordinateRegion
    @Binding var mapType: MKMapType
    var imageLocations: [CLLocationCoordinate2D]
    @Binding var weatherInfo: String
    @Binding var showWeatherInfo: Bool

    func makeUIView(context: Context) -> MKMapView {
        let mapView = MKMapView()
        mapView.setRegion(region, animated: true)
        mapView.mapType = mapType
        
        // Add annotations for image locations
        mapView.addAnnotations(imageLocations.map { location in
            let annotation = ImageAnnotation(coordinate: location)
            return annotation
        })

...

class ImageAnnotation: NSObject, MKAnnotation {
    let coordinate: CLLocationCoordinate2D
    
    init(coordinate: CLLocationCoordinate2D) {
        self.coordinate = coordinate
        super.init()
    }
}

struct ImageLocation: Codable {
    let latitude: Double
    let longitude: Double
    
    init(coordinate: CLLocationCoordinate2D) {
        self.latitude = coordinate.latitude
        self.longitude = coordinate.longitude
    }

...

private init() {}
    
    func saveImageLocation(_ location: CLLocationCoordinate2D) {
        var savedLocations = getSavedLocations()
        let imageLocation = ImageLocation(coordinate: location)
        savedLocations.append(imageLocation)
        
        do {
            let data = try JSONEncoder().encode(savedLocations)
            let fileURL = documentsDirectory.appendingPathComponent("ImageLocations.json")
            try data.write(to: fileURL)
        } catch {
            print("Error saving image locations: \(error.localizedDescription)")
        }
    }
    
    func getSavedLocations() -> [ImageLocation] {
        let fileURL = documentsDirectory.appendingPathComponent("ImageLocations.json")
        
        guard let data = try? Data(contentsOf: fileURL) else {
            return []
        }

...

 struct ImageInfo: Identifiable {
        let id = UUID()
        let address: String
        let imageUrl: URL
    }
    
    init() {
        loadSavedImages(for: "")
        loadSavedImageLocations() // Load saved image locations when the app launches
    }

...

 MapView(region: $mapAPI.region, mapType: $mapType, imageLocations: imageLocations,
                            weatherInfo: $weatherInfo, showWeatherInfo: $showWeatherInfo)
                        .ignoresSafeArea()


....

            // 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: {
                    Text("Memories")
                        .font(.title)
...

            .onAppear {
                loadSavedImages(for: text) 
                loadSavedImageLocations() 
                    
...

func saveImage(_ image: UIImage, for address: String) {
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        
        // Generate a unique filename based on address and timestamp
        let timestamp = Int(Date().timeIntervalSince1970)
        let filename = "\(address)_\(timestamp).jpg"
        let fileURL = documentsDirectory.appendingPathComponent(filename)
        
        if let imageData = image.jpegData(compressionQuality: 0.5) {
            do {
                try imageData.write(to: fileURL)
                print("Image saved at: \(fileURL)")
                
                // Add the file URL to the imageUrls array
                let imageInfo = ImageInfo(address: address, imageUrl: fileURL)
                imageUrls.append(imageInfo)
            } catch {
                print("Error saving image data: \(error.localizedDescription)")
            }
            
            // Append the location to the imageLocations array
            if let location = mapAPI.locations.last?.coordinate {
                imageLocations.append(location)
            }
        }
    }
    
    func loadSavedImages(for address: String) {
        images = [] // Clear the existing images
        
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        do {
            let fileURLs = try FileManager.default.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil, options: [])
            
            // Filter and get file URLs for the images associated with the specified address
            let imageFiles = fileURLs
                .filter { $0.pathExtension == "jpg" }
                .filter { $0.lastPathComponent.contains(address + "_") }
            
            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)")
        }
    }
    
    func loadSavedImageLocations() {
        let savedLocations = ImageDataManager.shared.getSavedLocations()
        imageLocations = savedLocations.map { $0.locationCoordinate }
    }
    
    func deleteImage(at index: Int) {
        let imageInfo = imageUrls[index]
        let fileManager = FileManager.default
        do {
            try fileManager.removeItem(at: imageInfo.imageUrl)
            images.remove(at: index)
            imageUrls.remove(at: index)
        } catch {
            print("Error deleting image: \(error.localizedDescription)")
        }
    }
    
    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ContentView()
        }
    }
}

Post not yet marked as solved Up vote post of Jharmi Down vote post of Jharmi
416 views