我有一个应用程序在其各种视图控制器中使用用户的位置,并且我已经了解到,为了获得该位置,您需要创建CLLocationManger实例并符合CLLocationManagerDelegate协议。
是否可以创建一个CLLocationManager实例并使用它的属性,例如我的不同视图控制器中的坐标,或者我应该在每个视图控制器类中创建一个CLLocationManager?
答案 0 :(得分:1)
快速且有点强大的黑客可能是:
@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)
}