Error when displaying Map() Annotation but not Marker

This code produces error "Publishing changes from within view updates is not allowed, this will cause undefined behavior."

when displaying Annotation, but not when displaying Marker. I'd like to understand why and so far have not figured it out.

import SwiftUI
import MapKit

struct ContentView: View {
    @StateObject var annotationViewModel = AnnotationViewModel()
    @State private var position: MapCameraPosition = .automatic

    var body: some View {
        Map(position: $position) {

            ForEach(annotationViewModel.annotations, id: \.self) { result in
//                Marker(result.title!, systemImage: "t.circle.fill", coordinate: result.coordinate)
                
                Annotation(result.title!, coordinate: result.coordinate) {
                    Image(systemName: "t.circle.fill")
                }
            }
        }
        .mapStyle(.standard(elevation: .flat))
    }
}

class MyAnnotation: NSObject, Identifiable {
    let id: UUID
    let title: String?
    let coordinate: CLLocationCoordinate2D
    
    init(id: UUID, title: String?, coordinate: CLLocationCoordinate2D) {
        self.id = id
        self.title = title
        self.coordinate = coordinate
    }
}

extension CLLocationCoordinate2D {
    static let ch = CLLocationCoordinate2D(latitude: 43.653734011477184, longitude: -79.38415146943686)
}

class AnnotationViewModel: NSObject, ObservableObject {

    @Published var annotations = [
        MyAnnotation(id: UUID(), title: "CITY HALL", coordinate: .ch),
    ]
    
}

Replies

I'm having the same issue. It seems related to the same warning with the older API which is discussed here: https://developer.apple.com/forums/thread/718697

What is interesting is that if you use the old API on Xcode 15 beta 1 the warning goes away but if you use the new API it comes back :(

  • Error appears to be gone in 15.0 beta 2.

Add a Comment