Integrating Spotify IOS SDK to play an audio track’s using SPTAudioStreaming music player


Spotify is a music, podcast, and video streaming service. With Spotify, it’s easy to find the right music for every moment on our phone, our computer, our tablet and more.

There are millions of tracks on Spotify. So whether  we are working out, partying or relaxing, the right music is always at our fingertips. We can choose what we want to listen to, or let Spotify surprise us.

we can also browse through the music collections of friends, artists and celebrities, or we can create a radio station and just we can sit back.

Features Of Spotify App:

On Spotify’s apps, music can be browsed or searched for via various parameters, such as artist, album, genre, playlists, or record label. Users c0n create, edit and share playlists, share tracks on social media, and make playlists with other users. Spotify provides access to over 30 million songs.

It is a freemium service, basic features are free with advertisements or limitations, while addition0l features, such as improved streaming quality and music downloads are offered via paid subscriptions.

Spotify is available across a range of devices, including computers, phones, tablets, speakers, TVs, and cars, and you can easily transition from one to another with Spotify Connect.

Steps to Register into Spotify Account:

First we should register our details in Spotify Developerʼs Portal, to generate Client ID and Client Secret ID. Below are the steps for that.

1. Open developer.spotify.com , now we can see one window as shown below and Click on My Apps.

SpotifyAccount

 

 2. Now another window will be opened as shown below, and there click on “CHECK IT OUT”.

checkitout

 

3. Now Spotify Port0l will be opened as shown below screen shot and in that Click on “CREATE AN APP”.

createApp

 

4. Here we should fill all our project details like Application Name, Application Description, What are you building (for Mobile App or for Desktop App, or for Website..so on). and Click on “NEXT”. this window will be as shown below.

register app

 

5. Now in popup window it will ask like  “Are You Developing Commercial Integration?”  Click on “NO”. This window will be as shown below.

popup

 

6. Now another window will be opened for Terms and Conditions click on checkmarks and then Click on “SUBMIT”. This window will be as shown below.

termsConditions

7.  Now we will see one window which will be showing Client ID and Client Secret ID,  and these credentials we will use later.

Steps to Integrate Spotify:

1. Create Single View Application as shown below

createApp copy

 

2. To Integrate Spotify in our project first we should create one header file n0me as “Config”, so in Config.h file we have to give Client Id , and CallbackURL, which were generated for your Spotify account. Based on our Callback URL, once authentication completes, safari will redirects our webpage to mentioned callbackURL.

headerFile

 

Open Config.h file and place the below code.

#ifndef Simple_Track_Playback_Config_h
 #define Simple_Track_Playback_Config_h
#warning Please update these values to match the settings for your own application as these example values could change at any time.

// For an in-depth auth demo, see the "Basic Auth" demo project supplied with the SDK.

// Don't forget to add your callback URL's prefix to the URL Types section in the target's Info pane!

// Your client ID
#define kClientId “——” //Your ClentId
// Your applications callback URL
#define kCallbackURL “____://“ //Your CalbackURL
// The URL to your token swap endpoint
// If you don't provide a token swap service url the login will use implicit grant tokens, which means that your user will need to sign in again every time the token expires.
// #define kTokenSwapServiceURL "http://localhost:1234/swap"
// The URL to your token refresh endpoint
// If you don't provide a token refresh service url, the user will need to sign in again every time their token expires.
// #define kTokenRefreshServiceURL "http://localhost:1234/refresh" #define kSessionUserDefaultsKey "SpotifySession"
#endif

 

3. Click on Project Navigator —>Click on info —> Click on URL Types —> Click on “+” Symbol. Now fill Identifier field with your project Bundle Identifier and fill URL Schemes field with Callback URL.

URLSchemes

 

4. Now drag Spotify Audio Playback framework, Spotify Authentication framework and Spotify Metadata framework (These frameworks can be available from GitHub) to your project and Click on Project Navigator —> Click on Build Phases —> Open Link Binary With Libraries —> Click on + symbol and add AVFoundation.Framework and Systemconfiguration.Framework and with these check Spotifyʼs frameworks 0re added or not.

buildPhases

 

