I currently have a test application to teach myself Core Location. It is an app with a button which will either show your location when you press a button, or an alert when location services are off.
I get a fatal error (unexpectedly found nil when unwrapping option value) When location services are on and I attempt to println the string. I cannot find anywhere in the documentation where the CLLocationManager.location.coordinate returns an optional value. I will include the code snippet. Thanks!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
if CLLocationManager.authorizationStatus() == .NotDetermined {
locationManager.requestWhenInUseAuthorization()
}
}
@IBAction func testLocation(sender: AnyObject) {
switch CLLocationManager.authorizationStatus() {
case .AuthorizedAlways, .AuthorizedWhenInUse:
printCurrentCoordinates()
case .Restricted, .Denied:
disabledLocationSeriveAlert()
default:
println("Failed")
}
func printCurrentCoordinates() {
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
println("\(locationManager.location.coordinate.latitude)")
println("\(locationManager.location.coordinate.longitude)")
}
func disabledLocationSeriveAlert() {
let alert = UIAlertController(title: "Unable to retrieve location", message: "Enable location services in system settings", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
It looks like you aren't giving the
CLLocationManagerenough time to update the location.I looked at the documentation, and in the statement
locationManager.location.coordinate.latitude,locationis the only one that's an optional. It's implicitly unwrapped, so that's why you don't need an!after it.In the
printCurrentCoordinatesmethod, you attempt to print the coordinates immediately after you callstartUpdatingLocation. The documentation forlocationsays:And the documentation for
startUpdatingLocationsays:So, you aren't giving the location manager enough time to get a location fix before you attempt to print the location.
You have a couple of choices - you can call
startUpdatingLocationearlier and then print the coordinates inprintCurrentCoordinates, or you could haveprintCurrentCoordinatesstart updating the location and then print the coordinates inlocationManager:didUpdateLocations:.