Authorisation with Spotify SDK in Swift

In this tutorial I would like to show you how to build a simple login screen using the Spotify SDK. This is based on the Getting Started tutorial on the Spotify Developer page, where all this code is written in Objective-C. However this code is not updated for iOS 9. Now lets get started.

We will start from a new project with a Single View Application template. Make sure your language is set to Swift. Once your newly created project is set up, we can download the latest Spotify SDK. At the time of writing the SDK is still in beta.

Spotify SDK @ Github

Make also sure to get the official login buttons from the Spotify SDK website. The design resources can be found here.

You can find initial setup guidance in the Beginner’s Tutorial. You can follow this guide until the Application Code section starts.

Connecting Objective-C to Swift

Because the Spotify SDK is written in Objective-C, we first need to create a connection from Objective-C to Swift. This is called a bridging header. In short, this is an Objective-C header file where you declare all the libraries you want to use in your project that don’t support Swift out of the box.

  • Add a header file called “SpotifyBridgingHeader.h” for example to your project and make sure you target it. Then add the following line of code.
  • #ifndef SpotifyBridgingHeader_h
    #define SpotifyBridgingHeader_h
    
    #import Spotify/Spotify.h
    
    #endif
    
  • Go to the Build Settings of your project and search for “Objective-C Bridging Header” and add the filename of the header file you just made.

If everything goes well, you should now be able to access all of the Spotify SDK functionality.

Programming the authentication

I assume you know how to add a button to the storyboard and perhaps modify this with the custom Spotify button. So we can skip this step to move on to the code.

import UIKit

class ViewController: UIViewController {
 
  var session: SPTSession?
  var player: SPTAudioStreamingController?
 
  let clientId = "get from developer portal"
  let callbackUrl = "spotifytutorial-login://callback"
  var loginUrl: NSURL?

  override func viewDidLoad() {
    super.viewDidLoad()
    self.setup()
  }

  @IBAction func authorize(sender: AnyObject) {
    if let url = loginUrl {
      self.openURL(url)
    }
  }
 
  func setup() {
    SPTAuth.defaultInstance().clientID = clientId
    SPTAuth.defaultInstance().redirectURL = NSURL(string: callbackUrl)
    SPTAuth.defaultInstance().requestedScopes = [SPTAuthStreamingScope] as [AnyObject]
    loginUrl = SPTAuth.defaultInstance().loginURL
 }
 
 func openURL(url: NSURL) {
    if UIApplication.sharedApplication().openURL(url) {
      if SPTAuth.defaultInstance().canHandleURL(url) {
        SPTAuth.defaultInstance().handleAuthCallbackWithTriggeredAuthURL(url, callback: {
          (error, session) in
          if error != nil {
            print("*** Auth error \(error)")
            return
          } 
          self.playUsingSession(session)
        })
      }
 }
 
 func playUsingSession(session: SPTSession) {
   if player == nil {
     player = SPTAudioStreamingController(clientId: SPTAuth.defaultInstance().clientID)
   } else {
     player?.loginWithSession(session, callback: { 
       error in 
       if error != nil { 
         print("*** Logging in got error: \(error)")
         return 
       } 

       let trackURI = NSURL(string: "spotify:track:58s6EuEYJdlb0kO7awm3Vp") 
           if let player = self.player { player.playURIs([trackURI!], withOptions: nil, callback: { 
               error in 
                   if error != nil { 
                      print("*** Starting playback got error: \(error)") 
                   } return 
           }) 
       } 
    })
   }
 }

To get this code working in iOS 9, you have to edit your Info.plist to add some changes to the AppTransportSecurity

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>cloudfront.net</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSThirdPartyExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>

Now you should be able to login with Spotify and let a song play. This tutorial is tested with a Spotify Premium account.

And that’s it for now.
Have fun!

Leave a Reply

Your email address will not be published. Required fields are marked *