Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
iOS SDK Quick Start
#import <SpotifyiOS/SpotifyiOS.h>
//
// AppDelegate.swift
// iOS SDK Quick Start
//
// Created by Spotify on 14/06/2018.
// Copyright © 2018 Spotify for Developers. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, SPTSessionManagerDelegate, SPTAppRemoteDelegate, SPTAppRemotePlayerStateDelegate {
var window: UIWindow?
let SpotifyClientID = "[your app client id here]"
let SpotifyRedirectURL = URL(string: "spotify-ios-quick-start://spotify-login-callback")!
lazy var configuration = SPTConfiguration(
clientID: SpotifyClientID,
redirectURL: SpotifyRedirectURL
)
lazy var sessionManager: SPTSessionManager = {
if let tokenSwapURL = URL(string: "https://[your token swap app domain here]/api/token"),
let tokenRefreshURL = URL(string: "https://[your token swap app domain here]/api/refresh_token") {
self.configuration.tokenSwapURL = tokenSwapURL
self.configuration.tokenRefreshURL = tokenRefreshURL
self.configuration.playURI = ""
}
let manager = SPTSessionManager(configuration: self.configuration, delegate: self)
return manager
}()
lazy var appRemote: SPTAppRemote = {
let appRemote = SPTAppRemote(configuration: configuration, logLevel: .debug)
appRemote.delegate = self
return appRemote
}()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let requestedScopes: SPTScope = [.appRemoteControl]
self.sessionManager.initiateSession(with: requestedScopes, options: .default)
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
self.sessionManager.application(app, open: url, options: options)
return true
}
func sessionManager(manager: SPTSessionManager, didInitiate session: SPTSession) {
self.appRemote.connectionParameters.accessToken = session.accessToken
self.appRemote.connect()
}
func sessionManager(manager: SPTSessionManager, didFailWith error: Error) {
print(error)
}
func sessionManager(manager: SPTSessionManager, didRenew session: SPTSession) {
print(session)
}
func appRemoteDidEstablishConnection(_ appRemote: SPTAppRemote) {
print("connected")
self.appRemote.playerAPI?.delegate = self
self.appRemote.playerAPI?.subscribe(toPlayerState: { (result, error) in
if let error = error {
debugPrint(error.localizedDescription)
}
})
// Want to play a new track?
// self.appRemote.playerAPI?.play("spotify:track:13WO20hoD72L0J13WTQWlT", callback: { (result, error) in
// if let error = error {
// print(error.localizedDescription)
// }
// })
}
func appRemote(_ appRemote: SPTAppRemote, didDisconnectWithError error: Error?) {
print("disconnected")
}
func appRemote(_ appRemote: SPTAppRemote, didFailConnectionAttemptWithError error: Error?) {
print("failed")
}
func playerStateDidChange(_ playerState: SPTAppRemotePlayerState) {
print("player state changed")
print("isPaused", playerState.isPaused)
print("track.uri", playerState.track.uri)
print("track.name", playerState.track.name)
print("track.imageIdentifier", playerState.track.imageIdentifier)
print("track.artist.name", playerState.track.artist.name)
print("track.album.name", playerState.track.album.name)
print("track.isSaved", playerState.track.isSaved)
print("playbackSpeed", playerState.playbackSpeed)
print("playbackOptions.isShuffling", playerState.playbackOptions.isShuffling)
print("playbackOptions.repeatMode", playerState.playbackOptions.repeatMode.hashValue)
print("playbackPosition", playerState.playbackPosition)
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
if self.appRemote.isConnected {
self.appRemote.disconnect()
}
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
if let _ = self.appRemote.connectionParameters.accessToken {
self.appRemote.connect()
}
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>spotify</string>
</array>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>com.spotify.iOS-SDK-Quick-Start</string>
<key>CFBundleURLSchemes</key>
<array>
<string>spotify-ios-quick-start</string>
</array>
</dict>
</array>
</dict>
</plist>
@orientalPiggy

This comment has been minimized.

Copy link

@orientalPiggy orientalPiggy commented Jan 29, 2019

cool example! Based on the appDelegate, how can I call the func playerStateDidChange in viewController file? Thanks~

@mejiagarcia

This comment has been minimized.

Copy link

@mejiagarcia mejiagarcia commented Feb 14, 2019

cool example! Based on the appDelegate, how can I call the func playerStateDidChange in viewController file? Thanks~

Maybe could be a good idea put this logic inside some kind of SpotifyManager class to handle the events from your view controllers with protocols or whatever you use.

@Alexs2424

This comment has been minimized.

Copy link

@Alexs2424 Alexs2424 commented Jun 27, 2019

This isn't working with the current version of Swift & Xcode projects. It just sits after going to the spotify app and opening back in your iOS app. None of the delegate functions are called after. Is there some sort of fix? (I deployed and created the web token service and triple checked all my ids to ensure they matched) @bih

@creaaa

This comment has been minimized.

Copy link

@creaaa creaaa commented Sep 16, 2019

It doesn't work neither (Swift5.1 GS)

@Kingamattack

This comment has been minimized.

Copy link

@Kingamattack Kingamattack commented Sep 26, 2019

Did anymore manage to make it works on iOS13/Xcode 11?
I never pass in the func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool

@kkarayannis

This comment has been minimized.

Copy link

@kkarayannis kkarayannis commented Oct 2, 2019

@creaaa @Alexs2424 @Kingamattack
Please take a look at the UIScene example

@DominicHolmes

This comment has been minimized.

Copy link

@DominicHolmes DominicHolmes commented Nov 23, 2019

@creaaa @Alexs2424 @Kingamattack
Please take a look at the UIScene example

Could you clarify why the AppDelegate version of this doesn't work? I also can't get this to work in iOS13/Xcode11, is this framework broken? Why are UIScenes required?

@DominicHolmes

This comment has been minimized.

Copy link

@DominicHolmes DominicHolmes commented Nov 23, 2019

Nevermind, got it working with that UIScene example. Y'all may want to add a note about this on your installation instructions though -- took me a while to find this thread

@marwan-at-work

This comment has been minimized.

Copy link

@marwan-at-work marwan-at-work commented Dec 3, 2019

I'm also curious why ios13 only works with SceneDelegate and not ApplicationDelegate. Thanks!

@kkarayannis

This comment has been minimized.

Copy link

@kkarayannis kkarayannis commented Dec 11, 2019

iOS 13 only calls the methods in SceneDelegate if the project is UIScene-based (the new default in Xcode 11).
If the project was created in Xcode 10 or earlier (or if you remove UIScenes manually) then iOS 13 will happily continue calling the methods in AppDelegate.

@marwan-at-work

This comment has been minimized.

Copy link

@marwan-at-work marwan-at-work commented Dec 21, 2019

@kkarayannis I got it to work with iOS11/AppDelegate using the SessionManager. However, I notice that after just a few seconds of idleness the connection between my app and Spotify is lost. Question: Is there a way to re-establish the connection without having to go to the spotify application and come back every time? appRemote.connect() fails because apparently iOS suspends the Spotify application.

@sean-williams24

This comment has been minimized.

Copy link

@sean-williams24 sean-williams24 commented Feb 24, 2020

Hey. I'm trying to setup my app using the iOS quick start guide, implementing the methods in my view controller and not the App Delegate: when calling the appRemote.authorizeAndPlayURI(self.playURI) method, it switches to Spotify, attempts to authorise - but gives me a big fat X every time and then that's that.... is someone able to let me know what I might be missing please?

@LuisMendez01

This comment has been minimized.

Copy link

@LuisMendez01 LuisMendez01 commented May 13, 2020

almost half way 2020 and this code does not work for iOS13 in the AppDelegate.swift, I am not using UIScene so it should work but nothing, every time I open the app it takes me to spotify to accept permission to use even though I already have, anyways I can't get tokens, refresh tokens, nothing I can't do anything to get past this. =/

@sean-williams24

This comment has been minimized.

Copy link

@sean-williams24 sean-williams24 commented May 13, 2020

almost half way 2020 and this code does not work for iOS13 in the AppDelegate.swift, I am not using UIScene so it should work but nothing, every time I open the app it takes me to spotify to accept permission to use even though I already have, anyways I can't get tokens, refresh tokens, nothing I can't do anything to get past this. =/

Hey Luis, I could not manage to get it working with App Delegate, when down the Scene Delegate route and its working all good - are you able to try using scene?

@LuisMendez01

This comment has been minimized.

Copy link

@LuisMendez01 LuisMendez01 commented May 13, 2020

Hi Sean, is it easy to convert to UIScene? I guess I'll have to do that 🤔.

@sean-williams24

This comment has been minimized.

Copy link

@sean-williams24 sean-williams24 commented May 13, 2020

Hi Sean, is it easy to convert to UIScene? I guess I'll have to do that 🤔.

It's doable! Basically called inititiateSession on session manager on a view controller, spotify returns an auth code to openURLContexts in SceneDelegate, then made a POST request to "https://accounts.spotify.com/api/token" with that auth code as a parameter along with spotify redirect url, client ID and secret, and that returns the access token.

 func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
        guard let url = URLContexts.first?.url else {
            return
        }
        print("scene openURLContexts called")
        
        let parameters = appRemote.authorizationParameters(from: url);
        
        if let code = parameters?["code"] {
            UserDefaults.standard.set(code, forKey: "SpotifyAuthCode")
            
            let baseURL = "https://accounts.spotify.com/api/token"
            
            AF.request(baseURL, method: .post, parameters: ["grant_type": "authorization_code", "code": code, "redirect_uri": redirectUri, "client_id": Auth.spotifyClientID, "client_secret": Auth.spotifyClientSecret], encoding: URLEncoding.default, headers: nil).response { (response) in
                
                if let data = response.data {
                    do {
                        let readableJSON = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: AnyObject]
                        let accessToken = readableJSON["access_token"] as! String
                        self.accessToken = accessToken
                        self.SpotifyConnectVC?.connectionEstablished()
                    } catch {
                        print(error)
                    }
                } else {
                    self.SpotifyConnectVC?.showAlert(title: "Connection Failed", message: "Network connection was lost during Spotify authorisation, please try again.")
                }

            }
        }
    }
