簡體   English   中英

蘋果Mapkit的computeETAWithCompletionHandler遍歷數組

[英]Apple Mapkit calculateETAWithCompletionHandler loop through array

我正在制作一個應用程序,當您單擊一個按鈕時,該應用程序將使用所有用戶及其估計的ETA填充表格視圖。 當我遍歷用戶並獲取他們的位置時,我一直遇到問題,它不能使Array的排列順序與遍歷用戶的順序相同,因此時間變得混亂起來。 我已經嘗試了幾種遍歷它們的方式,但是當它獲取了directions.calculateETA部分時,它似乎被延遲並在不同的時間運行。 誰能幫助我有效地完成此任務,以免循環發生混亂?

for user in usersArray {

    var userLocations:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: user["location"].latitude, longitude: user["location"].longitude)

    ETARequest(userLocations)

}

func ETARequest(destination:CLLocationCoordinate2D) {

    let request = MKDirectionsRequest()

    if let currentLocation = self.manager.location?.coordinate {

        request.source =  MKMapItem(placemark: MKPlacemark(coordinate: currentLocation, addressDictionary: nil))

        request.destination = MKMapItem(placemark: MKPlacemark(coordinate: destination, addressDictionary: nil))

        request.transportType = .Automobile

        let directions = MKDirections(request: request)

        directions.calculateETAWithCompletionHandler({ ( response, error) in

            if error == nil {

                if let interval = response?.expectedTravelTime  {

                    print(self.formatTimeInterval(interval))

                    self.durationArray.insert(self.formatTimeInterval(interval), atIndex: 0)

                    if self.durationArray.count == self.allUsers.count {

                        print(self.durationArray)

                        self.tableView.reloadData()

                    }

                }

            } else {

                print("Error Occurred")
            }

        })

    }
}

這里的問題是calculateETAWithCompletionHandler發出網絡請求。 這是一個異步函數,因此您不能假定對它的所有調用將以發送它們的相同順序返回。 這是解決此問題的一種方法:

如果您的user對象具有可選的duration屬性,則可以重構ETARequest方法以將其作為輸入:

func ETARequest(destination:CLLocationCoordinate2D, user: UserType) {
    //Do stuff...
}

然后,在完成處理程序塊中,傳遞給calculateETAWithCompletionHandler ,您可以將user.duration = self.formatTimeInterval(interval)替換self.durationArray.insert(self.formatTimeInterval(interval), atIndex: 0) user.duration = self.formatTimeInterval(interval) (您仍然可以使用計數器來確定何時完成所有請求。)

這樣,每個用戶都會有一個持續時間與之相關聯,您可以通過按所需順序遍歷用戶來相應地顯示它們。

暫無
暫無

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

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