我创建了一个包含2个单元格的tableview,每个单元格都显示了你的参议员(基于你的位置)。我使用CLGeocoder成功获取用户的zipcode,然后我将该值(字符串类型)放入在函数外部声明的变量中。
理想情况下,我想转到类中的不同函数,并使用该字符串变量(应该包含用户的邮政编码)来创建特定数据。但是,它不起作用!
以下是提取邮政编码并将其放入var zipCode的代码:(请注意,if条件下的print函数在运行程序时会在终端中成功打印邮政编码)。
let locationManager = CLLocationManager()
var zipcode: String = ""
func getTableInfo() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
locationManager.requestWhenInUseAuthorization()
locationManager.startMonitoringSignificantLocationChanges()
CLGeocoder().reverseGeocodeLocation(locationManager.location!, completionHandler: {(placemarks, error) -> Void in
if error != nil {
print("Reverse geocoder failed with error" + error!.localizedDescription)
}
if placemarks!.count > 0 {
let pm = placemarks![0]
self.zipcode = pm.postalCode!
print(self.zipcode)
}
else {
print("Problem with the data received from geocoder")
}
})
}
我在viewDidLoad()
中调用此函数,然后在viewDidLoad()
函数中使用if语句,我尝试使用邮政编码来更改字符串数组。 names[]
被声明为viewDidLoad()
函数正上方的空字符串数组。
if zipcode == "94108" {
names[1] = "WORKS!"
print(names)
}
由于某种原因,它不会打印名称! (请注意,邮政编码确实是94108,因为当我要求打印'zipcode'时,94108是在控制台中打印的内容)
答案 0 :(得分:2)
为getTableInfo方法创建一个完成处理程序,如下所示:
typealias ZipcodeCompletionBlock = (String?) -> Void
func getTableInfo(completionBlock: @escaping ZipcodeCompletionBlock) {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
locationManager.requestWhenInUseAuthorization()
locationManager.startMonitoringSignificantLocationChanges()
CLGeocoder().reverseGeocodeLocation(locationManager.location!, completionHandler: {(placemarks, error) -> Void in
if error != nil {
print("Reverse geocoder failed with error" + error!.localizedDescription)
completionBlock(nil)
} else if placemarks!.count > 0 {
let pm = placemarks![0]
self.zipcode = pm.postalCode!
completionBlock(self.zipcode)
} else {
print("Problem with the data received from geocoder")
completionBlock(nil)
}
})
}
现在你可以在viewDidLoad中调用这个函数:
self.getTableInfo { zipcode in
if zipcode == "94108" {
self.names[1] = "WORKS!"
print(self.names)
}
}
答案 1 :(得分:0)
这可能是因为执行保存邮政编码的代码略有延迟,因此在运行打印代码时,邮政编码仍然是“”。完成处理程序到位,因为它们在函数完成后执行代码。打印后立即输入以下代码(self.zipcode)
if zipcode == "94108" {
names[1] = "WORKS!"
print(names)
}
希望有所帮助!