SwiftUI Map: setting userTrackingMode causes console warning

Originator:indiekiduk
Number:rdar://FB9990674 Date Originated:2022-04-22
Status:Open Resolved:No
Product:SwiftUI Product Version:
Classification:Bug Reproducible:Always
 
Hi I noticed in the SwiftUI map when it is used with coordinateRegion binding and userTracking binding, e.g.

 Map(coordinateRegion: $region, interactionModes: .all, showsUserLocation: true, userTrackingMode: $tracking)

When a button is used to set the userTrackingMode, SwiftUI attempts to update the MKMapView calling [MKMapView _setUserTrackingMode:...] which results in mapLayerDidChangeVisibleRegion which unfortunately results in it setting the coordinateRegion binding. Of course we aren't supposed to update state when SwiftUI is trying to update the view, and it results in the the warning output to console:

[SwiftUI] Modifying state during view update, this will cause undefined behavior.

Hope this can be fixed!

I discovered this when I answered this Stackoverflow question

https://stackoverflow.com/questions/71953853/swiftui-map-causes-modifying-state-during-view-update/71954884#71954884

Xcode Version 13.3.1 (13E500a)
iPhone 13 simulator

Here is a View you can use

struct MapTestView: View {
    @State var region: MKCoordinateRegion = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 47.3769, longitude: 8.5417), latitudinalMeters: 2000, longitudinalMeters: 2000)
    @State var tracking = MapUserTrackingMode.follow
    
    var body: some View {
        let _ = Self._printChanges()
        VStack {
            Map(coordinateRegion: $region, interactionModes: .all, showsUserLocation: true, userTrackingMode: $tracking)
                .ignoresSafeArea()
                .task {
                    let locationManager = CLLocationManager()
                    locationManager.requestWhenInUseAuthorization();
                }
            Button {
                tracking = .follow
            } label: {
                Image(systemName: tracking == .follow ? "location.fill" : "location")
                    .padding()
            }
            .background(.white)
        }
    }
}

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!