John Welliem John Welliem -4 years ago 147
Swift Question

LocationManager dispatch queue Issue

What I have built:

I have built a simple

GMSMapView
with
CLLocationManagerDelegate
that just tracks users's current location and update on
GMSMapView
.

Issue:

When the
CLLocationManagerDelegate
(the
GMSMapView
screen) opens directly it works just fine, but when I try to reach to the
GMSMapView
screen using a
segue
it pushes an error.

A location manager (
0x145e5f9e0
) was created on a dispatch queue executing on a thread other than the main thread. It is the developer's responsibility to ensure that there is a run loop running on the thread on which the location manager object is allocated. In particular, creating location managers in arbitrary dispatch queues (not attached to the main queue) is not supported and will result in callbacks not being received.

Answer Source

Using Swift 3. So the Issue was with the Initialization of the variables GMSMapView and CLLocationManager. This Is how It worked for me:

I defined variables in the ViewController class as below

private var locationManager: CLLocationManager!
private var googleMapView: GMSMapView!

And in the viewDidLoad() I introduced a DispatchQueue to run it in main thread.

    DispatchQueue.main.async {
        //adding mapView
        self.googleMapView = GMSMapView()
        self.view.addSubview(self.googleMapView)
        self.googleMapView.translatesAutoresizingMaskIntoConstraints = false
        //auto layout constraints
        self.googleMapView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 0).isActive = true
        self.googleMapView.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: 0).isActive = true
        self.googleMapView.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 0).isActive = true
        self.googleMapView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: 0).isActive = true
        //location manager  setup
        self.locationManager = CLLocationManager()
        self.locationManager.delegate = self
        self.locationManager.startUpdatingHeading()
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download