Spotify SDK Integration in iOS(Swift)

Square Infosoft
6 min readJan 3, 2019

--

I am dividing this article in 3 Section:
1. Setup the iOS SDK
2. Fetch Tracks
3. Integrate Spotify Player

You’ll need login in with Spotify Developer Dashboard and Click on ‘CREATE CLIENT ID’ and fill the details and create app. Click on ‘Edit Settings’ and add ‘Redirect URIs’. Redirect url format is like ‘your_app_name://SpotifyAuthentication’ also add App bundle ID and save settings. Now Download the Spotify’s iOS SDK from our GitHub repository. You’ll need to add the SpotifyAudioPlayback.framework , SpotifyAuthentication.framework and SpotifyMetadata.framework file as a dependency in your iOS project.

Create iOS Project:

Select Single view app and click on ‘Next’
Add your product name and click on ‘Next’
add bundle id which use in Spotify Dashboard Settings screen

Now import Spotify SDK in your project. Unzip downloaded framework file and find SpotifyAudioPlayback.framework ,SpotifyAuthentication.framework and SpotifyMetadata.framework file and you can simply drag it into your Xcode project.

Select ‘copy item if needed’ and select target option

Now verify SpotifyAudioPlayback.framework , SpotifyAuthentication.framework and SpotifyMetadata.framework file is located in project directory.

Configure info.plist:
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 .

We’ll then need to put our Bundle ID in CFBundleURLName and our Redirect URI protocol in CFBundleURLSchemes:

<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string>your_bundle_id</string>
<key>CFBundleURLSchemes</key>
<array>
<string>your_app_name</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:

  1. In the File Navigator, click on your project.
  2. Click your project under Targets
  3. Go to Build Settings
  4. In the search box, enter Other Linker Flags
  5. Besides Other Linker Flags, double click and enter -ObjC

We’ll next need to add a bridging header next, which will allow us to include Objective-C binaries inside of our Swift app.

Click File > New > File and select file type header file and click on next. Typically, this is named with the your_app_name-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 <SpotifyAuthentication/SpotifyAuthentication.h>
#import <SpotifyAudioPlayback/SpotifyAudioPlayback.h>
#import <SpotifyMetadata/SpotifyMetadata.h>

Then you’ll need to set the location of this bridging header by:

  1. In the File Navigator, click on your project.
  2. Click your project under Targets
  3. Go to Build Settings
  4. In the search box, enter Objective-C Bridging Header
  5. Besides Objective-C Bridging Header, double click and enter [YourApp]-Bridging-Header.h

Now Spotify SDK setup is ready…🙂

User Authentication with Spotify in iOS(Swift)

Now Authentication with Spotify is very simple using Spotify iOS SDK. First Configure your AppDelegate class.

Add SourceApplication function in AppDelegate class. it will call while login is success and web page will redirect to your app (This topic is explain with details in next step). Here in this function have Spotify code for current user which is use for get access token from Spotify so Code is Save in User Default and Post Notification to Login class (This topic is explain with details in next step).

func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
if auth.canHandle(auth.redirectURL) {
let array = url.absoluteString.components(separatedBy: "=")
let spotifycode = array[1]
let userDefaults = UserDefaults.standard
userDefaults.set(spotifycode, forKey: "SpotifyCode")
NotificationCenter.default.post(name: Notification.Name(rawValue: "loginSuccess"), object: nil)return true
}
return false
}

Now write code in Login class so first Create SPTAuth, class Instance object and create SPTSession. Now Need Spotify Developer app clientId, clientSecret and redirectUrl which you want to get form Spotify Developer Dashboard and define in your app.

var auth = SPTAuth.defaultInstance()!
var session:SPTSession!
var loginUrl: URL?

Before start login process first initialise Spotify Authentication using client id, redirect URL and User scope like:

