我正在制作一个应用程序,当您单击按钮时,它会填充一个表格 View ,其中包含所有用户及其估计的预计到达时间。当我循环访问用户并获取他们的位置时,我一直遇到一个问题,它不会按照循环的顺序排列数组,因此时间变得很困惑。我尝试了几种不同的方式来循环它们,但似乎当它获得 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
发出网络请求。它是一个异步函数,因此您不能假设对它的所有调用都会按照您发送它们的顺序返回。这是解决此问题的一种方法:
如果您有一个带有可选 duration
属性的 user
对象,您可以重构 ETARequest
方法以将其作为输入:
func ETARequest(destination:CLLocationCoordinate2D, user: UserType) {
//Do stuff...
}
然后,在传递给 calculateETAWithCompletionHandler
的完成处理程序 block 中,您可以将 self.durationArray.insert(self.formatTimeInterval(interval), atIndex: 0)
替换为user.duration = self.formatTimeInterval(interval)
。 (您仍然可以使用计数器来确定所有请求何时完成。)
这样,每个用户都会有一个与其关联的持续时间,您可以通过按所需顺序循环用户来相应地显示它们。
关于ios - Apple MapkitcalculateETAWithCompletionHandler 通过数组循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37234001/