This tutorial leads you step-by-step through the creation of a simple app that uses the Spotify iOS SDK to play an audio track.

By using Spotify developer tools, you accept our Developer Terms of Use.

About This Tutorial

This tutorial leads you step-by-step through the creation of a simple app that uses the Spotify iOS SDK to play an audio track. We show you how to:

  • Set up an Xcode project for your app,
  • Authenticate a user,
  • Play an audio stream from Spotify. (Spotify Premium accounts only)

The app we will create is very simple. It has no storyboards, just the default views created by Xcode, and no controls other than those that belong to the authentication service. The complexities of iOS app development are beyond the scope of this tutorial; our aim is simply to help you set up your environment and project correctly and to make sure you can connect to the Spotify service. If you are new to iOS apps, we recommend Apple’s Start Developing iOS Apps Today tutorial which introduces Xcode and shows how to build and run a simple app.

We will be calling several of the iOS SDK functions in our code. Full documentation for these functions is available within the SDK’s download package on GitHub. The package also contains a Readme that contains important information about the SDK, including set-up and information for users wishing to migrate to it from CocoaLibSpotify.

Preparing Your Environment

To use the Spotify iOS SDK, the first thing you will need is a Spotify user account (Premium or Free). To get one, simply sign up at www.spotify.com. (Note, however, to complete this tutorial and play an audio stream you will require a Premium account.)

Next, if you do not already have it, download the Xcode development environment from the Apple App Store and install it using the default settings. You will need version 5 or later which requires OS X 10.9 (“Mavericks”).

Creating a New Project

Open Xcode and create a new project using the template called Single View Application.

Download the latest version of Spotify iOS SDK framework zip file from GitHub and unzip it.

Drag the unzipped Spotify.framework file into the Frameworks group in your Xcode project (create the group if it doesn’t already exist). In the import dialog, tick the box for Copy items into destinations group folder (or Destination: Copy items if needed). The iOS SDK files are now available for linking in your project.

Creating Your Client ID, Secret and Callback URI

Visit the Spotify My Applications page and log in with your Spotify credentials.

Once logged in, click the “Create an App” button, then fill in a name and description and click “Create”. On the next page, you will see your new Client ID and Client Secret. Make a note of these – they will be important later.

Before you leave this page, you also need to add a Redirect URI for your application. This Redirect URI will allow the Spotify authentication service to automatically launch your app again once the user has logged in.

Click the “Add URI” button, then enter an appropriate URI. Some things to bear in mind for an iOS App:

  • All characters in the URI should be lowercase.
  • Your URI’s prefix (the part before the first colon) must be unique to your application. It cannot be a general prefix like http.
  • Your URI’s prefix must only be used by your application for authenticating Spotify. If you already have a URL scheme handled by your application for other uses, you shouldn’t recycle it.
  • It’s a good convention to have the name of your application in there.
  • You should also have a path component to your URI (the part after the first set of forward slashes).

As an example, if your app is named “My Awesome App”, your URI might be something like my-awesome-app-login://callback or awesomeprotocol123://returnafterlogin.

Once you’ve entered your URI, click “Add” to add it, then “Save” at the bottom of the page.

Setting Up Your Build Environment

We need to link in a couple of frameworks to allow our app to work properly. To do this:

  1. Open Xcode and click on your project in the source list to the left of the main editor area.
  2. Select your application under the Targets section and go to the Build Phases tab.
  3. Expand the Link Binary With Libraries section then click the small “+” button at the bottom of the list of frameworks.
    Choosing framework in XCode
  4. In the sheet that appears, search for “AVFoundation” then click the Add button to add it to your project. Next, do the same for the “SystemConfiguration” framework.
  5. Next, we need to add your callback URL to your application’s Info.plist file so that iOS knows to launch your app when Spotify authentication is complete.
  6. Switch from the Build Phases tab to the Info tab then scroll down to the bottom and expand the URL Types section.
  7. Click the small “+” button inside URL Types and enter the first section of your Callback URI—everything before the colon—into the URL Schemes field, and an identifier (such as com.your-app.spotify-auth) into the Identifier field.
    spotify-ios-sdk-tutorial-other-linker-flags
  8. To complete the set up of your build environment, switch from the Info tab to the Build Settings tab and find the Other Linker Flags build setting (you can search for it using the search field at the top of the settings list). If you don’t see it you might need click on ‘All’ to show all build settings.
  9. Add the value -ObjC to this setting.spotify-ios-sdk-tutorial-url-scheme

