gpt4 book ai didi

ios - 返回数组的函数没有在 for 循环 Swift 中获取附加内容

转载 作者:行者123 更新时间:2023-11-29 05:13:40 27 4
gpt4 key购买 nike

我是请求路线的新手,并遵循 hackingwithswift ( https://www.hackingwithswift.com/example-code/location/how-to-find-directions-using-mkmapview-and-mkdirectionsrequest ) 的一篇文章,在跟踪新路线时,我能够获得我刚刚跟踪的路线的替代路线。我的目标是输入 [CLLocation]获取来自 MKDirection 的路线。问题是,在跟踪它时,我确实得到了一条替代路线,但是当从保存的路线(与我刚刚跟踪的相同)请求它时,我得到一个 nil response错误消息:

direction error : Error Domain=MKErrorDomain Code=1 "Indicazioni stradali non disponibili" UserInfo={NSLocalizedFailureReason=Le informazioni sull'itinerario non sono attualmente disponibili., MKErrorGEOError=-12, MKErrorGEOErrorUserInfo={ NSDebugDescription = "mapItem cannot be nil"; }, MKDirectionsErrorCode=3, NSLocalizedDescription=Indicazioni stradali non disponibili}

路线相同,因此起点和终点相同。你能看到我在这里做错了什么吗?一如既往,非常感谢。

 func repositionLocation(route: [CLLocation]) -> [CLLocation] {
var repositioned: [CLLocation] = []
let request = MKDirections.Request()
request.requestsAlternateRoutes = false
request.transportType = .walking
let directions = MKDirections(request: request)
let a = route.first?.coordinate
let b = route.last?.coordinate
print("a is: \(String(describing: a)), b is \(String(describing: b))") // prints correct CLLocationCoordinate2D
request.source = MKMapItem(placemark: MKPlacemark(coordinate: a!))
request.destination = MKMapItem(placemark: MKPlacemark(coordinate: b!))

directions.calculate { [unowned self] response, error in
if let err = error {
print("direction error : \(err)")
}
guard let unwrappedResponse = response else {print("no suggested routes available"); return } // here always returns
guard let coord = unwrappedResponse.routes.first?.steps else {return}
for location in coord {
let point: CLLocation = CLLocation(latitude: location.polyline.coordinate.latitude, longitude: location.polyline.coordinate.longitude)
repositioned.append(point)
}
}
return repositioned
}

更新:

我正在缩小问题范围,要么是我发出了太多请求(但我只发出了一个)并且服务器停止响应,要么是异步响应,该函数在实际获得有效响应之前退出,如下所示我从 TableView 中调用它。我如何等待 cellForRow 中的回复?

更新 2:

经过宝贵的建议后,它现在正在请求路线并获取响应,我从中创建了一个新的 CLLocation对于每个步骤,并将其附加到 repositioned完成时返回的数组。我实际上看到新的 CLLocationfor内正确创建当我打印它时循环,但数组的大小不会增加,并且返回的数组将仅具有输入路由中的第一个附加。

该函数的新版本是:

func repositionLocation(route: [CLLocation], completion: @escaping ([CLLocation]) -> Void) {
var pos = 0
var repositioned = [CLLocation]()
repositioned.append(route.first!)
guard route.count > 4 else {print("Reposision Location failed, not enough positions");return}
let request = MKDirections.Request()
request.requestsAlternateRoutes = false
request.transportType = .walking
while pos < route.count - 4 {

let a = repositioned.last!.coordinate
let b = route[pos + 4].coordinate
request.source = MKMapItem(placemark: MKPlacemark(coordinate: a))
request.destination = MKMapItem(placemark: MKPlacemark(coordinate: b))
let directions = MKDirections(request: request)
directions.calculate { [unowned self] response, error in
if let err = error {
print("direction error : \(err)")
}
guard let unwrappedResponse = response else {print("no suggested routes available"); return }
print("Response is: \(unwrappedResponse.debugDescription)")
guard let coord = unwrappedResponse.routes.first?.steps else {print("No coordinates");return}
print("coord is: \(coord)")
for location in coord {

let point: CLLocation = CLLocation(latitude: location.polyline.coordinate.latitude, longitude: location.polyline.coordinate.longitude)
print("point is: \(point)") // prints a correct CLLocation with coordinates
repositioned.append(point)
print("repositioned in for loop is : \(repositioned)") // prints just first appended location CLLocation with coordinates
}
}
print("repositioned in while loop is : \(repositioned)")
pos += 5
}

// last segment.
// let a = repositioned.last?.coordinate
// let b = route.last?.coordinate
//
// request.source = MKMapItem(placemark: MKPlacemark(coordinate: a!))
// request.destination = MKMapItem(placemark: MKPlacemark(coordinate: b!))
//
// let directions = MKDirections(request: request)
//
// directions.calculate { [unowned self] response, error in
// if let err = error {
// print("direction error : \(err)")
// }
// guard let unwrappedResponse = response else {print("no suggested routes available"); return }
// print("Response is: \(unwrappedResponse.debugDescription)")
// guard let coord = unwrappedResponse.routes.first?.steps else {print("No coordinates");return}
// for location in coord {
// let point: CLLocation = CLLocation(latitude: location.polyline.coordinate.latitude, longitude: location.polyline.coordinate.longitude)
// repositioned.append(point)
// }

print("repositioned at completion is : \(repositioned)")
completion(repositioned)
// }
}

不要看注释掉的部分,它将处理输入路由的最后一位,超出 while 内处理的部分。循环。

最佳答案

有几个问题:

首先,您正在尝试建立一条穿越整个美国的步行路线 - 这个问题无法通过传统方法解决。我建议将点的坐标设置为更近的距离。我已经在更近的地方测试了您的代码,并且路线出现了。

其次,您可以使用以下代码:

 func repositionLocation(route: [CLLocation], completion: @escaping ([CLLocation]) -> Void) {

var repositioned = [CLLocation]()

let request = MKDirections.Request()
request.requestsAlternateRoutes = false
request.transportType = .walking

let a = route.first?.coordinate
let b = route.last?.coordinate
request.source = MKMapItem(placemark: MKPlacemark(coordinate: a!))
request.destination = MKMapItem(placemark: MKPlacemark(coordinate: b!))

let directions = MKDirections(request: request)

print("a is: \(String(describing: a)), b is \(String(describing: b))") // prints correct CLLocationCoordinate2D
request.source = MKMapItem(placemark: MKPlacemark(coordinate: a!))
request.destination = MKMapItem(placemark: MKPlacemark(coordinate: b!))

directions.calculate { response, error in
if let err = error {
print("direction error : \(err)")
}
guard let unwrappedResponse = response else {print("no suggested routes available"); return } // here always returns

for route in unwrappedResponse.routes {
self.mapView.addOverlay(route.polyline)
self.mapView.setVisibleMapRect(route.polyline.boundingMapRect, animated: true)
}

guard let coord = unwrappedResponse.routes.first?.steps else {return}
for location in coord {
let point: CLLocation = CLLocation(latitude: location.polyline.coordinate.latitude, longitude: location.polyline.coordinate.longitude)
repositioned.append(point)
}
completion(repositioned)
}
}

您设置let Directions = MKDirections(request: request),但随后才配置request.sourcerequest.destination。除此之外,您会异步获取结果,因此我为结果添加了completion

为了进行测试,您可以这样调用:

repositionLocation(route: [CLLocation(latitude: 40.7127, longitude: -74.0059), CLLocation(latitude: 40.79, longitude: -74.011)]) { result in
print(result)
}

UPD2:

@Vincenzo 正如我所见,您错误地使用完成处理程序进行关闭,我建议您阅读有关异步和关闭的内容。

我建议使用此代码:

func repositionLocation(route: [CLLocation], completion: @escaping ([CLLocation]) -> Void) {
var pos = 0
var repositioned = [CLLocation]()
repositioned.append(route.first!)

guard route.count > 4 else {print("Reposision Location failed, not enough positions");return}
let request = MKDirections.Request()
request.requestsAlternateRoutes = false
request.transportType = .walking

while pos < route.count - 4 {

let a = repositioned.last!.coordinate
let b = route[pos + 4].coordinate
request.source = MKMapItem(placemark: MKPlacemark(coordinate: a))
request.destination = MKMapItem(placemark: MKPlacemark(coordinate: b))
let directions = MKDirections(request: request)
directions.calculate { [unowned self] response, error in
if let err = error {
print("direction error : \(err)")
}
guard let unwrappedResponse = response else {print("no suggested routes available"); return }
print("Response is: \(unwrappedResponse.debugDescription)")
guard let coord = unwrappedResponse.routes.first?.steps else {print("No coordinates");return}
print("coord is: \(coord)")
for location in coord {

let point: CLLocation = CLLocation(latitude: location.polyline.coordinate.latitude, longitude: location.polyline.coordinate.longitude)
print("point is: \(point)") // prints a correct CLLocation with coordinates
repositioned.append(point)
print("repositioned in for loop is : \(repositioned)") // prints just first appended location CLLocation with coordinates
}
completion(repositioned)
}
print("repositioned in while loop is : \(repositioned)")
pos += 5
}
}

关于ios - 返回数组的函数没有在 for 循环 Swift 中获取附加内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59414562/

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