Publishing changes from within view updates is not allowed, this will cause undefined behavior.

Im building the small Map View by accessing the Users Location From the App

Im getting this Error in Xcode 14 in Purple Color there is no error in this Code side it shows only while running in this simulator also according to the error My Location is not updating to it

Can any 1 say where am I going wrong

below is my code


//  MapUIView.swift

//  Login_Via_SwiftUI

//

//  Created by Makwin Santhosh K on 10/11/22.

//



import SwiftUI

import MapKit

import CoreLocationUI



struct MapUIView: View {

    @StateObject private var ViewModel = ContentViewModal()

    var body: some View {

        ZStack(alignment: .bottom) {

            Map(coordinateRegion: $ViewModel.region, showsUserLocation: true)

                .ignoresSafeArea()

            

            

            LocationButton(.currentLocation){

                ViewModel.requestUserLocationForOnce()

            }

            .foregroundColor(.white)

            .cornerRadius(8)

            .padding()

            

        }

    }

}



struct MapUIView_Previews: PreviewProvider {

    static var previews: some View {

        MapUIView()

            

    }

}



final class ContentViewModal: NSObject, ObservableObject, CLLocationManagerDelegate{

    

    @Published var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 40, longitude: 120), span: MKCoordinateSpan(latitudeDelta: 100, longitudeDelta: 100))

    

    let locationManager = CLLocationManager()

    

    override init() {

        super.init()

        locationManager.delegate = self

    }

    

    

    func requestUserLocationForOnce() {

        locationManager.requestLocation()

    }

    

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        guard let latestLocation = locations.first else{

            //show error

            return

        }

        DispatchQueue.main.async {

            self.region = MKCoordinateRegion(center: latestLocation.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05))

        }

    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {

        print(error.localizedDescription)

    }

}
Answered by darkpaw in 735695022

Try this:

struct MapUIView: View {
	@StateObject private var ViewModel = ContentViewModal()

	var body: some View {
		ZStack(alignment: .bottom) {
			AreaMap(region: $ViewModel.region)

			LocationButton(.currentLocation){
				ViewModel.requestUserLocationForOnce()
			}
			.foregroundColor(.white)
			.cornerRadius(8)
			.padding()
		}
	}
}


struct MapUIView_Previews: PreviewProvider {
	static var previews: some View {
		MapUIView()
	}
}


struct AreaMap: View {
	@Binding var region: MKCoordinateRegion

	var body: some View {
		let binding = Binding(
			get: { self.region },
			set: { newValue in
				DispatchQueue.main.async {
					self.region = newValue
				}
			}
		)
		return Map(coordinateRegion: binding, showsUserLocation: true)
			.ignoresSafeArea()
	}
}


final class ContentViewModal: NSObject, ObservableObject, CLLocationManagerDelegate{
	@Published var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 40, longitude: 120), span: MKCoordinateSpan(latitudeDelta: 100, longitudeDelta: 100))
	let locationManager = CLLocationManager()

	override init() {
		super.init()
		locationManager.delegate = self
	}

	func requestUserLocationForOnce() {
		locationManager.requestLocation()
	}

	func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
		guard let latestLocation = locations.first else {
			//show error
			return
		}
		self.region = MKCoordinateRegion(center: latestLocation.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05))
	}

	func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
		print(error.localizedDescription)
	}
}
Accepted Answer

Try this:

struct MapUIView: View {
	@StateObject private var ViewModel = ContentViewModal()

	var body: some View {
		ZStack(alignment: .bottom) {
			AreaMap(region: $ViewModel.region)

			LocationButton(.currentLocation){
				ViewModel.requestUserLocationForOnce()
			}
			.foregroundColor(.white)
			.cornerRadius(8)
			.padding()
		}
	}
}


struct MapUIView_Previews: PreviewProvider {
	static var previews: some View {
		MapUIView()
	}
}


struct AreaMap: View {
	@Binding var region: MKCoordinateRegion

	var body: some View {
		let binding = Binding(
			get: { self.region },
			set: { newValue in
				DispatchQueue.main.async {
					self.region = newValue
				}
			}
		)
		return Map(coordinateRegion: binding, showsUserLocation: true)
			.ignoresSafeArea()
	}
}


final class ContentViewModal: NSObject, ObservableObject, CLLocationManagerDelegate{
	@Published var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 40, longitude: 120), span: MKCoordinateSpan(latitudeDelta: 100, longitudeDelta: 100))
	let locationManager = CLLocationManager()

	override init() {
		super.init()
		locationManager.delegate = self
	}

	func requestUserLocationForOnce() {
		locationManager.requestLocation()
	}

	func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
		guard let latestLocation = locations.first else {
			//show error
			return
		}
		self.region = MKCoordinateRegion(center: latestLocation.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05))
	}

	func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
		print(error.localizedDescription)
	}
}

I will try it and update it today thanks for the code👍

also I have doubt I have created this code in separate SwiftUI File (MapView) let say if I call it in ContentView like MapView()

the location button is not functioning as it is programmed (in here it is programmed to show the current location but after calling the MapView in ContentView, the button is not working)

how should I make this button work after calling the MapView File in Content View

You're gonna have to provide some sort of code to explain your new issue.

Publishing changes from within view updates is not allowed, this will cause undefined behavior.
 
 
Q