gpt4 book ai didi

ios - 当我将其放入viewDidLoad中时,为什么我的for循环没有完成?

转载 作者:行者123 更新时间:2023-12-01 17:46:18 25 4
gpt4 key购买 nike

为什么我将函数的主体放入应该执行7次的for循环中,为什​​么函数的主体仅执行一次?

我的代码行如下

 override func viewDidLoad() {
super.viewDidLoad()
getLocationFromGeoCoding()
}
func getLocationFromGeoCoding() {
for index in 0...6{
geoCoder.reverseGeocodeLocation(sevenWorldWonderOb[index].location ?? CLLocation()) {[weak self] (placemarks, err) in
if let err = err {
print("Error",err.localizedDescription)
return
}else {
guard let placemark = placemarks?.first else {return}
let streetNumber = placemark.subThoroughfare
let street = placemark.thoroughfare
let city = placemark.locality
let state = placemark.administrativeArea
let country = placemark.country
let Address = "\(streetNumber == nil ? "" : streetNumber!) \(street == nil ? "" : street!) \(city == nil ? "" : city!) \(state == nil ? "" : state!) \(country == nil ? "" : country!)"
self?.addressLocation.append(Address)
self?.wonderAddress.text = self?.addressLocation[index]
}
}

}
}

最佳答案

异步工作时可以使用DispatchGroupreverseGeocodeLocation异步工作。如果您想知道何时在阵列中拥有所有地址

func getLocationFromGeoCoding() {
let group = DispatchGroup()
for index in 0...6{
group.enter()
geoCoder.reverseGeocodeLocation(sevenWorldWonderOb[index].location ?? CLLocation()) {[weak self] (placemarks, err) in
defer {
group.leave()
}
if let err = err {
print("Error",err.localizedDescription)

} else {
guard let placemark = placemarks?.first else { return}
let streetNumber = placemark.subThoroughfare
let street = placemark.thoroughfare
let city = placemark.locality
let state = placemark.administrativeArea
let country = placemark.country
let Address = "\(streetNumber == nil ? "" : streetNumber!) \(street == nil ? "" : street!) \(city == nil ? "" : city!) \(state == nil ? "" : state!) \(country == nil ? "" : country!)"
self?.addressLocation.append(Address)
self?.wonderAddress.text = self?.addressLocation[index]
}


group.notify(queue: .main, execute: { // executed after all async calls in for loop finish
print(“Got all addresses”)
// do whatever you want to do on getting all addresse
})

}

经过操场测试

enter image description here

关于ios - 当我将其放入viewDidLoad中时,为什么我的for循环没有完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59966094/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com