选择 "While using an app" 时 CLLocationManager 不起作用

CLLocationManager doesn't work when choosing "While using an app"

当我启动我的应用程序时,CLLocationManager 不工作 我收到拒绝跟踪位置的警告或仅在使用应用程序时或始终收到。如果我点击 "only while using an app",我的位置没有定义。知道为什么它不起作用吗?

我的代码:

// Used to start getting the users location
let locationManager = CLLocationManager()

func fetchCityAndCountry(location: CLLocation, completion: @escaping (_ city: String?, _ isoCode:  String?, _ error: Error?) -> ()) {
    CLGeocoder().reverseGeocodeLocation(location) { placemarks, error in
        completion(placemarks?.first?.locality,
                   placemarks?.first?.isoCountryCode,
                   error)
    }
}

// Print out the location to the console
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.first {
        let location = CLLocation(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
        //let location = CLLocation(latitude: 48.856614, longitude: 2.3522219)

        fetchCityAndCountry(location: location) {
            city, isoCode, error in guard let city = city, let isoCode = isoCode, error == nil else { return }
            //OTHER CODE
            } else {
                //OTHER CODE
            }
        }
    }
}

// If we have been deined access give the user the option to change it
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    if(status == CLAuthorizationStatus.denied) {
            showLocationDisabledPopUp()
        } else {
            //OTHER CODE
        }
    }
}

// Show the popup to the user if we have been deined access
func showLocationDisabledPopUp() {
    let alertController = UIAlertController(title: "\(self.localizedString(forKey: "locationAlertTitle"))",
                                            message: "\(self.localizedString(forKey: "locationAlertmsg"))",
                                            preferredStyle: .alert)
    let cancelAction = UIAlertAction(title: "\(self.localizedString(forKey: "continue"))", style: .default, handler: nil)
    alertController.addAction(cancelAction)
    let openAction = UIAlertAction(title: "\(self.localizedString(forKey: "locationAlertOk"))", style: .cancel) { (action) in
        if let url = URL(string: UIApplicationOpenSettingsURLString) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }
    }
    alertController.addAction(openAction)
    self.present(alertController, animated: true, completion: nil)
}

谢谢!

检查一下并确保您没有遗漏任何东西:

let locationManager = CLLocationManager()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.delegate = self
locationManager.startUpdatingLocation()

您也可以拨打 requestLocation 以便能够:

Request one-time delivery of the user’s current location.

locationManager.requestLocation()

您的错误发生是因为您没有要求应用程序获取位置并且您的 locations: [CLLocation] 是空的。您需要调用此函数:

func getLocation(){
    locationManager=CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()
}

另外,在您的 locationManager 中,您需要使用 locationManager.stopUpdatingLocation() 以便在不需要时停止持续更新位置。