5. Now Create one view controller having button to navigate web view, which will ask the credentials for Spotify p0id user account login. So login with credentials and click on “okay” button.

Below 0re the screen shots for Spotify login.

spotifyLogin

SpotifyAuth

After Successful login, safari will redirects you to the music player view controller. So in this time we will be working with 3 view controllers which 0re 1. spotifyLoginVC 2. webViewVC 3. MusicPl0yerVC . In AppDelegate.m first we will authenticate the user b0sed on the token and after generation of token we will allowing the user to listen Spotify music . So for that Paste the code as shown below.

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customisation after application launch.
self.auth = [SPTAuth defaultInstance];
self.player = [SPTAudioStreamingController sharedInstance];
// The client ID you got from the developer site
self.auth.clientID = @kClientId;
// The redirect URL as you entered it at the developer site self.auth.redirectURL = [NSURL URLWithString:@kCallbackURL];
// 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 authorise. `SPTAuthStreamingScope` is required for playing audio.
self.auth.requestedScopes = @[SPTAuthStreamingScope];
// Become the streaming controller delegate self.player.delegate = self;
// Strt 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];
// //
NSLog(@"application openURL options is called from AppDelegate"); NSLog(@"Value of url in application openURL options: %@",url);
// If the incoming url is what we expect we handle it NSLog(@"application openURL options is called from AppDelegate"); 
NSLog(@"Value of url in application openURL options",url);

if ([self.auth canHandleURL:url]) {
// Close the authentication window [self.authViewController.presentingViewController
});
NSLog(@"the dictionary in did finish launching with options %@", launchOptions);
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; NSString* strValue = [defaults objectForKey:@"token"];
rect = [[UIScreen mainScreen] bounds];

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url
options:(NSDictionary *)options {
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; 
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
NSLog(@"Value of called back url in AppDelegate is:%@",url);
return YES;
 }

-(BOOL) application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
NSLog(@"application openURL sourceApplication annotation"); NSLog(@"scheme value is:%@",url.scheme);
NSString* myAppScheme = @___://“; //Your CallbackURL
if ([url.scheme isEqualToString: myAppScheme])
{
return YES;
}
return YES; 
}

-(void)uriArray:(NSArray *)uri {
NSLog(@"our list of uri's: %@", uri);
}

- (void)audioStreamingDidLogin:(SPTAudioStreamingController *)audioStreaming
{
SPTAuth *auth = [SPTAuth defaultInstance];
NSLog(@"Spotify session accessToken:%@",auth.session.accessToken);
NSLog(@"AppDelegate auth clientID value is:%@",auth.clientID);

}

7. So in SpotifyLoginVC create one button to redirect to web view and paste code 0s shown below


#import <SpotifyAuthentication/SpotifyAuthentication.h>
 #import <SpotifyMetadata/SpotifyMetadata.h>
#import <SpotifyAudioPlayback/SpotifyAudioPlayback.h>
 #import "Config.h"
#import “SpotifyLoginVC.h”
#import <SafariServices/SafariServices.h>
 #import <WebKit/WebKit.h>
#import "WebViewVC.h”
@interface SpotifyLoginVC ()<SFSafariViewControllerDelegate, WebViewControllerDelegate, SPTStoreControllerDelegate>
{
CGRect rect;
 }
@property (atomic, readwrite) UIViewController *authViewController;
 @property (atomic, readwrite) BOOL firstLoad;
@end
@implementation MusicViewController
#pragma mark - View Did Load - (void)viewDidLoad {
[super viewDidLoad];
rect = [[UIScreen mainScreen] bounds]; self.view.frame = rect;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sessionUpdatedNotification:) name:@"sessionUpdated" object:nil];
self.statusLabel.text = @"";
self.firstLoad = YES;
 }

- (UIViewController *)authViewControllerWithURL:(NSURL *)url {
UIViewController *viewController;
if ([SFSafariViewController class]) {
SFSafariViewController *safari = [[SFSafariViewController alloc] initWithURL:url];
safari.delegate = self; viewController = safari;
} else {
WebViewController *webView = [[WebViewController alloc]
initWithURL:url];
webView.delegate = self;
viewController = [[UINavigationController aloc]
initWithRootViewController:webView]; }
viewController.modalPresentationStyle = UIModalPresentationPageSheet; NSLog(@"viewController value is:%@",viewController);
return viewController;
}