Creating the Application Code

We will put all of the code for our app in the AppDelegate.m file. That is the only file we will modify in this tutorial: all other project files will be left in their default state.

Open the AppDelegate.m file and delete all the code in it; we will replace it with our own code.

We start our code by importing the header file, Spotify.h, that provides the API to the functions in the iOS SDK library, as well as the iOS standard AppDelegate.h header file:

#import <Spotify/Spotify.h>
#import "AppDelegate.h"

Tip: If you ⌘-click on “Spotify.h” in the Xcode editor area, you will see a list of the functions that it makes available; ⌘-click again on a function to see that function’s documentation.

Next we need to add two properties definitions for the session and the audio streaming controller:

@interface AppDelegate ()
@property (nonatomic, strong) SPTSession *session;
@property (nonatomic, strong) SPTAudioStreamingController *player;
@end

Now we are ready to define the launch options for the app. We use SPTAuth to first set up the Client ID and Callback URL for our App.

The Client ID is the unique identifier for our app, which you created earlier in the tutorial. The Callback URL is the address the Spotify authorization service redirects to after authenticating the user (and to which the authorization code is returned).

We then use SPTAuth again to construct a login URL, then open that URL. This will open the default browser and present the user with the Spotify authorization dialog, before calling back into your application.

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[SPTAuth defaultInstance] setClientID:@"Your-Client-Id"];
    [[SPTAuth defaultInstance] setRedirectURL:[NSURL URLWithString:@"Your-Callback-URL"]];
    [[SPTAuth defaultInstance] setRequestedScopes:@[SPTAuthStreamingScope]];

    // Construct a login URL and open it
    NSURL *loginURL = [[SPTAuth defaultInstance] loginURL];
    
    // Opening a URL in Safari close to application launch may trigger
    // an iOS bug, so we wait a bit before doing so.
    [application performSelector:@selector(openURL:)
                      withObject:loginURL afterDelay:0.1];

    return YES;
}

Next we add a method to handle the callback from the Spotify authorization service: when the user has finished the authorization process, the authorization service will switch back to your app and trigger this method. In the method we ask SPTAuth to check if the URL given is a Spotify authentication callback and, if so, we call your token swap service (see the Readme in the download package for more information on this) to get an access token. Once we have the access token, we call the -playUsingSession: method to play a track.

// Handle auth callback
-(BOOL)application:(UIApplication *)application
           openURL:(NSURL *)url
 sourceApplication:(NSString *)sourceApplication
        annotation:(id)annotation {

    // Ask SPTAuth if the URL given is a Spotify authentication callback
    if ([[SPTAuth defaultInstance] canHandleURL:url]) {
        [[SPTAuth defaultInstance] handleAuthCallbackWithTriggeredAuthURL:url callback:^(NSError *error, SPTSession *session) {

             if (error != nil) {
                 NSLog(@"*** Auth error: %@", error);
                 return;
             }

             // Call the -playUsingSession: method to play a track
             [self playUsingSession:session];
        }];
        return YES;
    }

    return NO;
}

The last section of our code creates a new track player if needed, looks up an album, then plays that album:

