### 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
![]()