CLLocationManager.authorizationStatus导致EXC_BAD_ACCESS代码= 2

时间:2016-08-12 07:50:05

标签: ios swift core-location location-services

我的第一个应用程序到目前为止工作正常,如果允许位置服务。

我一旦禁用此应用程序的位置服务(飞行模式,以及一般禁用的位置服务正在按预期工作)。

The Error at runtime

代码如下:

    func locationServices()->Bool{
    if CLLocationManager.locationServicesEnabled() {
        switch(CLLocationManager.authorizationStatus()) {
        case .NotDetermined, .Restricted, .Denied:
            return false
        case .AuthorizedAlways, .AuthorizedWhenInUse:
            return true
        }
    } else {
        return false
    }

}

从viewDidLoad调用:

    override func viewDidLoad() {
    super.viewDidLoad()

    txtNotes.delegate = self
    datePicker.maximumDate = NSDate()
    if (inc != nil) {
        let Dateformatter = NSDateFormatter()
        Dateformatter.dateStyle = NSDateFormatterStyle.MediumStyle
        navigationItem.title = Dateformatter.stringFromDate((inc?.date)!)
        datePicker.date = (inc?.date)!
        txtNotes.text = inc?.notes
        ratingControl.rating = (inc?.rating)!
        lblAccuracy.text = inc?.geoloc
        self.location = inc?.geocor
    }
    else {
        if(locationServices()){
        self.locationManager = CLLocationManager()
        locationManager!.delegate = self
        locationManager!.requestWhenInUseAuthorization()
        locationManager!.desiredAccuracy = kCLLocationAccuracyBest
        locationManager!.startUpdatingLocation()

        }
        else{
            lblAccuracy.text = "Location Services Disabled"
            let alertController = UIAlertController(
                title: "Location Services Disabled",
                message: "Please allow this application to use location services",
                preferredStyle: .Alert)

            let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
            alertController.addAction(cancelAction)

            let openAction = UIAlertAction(title: "Open Settings", style: .Default) { (action) in
                if let url = NSURL(string:UIApplicationOpenSettingsURLString) {
                    UIApplication.sharedApplication().openURL(url)
                }
            }
            alertController.addAction(openAction)
            self.presentViewController(alertController, animated: true, completion: nil)
            viewDidLoad()
        }
    }
}

1 个答案:

答案 0 :(得分:0)

访问尚未初始化的委托并不是一个明智的想法......

在访问之前初始化解决了我的问题。