Location manager didUpdateLocations not being called

对着背影说爱祢 提交于 2019-12-02 05:46:00

Problem is here:

  override func viewDidAppear(_ animated: Bool) {
      locationManager = CLLocationManager()
      locationManager.requestWhenInUseAuthorization()
  }

This method will be called after viewDidLoad, but you new created a locationManager later in viewDidAppear and not pointed its delegate to self. That's why the delegate(self)'s methods is not be called.

The improved but not the best way is:

class OptionsViewController: UIViewController, UITableViewDelegate, CLLocationManagerDelegate {

    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        //Ask user for location
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest

        //Use users current location if no starting point set
        if CLLocationManager.locationServicesEnabled() {
            if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse
              || CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways {
                locationManager.startUpdatingLocation()
            }
            else{
                locationManager.requestWhenInUseAuthorization()
            }
        }
        else{
            //Alert user to open location service, bra bra bra here...
        }
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        //... nothing need to do for location here
    }

    public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if status == CLAuthorizationStatus.authorizedWhenInUse
          || status == CLAuthorizationStatus.authorizedAlways {
            locationManager.startUpdatingLocation()
        }
        else{
            //other procedures when location service is not permitted.
        }
    }

    //......
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!