Location manager didUpdateLocations not being called

后端 未结 1 1120
猫巷女王i
猫巷女王i 2021-01-24 16:22

For some reason didUpdateLocations is not being called, even when I set the delegate to the view controller. In info.plist I set the key Privacy

相关标签:
1条回答
  • 2021-01-24 16:57

    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.
            }
        }
    
        //......
    }
    
    0 讨论(0)
提交回复
热议问题