auth.redirectURL = URL(string: Spotify.redirectUrl)
auth.clientID = Spotify.clientId
auth.requestedScopes = [SPTAuthStreamingScope, SPTAuthPlaylistReadPrivateScope, SPTAuthPlaylistModifyPublicScope, SPTAuthPlaylistModifyPrivateScope, SPTAuthUserLibraryReadScope, SPTAuthUserFollowReadScope, SPTAuthUserReadTopScope]loginUrl = auth.spotifyWebAuthenticationURL()NotificationCenter.default.addObserver(self, selector: #selector(spotifyLogin), name: NSNotification.Name(rawValue: "loginSuccess"), object: nil)

Write above code in ViewDidLoad(). First set redirect URL and client id which get from Spotify Developer Dashboard and set user login scope for example read private data, Stream audio, read playlist, read user private data and etc. after your session is created you can got login url from auth.spotifyWebAuthenticationURL(). Login url is most important for authentication with Spotify. In above code add one Notification observer with selector ‘spotifyLogin’ function which is located in Login class. As per AppDelegate class configuration this notification post from AppDelegate while login is in progress. ‘spotifyLogin’ explain in next step.

Now open login url in web brower using below function. if you have to added ‘Login’ Button in your Controller than you can write this function in Button touch up inside Action method like:

@IBAction func onClickLoginWithSpotify(_ sender: UIButton) {
if UIApplication.shared.openURL(loginUrl!) {
if auth.canHandle(auth.redirectURL) {
// Url is automatically open in mobile default web browser
}
}
}

In web browser open Spotify Login Web Page. Enter your Spotify Account username and password and click to ‘Login’ and check your account is correct and click on ‘OKAY’ button if your account is correct. Now you can watch one dialog which have message like “Open this page in your_app_name”? and select ‘Open’ so web page is automatically redirect to your app.

As per AppDelegate class configuration call function sourceApplication and save spotify code in User Default and post notification to Login class and call ‘spotifyLogin’ function.

Now we have Spotify code but Spotify code is not useable for Streaming and Fetching tracks so need to convert code in to access token using API.

POST - https://accounts.spotify.com/api/token

Need to Pass Post Parameters in Body. In Spotify Parameter ‘Code’ from User Default which get in AppDelegate class and saved in User Default. ‘redirect_uri’, ‘client_id’ and ‘client_secret’ which is got from Spotify Developer Dashboard. ‘grant_type’ is ‘authorization_code’.

let parameters = ["code": "\(spotifyCode)",
"redirect_uri":"redirect_url",
"grant_type":"authorization_code",
"client_id":"client_id",
"client_secret":"clientSecret"]

Header:

let header = ["Content-Type":"application/x-www-form-urlencoded"]

Now call API and get ‘refresh_token’ from API JSON response and save in user default with key ‘refreshToken’. Need to renew session because Spotify access token is valid only for 24 Hour so we need to renew session after 24 hour so first we need to renew session so call API same as previous but now Post Parameters was changed:

let parameter:Parameters = ["grant_type":"refresh_token",
"refresh_token": \(refreshToken)",
"redirect_uri":"redirect_url",
"client_id":"client_id",
"client_secret":"clientSecret"]

As per above code in header ‘grant_type’ is ‘refresh_token’ so now it will return new access token, ‘refresh_token’ is which saved previously. ‘redirect_uri’, ‘client_id’ and ‘client_secret’ which is got from Spotify Developer Dashboard.

It will return new Access token with JSON key ‘access_token’ also have ‘expires_in’ token expire time so you can check token valid or not from any class in your app. ‘access_token’ is save in user default.

If session is successfully renew than call below API for get User profile details like user name, image, email or id:

GET - https://api.spotify.com/v1/me

Need to Pass access token in header as ‘Bearer’ token which is saved in user default while renew session:

let param  =  ["Accept":"application/json",
"Content-Type":"application/json",
"Authorization":"Bearer \(access_token)"]

It will return User info as per Spotify SDK Authentication Policy.

Now user connect with your app…🙂

--

--