如果我的应用程序在其各种视图控制器中使用位置管理器,我应该在哪里实例化它?
Where should I instantiate a location manager if my app uses it throughout its various view controllers?
我有一个应用程序在其各种视图控制器中使用用户的位置,我了解到,为了获得该位置,您需要创建一个 CLLocationManger 实例并遵守 CLLocationManagerDelegate 协议。
是否可以创建一个 CLLocationManager 实例并在我的不同视图控制器中使用它的属性(如坐标),或者我应该在每个视图控制器中创建一个 CLLocationManager class?
一个快速且有点强大的 hack 可能是:
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.startUpdatingLocation()
return true
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
lastLocation = locations.last!
}
在同一个源文件中,在全局范围内添加:
private var lastLocation: CLLocation? {
didSet {
locationCallback?(lastLocation!)
locationCallback = nil
}
}
private var locationCallback: ((CLLocation) -> Void)?
func getLastLocation(callback: (CLLocationManager) -> Void) {
guard let location = lastLocation else {
locationCallback = callback
return
}
locationCallback(location)
}
最后,在您的应用程序的其他地方,您可以通过以下方式获取您的最后 已知位置:
getLastLocation { location in
print(location)
}
我有一个应用程序在其各种视图控制器中使用用户的位置,我了解到,为了获得该位置,您需要创建一个 CLLocationManger 实例并遵守 CLLocationManagerDelegate 协议。
是否可以创建一个 CLLocationManager 实例并在我的不同视图控制器中使用它的属性(如坐标),或者我应该在每个视图控制器中创建一个 CLLocationManager class?
一个快速且有点强大的 hack 可能是:
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.startUpdatingLocation()
return true
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
lastLocation = locations.last!
}
在同一个源文件中,在全局范围内添加:
private var lastLocation: CLLocation? {
didSet {
locationCallback?(lastLocation!)
locationCallback = nil
}
}
private var locationCallback: ((CLLocation) -> Void)?
func getLastLocation(callback: (CLLocationManager) -> Void) {
guard let location = lastLocation else {
locationCallback = callback
return
}
locationCallback(location)
}
最后,在您的应用程序的其他地方,您可以通过以下方式获取您的最后 已知位置:
getLastLocation { location in
print(location)
}