> For the complete documentation index, see [llms.txt](https://docs.mapbox.com/ios/ja/navigation/llms.txt)

# 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](https://console.mapbox.com/). If you don't have an account, [sign up for free here](https://account.mapbox.com/auth/signup/).

Your account includes a [default public access token](https://docs.mapbox.com/accounts/guides/tokens/#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:

1.  From your account's [tokens page](https://console.mapbox.com/account/access-tokens/), click the **Create a token** button.
2.  From the token creation page, give your token a name and make sure the box next to the `Downloads:Read` scope is checked.
3.  Click the **Create token** button at the bottom of the page to create your token.
4.  The token you've created is a *secret token*, which means you will only have one opportunity to copy it somewhere secure.

> **Note (warning): Protect secret access tokens**
> 
> 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.

1.  In a terminal, go to your home directory.

```bash
$ cd ~
```

2.  Run `file .netrc` to check whether a `.netrc` file already exists. You will see the following message if there is no `.netrc` file:

```bash
$ file .netrc
.netrc: cannot open `.netrc' (No such file or directory)
```

3.  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:

```bash
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

**Finder**

1.  Go to your home directory: `/Users/[CurrentUser]`.

-   If you do not see the `.netrc` file, press `Command` + `Shift` + `.` (the period key).

2.  Right click on the `.netrc`.
3.  Click `Get Info`.
4.  Scroll down to `Sharing & Permissions`.
5.  Under your current username, make sure to set `Privilege` to `Read & Write`.

**Terminal**

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:

1.  Open your project's `Info.plist` file
2.  Hover over a key and click the plus button
3.  Type `MBXAccessToken` into the key field
4.  Click the value field and paste in your public access token.

> **Note: Rotating Tokens**
> 
> When you need to [rotate your access token](https://docs.mapbox.com/help/how-mapbox-works/access-tokens/), you will need to update the token value in your `Info.plist` file.

Your browser doesn't support HTML5 video. Open [link to the video](https://docs.mapbox.com/ios/ja/ios/ja/assets/medias/MapsInstallPublicToken-eb2f6fbf8715def5ae8eaa35a5b562c4.mp4).

> **Related content (guide): [Access token best practices](https://docs.mapbox.com/help/dive-deeper/private-access-token-android-and-ios/)**
> 
> 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.

**Swift Package Manager**

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

1.  Open your Xcode project or workspace, then go to **File** > **Add Package Dependencies...**.
2.  Enter `https://github.com/mapbox/mapbox-navigation-ios.git` as the URL and press `Enter` to pull in the package.
3.  Set **Dependency Rule** to **Up to Next Major Version** and enter `3.29.0` as the minimum version. Click **Add Package**.
4.  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` and `MapboxNavigationUIKit`. Click **Add Package**
5.  In your code, you can now import both packages:

```swift
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:

```swift
.package(url: "https://github.com/mapbox/mapbox-navigation-ios.git", from: "3.29.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**.

**CocoaPods**

CocoaPods support is currently in development and will be added in future versions.

> **Note (warning): Mapbox Maps SDK and Search SDK compatibility**
> 
> If you want to use the Navigation SDK with the Mapbox Maps and the Search SDKs, make sure you are using SDKs with the same sub-version number. For example if you are using v3.18.0 of the Navigation SDK, you should use v3.18.0 of the Maps SDK and use v2.18.0 of the Search SDK.
> 
> If you are using v3.16.0 of the Navigation SDK or older, review the [Navigation SDK release notes](https://github.com/mapbox/mapbox-navigation-ios/releases) to check for the correct compatible versions.

> **Related content (troubleshooting): [Running into problems installing?](https://docs.mapbox.com/help/troubleshooting/ios-sdk-installation/)**
> 
> 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:
    
    ```xml
    ...
    // highlight-start
    <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>
    // highlight-end
    ...
    ```
    
-   Add `LocationAccuracyAuthorizationDescription` as an element of the `NSLocationTemporaryUsageDescriptionDictionary` dictionary to give users a brief explanation of why a feature in your app requires their exact location:
    
    ```xml
    ...
    // highlight-start
    <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>
    // highlight-end
    ...
    ```
    

If necessary for your application, you can request permanent location access by setting `NSLocationAlwaysAndWhenInUseUsageDescription` instead of `NSLocationWhenInUseUsageDescription`

> **Note: Location tracking with the Maps SDK**
> 
> 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](https://docs.mapbox.com/ios/ja/maps/guides/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".

Your browser doesn't support HTML5 video. Open [link to the video](https://docs.mapbox.com/ios/ja/ios/ja/assets/medias/BackgroundModes-1969ba5972dc8baa0a13cbcf9891a4bf.mp4).

You can also manually edit your project's `Info.plist` source code to include `audio` and `location` as `UIBackgroundModes`:

```xml
...
// highlight-start
	<key>UIBackgroundModes</key>
	<array>
		<string>audio</string>
		<string>location</string>
	</array>
// highlight-end
...
```

## 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.

**SwiftUI**

```swift
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)
            }
        }
    }
}
```

**UIKit**

```swift
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)
            }
        }
    }
}
```

![](https://docs.mapbox.com/ios/ja/assets/ideal-img/navigation-guides-getting-started-install-hello-world.d67e4fc.480.png)

## Public examples

For further guidance on how to integrate Navigation SDK v3 into your own application, explore [our examples testbed app](https://github.com/mapbox/mapbox-navigation-ios?tab=readme-ov-file#examples).

## Use with Storyboards

To set up Mapbox Navigation in a storyboard:

-   Open the object library and drag in a new `ViewController`.
-   Set `Class` to `NavigationViewController`.
-   Set `Module` to `MapboxNavigationUIKit`.

![Storyboard view controller](https://docs.mapbox.com/ios/ja/assets/ideal-img/navigation-v3-guides-get-started-ib.e0cf1f5.480.png)

When you create a [`NavigationViewController`](https://docs.mapbox.com/ios/navigation/api/3.29.0/navigation/documentation/mapboxnavigationuikit/navigationviewcontroller/) instance from a storyboard, you need to pass a `navigationRoutes` and a `navigationOptions` to a newly created instance via [`prepareViewLoading(navigationRoutes:navigationOptions:)`](https://docs.mapbox.com/ios/navigation/api/3.29.0/navigation/documentation/mapboxnavigationuikit/navigationviewcontroller/prepareviewloading(navigationroutes:navigationoptions:)/) method.

To do that, override your `UIViewController`'s `prepare(for:sender:)`:

```swift
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
    }
}
```