我不会在控制台currentCity中打印,因为在另一个函数中使用城市名称!请帮助我。
var locationManager = CLLocationManager()
var currentCity: String?
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
print(currentCity) //----error not printing CITY NAME
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation: CLLocation = locations[0]
CLGeocoder().reverseGeocodeLocation(userLocation) { (placemarks, error) in
if error != nil {
print(error?.localizedDescription as Any)
} else {
if let placemark = placemarks?[0] {
if let city = placemark.addressDictionary?["City"] as? NSString {
self.cityLbl.text = city as String
self.currentCity = city as String
}
}
}
}
}
答案 0 :(得分:2)
位置管理器是一个异步功能。这意味着您的代码将启动该功能,但继续使用下一段代码,而不是等待获取该位置,最终将在稍后完成。
因此,即使您在打印功能之前调用更新位置,但在代码执行打印时,它还没有获得位置,而您当前的城市是零。
从位置管理器功能打印名称或添加完成闭包。这应该够了吧。
答案 1 :(得分:0)
首先调用func viewDidLoad(),但不提取该位置。在func locationManager(_ manager:CLLocationManager,didUpdateLocations locations:[CLLocation])被调用后尝试打印。
答案 2 :(得分:0)
您需要在didUpdateLocations
打印城市。
if let city = placemark.addressDictionary?["City"]
as? NSString {
self.cityLbl.text = city as String
self.currentCity = city as String
print(currentCity) // here you get string
// call that function here
self.myfunction(cityName: currentCity)
}
<强>功能强>
func myfunction(cityName : String) -> Void {
// your string with city name
}