Create a simple app that uses the Spotify iOS SDK to play an audio track.

Note: By using Spotify developer tools, you accept our Developer Terms of Service.

Creating a Simple App

The app you create here is very simple:

  • No storyboards, just the default views created by Xcode.
  • 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 with this simple app is to help you setup your environment and project correctly and to make sure you can connect to the Spotify service.

If you are new to iOS apps, see Apple’s Start Developing iOS Apps Today tutorial, which introduces Xcode and shows how to build and run a simple app.

If you are experienced with iOS applications, download the Spotify iOS SDK.

To create this simple app, we call several of the iOS SDK functions in our code. Find the detailed documentation for these functions within the SDK download package on GitHub. The package also contains a Readme file that contains important information about the SDK, including setup and information for users who want to migrate to it from CocoaLibSpotify.

To Create an Application:

  1. Register your app.
  2. Prepare your environment.
  3. Create the app.
  4. Test your app by playing an audio stream from Spotify.

Prepare Your Environment

  1. Create an account (Premium or Free) on www.spotify.com.

    Note: To complete this tutorial and play an audio stream you need a Premium account.

  2. Download the Xcode development environment from the Apple App Store and install it using the default settings. Make sure you download version 5 or newer, which requires OS X 10.9 (“Mavericks”).

Create the App

Create an Xcode Project

  1. Open Xcode and create a new project using the Single View Application template.
  2. Download the latest version of Spotify iOS SDK zip file from GitHub and unzip it.
  3. Drag the unzipped SpotifyAudioPlayback.framework and SpotifyAuthentication.framework into the Frameworks group in your Xcode project; create the group if it is not already there.
  4. In the import dialog, select either Copy items into destinations group folder or Destination: Copy items if needed; the iOS SDK files are now available for linking in your project.

Set Up Your Build Environment

Start by linking in a couple of frameworks:

  1. In Xcode, in the left pane, click your project.
  2. Expand the Targets pane, select your application, and click the Build Phases tab.
  3. Expand the Link Binary With Libraries section. At the bottom of the list of frameworks, click +. xcode choose framework
  4. In the view that opens, search for AVFoundation.framework and Add it to your project. Repeat with SystemConfiguration.framework.
  5. In order for iOS to launch your app when the Spotify authentication is complete, add your Redirect URL to your application Info.plist file:
    1. Switch your view from the Build Phases tab to the Info tab. Scroll down to the bottom and expand the URL Types section.
    2. Enter an identifier, such as com.your-app.spotify-auth, and paste them into the Identifier field. In URL Types click + and enter the first section of your Callback URI into the URL Schemes field. Be sure to copy all the characters preceding the colon. xcode other linker flags
  6. To complete the setup of your build environment, switch from the Info tab to the Build Settings tab and find the Other Linker Flags build setting. Search for it using the search field at the top of the settings list. If you do not see it, try clicking All to show all build settings.

  7. Add the value -ObjC to this setting, both in Debug and in Release. xcode url scheme

