Search code examples
iosswiftgoogle-mapscllocationmanagergoogle-maps-sdk-ios

CLLocationManager EXC_BAD_INSTRUCTION


I'm using GoogleMaps for my app and I properly setup everything from the Info.plist, locationManager...didChangeAuthorization using requestWhenInUseAuthorization how every I still get stuck with error

EXC_BAD_INSTRUCTION

even though I set it properly. Here is my code below.

locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
let camera = GMSCameraPosition.camera(withTarget: (self.locationManager.location?.coordinate)!, zoom: zoomLevel)
self.mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
self.view = self.mapView
self.initializeTheLocationManager()
self.mapView.isMyLocationEnabled = true

here is my locationManager delegate

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    if status == .authorizedAlways || status == .authorizedWhenInUse {
        mapView.delegate = self
        manager.startUpdatingLocation()
    } else {
        manager.requestWhenInUseAuthorization()
    }
}

Note: It seems that I requested twice for requestWhenInUseAuthorization.


Solution

  • This cannot work.

    startUpdatingLocation works asynchronously. You have to implement didUpdateLocations.

        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
    }
    
    ...
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let camera = GMSCameraPosition.camera(withTarget: (locations[0].coordinate, zoom: zoomLevel)
        self.locationManager.stopUpdatingLocation()
        self.mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
        self.view = self.mapView
        self.initializeTheLocationManager()
        self.mapView.isMyLocationEnabled = true
    }