- (void)sessionUpdatedNotification:(NSNotification *)notification {
self.statusLabel.text = @"";
SPTAuth *auth = [SPTAuth defaultInstance];
[self.presentedViewController dismissViewControllerAnimated:YES completion:nil];
if (auth.session && [auth.session isValid]) { self.statusLabel.text = @"";
[self showPlayer];
} else {
self.statusLabel.text = @"Login failed."; NSLog(@"*** Failed to log in");
} }
- (void)showPlayer {
self.firstLoad = NO;
self.statusLabel.text = @"Logged in.";
//[self performSegueWithIdentifier:@"ShowPlayer" sender:nil];
}
#pragma mark - SPTStoreControllerDelegate
- (void)productViewControllerDidFinish:(SPTStoreViewController *)viewController
{
self.statusLabel.text = @"App Store Dismissed.";
[viewController dismissViewControllerAnimated:YES completion:nil]; }
- (void)openLoginPage {
self.statusLabel.text = @"Logging in..."; 
SPTAuth *auth = [SPTAuth defaultInstance];
if ([SPTAuth supportsApplicationAuthentication]) {
NSLog(@"if openLoginPage is called");
[[UIApplication sharedApplication] openURL:[auth spotifyAppAuthenticationURL]];
} else {
NSLog(@"else openLoginPage is called");
self.authViewController = [self authViewControllerWithURL:[[SPTAuth defaultInstance] spotifyWebAuthenticationURL]];
self.definesPresentationContext = YES;
[self presentViewController:self.authViewController animated:YES completion:nil];

} }
- (void)renewTokenAndShowPlayer {
self.statusLabel.text = @"Refreshing token..."; SPTAuth *auth = [SPTAuth defaultInstance];
[auth renewSession:auth.session callback:^(NSError *error, SPTSession *session) {
auth.session = session;
if (error) {
self.statusLabel.text = @"Refreshing token failed."; NSLog(@"*** Error renewing session: %@", error); return;
}
[self showPlayer]; }];
}
#pragma mark WebViewControllerDelegate
- (void)webViewControllerDidFinish:(WebViewController *)controller {
// User tapped the close button. Treat as auth error }
#pragma mark SFSafariViewControllerDelegate
- (void)safariViewControllerDidFinish:(SFSafariViewController *)controller {
// User tapped the close button. Treat as auth error }
#pragma mark - IBActions
- (IBAction)loginClicked:(id)sender {
NSLog(@"spotify button is clicked in MusicPlayerVC”);
[self openLoginPage];
UIStoryboard* storyboard = [UIStoryboard
storyboardWithName:@"Dashboard" bundle:nil];
MusicPlayerVC*add =
[storyboard instantiateViewControllerWithIdentifier:@"MusicPlayerVC”];
[self presentViewController:add animated:YES
completion:nil];
}
- (IBAction)showSpotifyAppStoreClicked:(id)sender {
self.statusLabel.text = @"Presenting App Store...";
SPTStoreViewController *storeVC = [[SPTStoreViewController alloc] initWithCampaignToken:@"your_campaign_token"
storeDelegate:self]; [self presentViewController:storeVC animated:YES completion:nil];
}
- (IBAction)clearCookiesClicked:(id)sender {
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in [storage cookies]) {
if ([cookie.domain rangeOfString:@"spotify."].length > 0 ||
[cookie.domain rangeOfString:@"facebook."].length > 0) {
[storage deleteCookie:cookie]; }
}
[[NSUserDefaults standardUserDefaults] synchronize]; self.statusLabel.text = @"Cookies cleared.";
} @end
y. In webViewVC to 0uthentic0te user b0sed on login credenti0ls p0ste code 0s shown below.
P0ste below code in WebViewVC.h
#import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN
@protocol WebViewControllerDelegate; @interface WebViewController : UIViewController
@property (nonatomic, weak, nullable) id <WebViewControllerDelegate> delegate;
- (instancetype)initWithURL:(NSURL *)URL; 
@end
@protocol WebViewControllerDelegate <NSObject>
@optional /*! @abstract Delegate callback called when the user taps the Done button. Upon this call, the view controller is dismissed modally. */ 

- (void)webViewControllerDidFinish:(WebViewController *)controller; 
/*! @abstract Invoked when the initial URL load is complete.
 @param success YES if loading completed successfully, NO if loading failed. @discussion This method is invoked when SFSafariViewController completes the loading of the URL that you pass to its initializer. It is not invoked for any subsequent page loads in the same SFSafariViewController instance. */
 - (void)webViewController:(WebViewController *)controller didCompleteInitialLoad:(BOOL)didLoadSuccessfully; 
@end
 Paste below Code in WebViewVC.m
#import "WebViewController.h" 
#import <WebKit/WebKit.h> 
#import "MusicPlayerVC.h”
@interface WebViewController () <UIWebViewDelegate> 
@property (nonatomic, strong) UIWebView *webView; 
@property (nonatomic, copy) NSURL *initialURL;
@property (nonatomic, assign) BOOL loadComplete; @end
@implementation WebViewController
- (instancetype)initWithURL:(NSURL *)URL {
self = [super init]; if (self) {
 _initialURL = [URL copy];
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
NSURLRequest *initialRequest = [NSURLRequest requestWithURL:self.initialURL];
self.webView = [[UIWebView alloc] initWithFrame:self.view.bounds]; self.webView.delegate = self;
self.webView.autoresizingMask = UIViewAutoresizingFlexibleWidth |
UIViewAutoresizingFlexibleHeight; [self.view addSubview:self.webView];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
[self.webView loadRequest:initialRequest]; }

- (void)done {
if ([self.delegate respondsToSelector:@selector(webViewControllerDidFinish:)]) {
[self.delegate webViewControllerDidFinish:self]; }
[self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView {
if (!self.loadComplete) {
if ([self.delegate respondsToSelector:@selector(webViewController:didCompleteInitialLoad:)]) {
[self.delegate webViewController:self didCompleteInitialLoad:YES]; }
self.loadComplete = YES; }
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
if (!self.loadComplete) { if ([self.delegate
respondsToSelector:@selector(webViewController:didCompleteInitialLoad:)]) { [self.delegate webViewController:self didCompleteInitialLoad:NO];
}
self.loadComplete = YES; }
}
@end

9. After Successful login with Spotify Credentials Safari will redirects to MusicPlayerVC. Here we will play songs. So to play we have to create play/pause button, rewind button and fast forward buttons and for those we should create actions respectively.
To implement These functionalities paste the code in MusicPlayerVC.h

#import <SpotifyAuthentication/SpotifyAuthentication.h> #import <SpotifyAudioPlayback/SpotifyAudioPlayback.h> #import <SafariServices/SafariServices.h>

@protocol MusicPlayerDelegate -(void)uriArray:(NSArray*)uri;
@end
@interface MusicPlayerVC : UIViewController<SPTAudioStreamingPlaybackDelegate, SPTAudioStreamingDelegate>
@property id<MusicPlayerDelegate>delegate;
@end

Paste below Code in MusicPl0yerVC.m

#import "MusicPlayerVC.h”
#import <SpotifyAuthentication/SpotifyAuthentication.h> #import <SpotifyMetadata/SpotifyMetadata.h>
#import <AVFoundation/AVFoundation.h>
#import <SpotifyAudioPlayback/SpotifyAudioPlayback.h>
#import "AppDelegate.h" #import “SpotifyLoginVC.h"
@interface MusicPlayerViewController () <SPTAudioStreamingDelegate, SPTAudioStreamingPlaybackDelegate>
@property (weak, nonatomic) IBOutlet UILabel *trackTitle;
@property (weak, nonatomic) IBOutlet UILabel *artistTitle;
@property (weak, nonatomic) IBOutlet UIImageView *coverView; @property (weak, nonatomic) IBOutlet UIImageView *coverView2; @property (weak, nonatomic) IBOutlet UIActivityIndicatorView *spinner; @property (weak, nonatomic) IBOutlet UISlider *progressSlider; @property (weak, nonatomic) IBOutlet UILabel *playbackSourceTitle; @property (nonatomic, strong) SPTAudioStreamingController *player; @property NSMutableArray * uriArr;
@property IBOutlet UIButton* nextButton; @property IBOutlet UIButton* prevButton;
@property (nonatomic) BOOL isChangingProgress; - (IBAction)backBtn:(UIButton *)sender;
@end

@implementation MusicPlayerViewController
-(void)viewDidLoad {
[super viewDidLoad];
self.player = [SPTAudioStreamingController sharedInstance]; 
self.player.delegate = self; self.navigationController.navigationBar.hidden=YES; NSLog(@"ViewController viewDidLoad");
// self.trackTitle.text = @"Nothing Playing"; self.artistTitle.text = @"";
}

- (BOOL)prefersStatusBarHidden { 
NSLog(@"ViewController prefersStatusBarHidden"); 
return YES;
}

#pragma mark - Actions
-(IBAction)rewind:(id)sender { 
NSLog(@"ViewController rewind");
 [self.player skipPrevious:nil];
}
callback:^(NSError *error, SPTTrack *track) {
NSURL *imageURL = track.album.largestCover.imageURL; if (imageURL == nil) {
NSLog(@"Album %@ doesn't have any images!", track.album); self.coverView.image = nil;
self.coverView2.image = nil;
return;
}
// Pop over to a background queue to load the image over the
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFA ULT, 0), ^{
NSError *error = nil;
UIImage *image = nil;
NSData *imageData = [NSData
dataWithContentsOfURL:imageURL options:0 error:&error];
if (imageData != nil) {
image = [UIImage imageWithData:imageData];
}
// ...and back to the main queue to display the image. dispatch_async(dispatch_get_main_queue(), ^{
[self.spinner stopAnimating]; self.coverView.image = image; if (image == nil) {
NSLog(@"Couldn't load cover image with error: %@",
return; }
});
// Also generate a blurry version for the background
UIImage *blurred = [self applyBlurOnImage:image withRadius:
dispatch_async(dispatch_get_main_queue(), ^{ self.coverView2.image = blurred;
}); });
}]; 
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated]; NSLog(@"ViewController viewDidAppear");
[self handleNewSession]; }
-(void)handleNewSession {
NSLog(@"ViewController handleNewSession");
SPTAuth *auth = [SPTAuth defaultInstance];
NSLog(@"handleNewSession auth session accessToken: %@",auth.session.accessToken);
NSLog(@"handleNewSession auth clientID value is:%@",auth.clientID);
if (self.player == nil) {
NSError *error = nil;
self.player = [SPTAudioStreamingController sharedInstance];
if ([self.player startWithClientId:auth.clientID audioController:nil
allowCaching:YES error:&error]) { self.player.delegate = self;
self.player.playbackDelegate = self;
self.player.diskCache = [[SPTDiskCache alloc] initWithCapacity:1024 * 1024 * 64];
[self.player loginWithAccessToken:auth.session.accessToken]; } else {
self.player = nil;
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Error init" message:[error description] preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil]];
[self presentViewController:alert animated:YES completion:nil];
[self closeSession]; }
} }
//-(void)parseDataWithResponse:(NSDictionary *)response //{
// NSArray *itemsArray = [response objectForKey:@"items"];
// NSLog(@"itemsArray count is:%lu",(unsigned long)itemsArray.count);
// for (NSDictionary *dic in itemsArray)
// // // // // //}
{
NSDictionary *tracksDic = [dic objectForKey:@"tracks"]; NSString *tracksStr = [tracksDic objectForKey:@"href"]; NSLog(@"tracksStr value is:%@",tracksStr);
}
- (void)closeSession {
NSLog(@"ViewController closeSession");
NSError *error = nil;
if (![self.player stopWithError:&error]) {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Error deinit" message:[error description] preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil]];
[self presentViewController:alert animated:YES completion:nil]; }
[SPTAuth defaultInstance].session = nil;
[self.navigationController popViewControllerAnimated:YES]; }

#pragma mark - Track Player Delegates
- (void)audioStreaming:(SPTAudioStreamingController *)audioStreaming didReceiveMessage:(NSString *)message
{
NSLog(@"ViewController audioStreaming didReceiveMessage");
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Message from Spotify"
 [alertView show]; 
}
message:message delegate:nil
cancelButtonTitle:@"OK" otherButtonTitles:nil];

