-
-
Save bih/38aadb1e618623589d54902e016d32eb to your computer and use it in GitHub Desktop.
#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> |
Hi Sean, is it easy to convert to UIScene? I guess I'll have to do that 🤔.
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.")
}
}
}
}
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.
@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.
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
.
Wow this is rediculously confusing.
can we stream crossfade 2 songs at a time?if there is away please support.
Is any one trying this feature or does Spotify prevent multiple instances of players?
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?