你可以使用
Notification
就像保罗所说的。你需要更新
didUpdateLocations
. 这是您要发布通知的地方。
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let userLocation = locations.first else {return}
if userLocation.horizontalAccuracy > 0 {
manager.stopUpdatingLocation()
let coordinate = Coordinate(location: userLocation)
let locationDictionary: [String: Double] = ["lat": location.coordinate.latitude,
"long": location.coordinate.longitude]
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "YourNotificationNameAsYouWantToNameIt"), object: nil, userInfo: locationDictionary)
}
}
现在在
viewDidLoad
在您想要此位置的每个视图控制器中,您需要观察此通知:
NotificationCenter.default.addObserver(self, selector: #selector(doSomethingAboutLocation(_:)), name: NSNotification.Name(rawValue: "YourNotificationNameAsYouWantToNameIt"), object: nil)
然后在从选择器调用的函数中这样访问您的位置:
@objc func doSomethingAboutLocation(_ notification: Notification) {
if let notificationInfo = notification.userInfo {
let coordinate = CLLocation(latitude: notificationInfo["lat"] as! Double, longitude: notificationInfo["long"] as! Double)
}
}