AppDelegate Extension未被调用

时间:2017-05-24 01:50:46

标签: ios swift delegates core-location appdelegate

我正在尝试在启动时立即获取用户位置,为此,我实现了一个全局变量userLocation,它将在AppDelegate的didFinishLaunchingWithOptions函数中得到更新。我已经像这样实现了位置管理器:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    var locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.requestWhenInUseAuthorization()
    if CLLocationManager.locationServicesEnabled(){
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestLocation()
    }
    return true
}

和扩展名:

extension AppDelegate: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        usersLocation = locations.last!
    }
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error)
    }
}

userLocation永远不会更新,我在userLocation = locations.last!行放置了一个断点,它永远不会到达。

感谢您的任何建议

1 个答案:

答案 0 :(得分:1)

我认为你也应该保留locationManager变量。

var locationManager: CLLocationManager!

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.requestWhenInUseAuthorization()
    if CLLocationManager.locationServicesEnabled(){
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestLocation()
    }
    return true
}