Write the Application Code

  1. Open the AppDelegate.h file. To provide the API to the functions in the iOS SDK library, import the header files SpotifyAuthentication.h and SpotifyAudioPlayback.h, after the UIKit import:
      #import <SpotifyAuthentication/SpotifyAuthentication.h>
      #import <SpotifyAudioPlayback/SpotifyAudioPlayback.h>
      #import <SafariServices/SafariServices.h>
    

    Tip: To see a list of the functions that a header file makes available, ⌘-click the file name in the Xcode editor area. In the functions list ⌘-click a function to see its documentation.

  2. To receive callbacks from the iOS SDK, such as when SDK is logged in and ready to be used, add the SPTAudioStreamingDelegate protocol to the AppDelegate class. @interface AppDelegate : UIResponder <UIApplicationDelegate, SPTAudioStreamingDelegate>

  3. Open the AppDelegate.m file and delete all the code between @implementation and @end. Your file should look like the following:
     #import "AppDelegate.h"
    
     @interface AppDelegate ()
     @end
    
     @implementation AppDelegate
     @end
    
  4. Add the following property definitions for the Auth session and for the audio streaming controller:
     @interface AppDelegate ()
     @property (nonatomic, strong) SPTAuth *auth;
     @property (nonatomic, strong) SPTAudioStreamingController *player;
     @property (nonatomic, strong) UIViewController *authViewController;
     @end
    
  5. Use the code below to define the launch options for the app:

    With SPTAuth we set up the Client ID and Redirect URL for our App. Client ID is the unique identifier for the app. Redirect URL is the address to which Spotify authorization service redirects after authenticating the user, and also the address to which the authorization code is returned. SPTAuth is used again. This time, to construct a login URL, and to open that URL. This opens the default browser and presents the user with the Spotify authorization dialog, before calling back into the application.

    @implementation AppDelegate

     - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
         self.auth = [SPTAuth defaultInstance];
         self.player = [SPTAudioStreamingController sharedInstance];
         // The client ID you got from the developer site
         self.auth.clientID = @"Your-Client-Id";
         // The redirect URL as you entered it at the developer site
         self.auth.redirectURL = [NSURL URLWithString:@"Your-Callback-URL"];
         // Setting the `sessionUserDefaultsKey` enables SPTAuth to automatically store the session object for future use.
         self.auth.sessionUserDefaultsKey = @"current session";
         // Set the scopes you need the user to authorize. `SPTAuthStreamingScope` is required for playing audio.
         self.auth.requestedScopes = @[SPTAuthStreamingScope];
    
         // Become the streaming controller delegate
         self.player.delegate = self;
    
         // Start up the streaming controller.
         NSError *audioStreamingInitError;
         if (![self.player startWithClientId:self.auth.clientID error:&audioStreamingInitError]) {
               NSLog(@"There was a problem starting the Spotify SDK: %@", audioStreamingInitError.description);
         }
            
         // Start authenticating when the app is finished launching
         dispatch_async(dispatch_get_main_queue(), ^{
             [self startAuthenticationFlow];
         });
    
         return YES;
     }
    
  6. Use the following code to create the -startAuthenticationFlow: function that checks if the token is. If it is not, this procedure opens a request in a SFSafariViewController.

     - (void)startAuthenticationFlow
     {
       // Check if we could use the access token we already have
       if ([self.auth.session isValid]) {
         // Use it to log in
         [self.player loginWithAccessToken:self.auth.session.accessToken];
       } else {
         // Get the URL to the Spotify authorization portal
         NSURL *authURL = [self.auth spotifyWebAuthenticationURL];
         // Present in a SafariViewController
         self.authViewController = [[SFSafariViewController alloc] initWithURL:authURL];
         [self.window.rootViewController presentViewController:self.authViewController animated:YES completion:nil];
       }
     }
    
  7. Add a method to handle the callback from the Spotify authorization service.

    When the user has finished the authorization process, the authorization service closes the SFSafariViewController and triggers this method. In the method SPTAuth checks if the provided URL is a Spotify authentication callback. If so, to get an access token, the procedure calls the token swap service (see the Readme in the download package). When the access token is generated, this procedure calls -loginWithAccessToken: to login the player.

     // Handle auth callback
     - (BOOL)application:(UIApplication *)app
                 openURL:(NSURL *)url
                 options:(NSDictionary *)options
     {
         // If the incoming url is what we expect we handle it
         if ([self.auth canHandleURL:url]) {
             // Close the authentication window
             [self.authViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
             self.authViewController = nil;
             // Parse the incoming url to a session object
             [self.auth handleAuthCallbackWithTriggeredAuthURL:url callback:^(NSError *error, SPTSession *session) {
                 if (session) {
                     // login to the player
                     [self.player loginWithAccessToken:self.auth.session.accessToken];
                 }
             }];
             return YES;
         }
         return NO;
     }
    
  8. Lastly, this procedure is called when the SDK is logged into. This procedure takes a track URI and plays it. Tracks are specified with their Spotify URI. You can use the Web API Search Endpoint to search the URI of tracks, albums, and artists in the Spotify catalog. In this app example, use the track True Survivor (From “Kung Fury”) by David Hasselhoff, which track URI is: spotify:track:58s6EuEYJdlb0kO7awm3Vp.

       - (void)audioStreamingDidLogin:(SPTAudioStreamingController *)audioStreaming {
           [self.player playSpotifyURI:@"spotify:track:58s6EuEYJdlb0kO7awm3Vp" startingWithIndex:0 startingWithPosition:0 callback:^(NSError *error) {
               if (error != nil) {
                   NSLog(@"*** failed to play: %@", error);
                   return;
               }
           }];
       }
    
       @end
    

    AppDelegate.h should now look like this:

     #import <UIKit/UIKit.h>
    
    
     #import <UIKit/UIKit.h>
     #import <SpotifyAuthentication/SpotifyAuthentication.h>
     #import <SpotifyAudioPlayback/SpotifyAudioPlayback.h>
     #import <SafariServices/SafariServices.h>
    
     @interface AppDelegate : UIResponder <UIApplicationDelegate, SPTAudioStreamingDelegate>
    
     @property (strong, nonatomic) UIWindow *window;
    
     @end
    

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

     #import "AppDelegate.h"
    
     @interface AppDelegate ()
     @property (nonatomic, strong) SPTAuth *auth;
     @property (nonatomic, strong) SPTAudioStreamingController *player;
     @property (nonatomic, strong) UIViewController *authViewController;
     @end
    
     @implementation AppDelegate
    
     - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
     {
         self.auth = [SPTAuth defaultInstance];
         self.player = [SPTAudioStreamingController sharedInstance];
    
         // The client ID you got from the developer site
         self.auth.clientID = @"Your-Client-Id";
         // The redirect URL as you entered it at the developer site
         self.auth.redirectURL = [NSURL URLWithString:@"Your-Callback-URL"];
         // Setting the `sessionUserDefaultsKey` enables SPTAuth to automatically store the session object for future use.
         self.auth.sessionUserDefaultsKey = @"current session";
         // Set the scopes you need the user to authorize. `SPTAuthStreamingScope` is required for playing audio.
         self.auth.requestedScopes = @[SPTAuthStreamingScope];
    
         // Become the streaming controller delegate
         self.player.delegate = self;
    
         // Start up the streaming controller.
         NSError *audioStreamingInitError;
         NSAssert([self.player startWithClientId:self.auth.clientID error:&audioStreamingInitError],
                  @"There was a problem starting the Spotify SDK: %@", audioStreamingInitError.description);
    
         // Start authenticating when the app is finished launching
         dispatch_async(dispatch_get_main_queue(), ^{
             [self startAuthenticationFlow];
         });
    
         return YES;
     }
    
     - (void)startAuthenticationFlow
     {
         // Check if we could use the access token we already have
         if ([self.auth.session isValid]) {
             // Use it to log in
             [self.player loginWithAccessToken:self.auth.session.accessToken];
         } else {
             // Get the URL to the Spotify authorization portal
             NSURL *authURL = [self.auth spotifyWebAuthenticationURL];
             // Present in a SafariViewController
             self.authViewController = [[SFSafariViewController alloc] initWithURL:authURL];
             [self.window.rootViewController presentViewController:self.authViewController animated:YES completion:nil];
         }
     }
    
     - (BOOL)application:(UIApplication *)app
                 openURL:(NSURL *)url
                 options:(NSDictionary *)options
     {
         // If the incoming url is what we expect we handle it
         if ([self.auth canHandleURL:url]) {
             // Close the authentication window
             [self.authViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
             self.authViewController = nil;
             // Parse the incoming url to a session object
             [self.auth handleAuthCallbackWithTriggeredAuthURL:url callback:^(NSError *error, SPTSession *session) {
                 if (session) {
                     // login to the player
                     [self.player loginWithAccessToken:self.auth.session.accessToken];
                 }
             }];
             return YES;
         }
         return NO;
     }
    
     - (void)audioStreamingDidLogin:(SPTAudioStreamingController *)audioStreaming
     {
         [self.player playSpotifyURI:@"spotify:track:58s6EuEYJdlb0kO7awm3Vp" startingWithIndex:0 startingWithPosition:0 callback:^(NSError *error) {
             if (error != nil) {
                 NSLog(@"*** failed to play: %@", error);
                 return;
             }
         }];
     }
    
     @end
    

Build and Run Your Project

To build and run your app, in Xcode click Run. If prompted, enable the Xcode Developer Mode; the app should start in the Xcode iPhone simulator. If the app does not start and you get build error messages, check your Build Settings.

Test Playback

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

The data that the app is about to access appears on your screen:

  1. Log in with your Spotify account ID and password.

    Note: This test works only with a Spotify Premium account.

  2. To allow the app to access the Spotify API, click OKAY; the authorization service redirects your view back to your app immediately. The app 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.

Feel free to experiment with the iOS SDK Beta releases and to report problems through the public issue tracker on GitHub.

More Resources for Beginners

Support

Report a bug/Request a Feature on GitHub Get programming help on Stack Overflow (tag: Spotify)