如何获取顺序MKDirection请求响应Swift

时间:2019-12-21 18:49:05

标签: ios swift mkdirection

我有一个将[CLLocation]作为输入的函数。在while循环内,它将其分成多个块,每个块发出一个MKDirection请求,将响应存储在新的[CLLocation]中,并在完成后返回。

问题在于新数组中的所有块都不是连续的,因此生成的路由会在整个位置上跳跃。我该如何等待上一个请求获得响应,然后再做出新请求?我尝试了DispatchQueue.global().syncDispatchQueue.main.sync,但没有任何区别。 我尝试从Cannot wait for the result of MKDirections.calculate, getting nil instead of it实施第一个答案,这似乎是我的同样问题,但我不了解如何使其适应我的情况。 您能帮我按顺序获得答复吗? 这是函数,注释掉的部分用于路由的最新点,这将是最后一个请求。 一如既往,非常感谢您的帮助和时间。

    func repositionLocation2(route: [CLLocation], completion: @escaping ([CLLocation]) -> Void) {
        let group = DispatchGroup()
        var pos = 0
        var nextPos = 3
        var repositioned = [CLLocation]()
        //        repositioned.append(route.first!)

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

        while pos < route.count - nextPos {
            print(" pos in \(pos)")
            //            repositioned.removeAll()

            group.enter()
            // get a small chunk of the input route
            let a = route[pos].coordinate//repositioned.last!.coordinate//
            let b = route[pos + nextPos].coordinate


            // get directions for the small chunk
            request.source = MKMapItem(placemark: MKPlacemark(coordinate: a))
            request.destination = MKMapItem(placemark: MKPlacemark(coordinate: b))
            let directions = MKDirections(request: request)
//            DispatchQueue.main.sync {
//            DispatchQueue.global().sync {
//                group.enter()
                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)")
                    // save response coordinates into a new array
                    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
//                        group.leave() 
                    }
//                    group.wait() // hangs the app
                    completion(repositioned)
                }
//            }
            print("repositioned in while loop is : \(repositioned)")
            // shift to nex addiacent chunk
            pos += 3
            nextPos += 3
        }

        //        // last chunk
        //        let a = route[pos - 5].coordinate//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}
        //            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)")
        //                repositioned.append(point)
        //                print("repositioned in for loop is : \(repositioned)")
        //            }
        //            completion(repositioned)
        //        }
        //        print("repositioned in while loop is : \(repositioned)")

    }

1 个答案:

答案 0 :(得分:1)

当您有一系列异步任务(可以按任意顺序完成)需要按顺序排列结果时,只需将其保存到与顺序无关紧要的结构中,最后对其进行排序即可。例如,您可以使用由整数索引索引的字典:

var routes: [Int: [CLLocationCoordinate2D]] = [:]

然后,当任何给定的循环结束时,就可以更新此字典:

routes[i] = ...

如果要在末尾进行排序的平面数组

let coordinates = steps.sorted { $0.0 < $1.0 }
    .flatMap { $0.1 }

或者,您可以使用预先填充的可选数组,您可以在其中将特定路线插入数组中的正确位置:

var routes: [[CLLocationCoordinate2D]?] = Array(repeating: nil, count: pointCount - 1)

当您要更新一个时:

routes[i-1] = ...

然后,最后,您可以使用compactMap删除可选内容,并使用flatMap对其进行展平:

let coordinates = steps.compactMap { $0 }.flatMap { $0 }

因此:

func fetchDirections(_ locations: [CLLocation], completion: @escaping ([CLLocationCoordinate2D]) -> Void) {
    let pointCount = locations.count

    guard pointCount > 1 else { return }

    var routes: [[CLLocationCoordinate2D]?] = Array(repeating: nil, count: pointCount - 1)
    let group = DispatchGroup()

    for i in 1 ..< pointCount {
        group.enter()
        directions(from: locations[i-1], to: locations[i]).calculate { response, error in
            defer { group.leave() }

            guard
                error == nil,
                let response = response,
                let route = response.routes.first
            else { return }

            routes[i-1] = self.coordinates(for: route.steps)
        }
    }

    group.notify(queue: .main) {
        let coordinates = routes.compactMap { $0 }.flatMap { $0 }
        completion(coordinates)
    }
}

func directions(from: CLLocation, to: CLLocation) -> MKDirections {
    let request = MKDirections.Request()
    request.source = MKMapItem(placemark: MKPlacemark(coordinate: from.coordinate))
    request.destination = MKMapItem(placemark: MKPlacemark(coordinate: to.coordinate))
    request.requestsAlternateRoutes = false
    request.transportType = .walking
    return MKDirections(request: request)
}

func coordinates(for steps: [MKRoute.Step]) -> [CLLocationCoordinate2D] {
    guard !steps.isEmpty else { return [] }

    var coordinates: [CLLocationCoordinate2D] = []

    for step in steps {
        let count = step.polyline.pointCount
        let pointer = step.polyline.points()
        for i in 0 ..< count {
            let coordinate = pointer[i].coordinate
            if coordinate.latitude != coordinates.last?.latitude, coordinate.longitude != coordinates.last?.longitude {
                coordinates.append(coordinate)
            }
        }
    }

    return coordinates
}

位置:

fetchDirections(locations) { coordinates in
    let polyline = MKPolyline(coordinates: coordinates, count: coordinates.count)
    self.mapView.addOverlay(polyline)
}

屈服,在Apple大楼内漫步:

enter image description here


顺便说一句,请注意,我不仅在使用coordinate的{​​{1}}中的polyline。那是折线的中心。您大概想遍历points()

话虽这么说,当我获得路线指示时,通常只是将其显示在地图上,所以我通常只是直接将MKRoute.Step添加为叠加层,而不必理会将其分解为polyline,但我认为您还有其他理由要这样做。