启动应用后,我正在尝试让该应用找到用户的位置。但是,当我尝试requestWhenInUseAuthorization时,我在viewDidLoad方法中不断发现错误,并且收到以下错误:

    fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)


如果有人可以帮助我找到解决该问题的方法,我将非常感谢。谢谢!

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

@IBOutlet weak var mapView: MKMapView!

var lastLocation = CLLocation()
var locationAuthorizationStatus:CLAuthorizationStatus!
var window: UIWindow?

let locationManager: CLLocationManager!

var seenError : Bool = false
var locationFixAchieved : Bool = false
var locationStatus : NSString = "Not Started"

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)


    self.initLocationManager()

}


override func viewDidLoad() {
    super.viewDidLoad()




    if (CLLocationManager.locationServicesEnabled()) {
        seenError = false
        locationFixAchieved = false

        locationManager = CLLocationManager()

        self.initLocationManager()

        locationManager.requestWhenInUseAuthorization()

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

    }



    mapView.showsUserLocation = true
    mapView.delegate = self
    self.mapView.setUserTrackingMode(MKUserTrackingMode.Follow, animated: true);

}

// Location Manager helper stuff
func initLocationManager() {


    locationManager.requestWhenInUseAuthorization()
}

// Location Manager Delegate stuff

func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
    locationManager.stopUpdatingLocation()
    if ((error) != nil) {
        if (seenError == false) {
            seenError = true
            print(error)
        }
    }
}



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


}

最佳答案

您的didload方法在didAppear方法之前被调用。因此,您的位置管理器尚未初始化。因此,您需要在使用它之前对其进行初始化。

关于ios - 尝试在启动应用时使用Swift在Xcode中找到用户位置,但出现可选错误?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28769848/

10-14 21:45
查看更多