How to return value out of completion handler (special case)?

徘徊边缘 提交于 2020-07-10 08:45:08

问题


I'm trying to get Mapbox's in app navigation to work on SwiftUI. Right now viewController returns nil. I've looked at other answers to this question and most of them recommend putting another completion handler in the function where the callback takes place. Here is the code:

 func makeUIViewController(context: Context) -> NavigationViewController {
    getRoute { route in
           let viewController = NavigationViewController(for: route as! Route)
           viewController.modalPresentationStyle = .fullScreen
    }
    //Use of unresolved identifier viewController
    return viewController
}

Adding a closure to this function gives me the error:

Type 'NavView' does not conform to protocol 'UIViewControllerRepresentable'

Aside from adding a closure to the function, what else can I do to get the value out of getRoute{}?

Here is rest of code:

struct NavView: UIViewControllerRepresentable{

typealias CompletionHandler = (Any) -> Void

func makeUIViewController(context: Context) -> NavigationViewController {
    getRoute { route in
           let viewController = NavigationViewController(for: route as! Route)
           viewController.modalPresentationStyle = .fullScreen
    }
    //Use of unresolved identifier viewController
    return viewController
}

func updateUIViewController(_ uiView: NavigationViewController, context: Context) {

}

func getRoute(_ completionHandler: @escaping CompletionHandler){
       // Define two waypoints to travel between
       let origin = Waypoint(coordinate: CLLocationCoordinate2D(latitude: 38.9131752, longitude: -77.0324047), name: "Mapbox")
       let destination = Waypoint(coordinate: CLLocationCoordinate2D(latitude: 38.8977, longitude: -77.0365), name: "White House")

       // Set options
       let options = NavigationRouteOptions(waypoints: [origin, destination])

       // Request a route using MapboxDirections.swift
       Directions.shared.calculate(options) { (waypoints, routes, error) in
          guard let route = routes?.first else { return }
          completionHandler(route)
       }
}

来源:https://stackoverflow.com/questions/61416364/how-to-return-value-out-of-completion-handler-special-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!