TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SwiftUI MapKit - MapAnnotation - Publishing changes from within view updates is not allowed, this will cause undefined behavior

Forums > SwiftUI

@ASH  

Been experimenting with MapKit in a SwiftUI project. Using MapMarkers I don't get any error. If I switch over to using a MapAnnotation I get the run time errors as I move or zoom in the map view. Doing a quick Google search shows that other people are having the same issue and that it's potentially a known Apple bug. Any workarounds would be appreciated!

The problem is reproducible using Paul's [https://www.hackingwithswift.com/books/ios-swiftui/integrating-mapkit-with-swiftui]

import SwiftUI
import MapKit

struct Location: Identifiable {
    let id = UUID()
    let name: String
    let coordinate: CLLocationCoordinate2D
}

struct ContentView: View {
    @State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 51.5, longitude: -0.12), span: MKCoordinateSpan(latitudeDelta: 0.2, longitudeDelta: 0.2))

    let locations = [
        Location(name: "Buckingham Palace", coordinate: CLLocationCoordinate2D(latitude: 51.501, longitude: -0.141)),
        Location(name: "Tower of London", coordinate: CLLocationCoordinate2D(latitude: 51.508, longitude: -0.076))
    ]

    var body: some View {
        Map(coordinateRegion: $region, annotationItems: locations) { location in
            MapAnnotation(coordinate: location.coordinate) {
                Circle()
                    .stroke(.red, lineWidth: 3)
                    .frame(width: 44, height: 44)
            }
        }
        .navigationTitle("Map")
        .edgesIgnoringSafeArea(.all)
    }
}

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

Reply to this topic…

You need to create an account or log in to reply.

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.