@LuisMendez01

This comment has been minimized.

Copy link

@LuisMendez01 LuisMendez01 commented May 14, 2020

Hi Sean, is it easy to convert to UIScene? I guess I'll have to do that 🤔.

It's doable! Basically called inititiateSession on session manager on a view controller, spotify returns an auth code to openURLContexts in SceneDelegate, then made a POST request to "https://accounts.spotify.com/api/token" with that auth code as a parameter along with spotify redirect url, client ID and secret, and that returns the access token.

 func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
        guard let url = URLContexts.first?.url else {
            return
        }
        print("scene openURLContexts called")
        
        let parameters = appRemote.authorizationParameters(from: url);
        
        if let code = parameters?["code"] {
            UserDefaults.standard.set(code, forKey: "SpotifyAuthCode")
            
            let baseURL = "https://accounts.spotify.com/api/token"
            
            AF.request(baseURL, method: .post, parameters: ["grant_type": "authorization_code", "code": code, "redirect_uri": redirectUri, "client_id": Auth.spotifyClientID, "client_secret": Auth.spotifyClientSecret], encoding: URLEncoding.default, headers: nil).response { (response) in
                
                if let data = response.data {
                    do {
                        let readableJSON = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: AnyObject]
                        let accessToken = readableJSON["access_token"] as! String
                        self.accessToken = accessToken
                        self.SpotifyConnectVC?.connectionEstablished()
                    } catch {
                        print(error)
                    }
                } else {
                    self.SpotifyConnectVC?.showAlert(title: "Connection Failed", message: "Network connection was lost during Spotify authorisation, please try again.")
                }

            }
        }
    }