- (void)audioStreaming:(SPTAudioStreamingController *)audioStreaming didChangePlaybackStatus:(BOOL)isPlaying
{
NSLog(@"ViewController audioStreaming didChangePlaybackStatus");
NSLog(@"is playing = %d", isPlaying); if (isPlaying) {
[self activateAudioSession]; } else {
[self deactivateAudioSession]; }
}

-(void)audioStreaming:(SPTAudioStreamingController *)audioStreaming didChangeMetadata:(SPTPlaybackMetadata *)metadata
{
NSLog(@"ViewController audioStreaming didChangeMetadata");
[self updateUI]; }
-(void)audioStreaming:(SPTAudioStreamingController *)audioStreaming didReceivePlaybackEvent:(SpPlaybackEvent)event withName:(NSString *)name
{
NSLog(@"ViewController audioStreaming didReceivePlaybackEvent withName");
NSLog(@"didReceivePlaybackEvent: %zd %@", event, name);
NSLog(@"isPlaying=%d isRepeating=%d isShuffling=%d isActiveDevice=%d positionMs=%f",
self.player.playbackState.isPlaying, self.player.playbackState.isRepeating, self.player.playbackState.isShuffling, self.player.playbackState.isActiveDevice, self.player.playbackState.position);
}

- (void)audioStreamingDidLogout:(SPTAudioStreamingController *)audioStreaming
{
NSLog(@"ViewController audioStreamingDidLogout ");
[self closeSession]; }

