Skip to content

Getting Started with iOS SDK

Welcome! In this Getting Started guide, 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.

Important policy notes

Prepare Your Environment

Register a Developer App

Go to the Developer Dashboard and create an app with the following configuration values:

  • Redirect URI: Set this to spotify-ios-quick-start://spotify-login-callback. We'll use this to send users back to your application
  • Bundle ID: This is your iOS app bundle identifier, in a format similar to com.spotify.iOS-SDK-Quick-Start.
  • Which API/SDKs are you planning to use: iOS

Install the Spotify App

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

Info: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

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.

Set up 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 are two things we need to add:

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:


_10
<key>LSApplicationQueriesSchemes</key>
_10
<array>
_10
<string>spotify</string>
_10
</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:


_11
<key>CFBundleURLTypes</key>
_11
<array>
_11
<dict>
_11
<key>CFBundleURLName</key>
_11
<string>com.spotify.iOS-SDK-Quick-Start</string>
_11
<key>CFBundleURLSchemes</key>
_11
<array>
_11
<string>spotify-ios-quick-start</string>
_11
</array>
_11
</dict>
_11
</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 the last step, we added the linker flag to compile Objective-C code. Next, we need to add a bridging header, 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:


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

Instantiate SPTConfiguration

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


_10
let SpotifyClientID = "[your spotify client id here]"
_10
let SpotifyRedirectURL = URL(string: "spotify-ios-quick-start://spotify-login-callback")!
_10
_10
lazy var configuration = SPTConfiguration(
_10
clientID: SpotifyClientID,
_10
redirectURL: SpotifyRedirectURL
_10
)

Configure Auth Callback

Once a user successfully returns to your application, we'll need to the assign the access token to the appRemote connection parameters


_11
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
_11
let parameters = appRemote.authorizationParameters(from: url);
_11
_11
if let access_token = parameters?[SPTAppRemoteAccessTokenKey] {
_11
appRemote.connectionParameters.accessToken = access_token
_11
self.accessToken = access_token
_11
} else if let error_description = parameters?[SPTAppRemoteErrorDescriptionKey] {
_11
// Show the error
_11
}
_11
return true
_11
}

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


_14
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
_14
guard let url = URLContexts.first?.url else {
_14
return
_14
}
_14
_14
let parameters = appRemote.authorizationParameters(from: url);
_14
_14
if let access_token = parameters?[SPTAppRemoteAccessTokenKey] {
_14
appRemote.connectionParameters.accessToken = access_token
_14
self.accessToken = access_token
_14
} else if let error_description = parameters?[SPTAppRemoteErrorDescriptionKey] {
_14
// Show the error
_14
}
_14
}

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

Set up 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:


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

or if you are using UIScene:


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

These will require us to implement the following methods:


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

Initialize App Remote

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


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

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:


_10
self.playURI = ""

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


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

Authorizing and Connecting to Spotify

We need to initiate authorization and connect to Spotify:


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

Upon a successful connection, this 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:


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

Inside playerStateDidChange, we can begin logging the output:


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

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:


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

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:


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

Or if you are using UIScene:


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

Having issues? Take a look at a full example of AppDelegate.swift. Or check out the SceneDelegate example.

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.