i have been trying to make so that when you press an annotation on the map that has been created by Core Data's object to show the LocationPreviewView(fish: fish)
. So how can i get the selected item and pass it to the LocationPreviewView()
?
I have already tried to do it by UIViewRepresentable
way and already posted about it, but without success.
import SwiftUI
import MapKit
import CoreData
import CoreLocationUI
import StoreKit
struct MapMainView: View {
//???
@State private var selectedFish: Fish?
@Environment(\.managedObjectContext) private var moc
@ObservedObject var locationManager = LocationManager.shared
@State private var region = MKCoordinateRegion(center: LocationManager.currentLocation, span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1))
var body: some View {
ZStack {
Map(coordinateRegion: $region,
interactionModes: .all,
showsUserLocation: true,
annotationItems: annotations) {
MapMarker(coordinate: $0.coordinate)
}
.ignoresSafeArea()
VStack(spacing: 0) {
ZStack {
ForEach(fetchFish()) { fish in
// Here pass the selected fish?????????
LocationPreviewView(fish: fish)
.shadow(color: Color.black.opacity(0.3), radius: 20)
.padding()
.transition(.asymmetric(insertion: .move(edge: .trailing), removal: .move(edge: .leading)))
}
}
}
}
}
var annotations: [FishAnnotation] {
let fish = fetchFish()
return fish.map { FishAnnotation(name: $0.title ?? "No data found", coordinate: CLLocationCoordinate2D(latitude: $0.lat, longitude: $0.long)) }
}
func fetchFish() -> [Fish] {
let request: NSFetchRequest<Fish> = Fish.fetchRequest()
do {
return try moc.fetch(request)
} catch {
print("Error fetching fish entities: \(error)")
return []
}
}
}
struct MapMainView_Previews: PreviewProvider {
@State static var mapView: MKMapView = MKMapView()
static var previews: some View {
MapMainView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
}
}