为位置权限调用requestWhenInUseAuthorization时出错

时间:2018-08-27 14:19:41

标签: swift xcode location swift4 cllocationmanager

我正在尝试使用位置管理器在应用程序中检索用户的位置;如Apple文档中所述,我创建了以下方法:

func startReceivingLocationChanges() {
    let authorizationStatus = CLLocationManager.authorizationStatus()
    if authorizationStatus != .authorizedWhenInUse && authorizationStatus != .authorizedAlways {
        locationManager.requestWhenInUseAuthorization()
        startReceivingLocationChanges()
        return
    }

    if !CLLocationManager.locationServicesEnabled() {
        displayError(withTitle: "Location Not Available", withDescription: "Enable Location Services at Settings > Privacy > Location Services", sender: self)
        return
    }

    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.distanceFilter = 100.0  // In meters.
    locationManager.pausesLocationUpdatesAutomatically = true
    locationManager.activityType = .other
    locationManager.delegate = self
    locationManager.startUpdatingLocation()
}

但是当我启动该应用程序时,此崩溃显示在行附近的错误“线程1:EXC_BAD_ACCESS(code = 2,address = 0x16f0a7f60)”

locationManager.requestWhenInUseAuthorization()

我指定我在info.plist中添加了相对的“隐私-始终且使用时位置使用情况说明”和“隐私-何时使用时位置使用情况说明”键。

有人知道是什么原因引起的吗?谢谢。

2 个答案:

答案 0 :(得分:0)

发现了问题,这与对函数的递归调用有关

startReceivingLocationChanges

在函数本身内部。我解决了这个问题,要求在ViewDidLoad方法内请求位置权限并删除递归调用。

答案 1 :(得分:0)

您的代码中有一些错误,例如递归,以防用户在使用时不给予许可,请查看我的代码。假设您已在info.plist中添加了“隐私-始终且在使用时位置用法说明”和“隐私-何时在使用时位置用法说明”键。下面的代码完美无瑕,建议苹果使用。

import Foundation
import CoreLocation

typealias LocateMeCallback = (_ location: CLLocation?) -> Void

class LocationTracker: NSObject {

    static let shared = LocationTracker()

    var locationManager: CLLocationManager = {
       let locationManager = CLLocationManager()
       locationManager.activityType = .automotiveNavigation
       locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
       locationManager.distanceFilter = 10

       return locationManager
    }()

    var locateMeCallback: LocateMeCallback?
    var currentLocation: CLLocation?
    var isCurrentLocationAvailable: Bool {
        return currentLocation != nil
    }

    func enableLocationServices() {
        locationManager.delegate = self
        switch CLLocationManager.authorizationStatus() {
        case .notDetermined:
            // Request when-in-use authorization initially
            locationManager.requestWhenInUseAuthorization()
        case .restricted, .denied:
            // Disable location features
            print("Fail permission to get current location of user")
        case .authorizedWhenInUse:
            // Enable basic location features
            enableMyWhenInUseFeatures()
       case .authorizedAlways:
            // Enable any of your app's location features
            enableMyAlwaysFeatures()
       }
    }

    func enableMyWhenInUseFeatures() {
       locationManager.startUpdatingLocation()
    }

    func enableMyAlwaysFeatures() {
       locationManager.allowsBackgroundLocationUpdates = true
       locationManager.pausesLocationUpdatesAutomatically = true
       locationManager.startUpdatingLocation()
    }

    func locateMe(callback: @escaping LocateMeCallback) {
        self.locateMeCallback = callback
        enableLocationServices()
    }

    private override init() {}

}


// MARK: - CLLocationManagerDelegate
extension LocationTracker: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.first else { return }
        print("locations = \(location.coordinate.latitude) \(location.coordinate.longitude)")
        locateMeCallback?(location)
    }
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error.localizedDescription)
    }
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        enableLocationServices()
    }
}

用法

LocationTracker.shared.locateMe {  location in
            guard let location = location else {
                print("Cann't retrieve current location of user")
                return
            }
           // do what ever you want to do with location            
        }