On 11 September 2018, we made updates to our iOS and Android SDKs. These new SDKs work for both Spotify Free and Spotify Premium users, offer built-in offline support, and more. Read more about the updates on our blog..

Welcome! In this Quick Start, we will go through how to use the Spotify iOS SDK in your existing Xcode application to integrate:

  • Authentication (via the Spotify Accounts API) 🔒
  • Shuffle playback for Spotify Free users 🔈
  • On-demand playback for Spotify Premium users 🔈
  • Real-time player state updates 👂

You can read more about the iOS SDK in the overview, or dig into the reference documentation.

Prepare Your Environment

Register a Developer App

You’ll need to do the following in our Developer Dashboard:

  • Create a Client ID for free in our Developer Dashboard *
    • Settings: Register a Redirect URI for your new Client ID. We’ll use this to send users back to your application. For this tutorial, set this to spotify-ios-quick-start://spotify-login-callback.
    • Settings: Register your Bundle ID for your new Client ID. This is your iOS app bundle identifier, in a format similar to com.spotify.iOS-SDK-Quick-Start.

* If your app has non-commercial use, it will have an instant setup. Commercial use requires explicit approval from Spotify.

Register a Client ID from our Developer Dashboard

Install the Spotify App

Install the latest version of Spotify from the Apple App Store on the device you wish to use for this Quick Start. Run the Spotify app and be sure to login or register to Spotify on your device.

Note: You must use a physical iOS device to test the iOS SDK as the Spotify app cannot be installed on a simulator. More information on how to install apps here.

Install Spotify from the App Store

Download the iOS SDK

Download the latest version of Spotify’s iOS SDK from our GitHub repository. You’ll need to add the SpotifyiOS.framework file as a dependency in your iOS project for the next section.

Download the iOS SDK from GitHub

Setup the iOS SDK

At this point, we should have the following:

  • A registered Client ID
  • A downloaded copy of the Spotify iOS SDK
  • The latest version of the Spotify app installed on an iOS device

Next we’ll focus on installing the SDK inside of an existing Xcode application.

Import SpotifyiOS.framework

You’ll need to import the SpotifyiOS.framework. You can simply drag it into your Xcode project.

Configure Info.plist

We’ll need to configure our Info.plist to support the iOS SDK. There is two things we need to add:

  1. Add spotify to LSApplicationQueriesSchemes
  2. Add a URI Scheme in CFBundleURLTypes
1. Add spotify to LSApplicationQueriesSchemes

We’ll need this to check if the Spotify main application is installed. The LSApplicationQueriesSchemes key in Info.plist allows your application to perform this check. To set this up, add this to your Info.plist:

<key>LSApplicationQueriesSchemes</key>
<array>
  <string>spotify</string>
</array>
2. Add a URI Scheme in CFBundleURLTypes

In order for Spotify to send users back to your application, we need to set up a URI scheme in our Info.plist. To do this, we’ll need our Bundle ID and Redirect URI from earlier. From the Redirect URI, we just need the protocol (which for spotify-ios-quick-start://spotify-login-callback would be spotify-ios-quick-start).

We’ll then need to put our Bundle ID in CFBundleURLName and our Redirect URI protocol in CFBundleURLSchemes:

<key>CFBundleURLTypes</key>
<array>
  <dict>
    <key>CFBundleURLName</key>
    <string>com.spotify.iOS-SDK-Quick-Start</string>
    <key>CFBundleURLSchemes</key>
    <array>
      <string>spotify-ios-quick-start</string>
    </array>
  </dict>
</array>
Set -ObjC Linker Flag

In order to support the iOS SDK, we will need to add the -ObjC linker flag. This allows us to compile the Objective-C code that is contained within the iOS SDK.

In XCode, to add the linker flag, we need to do the following:

  • In the File Navigator, click on your project.
  • Click your project under Targets
  • Go to Build Settings
  • In the search box, enter Other Linker Flags
  • Besides Other Linker Flags, double click and enter -ObjC
Add Bridging Header

In our last step, we added the linker flag to compile Objective-C code. We’ll next need to add a bridging header next, which will allow us to include Objective-C binaries inside of our Swift app.

Typically, this is named with the [YourApp]-Bridging-Header.h convention. Xcode may generate this for you, otherwise you will need to create this in the root directory of your project.

In your newly created file, you’ll need to replace it with the following contents:

#import <SpotifyiOS/SpotifyiOS.h>

Then you’ll need to set the location of this bridging header by:

  • In the File Navigator, click on your project.
  • Click your project under Targets
  • Go to Build Settings
  • In the search box, enter Objective-C Bridging Header
  • Besides Objective-C Bridging Header, double click and enter [YourApp]-Bridging-Header.h

Set Up User Authorization

In order for the iOS SDK to control the Spotify app, they will need to authorize your app. If you need to authorize for more scopes than just controlling Spotify with App Remote please take a look at advanced auth otherwise please read on.

Instantiate SPTConfiguration

At a class-level, we can define our Client ID, Redirect URI and instantiate the SDK:

let SpotifyClientID = "[your spotify client id here]"
let SpotifyRedirectURL = URL(string: "spotify-ios-quick-start://spotify-login-callback")!

lazy var configuration = SPTConfiguration(
  clientID: SpotifyClientID,
  redirectURL: SpotifyRedirectURL
)

Configure Auth Callback

Once a user successfully returns to your application, we’ll need to the access token to the App Remote

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
  let parameters = appRemote.authorizationParameters(from: url);

        if let access_token = parameters?[SPTAppRemoteAccessTokenKey] {
            appRemote.connectionParameters.accessToken = access_token
            self.accessToken = access_token
        } else if let error_description = parameters?[SPTAppRemoteErrorDescriptionKey] {
            // Show the error
        }
  return true
}

