Get Started
Before developing your application with the Navigation SDK v3, you’ll need to configure your credentials and add the SDK as a dependency.
Part 1: Create and configure your credentials
To download and install the SDK, follow the steps below. Start by logging into your Mapbox account, then create and configure a secret access token, and lastly add your public access token to your Info.plist
.
Step 1: Log in/Sign up for a Mapbox account
Login to your Mapbox account at https://account.mapbox.com. If you don't have an account, sign up for free here.
Your account includes a default public access token, and allows you to create a secret access token for use in the installation of the SDK.
Step 2: Create a secret token
A secret access token can enable access to various products/services at Mapbox, including the ability to download an SDK. To allow download access to an SDK, follow these steps:
- From your account's tokens page, click the Create a token button.
- From the token creation page, give your token a name and make sure the box next to the
Downloads:Read
scope is checked. - Click the Create token button at the bottom of the page to create your token.
- The token you've created is a secret token, which means you will only have one opportunity to copy it somewhere secure.
Store secret tokens in secure a location, outside of your project folder to make sure unauthorized users cannot find it.
Step 3: Configure your secret token
Your secret access token is used only when downloading the SDK binaries for use in your project.
To use your secret token, you must store it in a .netrc
file in your home directory (not your project folder). This approach helps avoid accidentally exposing your secret token by keeping it out of your application's source code.
To create a .netrc
file follow these steps:
Step 3-1: Check if you have already created a .netrc
file on your computer.
- In a terminal, go to your home directory.
$cd ~
- Run
file .netrc
to check whether a.netrc
file already exists. You will see the following message if there is no.netrc
file:
$file .netrc
.netrc: cannot open `.netrc' (No such file or directory)
- If you already have a
.netrc
file, skip the next step.
Step 3-2: Create the .netrc
file.
- From the same terminal, run
touch .netrc
.
Step 3-3: Open the .netrc
file.
- From the same terminal, run
open .netrc
.
Step 3-4: Add Mapbox credentials to the .netrc
file
Add the following lines of text to your .netrc
file, replacing <INSERT SECRET ACCESS TOKEN>
with the secret access token you created in step 2:
machine api.mapbox.com
login mapbox
password <INSERT SECRET ACCESS TOKEN>
Step 3-5: Set .netrc
file permissions to Read & Write for the current user
- Go to your home directory:
/Users/[CurrentUser]
.
- If you do not see the
.netrc
file, pressCommand
+Shift
+.
(the period key).
- Right click on the
.netrc
. - Click
Get Info
. - Scroll down to
Sharing & Permissions
. - Under your current username, make sure to set
Privilege
toRead & Write
.
From the same terminal, run chmod -R 0600 .netrc
Step 4: Configure your public token
Your public access token is used in your application code when requesting Mapbox resources.
To configure your public access token, follow these steps:
- Open your project's
Info.plist
file - Hover over a key and click the plus button
- Type
MBXAccessToken
into the key field - Click the value field and paste in your public access token.
When you need to rotate your access token, you will need to update the token value in your Info.plist
file.
Learn how to keep access tokens private in mobile apps.
Part 2: Add the dependency
Currently, Mapbox provides the SDK via Swift Package Manager in the form of source code.
The Mapbox Navigation v3 can be consumed via Swift Package Manager (SPM). To add it with SPM, you will need to configure your environment to download it from Mapbox. This requires a Mapbox access token with the Downloads:Read
scope. In a previous step, you added this token to your .netrc
file.
You can add the dependency to either an application or another package.
Option 1: Add to an application
- Open your Xcode project or workspace, then go to File > Add Package Dependencies....
- Enter
https://github.com/mapbox/mapbox-navigation-ios.git
as the URL and pressEnter
to pull in the package. - Set Dependency Rule to Up to Next Major Version and enter
3.5.0
as the minimum version. Click Add Package. - In the Choose Package Products for mapbox-navigation-ios.git modal, select your project's name in the Add to Target column for both
MapboxNavigationCore
andMapboxNavigationUIKit
. Click Add Package - In your code, you can now import both packages:
import MapboxNavigationCore
import MapboxNavigationUIKit
...
Option 2: Add to an another package
To install the MapboxNavigation framework in another package rather than in an application, run swift package init
to create a Package.swift, or click File > New > Package. Then, add the following dependency:
.package(url: "https://github.com/mapbox/mapbox-navigation-ios.git", from: "3.5.0")
Notes
- If you need to update your packages, you can click on File > Swift Packages > Update To Latest Package Versions.
- Sometimes, artifacts cannot be resolved or errors can occur, in this case select File > Swift Packages > Reset Package Cache.
Read more about common installation issues in our troubleshooting guide.
Part 3: Configure Location Permissions
Users must grant your application permission before it can access information about their location. During this permission prompt, a custom string may be presented explaining how location will be used. This is specified by adding the key NSLocationWhenInUseUsageDescription
to the Info.plist
file with a value that describes why the application is requesting these permissions.
Before iOS 14, the device could only send the user's exact location. With iOS 14, users can opt into only sharing reduced-accuracy locations. Since users may toggle full-accuracy location off when initial permission for their location is requested by the app or in the System settings, developers are strongly encouraged to support reduced-accuracy locations.
Request temporary access to full-accuracy location
Certain application features may require full-accuracy locations. The SDK provides a wrapper of Apple's Core Location APIs that requests temporary access to full-accuracy locations when the user has opted out.
Make the following adjustments to your Info.plist
file to enable these prompts and provide explanations to appear within them:
- Provide users with a brief explanation of how the app will use their location data for temporary access:
Info.plist
...
<key>NSLocationWhenInUseUsageDescription</key><string>Your precise location is used to calculate turn-by-turn directions, show your location on the map, and help improve the map.</string>
... - Add
LocationAccuracyAuthorizationDescription
as an element of theNSLocationTemporaryUsageDescriptionDictionary
dictionary to give users a brief explanation of why a feature in your app requires their exact location:Info.plist...
<key>NSLocationTemporaryUsageDescriptionDictionary</key><dict><key>LocationAccuracyAuthorizationDescription</key><string>Please enable precise location. Turn-by-turn directions only work when precise location data is available.</string></dict>
...
If necessary for your application, you can request permanent location access by setting NSLocationAlwaysAndWhenInUseUsageDescription
instead of NSLocationWhenInUseUsageDescription
Maps SDK is a dependency of the Navigation SDK, you have access to additional location tracking capabilities including a protocol for handling changes in location authorization, customizing accuracy authorization handling, and custom location providers. Read more in the Maps SDK's User location guide.
Part 4: Configure Background Modes
Users expect navigation to continue to track their location and play audible instructions even while a different application is visible or the device is locked.
You can configure location and audio background modes in the Xcode user interface under Signing & Capabilities > Background Modes.
Enable “Audio, AirPlay, and Picture in Picture” and “Location updates”.
You can also manually edit your project's Info.plist
source code to include audio
and location
as UIBackgroundModes
:
...
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
<string>location</string>
</array>
...
Part 5: Add a NavigationViewController
This minimal example code creates a full screen NavigationViewController
with navigation between specified origin and destination coordinates. It includes simulated device location updates to show how the NavigationViewController
will animate the map and inform the user of upcoming turns as they navigate the route.
import CoreLocation
import SwiftUI
import MapboxDirections
import MapboxNavigationCore
import MapboxNavigationUIKit
@main
struct navApp: App {
var body: some Scene {
WindowGroup {
NavigationViewControllerRepresentable()
.edgesIgnoringSafeArea(.all)
}
}
}
struct NavigationViewControllerRepresentable: UIViewControllerRepresentable {
typealias UIViewControllerType = UIViewController
func makeUIViewController(context: Context) -> UIViewController {
let viewController = UIViewController() // Placeholder UIViewController for now
calculateRoutes { navigationViewController in
DispatchQueue.main.async {
// display the NavigationViewController
viewController.present(navigationViewController, animated: true, completion: nil)
}
}
return viewController
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
// No updates needed at this point
}
@MainActor private func calculateRoutes(completion: @escaping (NavigationViewController) -> Void) {
// create a new navigation provider using simulated device location
let mapboxNavigationProvider = MapboxNavigationProvider(
coreConfig: .init(
locationSource: .simulation() // replace with .live to use the device's location
)
)
let mapboxNavigation = mapboxNavigationProvider.mapboxNavigation
// set up navigation by specifying origin and destination coordinates
let origin = CLLocationCoordinate2DMake(37.77440680146262, -122.43539772352648)
let destination = CLLocationCoordinate2DMake(37.76556957793795, -122.42409811526268)
let options = NavigationRouteOptions(coordinates: [origin, destination])
// create the navigation request
let request = mapboxNavigation.routingProvider().calculateRoutes(options: options)
Task {
switch await request.result {
case .failure(let error):
print(error.localizedDescription)
case .success(let navigationRoutes):
// set up options for NavigationViewController
let navigationOptions = NavigationOptions(
mapboxNavigation: mapboxNavigation,
voiceController: mapboxNavigationProvider.routeVoiceController,
eventsManager: mapboxNavigationProvider.eventsManager()
)
// create the NavigationViewController, combining the returned routes and the options defined above
let navigationViewController = NavigationViewController(
navigationRoutes: navigationRoutes,
navigationOptions: navigationOptions
)
// set additional options on the NavigationViewController
navigationViewController.modalPresentationStyle = .fullScreen
// Render part of the route that has been traversed with full transparency, to give the illusion of a disappearing route.
navigationViewController.routeLineTracksTraversal = true
// Return the navigation view controller in the completion handler
completion(navigationViewController)
}
}
}
}
import CoreLocation
import Foundation
import MapboxNavigationCore
import MapboxNavigationUIKit
import UIKit
class ViewController: UIViewController {
// create a new navigation provider using simulated device location
let mapboxNavigationProvider = MapboxNavigationProvider(
coreConfig: .init(
locationSource: .simulation() // replace with .live to use the device's location
)
)
private var mapboxNavigation: MapboxNavigation {
mapboxNavigationProvider.mapboxNavigation
}
override func viewDidLoad() {
super.viewDidLoad()
// set up navigation by specifying origin and destination coordinates
let origin = CLLocationCoordinate2DMake(37.77440680146262, -122.43539772352648)
let destination = CLLocationCoordinate2DMake(37.76556957793795, -122.42409811526268)
let options = NavigationRouteOptions(coordinates: [origin, destination])
// create the navigation request
let request = mapboxNavigation.routingProvider().calculateRoutes(options: options)
// the request calls Mapbox's Directions API to get viable routes between the origin and destination
Task {
switch await request.result {
case .failure(let error):
print(error.localizedDescription)
case .success(let navigationRoutes):
// set up options for NavigationViewController
let navigationOptions = NavigationOptions(
mapboxNavigation: mapboxNavigation,
voiceController: mapboxNavigationProvider.routeVoiceController,
eventsManager: mapboxNavigationProvider.eventsManager()
)
// create the NavigationViewController, combining the returned routes and the options defined above
let navigationViewController = NavigationViewController(
navigationRoutes: navigationRoutes,
navigationOptions: navigationOptions
)
// set additional options on the NavigationViewController
navigationViewController.modalPresentationStyle = .fullScreen
// Render part of the route that has been traversed with full transparency, to give the illusion of a disappearing route.
navigationViewController.routeLineTracksTraversal = true
// display the NavigationViewController
present(navigationViewController, animated: true, completion: nil)
}
}
}
}
Public examples
For further guidance on how to integrate Navigation SDK v3 into your own application, explore our examples testbed app.
Use with Storyboards
To set up Mapbox Navigation in a storyboard:
- Open the object library and drag in a new
ViewController
. - Set
Class
toNavigationViewController
. - Set
Module
toMapboxNavigationUIKit
.
When you create a NavigationViewController
instance from a storyboard, you need to pass a navigationRoutes
and a navigationOptions
to a newly created instance via prepareViewLoading(navigationRoutes:navigationOptions:)
method.
To do that, override your UIViewController
's prepare(for:sender:)
:
var mapboxNavigationProvider = MapboxNavigationProvider(coreConfig: .init())
var routingProvider = mapboxNavigationProvider.mapboxNavigation.routingProvider()
self.navigationRoutes = try? await routingProvider.calculateRoutes(options: options).value
// Make sure to deinitialize the previous MapboxNavigationProvider instance before starting the segue.
override func prepare(for segue: UIStoryboardSegue, sender _: Any?) {
switch segue.identifier {
case "MyNavigationSegue":
if let controller = segue.destination as? NavigationViewController,
let navigationProvider = controller.mapboxNavigation as? MapboxNavigationProvider
{
let navigationOptions = NavigationOptions(
mapboxNavigation: controller.mapboxNavigation,
voiceController: navigationProvider.routeVoiceController,
eventsManager: controller.mapboxNavigation.eventsManager()
)
_ = controller.prepareViewLoading(navigationRoutes: navigationRoutes, navigationOptions: navigationOptions)
}
default:
break
}
}