- (void)audioStreaming:(SPTAudioStreamingController *)audioStreaming didReceiveError:(NSError* )error
{
NSLog(@"ViewController audioStreaming didReceiveError");
NSLog(@"didReceiveError: %zd %@", error.code, error.localizedDescription);
if (error.code == SPErrorNeedsPremium) { UIAlertController *alert = [UIAlertController
alertControllerWithTitle:@"Premium account required" message:@"Premium account is required to showcase application functionality. Please login using premium account." preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction* action) {
[self closeSession]; }]];
[self presentViewController:alert animated:YES completion:nil];
} }
- (void)audioStreaming:(SPTAudioStreamingController *)audioStreaming didChangePosition:(NSTimeInterval)position
{
//NSLog(@"ViewController audioStreaming didChangePosition");
if (self.isChangingProgress) {
return; }
self.progressSlider.value = position/ self.player.metadata.currentTrack.duration;
}
- (void)audioStreaming:(SPTAudioStreamingController *)audioStreaming didStartPlayingTrack:(NSString *)trackUri
{
NSLog(@"ViewController audioStreaming didStartPlayingTrack");
NSLog(@"Starting %@", trackUri);
NSLog(@"Source %@", self.player.metadata.currentTrack.playbackSourceUri);
// If context is a single track and the uri of the actual track being played is different
// than we can assume that relink has happend
BOOL isRelinked = [self.player.metadata.currentTrack.playbackSourceUri containsString: @"spotify:track"]
&& ![self.player.metadata.currentTrack.playbackSourceUri isEqualToString:trackUri];
NSLog(@"Relinked %d", isRelinked); }
- (void)audioStreaming:(SPTAudioStreamingController *)audioStreaming didStopPlayingTrack:(NSString *)trackUri
{
NSLog(@"ViewController audioStreaming didStopPlayingTrack");
NSLog(@"Finishing: %@", trackUri); }
#pragma mark - Audio Session
- (void)activateAudioSession {
NSLog(@"ViewController activateAudioSession");
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
error:nil];
[[AVAudioSession sharedInstance] setActive:YES error:nil];
}
- (void)deactivateAudioSession {
NSLog(@"ViewController deactivateAudioSession");
[[AVAudioSession sharedInstance] setActive:NO error:nil]; }
@end

10. Now we can enjoy the music of Spotify, and the screen will be as shown below.

player