iOS Spotify SDK — Swift 3.0+ Tutorial

Elon Rubin
6 min readFeb 16, 2017

--

Most Spotify iOS SDK tutorials either deal with Objective C or Swift 2.3 or less. This is a step by step guide to integrate iOS Spotify SDK for Swift 3.0+.

1. Create new xCode Project.

It is important that your project name not include any spaces.

2. Register app via Spotify here

  • Under your app page, under Redirect URIs, create a new redirect URI /(yourAppName)://returnAfterLogin.
  • Make sure to put in your bundle ID from your app. Get your bundle app id by clicking on your xCode project, and looking under the general tab
  • Save Client ID and Client Secret generated under my applications/settings

3. Download Spotify SDK framework here

  • Drag three frameworks to your project. Make sure to click copy to target.

4. Create bridging header

Click new file, cocoa touch class file, objective C. You can name it what ever.

Click create. You’ll then be asked to create a bridging header. Select create bridging header.

It should create a file name \(yourProjectName)-Bridging-Header.h.

Click on this file, then paste the following:

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

5. Double Check Link Binary With Libraries Include Spotify Frameworks

Under project/build phases, double check that SpotifyAuthentication, SpotifyAudioPlayback and SpotifyMetadata frameworks were added (it should have been done automatically. If not, add the three Spotify Frameworks

6. Create URL Scheme

Under Target/info, create new URL type.

Make sure to add your bundle identifier and callback URL \(yourAppName)

7. On your main storyboard, add a sign in button.

8. Add the following variables to MainViewController

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

9. Add The Following Method To MainViewController

Under client ID and redirect URL, put your client ID and redirect URL (which you saved in step 2)

10. Add An Outlet and an Action From The Login Button

@IBActionFunc loginBtnPressed(_ sender: Any) {if UIApplication.shared.openURL(loginUrl!) {if auth.canHandle(auth.redirectURL) {// To do - build in error handling}}     
}

The Spotify SDK generates an authentication URL. You then specify the application to open this url.

When a user taps on this button, it redirects to safari where a user signs in.

11. Handle return url (in App Delegate)

Now click on your app delegate. Add this variable

var auth = SPTAuth()

Add the following to application didFinishLaunchingWithOptions:

auth.redirectURL     = URL(string: "\
(yourRedirectURLhere)")
auth.sessionUserDefaultsKey = "current session"

Your App Delegate should now have this:

You now need to handle the return URL in the app delegate. Add the following function & code:

// 1
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
// 2- check if app can handle redirect URL
if auth.canHandle(auth.redirectURL) {
// 3 - handle callback in closure
auth.handleAuthCallback(withTriggeredAuthURL: url, callback: { (error, session) in
// 4- handle error
if error != nil {
print("error!")}// 5- Add session to User Defaultslet userDefaults = UserDefaults.standardlet sessionData = NSKeyedArchiver.archivedData(withRootObject: session)userDefaults.set(sessionData, forKey: "SpotifySession")userDefaults.synchronize()// 6 - Tell notification center login is successfulNotificationCenter.default.post(name: Notification.Name(rawValue: "loginSuccessfull"), object: nil)})return true}return false}
  1. This function tells the app how to handle the callback URL
  2. This checks whether your redirect URL is appropriate
  3. Handle the callback in the handleWithCallback closure,
  4. If there is an error, handle it
  5. If there is a valid session token, add to user defaults
  6. Tell notification center to fire firstLogin: method in Main view controller controller

12. Create First Login Function In Main View Controller

  1. Head back over to the MainViewController. Add to ViewDidLoad:
setup()
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.updateAfterFirstLogin)

2. Then add the following function below ViewDidLoad:

func updateAfterFirstLogin () { 
if let sessionObj:AnyObject = userDefaults.object(forKey: "SpotifySession") as AnyObject? {
let sessionDataObj = sessionObj as! Datalet firstTimeSession = NSKeyedUnarchiver.unarchiveObject(with: sessionDataObj) as! SPTSessionself.session = firstTimeSessioninitializePlayer(authSession: session)
}

3. Add this function below updateAfterFirstLogin:

func initializePlayer(authSession:SPTSession){if self.player == nil {self.player = SPTAudioStreamingController.sharedInstance()self.player!.playbackDelegate = selfself.player!.delegate = selftry! player!.start(withClientId: auth.clientID)self.player!.login(withAccessToken: authSession.accessToken)}}

There’s a lot going on here. Let’s break it down, step by step

  1. This tells the notification center to fire updateAfterFirstLogin method, which you create in the next substep
  2. Declares global session and player variables. SPTSession is the subclassed Spotify SDK session, and SPTAudioStreamingController is the SDK alternative to AVFoundation’s player
  3. This function unwraps the archived SPT session object. If it exists, it then passes this object to the initalizePlayer() function (in next step)
  4. This function is vitally important. It first checks whether the SPTAudiosStreamingController is initialized. If it isn’t, the function the initializes the player, makes the view controller its delegate, and gets the player working.

4. Paste this function in your MainViewController:

func audioStreamingDidLogin(_ audioStreaming: SPTAudioStreamingController!) {// after a user authenticates a session, the SPTAudioStreamingController is then initialized and this method calledprint("logged in")self.player?.playSpotifyURI("spotify:track:58s6EuEYJdlb0kO7awm3Vp", startingWith: 0, startingWithPosition: 0, callback: { (error) inif (error != nil) {print("playing!")}})}

The SpotifyAudioStreamingDelegate has several functions, one of which is audioDidLogin. Once the audio is logged in, it plays “True Survivor” from King Fury by David Hasselhoff

13. Run The Project

Tap login

Put in credentials for Spotify premium account

Tap open page:

If it worked, the login button will be hidden and you should hear music streaming!

Download the source code on Github here

Part II of this tutorial will go more in depth into playing songs, albums and playlists. Have any questions? Connect with me on Twitter or Linkedin.

About Elon : Elon is an iOS Developer (full stack), UI/UX designer, Product Manager, data architect, attorney and musician. He is Lead iOS Engineer for Venn (iOS, download here). He also serves as a technical advisor to AngelHack, and has founded several tech companies prior. You can connect with him on Twitter or Linkedin.

--

--

Elon Rubin

iOS Developer (full stack), Product Manager, UI/UX Designer, Data Architect, Innovator, Musician & Attorney