簡體   English   中英

在循環中使用 async/await 的問題 | Swift

[英]Issue using async/await in loop | Swift

本質上,我將字符串地址轉換為 CLLocationCoordinate2D,為了實現這一點,我正在循環按特定順序的地址數組,我需要保持不變,但是當 escaping 異步 function 運行時,它會將數組地址的順序更改為結果,如何使用 async/await 來達到這個結果?

像這樣的資源很有幫助,但我仍在努力理解正確的實施方式。 https://www.biteinteractive.com/swift-5-5-asynchronous-looping-with-async-await/

func getLocation(from address: String, completion: @escaping (_ location: CLLocationCoordinate2D?)-> Void) {
    let geocoder = CLGeocoder()
    geocoder.geocodeAddressString(address) { (placemarks, error) in
        guard let placemarks = placemarks,
              let location = placemarks.first?.location?.coordinate
        else {
            completion(nil)
            return
        }
        completion(location)
    }
}

let addresses = ["SAUGET, IL", "SAN FRANCISCO, CA", "SAINT LOUIS, MO"]

for address in addresses {
    print(address)
    getLocation(from: address) { location in
        
        //printing not the same order as the order the loop is sending them in.
        print("address: \(address)")
    }
}

只需制作一個使用geocodeAddressString的異步等待再現的再現:

func getCoordinate(from address: String) async throws -> CLLocationCoordinate2D {
    let geocoder = CLGeocoder()

    guard let location = try await geocoder.geocodeAddressString(address)
        .compactMap( { $0.location } )
        .first(where: { $0.horizontalAccuracy >= 0 } )
    else {
        throw CLError(.geocodeFoundNoResult)
    }

    return location.coordinate
}

然后你可以這樣做:

func lookupCoordinates() async throws {
    let addresses = ["SAUGET, IL", "SAN FRANCISCO, CA", "SAINT LOUIS, MO", "NEW YORK, NY"]
    
    for address in addresses {
        let coordinate = try await getCoordinate(from: address)
        print("address: \(coordinate)")
    }
}

無關,我們應該注意到geocodeAddressString 文檔警告我們:

發起前向地理編碼請求后,不要嘗試發起另一個反向或前向地理編碼請求。

CLGeocoder 文檔還警告我們:

每個應用程序的地理編碼請求都有速率限制,因此在短時間內發出過多請求可能會導致某些請求失敗。 ... 最多為任何一項用戶操作發送一個地理編碼請求。

僅供參考。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM