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.
Want to access the 2014 iOS streaming SDK? It is available on GitHub by clicking here.

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

Setup User Authentication

In order for the iOS SDK to control the Spotify app, they will need to authorize your app. The functionality to do this is built in and can be implemented directly inside of your AppDelegate.swift:

Implement Session Delegate

In order to handle auth, we need to add a SPTSessionManagerDelegate inside of our AppDelegate.swift:

class AppDelegate: UIResponder, UIApplicationDelegate, SPTSessionManagerDelegate {
  ...

This will require us to implement the following three methods:

func sessionManager(manager: SPTSessionManager, didInitiate session: SPTSession) {
  print("success", session)
}
func sessionManager(manager: SPTSessionManager, didFailWith error: Error) {
  print("fail", error)
}
func sessionManager(manager: SPTSessionManager, didRenew session: SPTSession) {
  print("renewed", session)
}

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
)

Setup Token Swap

The authentication process provides a refresh_token, which can be stored locally inside of your app. This can be used, along with your Client ID, Client Secret and Redirect URL, to obtain an access_token that is valid for 60 minutes.

However, as we strongly discourage the use of Client Secrets in your iOS app code, we have written two well-documented web server examples that can do this for you:

Once you have set them up, and have the tokenSwapURL and tokenRefreshURL we can set this up in our AppDelegate.swift in a class-level closure:

lazy var sessionManager: SPTSessionManager = {
  if let tokenSwapURL = URL(string: "https://[my token swap app domain]/api/token"),
     let tokenRefreshURL = URL(string: "https://[my token swap app domain]/api/refresh_token") {
    self.configuration.tokenSwapURL = tokenSwapURL
    self.configuration.tokenRefreshURL = tokenRefreshURL
    self.configuration.playURI = ""
  }
  let manager = SPTSessionManager(configuration: self.configuration, delegate: self)
  return manager
}()

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. There’s two values self.configuration.playURI accepts:

An empty value: If empty, it will resume playback of user’s last track. Example:

self.configuration.playURI = ""

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

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

Invoke Auth Modal

With SPTConfiguration and SPTSessionManager both configured, we can invoke the authorization screen:

let requestedScopes: SPTScope = [.appRemoteControl]
self.sessionManager.initiateSession(with: requestedScopes, options: .default)

Configure Auth Callback

Once a user successfully returns to your application, we’ll need to notify sessionManager about it by implementing the following method:

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
  self.sessionManager.application(app, open: url, options: options)
  return true
}

Now, when a user authorizes they should return to your application with the sessionManager(manager: SPTSessionManager, didInitiate session: SPTSession) method being successfully invoked.

Setup App Remote

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

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, SPTSessionManagerDelegate, 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.delegate = self
  return appRemote
}()

Connecting to Spotify

We’ll next need to connect to Spotify once a user successfully authenticates. This would be inside of the sessionManager(manager: SPTSessionManager, didInitiate session: SPTSession) method as follows:

func sessionManager(manager: SPTSessionManager, didInitiate session: SPTSession) {
  self.appRemote.connectionParameters.accessToken = session.accessToken
  self.appRemote.connect()
}

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()
  }
}

Having issues? You can take a look at a full example of AppDelegate.swift by clicking 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.