How do I get my implementation of a NavigationServiceDelegate function to be called?

123 views Asked by At

I'm building an iOS app with SwiftUI and am using Mapbox's NavigationViewController to provide turn-by-turn navigation instructions. I'd like to have custom code run when the visual instructions are updated in the navigation view, but my attempts at implementing the relevant delegate methods aren't getting called.

In Mapbox's online guide, it says it's possible to listen for changes to visual instructions when NavigationServiceDelegate.navigationService(_:didPassVisualInstructionPoint:routeProgress:) is called. So I created a MapboxNavigationService, assigned the coordinator as the service's delegate, and then added the service to the NavigationViewController via NavigationOptions. However, when I run the app and the Navigation View comes up complete with visual and audio instructions, nothing is printed and it seems that the delegate functions I implemented in the Coordinator are never run.

Can anyone help me figure out how to hook into the NavigationService callbacks?

Here's my UIViewControllerRepresentable implementation for reference:

struct NavView: UIViewControllerRepresentable {
    @ObservedObject var mapData: MapViewModel
    
    func makeUIViewController(context: Context) -> NavigationViewController {
        
        let indexedRouteResponse = IndexedRouteResponse(routeResponse: mapData.routeResponse!,routeIndex: 0)

        // Create a NavigationService and attach a delegate
        let navigationService = MapboxNavigationService(indexedRouteResponse: indexedRouteResponse, credentials: NavigationSettings.shared.directions.credentials)
        navigationService.delegate = context.coordinator

        let navOptions = NavigationOptions(navigationService: navigationService)
        
        let navViewController = NavigationViewController(for: indexedRouteResponse, navigationOptions: navOptions)
                                
        return navViewController
    }
    
    func updateUIViewController(_ uiViewController: NavigationViewController, context: Context) {}
    
    func makeCoordinator() -> Coordinator {
        return Coordinator()
    }
    
    class Coordinator: NSObject, NavigationServiceDelegate {
        func navigationService(_ service: NavigationService, didPassVisualInstructionPoint instruction: VisualInstructionBanner, routeProgress: RouteProgress) {
            print("Visual Instruction") // Not getting called
        }
        
        func navigationService(_ service: NavigationService, didPassSpokenInstructionPoint instruction: SpokenInstruction, routeProgress: RouteProgress) {
            print("Spoken Instruction") // Not getting called
        }
    }
}
0

There are 0 answers