从 AppDelegate 和 ViewController 访问 locaitonManager

Accessing locaitonManager from both AppDelegate and ViewController

在我的应用委托 class 中,我声明了 locaitonManager:

var locationManager: CLLocationManager?

稍后在我的应用程序中的一个视图控制器 classes 中,我需要停止位置更新:

locationManager?.stopUpdatingLocation()

但我得到错误:

Value of type CLLocation Manager.... has no member ....

因为视图控制器无法访问在应用程序委托中声明的位置管理器 class。我的简单出路是什么?我必须在应用程序委托中拥有 locationManager 访问权限。

注:奇怪的是,我的 func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) 也在视图控制器中,它似乎工作正常。

回答我自己的问题以备将来参考:

在ViewController的class中:

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

然后在代码的后面,我可以像这样引用 App Delegate 中声明的 locationManager:

appDelegate.locationManager!.requestAlwaysAuthorization()

希望这对其他人有帮助。