【发布时间】:2023-04-10 11:04:02
【问题描述】:
我需要在多个视图控制器中获取zipCode 和city。
这是我目前的做法......
import CoreLocation
let locationManager = CLLocationManager()
class MyViewController: UIViewController, CLLocationManagerDelegate{
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)-> Void in
if error != nil {
//AlertView to show the ERROR message
}
if placemarks!.count > 0 {
let placemark = placemarks![0]
self.locationManager.stopUpdatingLocation()
let zipCode = placemark.postalCode ?? ""
let city:String = placemark.locality ?? ""
// Do something with zipCode
// Do something with city
}else{
print("No placemarks found.")
}
})
}
func someFunction() {
locationManager.startUpdatingLocation()
}
一切正常,但正如您所见,在多个 viewController 中这样做会导致大量代码重复(当然,我没有展示整个代码)。
从多个视图控制器中以更实用的方式从CLLocationManager() 中检索zipCode 和city 的最常见方法是什么?
我的想法是……
MyLocationManager.zipCode() // returns zipCode as a string
MyLocationManager.city() // returns city as a string
【问题讨论】:
-
如果你创建一个单例来跟踪用户位置呢?检查以下内容,它可能会有所帮助:stackoverflow.com/questions/11513259/…
标签: ios swift core-location cllocationmanager