Michael Rowe
Michael Rowe

Reputation: 956

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

I've been playing around with MapKit to display a map at the top of View in SwiftUI, when an address is contained; however, I keep getting [SwiftUI] Modifying state during view update, this will cause undefined behavior. when the user rotates the view. Here's how I have my Map being rendered

HStack {
   if let region = region {
    MapView(region: region)
       .frame(width: geo.size.width * 0.3, height: geo.size.height * 0.2)
       .mask(RoundedRectangle(cornerRadius: 25))
       .padding([.top, .leading], 15 )
    AddressView(recipient: recipient)
  }
  Spacer()
  .onAppear {
      let addressString = String("\(recipient.addressLine1 ?? "One Apple Park Way") \(recipient.city ?? "Cupertino") \(recipient.state ?? "CA") \(recipient.zip ?? "95014") \(recipient.country ?? "")")
      getLocation(from: addressString) { coordinates in
         if let coordinates = coordinates {
           self.region = MKCoordinateRegion(
             center: coordinates,
             span: MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005))
           }
     }
  }
}

The recipient is in CoreData and is passed into the view. Region is defined as follows: @State var region: MKCoordinateRegion?

Any suggestions on how to remove the error message?

here's the getLocation function

func getLocation(from address: String, completion: @escaping (_ location: CLLocationCoordinate2D?) -> Void) {
        let geocoder = CLGeocoder()
        geocoder.geocodeAddressString(address) { (placemarks, _) in
            guard let placemarks = placemarks,
                  let location = placemarks.first?.location?.coordinate else {
                completion(nil)
                return
            }
            completion(location)
        }
}

Upvotes: 1

Views: 278

Answers (1)

EmilioPelaez
EmilioPelaez

Reputation: 19912

My experience with Map is that some of these logs are internal and unavoidable, but I fixed about half of them like this:

    @State var region: MKCoordinateRegion = .init(...)
    //  Fix for "Modifying state" logs
    var regionBinding: Binding<MKCoordinateRegion> {
        .init(
            get: { region },
            set: { newValue in DispatchQueue.main.async { region = newValue } }
        )
    }

And then pass regionBinding instead of $region

Upvotes: 1

Related Questions