If you are using UIScene then you need to use appropriate method in your scene delegate.

func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
    guard let url = URLContexts.first?.url else {
        return
    }

    let parameters = appRemote.authorizationParameters(from: url);

    if let access_token = parameters?[SPTAppRemoteAccessTokenKey] {
        appRemote.connectionParameters.accessToken = access_token
        self.accessToken = access_token
    } else if let error_description = parameters?[SPTAppRemoteErrorDescriptionKey] {
        // Show the error
    }
}

User authorization provides offline support. This means that a user can be authorized even if the device is currently offline. Offline support works out of the box, so it doesn’t require any additional implementation.

To successfully authorize a user while offline, the following conditions have to be met:

  • Your application has successfully connected to Spotify within the last 24 hours
  • Your application uses the same redirect URI, client ID and scopes when connecting to Spotify

Setup App Remote

With authentication implemented, we can now control the Spotify main application to play music and notify us on playback state:

Implement Remote Delegates

We’ll need to implement two delegates: SPTAppRemoteDelegate and SPTAppRemotePlayerStateDelegate. These will respectively provide connection and playback state methods to implement inside of our AppDelegate.swift:

class AppDelegate: UIResponder, UIApplicationDelegate, SPTAppRemoteDelegate, SPTAppRemotePlayerStateDelegate {
  ...

or if you are using UIScene:

class SceneDelegate: UIResponder, UIWindowSceneDelegate, SPTAppRemoteDelegate, SPTAppRemotePlayerStateDelegate
  ...

These will require us to implement the following methods:

func appRemoteDidEstablishConnection(_ appRemote: SPTAppRemote) {
  print("connected")
}
func appRemote(_ appRemote: SPTAppRemote, didDisconnectWithError error: Error?) {
  print("disconnected")
}
func appRemote(_ appRemote: SPTAppRemote, didFailConnectionAttemptWithError error: Error?) {
  print("failed")
}
func playerStateDidChange(_ playerState: SPTAppRemotePlayerState) {
  print("player state changed")
}

Initialize App Remote

We’ll next need to initialize App Remote on a class-level closure, which can take the self.configuration we defined earlier:

lazy var appRemote: SPTAppRemote = {
  let appRemote = SPTAppRemote(configuration: self.configuration, logLevel: .debug)
  appRemote.connectionParameters.accessToken = self.accessToken
  appRemote.delegate = self
  return appRemote
}()

Configure Initial Music

iOS requires us to define a playURI (as shown in the last step) in order to play music to wake up the Spotify main application. This is an iOS-specific requirement. This can be:

An empty value: If empty, it will resume playback of user’s last track or play a random track. If offline, one of the downloaded for offline tracks will play. Example:

self.playURI = ""

A valid Spotify URI: Otherwise, provide a Spotify URI. Example:

self.playURI = "spotify:track:20I6sIOMTCkB6w7ryavxtO"

Authorizing and Connecting to Spotify

We’ll next need to initiate authorization and connect to Spotify.

func connect()) {
  self.appRemote.authorizeAndPlayURI(self.playURI)
}

This, upon a successful connection, will invoke the appRemoteDidEstablishConnection(_ appRemote: SPTAppRemote) method we defined earlier.

Subscribing to state changes

We’ll need to invoke a request to subscribe to player state updates, which we can do in the appRemoteDidEstablishConnection method:

func appRemoteDidEstablishConnection(_ appRemote: SPTAppRemote) {
  // Connection was successful, you can begin issuing commands
  self.appRemote.playerAPI?.delegate = self
  self.appRemote.playerAPI?.subscribe(toPlayerState: { (result, error) in
    if let error = error {
      debugPrint(error.localizedDescription)
    }
  })
}

And inside of the playerStateDidChange, we can begin logging the output:

func playerStateDidChange(_ playerState: SPTAppRemotePlayerState) {
  debugPrint("Track name: %@", playerState.track.name)
}

Cleaning up

When the user switches from our application, we should disconnect from App Remote. We can do this by inserting the following code into our applicationWillResignActive method:

func applicationWillResignActive(_ application: UIApplication) {
  if self.appRemote.isConnected {
    self.appRemote.disconnect()
  }
}

And similarly when a user re-opens our application, we should re-connect to App Remote. We can do by inserting the following code into our applicationDidBecomeActive method:

func applicationDidBecomeActive(_ application: UIApplication) {
  if let _ = self.appRemote.connectionParameters.accessToken {
    self.appRemote.connect()
  }
}

Or if you are using UIScene:

func sceneDidBecomeActive(_ scene: UIScene) {
  if let _ = self.appRemote.connectionParameters.accessToken {
    self.appRemote.connect()
  }
    }

func sceneWillResignActive(_ scene: UIScene) {
  if self.appRemote.isConnected {
    self.appRemote.disconnect()
  }
}

Having issues? You can take a look at a full example of AppDelegate.swift by clicking here. For a SceneDelegate example click here.

Next Steps

Congratulations! You’ve interacted with the Spotify iOS SDK for the first time. Time to celebrate, you did great! 👏

Want more? Here’s what you can do next:

  • Learn about how our iOS SDK interacts with iOS in our application lifecycle guide.
  • Dive into other things you can do with the SDK in the reference documentation.
  • Be sure to check out the sample code in the Demo Projects folder included with the SDK.