### Install Mapbox Navigation SDK via Swift Package Manager Source: https://context7.com/mapbox/mapbox-navigation-ios/llms.txt Add the Mapbox Navigation SDK to your project using Swift Package Manager. Ensure `MBXAccessToken` and background modes are configured in `Info.plist`. ```swift // Package.swift dependency .package(url: "https://github.com/mapbox/mapbox-navigation-ios.git", from: "3.1.0") // Info.plist (set via Xcode target → Info tab) // MBXAccessToken = pk.eyJ1... // NSLocationWhenInUseUsageDescription = "Shows your location on the map..." // UIBackgroundModes = ["audio", "location"] ``` -------------------------------- ### Script Tag with Path Obfuscation Source: https://github.com/mapbox/mapbox-navigation-ios/blob/main/Sources/TestHelper/Fixtures/encoding_crazy_strings.txt Demonstrates attempts to load external scripts using obfuscated paths in the 'src' attribute of a script tag. This includes examples using percent-encoding and backslashes. ```html ``` ```html ``` -------------------------------- ### JavaScript URI Injection Attempts Source: https://github.com/mapbox/mapbox-navigation-ios/blob/main/Sources/TestHelper/Fixtures/encoding_crazy_strings.txt These examples show various Unicode and ASCII control characters prepended to 'javascript:' URIs to test for XSS vulnerabilities in link handling. ```HTML test ``` ```HTML test ``` ```HTML test ``` ```HTML test ``` ```HTML test ``` ```HTML test ``` ```HTML test ``` ```HTML test ``` ```HTML test ``` ```HTML test ``` ```HTML test ``` ```HTML test ``` ```HTML test ``` ```HTML test ``` ```HTML test ``` ```HTML test ``` ```HTML test ``` ```HTML test ``` ```HTML test ``` ```HTML test ``` ```HTML test ``` ```HTML test ``` ```HTML test ``` ```HTML test ``` ```HTML test ``` ```HTML test ``` ```HTML test ``` -------------------------------- ### JavaScript URI Injection with Null/Special Characters Source: https://github.com/mapbox/mapbox-navigation-ios/blob/main/Sources/TestHelper/Fixtures/encoding_crazy_strings.txt These examples test 'javascript:' URI injection by inserting null bytes or other special characters directly within the 'javascript' protocol. ```HTML test ``` ```HTML test ``` ```HTML test ``` ```HTML test ``` ```HTML test ``` -------------------------------- ### User Interaction Event XSS Source: https://github.com/mapbox/mapbox-navigation-ios/blob/main/Sources/TestHelper/Fixtures/encoding_crazy_strings.txt Demonstrates XSS vulnerabilities triggered by user interactions like 'oncopy' and 'onwheel' events. These examples show how simple user actions can lead to script execution if event handlers are not properly sanitized. ```html Copy me ``` ```html Scroll over me ``` -------------------------------- ### Enable Debug History Recording Source: https://context7.com/mapbox/mapbox-navigation-ios/llms.txt Configure `HistoryRecording` within `CoreConfig` to enable recording of navigator events for debugging and Copilot integration. You can start, stop, and push custom events to the recording. ```swift import MapboxNavigationCore // Enable history recording in CoreConfig let config = CoreConfig( historyRecordingConfig: HistoryRecordingConfig( historyDirectoryURL: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] .appendingPathComponent("navigation-history") ) ) let provider = MapboxNavigationProvider(coreConfig: config) guard let recorder = provider.historyRecorder() else { print("History recording not configured") return } // Start recording recorder.startRecordingHistory() // Push a custom event try recorder.pushHistoryEvent(type: "user_action", value: ["action": "button_tapped", "screen": "map"]) // Stop and save recorder.stopRecordingHistory { url in guard let url else { return } print("History saved to: \(url.path)") // Share or upload the .gz file for debugging } ``` -------------------------------- ### XSS via SCRIPT Tag with Encoded Characters Source: https://github.com/mapbox/mapbox-navigation-ios/blob/main/Sources/TestHelper/Fixtures/encoding_crazy_strings.txt These examples test XSS by injecting 'javascript:' URIs into SCRIPT tags, using various Unicode and ASCII control characters for obfuscation. ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` -------------------------------- ### XSS via IMG Tag with Null/Control Characters Source: https://github.com/mapbox/mapbox-navigation-ios/blob/main/Sources/TestHelper/Fixtures/encoding_crazy_strings.txt These examples test XSS by injecting onerror attributes into an IMG tag, using null bytes and control characters directly within the attribute. ```HTML ``` ```HTML ``` ```HTML ``` -------------------------------- ### Calculate and Refresh Routes with Directions API Source: https://context7.com/mapbox/mapbox-navigation-ios/llms.txt Fetch routes using the Mapbox Directions API and handle the response, including route details and legs. Also demonstrates how to refresh an existing route to get updated traffic information. ```swift import MapboxDirections let directions = Directions.shared // reads MBXAccessToken from Info.plist let origin = Waypoint(coordinate: CLLocationCoordinate2D(latitude: 38.9131, longitude: -77.0324), name: "Mapbox DC") let destination = Waypoint(coordinate: CLLocationCoordinate2D(latitude: 38.8977, longitude: -77.0365), name: "White House") let options = RouteOptions(waypoints: [origin, destination], profileIdentifier: .automobileAvoidingTraffic) options.includesSteps = true options.includesAlternativeRoutes = true options.routeShapeResolution = .full options.attributeOptions = [.congestionLevel, .speed, .expectedTravelTime] options.refreshingEnabled = true // Callback-based (returns URLSessionDataTask for cancellation) let task = directions.calculate(options) { result in switch result { case .failure(let error): print("Directions error: \(error.localizedDescription)") case .success(let response): guard let route = response.routes?.first else { return } print("Route distance: \(route.distance) m") print("ETA: \(route.expectedTravelTime) s") for leg in route.legs { print("Leg: \(leg.source?.name ?? "") → \(leg.destination?.name ?? "")") for step in leg.steps { print(" \(step.instructions) (\(step.distance) m)") } } } } // Cancel if needed task.cancel() // Route refresh (update live traffic on existing route) directions.refreshRoute( responseIdentifier: response.identifier ?? "", routeIndex: 0, fromLegAtIndex: 0 ) { credentials, result in switch result { case .success(let refreshResponse): print("Route refreshed: \(refreshResponse.route)") case .failure(let error): print("Refresh failed: \(error)") } } ``` -------------------------------- ### Initialize and Present NavigationViewController Source: https://context7.com/mapbox/mapbox-navigation-ios/llms.txt Use `NavigationViewController` for a drop-in turn-by-turn UI. Initialize it with `NavigationRoutes` and `NavigationOptions`, then present it modally. Configure various properties to customize the UI behavior and appearance. ```swift import MapboxNavigationUIKit import MapboxNavigationCore // Build NavigationOptions let navigationOptions = NavigationOptions( mapboxNavigation: navigationProvider.mapboxNavigation, voiceController: navigationProvider.routeVoiceController, // @MainActor eventsManager: navigationProvider.eventsManager(), styles: [StandardDayStyle(), StandardNightStyle()], predictiveCacheManager: navigationProvider.predictiveCacheManager ) // Present NavigationViewController let navVC = NavigationViewController( navigationRoutes: navigationRoutes, navigationOptions: navigationOptions ) navVC.delegate = self navVC.modalPresentationStyle = .fullScreen navVC.routeLineTracksTraversal = true // fade traversed route line navVC.showsReportFeedback = true navVC.showsSpeedLimits = true navVC.annotatesIntersectionsAlongRoute = true navVC.usesNightStyleWhileInTunnel = true navVC.usesNightStyleInDarkMode = true navVC.automaticallyAdjustsStyleForTimeOfDay = true present(navVC, animated: true) // Implement NavigationViewControllerDelegate extension MyViewController: NavigationViewControllerDelegate { func navigationViewController(_ vc: NavigationViewController, didUpdate progress: RouteProgress, with location: CLLocation, rawLocation: CLLocation) { print("Distance remaining: \(progress.distanceRemaining) m") print("Duration remaining: \(progress.durationRemaining) s") print("Fraction traveled: \(progress.fractionTraveled)") } func navigationViewControllerDidDismiss(_ vc: NavigationViewController, byCanceling canceled: Bool) { dismiss(animated: true) } func navigationViewController(_ vc: NavigationViewController, didArriveAt waypoint: Waypoint) -> Bool { print("Arrived at \(waypoint.name ?? "waypoint")") return true // return false to prevent auto-advance to next leg } func navigationViewController(_ vc: NavigationViewController, didRerouteAlong route: Route) { print("Rerouted to new route") } } ``` -------------------------------- ### Configure .netrc for Private Token Source: https://github.com/mapbox/mapbox-navigation-ios/blob/main/README.md Set up your .netrc file in your home directory to authenticate with Mapbox for downloading SDK components. Replace PRIVATE_MAPBOX_API_TOKEN with your actual token that has the DOWNLOADS:READ scope. ```shell machine api.mapbox.com login mapbox password PRIVATE_MAPBOX_API_TOKEN ``` -------------------------------- ### Run MapboxDirectionsCLI for Usage Source: https://github.com/mapbox/mapbox-navigation-ios/blob/main/docs/CommandLineTool.md Execute the MapboxDirectionsCLI tool to view its usage instructions. This command also builds the tool if it hasn't been built already. ```bash swift run mapbox-directions-swift -h ``` -------------------------------- ### Initialize MapboxNavigationProvider Source: https://context7.com/mapbox/mapbox-navigation-ios/llms.txt Instantiate `MapboxNavigationProvider` once per app lifecycle with `CoreConfig`. Access the `mapboxNavigation` protocol and update configuration at runtime with caution. ```swift import MapboxNavigationCore import MapboxDirections // Configure and create the provider (create only once — a second instance crashes) let navigationProvider = MapboxNavigationProvider( coreConfig: CoreConfig( locationSource: .live, // .live, .simulation(locationArray), .custom(publisher) routingConfig: RoutingConfig( routingProviderSource: .hybrid, // .online, .offline, .hybrid fasterRouteDetectionConfig: FasterRouteDetectionConfig() ), predictiveCacheConfig: PredictiveCacheConfig(), historyRecordingConfig: HistoryRecordingConfig( historyDirectoryURL: FileManager.default.temporaryDirectory.appendingPathComponent("history") ), ttsConfig: .default, // .default (Mapbox+System), .localOnly, .custom(synthesizer) copilotEnabled: false, locale: .current, logLevel: .warning ) ) // Access the shared MapboxNavigation protocol let mapboxNavigation = navigationProvider.mapboxNavigation // @MainActor // Update config at runtime (use with caution) var updated = navigationProvider.coreConfig updated.routingConfig.routingProviderSource = .online navigationProvider.apply(coreConfig: updated) ``` -------------------------------- ### XSS via IMG Tag with Encoded Characters Source: https://github.com/mapbox/mapbox-navigation-ios/blob/main/Sources/TestHelper/Fixtures/encoding_crazy_strings.txt These examples attempt XSS by injecting onerror attributes into an IMG tag, using various encoded characters within the attribute value. ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` ```HTML "'> ``` -------------------------------- ### Initialize Mapbox Navigation Source: https://github.com/mapbox/mapbox-navigation-ios/blob/main/README.md Define the entry point for Mapbox Navigation and initialize the core navigation object. ```swift // Define the Mapbox Navigation entry point. let mapboxNavigationProvider = MapboxNavigationProvider(coreConfig: .init()) lazy var mapboxNavigation = mapboxNavigationProvider.mapboxNavigation ``` -------------------------------- ### Configure CoreConfig for Mapbox Navigation SDK Source: https://context7.com/mapbox/mapbox-navigation-ios/llms.txt Set up `CoreConfig` with detailed settings for credentials, routing, location sources, and other SDK features. This configuration is passed to `MapboxNavigationProvider`. ```swift import MapboxNavigationCore let config = CoreConfig( credentials: NavigationCoreApiConfiguration( navigation: ApiConfiguration(accessToken: "pk.eyJ1..."), map: ApiConfiguration(accessToken: "pk.eyJ1...") ), routingConfig: RoutingConfig( routingProviderSource: .hybrid, fasterRouteDetectionConfig: FasterRouteDetectionConfig( isFasterRouteEnabled: true, minTimeSaved: 120 ), alternativeRoutesDetectionConfig: AlternativeRoutesDetectionConfig(), rerouteConfig: RerouteConfig() ), locationSource: .live, copilotEnabled: true, locale: Locale(identifier: "en-US"), disableBackgroundTrackingLocation: true, congestionConfig: .default, predictiveCacheConfig: PredictiveCacheConfig( predictiveCacheMapsConfig: PredictiveCacheMapsConfig(zoomRange: 0...16), predictiveCacheNavigationConfig: PredictiveCacheNavigationConfig() ), electronicHorizonConfig: ElectronicHorizonConfig( length: 500, expansionLevel: 1, branchLength: 50, minTimeDeltaBetweenUpdates: 1.0 ), ttsConfig: .default, tilestoreConfig: .default ) ``` -------------------------------- ### PreviewViewController for Route Preview Source: https://context7.com/mapbox/mapbox-navigation-ios/llms.txt Provides a pre-navigation preview experience. Configure with styles and present destination or route previews. ```swift import MapboxNavigationUIKit import MapboxNavigationCore let previewOptions = PreviewOptions( styles: [StandardDayStyle(), StandardNightStyle()] ) let previewVC = PreviewViewController( navigationProvider: navigationProvider, previewOptions: previewOptions ) previewVC.delegate = self // Show destination preview banner let destinationOptions = DestinationOptions( destinations: [CLLocationCoordinate2D(latitude: 34.0522, longitude: -118.2437)] ) previewVC.present( destination: DestinationPreviewViewController(destinationOptions: destinationOptions), animated: true ) // After routes are computed, show route preview let routePreviewOptions = RoutePreviewOptions(navigationRoutes: navigationRoutes) previewVC.present( route: RoutePreviewViewController(routePreviewOptions: routePreviewOptions), animated: true ) // Implement delegate extension MyViewController: PreviewViewControllerDelegate { func previewViewController(_ vc: PreviewViewController, didFinishPreviewing options: PreviewOptions) { // Transition to NavigationViewController } } ``` -------------------------------- ### Build MapboxDirectionsCLI with SPM Source: https://github.com/mapbox/mapbox-navigation-ios/blob/main/docs/CommandLineTool.md Build the MapboxDirectionsCLI tool using Swift Package Manager. This command compiles the tool for use. ```bash swift build --target "MapboxDirectionsCLI" ``` -------------------------------- ### Access Route Progress Metrics Source: https://context7.com/mapbox/mapbox-navigation-ios/llms.txt Retrieve and display real-time route progress, including distance, duration, leg, and step information. Also shows how to access upcoming steps, congestion levels, and route alerts. ```swift import MapboxNavigationCore // Access current route progress from the navigation controller if let state = mapboxNavigation.navigation().currentRouteProgress { let progress: RouteProgress = state.routeProgress // Route-level metrics print("Distance traveled: \(progress.distanceTraveled) m") print("Distance remaining: \(progress.distanceRemaining) m") print("Duration remaining: \(progress.durationRemaining) s") print("Fraction traveled: \(String(format: \"%.1f%%\", progress.fractionTraveled * 100))") print("Route complete: \(progress.routeIsComplete)") // Current leg let legProgress = progress.currentLegProgress print("Leg index: \(progress.legIndex) of \(progress.route.legs.count - 1)") print("Leg distance remaining: \(legProgress.distanceRemaining) m") // Current step let stepProgress = legProgress.currentStepProgress print("Step instruction: \(legProgress.currentStep.instructions)") print("Step distance remaining: \(stepProgress.distanceRemaining) m") print("Step fraction: \(stepProgress.fractionTraveled)") // Upcoming step if let upcoming = progress.upcomingStep { print("Next maneuver: \(upcoming.maneuverType?.description ?? \"unknown\")") } // Congestion ahead if let congestion = progress.averageCongestionLevelRemainingOnLeg { print("Congestion ahead: \(congestion)") // .low, .moderate, .heavy, .severe, .unknown } // Upcoming route alerts (tunnels, toll booths, rest areas) for alert in progress.upcomingRouteAlerts { print("Upcoming: \(alert.roadObject.kind) in \(alert.distanceToStart) m") } } ``` -------------------------------- ### HTML Image Tag XSS with Hex Escapes Source: https://github.com/mapbox/mapbox-navigation-ios/blob/main/Sources/TestHelper/Fixtures/encoding_crazy_strings.txt Demonstrates XSS vulnerabilities using image tags with various hexadecimal character encodings for attributes like 'src' and 'onerror'. These examples show how non-standard character representations can bypass simple filters. ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` -------------------------------- ### Generate GPX Trace for Xcode Simulator Source: https://github.com/mapbox/mapbox-navigation-ios/blob/main/docs/CommandLineTool.md Use the Mapbox Directions CLI to convert a Directions API response into a GPX trace format compatible with the Xcode Simulator. Ensure you provide paths to your configuration, input response, and desired output file. ```bash swift run mapbox-directions-swift route -c < PATH TO CONFIG FILE (with your RouteOptions JSON) > \ -f gpx \ -i < PATH TO INPUT FILE (with your Directions API response) > \ -o < PATH TO OUTPUT FILE > ``` -------------------------------- ### NavigationController - Real-Time Navigation Events Source: https://context7.com/mapbox/mapbox-navigation-ios/llms.txt Exposes Combine publishers for all navigation events during active guidance or free drive. Access it via `mapboxNavigation.navigation()`. ```APIDOC ## `NavigationController` — Real-Time Navigation Events `NavigationController` exposes Combine publishers for all navigation events during active guidance or free drive. Access it via `mapboxNavigation.navigation()`. ```swift import MapboxNavigationCore import Combine let nav = mapboxNavigation.navigation() var cancellables = Set() // Location matching (speed, road name, map-matched position) nav.locationMatching .sink { state in print("Speed: \(state.speed) m/s") print("Road: \(state.roadName?.text ?? \"unknown\")") print("Enhanced location: \(state.enhancedLocation.coordinate)") } .store(in: &cancellables) // Route progress nav.routeProgress .compactMap { $0 } .sink { state in let progress = state.routeProgress print("Step: \(progress.currentLegProgress.currentStep.instructions)") print("Distance to next: \(progress.currentLegProgress.currentStepProgress.distanceRemaining) m") } .store(in: &cancellables) // Rerouting events nav.rerouting .sink { status in switch status.event { case is ReroutingStatus.Events.FetchingRoute: print("Fetching new route...") case let failed as ReroutingStatus.Events.Failed: print("Reroute failed: \(failed.error)") default: print("Rerouted successfully") } } .store(in: &cancellables) // Voice instructions nav.voiceInstructions .sink { state in print("Speak: \(state.spokenInstruction.text)") } .store(in: &cancellables) // Waypoint arrival nav.waypointsArrival .sink { status in switch status.event { case let toFinal as WaypointArrivalStatus.Events.ToFinalDestination: print("Arrived at destination: \(toFinal.destination.name ?? \"\")") case let toWaypoint as WaypointArrivalStatus.Events.ToWaypoint: print("Arrived at intermediate waypoint") default: break } } .store(in: &cancellables) // Alternative routes nav.continuousAlternatives .sink { status in if let updated = status.event as? AlternativesStatus.Events.Updated { print("Alternatives updated: \(updated.actualAlternativeRoutes.count) routes") } } .store(in: &cancellables) // Programmatically switch to an alternative nav.selectAlternativeRoute(at: 0) nav.switchLeg(newLegIndex: 1) ``` ``` -------------------------------- ### Calculate and Display a Route Source: https://github.com/mapbox/mapbox-navigation-ios/blob/main/README.md Define origin and destination waypoints, request a route using the RoutingProvider, and present the NavigationViewController with the calculated route. ```swift // 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 RoutingProvider let request = mapboxNavigation.routingProvider().calculateRoutes(options: options) Task { switch await request.result { case .failure(let error): print(error.localizedDescription) case .success(let navigationRoutes): // Pass the generated navigation routes to the the NavigationViewController let navigationOptions = NavigationOptions(mapboxNavigation: mapboxNavigation, voiceController: mapboxNavigationProvider.routeVoiceController, eventsManager: mapboxNavigationProvider.eventsManager()) let navigationViewController = NavigationViewController(navigationRoutes: navigationRoutes, navigationOptions: navigationOptions) navigationViewController.modalPresentationStyle = .fullScreen present(navigationViewController, animated: true, completion: nil) } } ``` -------------------------------- ### Import Core Navigation SDK Modules Source: https://github.com/mapbox/mapbox-navigation-ios/blob/main/README.md Import necessary modules from the Mapbox Navigation SDK for iOS to utilize its features. ```swift import MapboxDirections import MapboxNavigationCore import MapboxNavigationUIKit import UIKit import CoreLocation ``` -------------------------------- ### `NavigationViewController` — Drop-in Turn-by-Turn UI Source: https://context7.com/mapbox/mapbox-navigation-ios/llms.txt The `NavigationViewController` provides a full-featured turn-by-turn navigation UI. It can be initialized with `NavigationRoutes` and `NavigationOptions`, and then presented modally. ```APIDOC ## `NavigationViewController` — Drop-in Turn-by-Turn UI `NavigationViewController` is the full-featured navigation UI. Initialize it with `NavigationRoutes` and `NavigationOptions`, then present it modally. ```swift import MapboxNavigationUIKit import MapboxNavigationCore // Build NavigationOptions let navigationOptions = NavigationOptions( mapboxNavigation: navigationProvider.mapboxNavigation, voiceController: navigationProvider.routeVoiceController, // @MainActor eventsManager: navigationProvider.eventsManager(), styles: [StandardDayStyle(), StandardNightStyle()], predictiveCacheManager: navigationProvider.predictiveCacheManager ) // Present NavigationViewController let navVC = NavigationViewController( navigationRoutes: navigationRoutes, navigationOptions: navigationOptions ) navVC.delegate = self navVC.modalPresentationStyle = .fullScreen navVC.routeLineTracksTraversal = true // fade traversed route line navVC.showsReportFeedback = true navVC.showsSpeedLimits = true navVC.annotatesIntersectionsAlongRoute = true navVC.usesNightStyleWhileInTunnel = true navVC.usesNightStyleInDarkMode = true navVC.automaticallyAdjustsStyleForTimeOfDay = true present(navVC, animated: true) // Implement NavigationViewControllerDelegate extension MyViewController: NavigationViewControllerDelegate { func navigationViewController(_ vc: NavigationViewController, didUpdate progress: RouteProgress, with location: CLLocation, rawLocation: CLLocation) { print("Distance remaining: \(progress.distanceRemaining) m") print("Duration remaining: \(progress.durationRemaining) s") print("Fraction traveled: \(progress.fractionTraveled)") } func navigationViewControllerDidDismiss(_ vc: NavigationViewController, byCanceling canceled: Bool) { dismiss(animated: true) } func navigationViewController(_ vc: NavigationViewController, didArriveAt waypoint: Waypoint) -> Bool { print("Arrived at \(waypoint.name ?? \"waypoint\")") return true // return false to prevent auto-advance to next leg } func navigationViewController(_ vc: NavigationViewController, didRerouteAlong route: Route) { print("Rerouted to new route") } } ``` ``` -------------------------------- ### Manage Navigation Session States with SessionController Source: https://context7.com/mapbox/mapbox-navigation-ios/llms.txt Use SessionController to transition between Idle, Free Drive, and Active Guidance states. Subscribe to session state changes and observe navigation routes. ```swift import MapboxNavigationCore import Combine let session = mapboxNavigation.tripSession() // Subscribe to session state changes var cancellables = Set() session.session .sink { sessionState in switch sessionState.state { case .idle: print("Navigation idle") case .freeDrive: print("Free drive active") case .activeGuidance(let info): print("Navigating leg \(info.legIndex)") } } .store(in: &cancellables) // Transition to Free Drive (passive location tracking) session.startFreeDrive() // Start Active Guidance session.startActiveGuidance(with: navigationRoutes, startLegIndex: 0) // Pause free drive (background optimization) session.pauseFreeDrive() // Stop all navigation session.setToIdle() // Observe current NavigationRoutes session.navigationRoutes .compactMap { $0 } .sink { routes in print("Active route: \(routes.mainRoute.routeId)") } .store(in: &cancellables) ``` -------------------------------- ### SessionController - Navigation Session Lifecycle Source: https://context7.com/mapbox/mapbox-navigation-ios/llms.txt Controls transitions between Idle, Free Drive, and Active Guidance states. Access it via `mapboxNavigation.tripSession()`. ```APIDOC ## `SessionController` — Navigation Session Lifecycle `SessionController` controls transitions between Idle, Free Drive, and Active Guidance states. Access it via `mapboxNavigation.tripSession()`. ```swift import MapboxNavigationCore import Combine let session = mapboxNavigation.tripSession() // Subscribe to session state changes var cancellables = Set() session.session .sink { sessionState in switch sessionState.state { case .idle: print("Navigation idle") case .freeDrive: print("Free drive active") case .activeGuidance(let info): print("Navigating leg \(info.legIndex)") } } .store(in: &cancellables) // Transition to Free Drive (passive location tracking) session.startFreeDrive() // Start Active Guidance session.startActiveGuidance(with: navigationRoutes, startLegIndex: 0) // Pause free drive (background optimization) session.pauseFreeDrive() // Stop all navigation session.setToIdle() // Observe current NavigationRoutes session.navigationRoutes .compactMap { $0 } .sink { routes in print("Active route: \(routes.mainRoute.routeId)") } .store(in: &cancellables) ``` ``` -------------------------------- ### Manage Routes with NavigationRoutes Source: https://context7.com/mapbox/mapbox-navigation-ios/llms.txt Access and manage main and alternative routes, waypoints, and compare route sets. Select alternative routes to become the main route. ```swift import MapboxNavigationCore // Access routes let mainRoute: NavigationRoute = navigationRoutes.mainRoute let alternatives: [AlternativeRoute] = navigationRoutes.alternativeRoutes let waypoints: [Waypoint] = navigationRoutes.waypoints print("Route ID: \(mainRoute.routeId)") print("Distance: \(mainRoute.route.distance) m") print("ETA: \(mainRoute.route.expectedTravelTime) s") // Enumerate all Route objects let allRoutes: [Route] = navigationRoutes.allRoutes { route in route.distance < 200_000 // filter under 200 km } // Swap to an alternative route (async, re-parses all route data) if let updated = await navigationRoutes.selectingAlternativeRoute(at: 0) { mapboxNavigation.tripSession().startActiveGuidance(with: updated, startLegIndex: 0) } // Or select by AlternativeRoute value if let updated = await navigationRoutes.selecting(alternativeRoute: alternatives[0]) { mapboxNavigation.tripSession().startActiveGuidance(with: updated, startLegIndex: 0) } // Compare route sets let isSame = navigationRoutes.containsSameRoutes(as: otherRoutes) ``` -------------------------------- ### Handle Real-Time Navigation Events with NavigationController Source: https://context7.com/mapbox/mapbox-navigation-ios/llms.txt Subscribe to Combine publishers from NavigationController for location matching, route progress, rerouting, voice instructions, waypoint arrivals, and alternative routes. ```swift import MapboxNavigationCore import Combine let nav = mapboxNavigation.navigation() var cancellables = Set() // Location matching (speed, road name, map-matched position) nav.locationMatching .sink { state in print("Speed: \(state.speed) m/s") print("Road: \(state.roadName?.text ?? "unknown")") print("Enhanced location: \(state.enhancedLocation.coordinate)") } .store(in: &cancellables) // Route progress nav.routeProgress .compactMap { $0 } .sink { state in let progress = state.routeProgress print("Step: \(progress.currentLegProgress.currentStep.instructions)") print("Distance to next: \(progress.currentLegProgress.currentStepProgress.distanceRemaining) m") } .store(in: &cancellables) // Rerouting events nav.rerouting .sink { status in switch status.event { case is ReroutingStatus.Events.FetchingRoute: print("Fetching new route...") case let failed as ReroutingStatus.Events.Failed: print("Reroute failed: \(failed.error)") default: print("Rerouted successfully") } } .store(in: &cancellables) // Voice instructions nav.voiceInstructions .sink { state in print("Speak: \(state.spokenInstruction.text)") } .store(in: &cancellables) // Waypoint arrival nav.waypointsArrival .sink { status in switch status.event { case let toFinal as WaypointArrivalStatus.Events.ToFinalDestination: print("Arrived at destination: \(toFinal.destination.name ?? "")") case let toWaypoint as WaypointArrivalStatus.Events.ToWaypoint: print("Arrived at intermediate waypoint") default: break } } .store(in: &cancellables) // Alternative routes nav.continuousAlternatives .sink { status in if let updated = status.event as? AlternativesStatus.Events.Updated { print("Alternatives updated: \(updated.actualAlternativeRoutes.count) routes") } } .store(in: &cancellables) // Programmatically switch to an alternative nav.selectAlternativeRoute(at: 0) nav.switchLeg(newLegIndex: 1) ``` -------------------------------- ### Configure Info.plist for Location Usage Description Source: https://github.com/mapbox/mapbox-navigation-ios/blob/main/README.md Provide a description for location usage in your application's Info.plist. This message will be displayed to users when requesting location permissions. ```plist NSLocationWhenInUseUsageDescription Shows your location on the map and helps improve the map. ``` -------------------------------- ### Configure Info.plist for Mapbox Access Token Source: https://github.com/mapbox/mapbox-navigation-ios/blob/main/README.md Set your Mapbox API access token in your application's Info.plist file under the key MBXAccessToken. This is required for Mapbox APIs and vector tiles. ```plist MBXAccessToken YOUR_MAPBOX_ACCESS_TOKEN ``` -------------------------------- ### Basic Script Injection Source: https://github.com/mapbox/mapbox-navigation-ios/blob/main/Sources/TestHelper/Fixtures/encoding_crazy_strings.txt Demonstrates a direct attempt to inject a JavaScript alert. Use this to test basic XSS filters. ```html ``` ```html <script>alert('123');</script> ``` ```html ``` ```html ``` ```html "> ``` ```html '> ``` ```html > ``` ```html ``` ```html < / script >< script >alert(123)< / script > ``` ```html --> ``` ```html ";alert(123);t=" ';alert(123);t=' ``` -------------------------------- ### Directions.calculate(_:completionHandler:) — Low-Level Route Fetching Source: https://context7.com/mapbox/mapbox-navigation-ios/llms.txt Use the `Directions` class to directly fetch routes from the Mapbox Directions API. This method allows for detailed route options and provides a callback for handling results or errors. It also supports refreshing existing routes. ```APIDOC ## `Directions.calculate(_:completionHandler:)` — Low-Level Route Fetching The `Directions` class provides a callback-based interface to the Mapbox Directions API for cases where `RoutingProvider` is not used. ```swift import MapboxDirections let directions = Directions.shared // reads MBXAccessToken from Info.plist let origin = Waypoint(coordinate: CLLocationCoordinate2D(latitude: 38.9131, longitude: -77.0324), name: "Mapbox DC") let destination = Waypoint(coordinate: CLLocationCoordinate2D(latitude: 38.8977, longitude: -77.0365), name: "White House") let options = RouteOptions(waypoints: [origin, destination], profileIdentifier: .automobileAvoidingTraffic) options.includesSteps = true options.includesAlternativeRoutes = true options.routeShapeResolution = .full options.attributeOptions = [.congestionLevel, .speed, .expectedTravelTime] options.refreshingEnabled = true // Callback-based (returns URLSessionDataTask for cancellation) let task = directions.calculate(options) { result in switch result { case .failure(let error): print("Directions error: \(error.localizedDescription)") case .success(let response): guard let route = response.routes?.first else { return } print("Route distance: \(route.distance) m") print("ETA: \(route.expectedTravelTime) s") for leg in route.legs { print("Leg: \(leg.source?.name ?? \"\") → \(leg.destination?.name ?? \"\")") for step in leg.steps { print(" \(step.instructions) (\(step.distance) m)") } } } } // Cancel if needed task.cancel() // Route refresh (update live traffic on existing route) directions.refreshRoute( responseIdentifier: response.identifier ?? "", routeIndex: 0, fromLegAtIndex: 0 ) { credentials, result in switch result { case .success(let refreshResponse): print("Route refreshed: \(refreshResponse.route)") case .failure(let error): print("Refresh failed: \(error)") } } ``` ```