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 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 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 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 commented Sep 16, 2019

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

@Kingamattack

This comment has been minimized.

Copy link

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 commented Oct 2, 2019

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.