Keep access tokens private in open source iOS apps

    An app using the Mapbox Maps SDK for iOS must provide an access token to display Mapbox-hosted maps. If the app’s source code is made public, for example on GitHub, you should rotate your access token regularly to prevent abuse by other developers. You can go one step further by keeping your access token out of the project’s repository entirely:

    1. Create a new plain text file containing your access token, named either .mapbox or mapbox. To avoid accidentally committing this file to an open-source project, either you can save it to a location outside your project's version-controlled directory, or you can add this file to your project’s .gitignore file.
    2. Open your project in Xcode. In the project editor, go to the Build Phases tab, then click the + button to add a new Run Script phase to the end.
    3. Customize the Run Script build phase to run the following code (replacing ~/.mapbox or ~/mapbox with the path to the file you added in step 1):

      # Look for a global file named 'mapbox' or '.mapbox' within the home directory
      token="$(cat $token_file 2>/dev/null || cat $token_file2 2>/dev/null)"
      if [ "$token" ]; then
        plutil -replace MGLMapboxAccessToken -string $token "$TARGET_BUILD_DIR/$INFOPLIST_PATH"
        echo 'warning: Missing Mapbox access token'
        open ''
        echo "warning: Get an access token from <>, then create a new file at $token_file or $token_file2 that contains the access token."
    4. Add $(TARGET_BUILD_DIR)/$(INFOPLIST_PATH) to the build phase’s Input Files section. Otherwise, the access token may be overridden during incremental builds. Optionally, you can also add ~/.mapbox or ~/mapbox to this section, so that Xcode will automatically update Info.plist after you change your access token.

    When building the project in Xcode, the access token will be inserted into the Info.plist inside your built app, but not into the Info.plist that you’d commit.