Nil when obtain coordinates in swift

2019-09-02 06:08发布

问题:

I am trying to abstain coordinates from the device, but the app crash. Anyone know what might have happened? I suppose the error happened when it asked for permission but the request was denied, maybe creating an if statement it works, but I couldn't find any information about that.

output:fatal error: unexpectedly found nil while unwrapping an Optional value

import UIKit  
import Foundation  
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {
 let locationManager = CLLocationManager()

 override func viewDidLoad() {
    super.viewDidLoad()

    println("\(locationManager.location.coordinate.latitude), \(locationManager.location.coordinate.longitude)")
    self.locationManager.requestAlwaysAuthorization() // Ask for Authorisation from the User.

    // For use in foreground

    self.locationManager.requestWhenInUseAuthorization()

    if (CLLocationManager.locationServicesEnabled())
    {

        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        self.locationManager.startUpdatingLocation()
    }



}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    var locValue:CLLocationCoordinate2D = manager.location.coordinate
    var latitudeactual:Double = 0
    var longitudeactual:Double = 0

    latitudeactual = locValue.latitude
    longitudeactual = locValue.longitude

    locationManager.stopUpdatingLocation()
    if latitudeactual != 0 || longitudeactual != 0 {
        latitudeactual = locValue.latitude
        longitudeactual = locValue.longitude

        }

}
}

回答1:

The location property is an implicitly unwrapped CLLocation optional, and it is likely nil. You should never access members of implicitly unwrapped optional unless you know it is not nil. You can confirm it is nil with the following:

if locationManager.location != nil {
    println("\(locationManager.location.coordinate.latitude), \(locationManager.location.coordinate.longitude)")
} else {
    println("locationManager.location is nil")
}

Or you could just:

println("\(locationManager.location)")

But don't try to access the properties of an implicitly unwrapped object without first checking to see if it's nil or not.


As a general rule, you should not expect a valid CLLocation object for the location property unless location services were started and location updates have already started to come in (e.g. you've seen didUpdateLocations called). The process of determining location happens asynchronously and is not to be expected to be available in viewDidLoad. One should put location-specific logic inside the didUpdateLocations method.