2

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?

SimplGy
  • 20,079
  • 15
  • 107
  • 144

1 Answers1

0

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)
        }

    }
SKYnine
  • 2,708
  • 7
  • 31
  • 41
  • I use CLLocationManaager's `didUpdateLocations` in other places.. I even store the most recent location in an external property (like `myLocation` here). I don't love it. It comes out of sync with reality. Say there's an error next time. Then your state says you have a location but you don't really. Then you catch the error and write your state var to nil. Works, but are you missing a different case? External state sucks for this. – SimplGy Aug 14 '15 at 14:25