Hey Sean thanks, I got it to work, but one thing I don't understand is how to play tracks, for example I have a tableView and I select a song from one of the cells and I want this sdk to start playing the specific song ex. spotify:track:2Oehrcv4Kov0SuIgWyQY9e or spotify:track:6nDAs3PRe37fgqLfx51lBB as I'm clicking cells. Thanks in advance.

@sean-williams24

This comment has been minimized.

Copy link

@sean-williams24 sean-williams24 commented May 14, 2020

@LuisMendez01 > Hey Sean thanks, I got it to work, but one thing I don't understand is how to play tracks, for example I have a tableView and I select a song from one of the cells and I want this sdk to start playing the specific song ex. spotify:track:2Oehrcv4Kov0SuIgWyQY9e or spotify:track:6nDAs3PRe37fgqLfx51lBB as I'm clicking cells. Thanks in advance.

Thats awesome you got it going nice work. I couldn't say for sure on how to get tracks playing mate as I didn't implement that in my app but, I'd imagine its something along the lines of using the appRemote. So when a user taps a cell, call something like:

        func playTrack() {
            let playerURI = "spotify:track:6nDAs3PRe37fgqLfx51lBB"
              appRemote.playerAPI?.play(playerURI, asRadio: false, callback: { (result, error) in
                  // Handle Error
                  
                  // Result will be YES if track plays successfully
              })
        }

... each time passing in the cell's text as the player URI

If you haven't already, implement SPTAppRemotePlayerStateDelegate and set yourself as delegate in order to be notified when the the track begins to play.

@bzhoek

This comment has been minimized.

Copy link

@bzhoek bzhoek commented Jun 4, 2020

FYI: Xcode 11 will call func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any]) when you set the target back to iOS 12 or below, add var window: UIWindow? to your AppDelegate, and remove the UIApplicationSceneManifest from Info.plist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment