Ios 如何从函数中获取另一个函数的变量SWIFT 3
我不会在控制台currentCity中打印,因为在另一个函数中使用城市名称!请帮帮我。Ios 如何从函数中获取另一个函数的变量SWIFT 3,ios,xcode,swift3,Ios,Xcode,Swift3,我不会在控制台currentCity中打印,因为在另一个函数中使用城市名称!请帮帮我。 var locationManager = CLLocationManager() var currentCity: String? override func viewDidLoad() { super.viewDidLoad() locationManager.delegate = self locationManager.desiredAccuracy = kCLLoca
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
}
}
}
}
}
首先调用func viewDidLoad(),并且在未提取位置时调用。调用func locationManager(manager:CLLocationManager,didUpdateLocations locations:[CLLocation])后尝试打印。您需要在
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
}
位置管理器是一个异步函数。这意味着您的代码将启动函数,但继续执行下一段代码,而不是等待获取位置,最终将在稍后完成 因此,即使您在print函数之前调用了update location,但当代码执行print时,它还没有得到位置,并且您当前的城市为零
从location manager功能打印名称或添加完成闭包。这应该能奏效 在
else
范围末尾的didUpdateLocations
delegate方法中放置打印行。我需要在另一个函数中使用城市名称!您的变体已完成,但我不需要在didUpdateLocations中打印。我不会在jsonThink异步中使用这个城市名称,也不会从委托方法调用另一个函数。我需要在另一个函数中使用城市名称!您的变体已完成,但我不需要在didUpdateLocations中打印。我不会把这个城市的名字用在你得到这个字符串的城市名字下面的jsonthen调用函数中。非常感谢我的朋友!我正在尝试这个变体并说你在工作或不在。对不起,我的英语很差)我来自高加索)我正在尝试在didUpdateLocations之后创建新的func示例:func printVar(){print(currentCity)},并在ViewDidLoad中调用此func,但再次为nil!