-(void)playUsingSession:(SPTSession *)session {
    
    // Create a new player if needed
    if (self.player == nil) {
        self.player = [[SPTAudioStreamingController alloc] initWithClientId:[SPTAuth defaultInstance].clientID];
    }
    
    [self.player loginWithSession:session callback:^(NSError *error) {
        if (error != nil) {
            NSLog(@"*** Logging in got error: %@", error);
            return;
        }

        NSURL *trackURI = [NSURL URLWithString:@"spotify:track:58s6EuEYJdlb0kO7awm3Vp"];
        [self.player playURIs:@[ trackURI ] fromIndex:0 callback:^(NSError *error) {
            if (error != nil) {
                NSLog(@"*** Starting playback got error: %@", error);
                return;
            }
        }];
    }];
}

@end

The completed code of AppDelegate.m should now look like this (but with your own client ID and URLs):

#import <Spotify/Spotify.h>
#import "AppDelegate.h"

@interface AppDelegate ()
@property (nonatomic, strong) SPTSession *session;
@property (nonatomic, strong) SPTAudioStreamingController *player;
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[SPTAuth defaultInstance] setClientID:@"Your-Client-Id"];
    [[SPTAuth defaultInstance] setRedirectURL:[NSURL URLWithString:@"Your-Callback-URL"]];
    [[SPTAuth defaultInstance] setRequestedScopes:@[SPTAuthStreamingScope]];
    
    // Construct a login URL and open it
    NSURL *loginURL = [[SPTAuth defaultInstance] loginURL];
    
    // Opening a URL in Safari close to application launch may trigger
    // an iOS bug, so we wait a bit before doing so.
    [application performSelector:@selector(openURL:)
                      withObject:loginURL afterDelay:0.1];
    return YES;
}

// Handle auth callback
-(BOOL)application:(UIApplication *)application
           openURL:(NSURL *)url
 sourceApplication:(NSString *)sourceApplication
        annotation:(id)annotation {
    
    // Ask SPTAuth if the URL given is a Spotify authentication callback
    if ([[SPTAuth defaultInstance] canHandleURL:url]) {
        [[SPTAuth defaultInstance] handleAuthCallbackWithTriggeredAuthURL:url callback:^(NSError *error, SPTSession *session) {
            
            if (error != nil) {
                NSLog(@"*** Auth error: %@", error);
                return;
            }
        
            // Call the -playUsingSession: method to play a track
            [self playUsingSession:session];
        }];
        return YES;
    }
    
    return NO;
}

-(void)playUsingSession:(SPTSession *)session {
    
    // Create a new player if needed
    if (self.player == nil) {
        self.player = [[SPTAudioStreamingController alloc] initWithClientId:[SPTAuth defaultInstance].clientID];
    }
    
    [self.player loginWithSession:session callback:^(NSError *error) {
        if (error != nil) {
            NSLog(@"*** Logging in got error: %@", error);
            return;
        }

        NSURL *trackURI = [NSURL URLWithString:@"spotify:track:58s6EuEYJdlb0kO7awm3Vp"];
        [self.player playURIs:@[ trackURI ] fromIndex:0 callback:^(NSError *error) {
            if (error != nil) {
                NSLog(@"*** Starting playback got error: %@", error);
                return;
            }
        }];
    }];
}


@end

Building and Running Your Project

Click Xcode’s Run button to build and run your app. (If prompted, enable Xcode “Developer Mode”.)

The app should start in Xcode’s iPhone simulator. If the app doesn’t start and you get build errors, check your Build Settings.)

As soon as the app starts, it starts the Safari browser and opens the Spotify authorization service login dialog.

ios-sdk

The data that the app wants to access is shown. Log in with your Spotify account ID and password and then click the button that allows the app to access the Spotify API’s. The authorization service will then redirect back to your app which immediately. The app then creates a track player and starts playback of the selected track. If you hear music playing you have completed this tutorial. (Note, if you do not hear music playing, check your volume control first!)

Download the Spotify iOS SDK from GitHub.

Feel free to experiment with the iOS SDK Beta releases and to report problems through the public issue tracker on GitHub. If you would like to give us feedback on this tutorial you can use the comment form below.

More resources for beginners