Detect when mapItemForCurrentLocation fails to locate your device

230 views Asked by At

I can't figure out how to test for a lack of success when getting the map's current location.

let source = MKMapItem.mapItemForCurrentLocation()
// returns an object with:
//   isCurrentLocation = 1
//   name="Unknown location"

I could test source.name == "Unknown location" but that would be terrible and bad.

So... how do I detect failure/nil in this case?

1

There are 1 answers

1
SKYnine On

Something like this ?

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

    @IBOutlet weak var mapView: MKMapView!
    var locationManager = CLLocationManager()

in viewDidLoad:

locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()

...

Delegates

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {

        if (!locations.isEmpty)
        {

            let myLocation  = locations[0] as! CLLocation

            mapView.setRegion(MKCoordinateRegionMake(CLLocationCoordinate2DMake(myLocation.coordinate.latitude, myLocation.coordinate.longitude),
                MKCoordinateSpanMake(0.06, 0.06)), animated: true)
        }

    }