Spotify iOS 框架可讓您的應用程式與在使用者裝置後台執行的 Spotify 應用程式互動。功能包括授權、獲取當前播放曲目和上下文的元資料以及發出播放命令。
請注意:使用 Spotify 開發者工具即表示您接受我們的開發者使用條款。
Spotify iOS SDK 是一組輕量級對象,可與 Spotify 應用程式連接並讓您控制它,同時將所有繁重的播放工作卸載到 Spotify 應用程式本身。 Spotify 應用程式負責播放、網路、離線快取和作業系統音樂集成,讓您可以專注於使用者體驗。從您的應用程式遷移到 Spotify 應用程式(反之亦然)是一種簡化的體驗,播放和元資料始終保持同步。
主要特點
提交錯誤
成分
應用程式遠端通話如何運作?
使用條款
教學
常見問題解答
我們喜歡來自開發者社群的回饋,因此請隨時在我們的問題追蹤器上提交缺少的功能或錯誤。確保在建立新問題之前搜尋現有問題。
開啟錯誤票 |開啟功能請求
Spotify iOS 框架需要 iOS 12 或更高版本的部署目標。 SDK 支援以下架構:
SPTAppRemoteAlbum
SPTAppRemoteArtist
SPTAppRemoteLibraryState
SPTAppRemotePlaybackRestrictions
SPTAppRemotePlaybackOptions
SPTAppRemotePlayerState
SPTAppRemoteTrack
SPTAppRemoteContentItem
SPTAppRemoteUserCapabilities
SPTAppRemoteImageRepresentable
SPTConfiguration
連接 Spotify 應用程式並檢索 API 元件的主要入口點。使用它來建立、監視和終止連線。
發送播放相關指令如:
取得SPTAppRemoteImageRepresentable
的圖像
取得/訂閱/設定用戶相關數據,例如:
SPTAppRemoteUserCapabilities
為用戶獲取推薦內容。
當您與任何 App Remote API 互動時,您會傳入一個SPTAppRemoteCallback
區塊,如果操作失敗,該區塊將透過預期結果項目或NSError
來呼叫。 Spotify 應用程式收到命令後(或無法建立連線)會觸發該封鎖。
以下是使用SPTRemotePlayerAPI
跳過歌曲的範例:
[appRemote.playerAPI skipToNext: ^( id _Nullable result, NSError * _Nullable error) {
if (error) {
// Operation failed
} else {
// Operation succeeded
}
}];
我們在 DemoProjects 資料夾中提供了一些範例專案來幫助您開始使用 iOS 框架。有關每個範例的用途的更多信息,請參閱 DemoProjects 資料夾中的自述文件。
要與 Spotify 應用程式通信,您的應用程式需要先使用 App Remote 的內建授權來獲得使用者的控製播放權限。為此,您需要在連接到 Spotify 時請求授權視圖。如果使用者尚未同意,框架將自動請求app-remote-control
範圍並顯示 auth 視圖。
請注意,使用 Spotify 開發者工具即表示您接受我們的開發者使用條款。
本教學將引導您逐步創建一個簡單的應用程序,該應用程式使用 Spotify iOS SDK 來播放音軌並訂閱播放器狀態。它將逐步完成授權流程。
請按照以下步驟確保您準備好開始編碼。
將 SpotifyiOS 套件新增到您的專案中。您可以透過 Swift Package Manager (SPM) 來完成此操作,也可以直接將SpotifyiOS.xcframework
新增至 Xcode 專案來完成此操作。
在您的 info.plist 中新增您在「我的應用程式」中註冊的重定向 URI。您需要在「URL 類型」和「URL 方案」下新增重定向 URI。請務必設定唯一的「URL 識別碼」。
將庫新增到您的來源檔案中。
迅速
import SpotifyiOS
Objective-c
# import < SpotifyiOS/SpotifyiOS.h >
為了能夠使用 SDK 的播放控制部分,使用者需要授權您的應用程式。如果沒有,連線將失敗並出現No token provided
錯誤。要允許使用者授權您的應用程序,您可以使用內建授權流程。
使用您的客戶端 ID 和重定向 URI 初始化SPTConfiguration
。
迅速
let configuration = SPTConfiguration (
clientID : " YOUR_CLIENT_ID " ,
redirectURL : URL ( string : " your_redirect_uri " ) !
)
Objective-c
SPTConfiguration *configuration = [[SPTConfiguration alloc ] initWithClientID: @" your_client_id "
redirectURL: [ NSURL URLWithString: @" your_redirect_uri " ]];
使用您的SPTConfiguration
初始化SPTAppRemote
迅速
self . appRemote = SPTAppRemote ( configuration : configuration , logLevel : . debug )
Objective-c
self.appRemote = [[SPTAppRemote alloc ] initWithConfiguration: configuration logLevel: SPTAppRemoteLogLevelDebug];
啟動身份驗證流程(有關檢測 Spotify 是否已安裝以及歸因安裝的其他方法,請參閱我們的內容連結指南)。
迅速
// Note: A blank string will play the user's last song or pick a random one.
self . appRemote . authorizeAndPlayURI ( " spotify:track:69bp2EbF7Q2rqc5N3ylezZ " ) { spotifyInstalled in
if !spotifyInstalled {
/*
* The Spotify app is not installed.
* Use SKStoreProductViewController with [SPTAppRemote spotifyItunesItemIdentifier] to present the user
* with a way to install the Spotify app.
*/
}
}
Objective-c
// Note: A blank string will play the user's last song or pick a random one.
[ self .appRemote authorizeAndPlayURI: @" spotify:track:69bp2EbF7Q2rqc5N3ylezZ " completionHandler: ^( BOOL spotifyInstalled) {
if (!spotifyInstalled) {
/*
* The Spotify app is not installed.
* Use SKStoreProductViewController with [SPTAppRemote spotifyItunesItemIdentifier] to present the user
* with a way to install the Spotify app.
*/
}
}];
設定您的AppDelegate
以解析application:openURL:options:
中的 accessToken 並將其設定在SPTAppRemote
連接參數上。
Objective-c
- ( BOOL )application:(UIApplication *)app openURL:( NSURL *)url options:( NSDictionary <UIApplicationOpenURLOptionsKey, id > *)options
{
NSDictionary *params = [ self .appRemote authorizationParametersFromURL: url];
NSString *token = params[SPTAppRemoteAccessTokenKey];
if (token) {
self. appRemote . connectionParameters . accessToken = token;
} else if (params[SPTAppRemoteErrorDescriptionKey]) {
NSLog ( @" %@ " , params[SPTAppRemoteErrorDescriptionKey]);
}
return YES ;
}
如果您使用 UIScene,那麼您需要在場景委託中使用適當的方法。
迅速
func scene ( _ scene : UIScene , openURLContexts URLContexts : Set < UIOpenURLContext > ) {
guard let url = URLContexts . first ? . url else {
return
}
let parameters = appRemote . authorizationParameters ( from : url ) ;
if let access_token = parameters ? [ SPTAppRemoteAccessTokenKey ] {
appRemote . connectionParameters . accessToken = access_token
self . accessToken = access_token
} else if let error_description = parameters ? [ SPTAppRemoteErrorDescriptionKey ] {
// Show the error
}
}
設定您的連線委託並嘗試連線。
迅速
self . appRemote . delegate = self
self . appRemote . connect ( )
// MARK: AppRemoteDelegate
func appRemoteDidEstablishConnection ( _ appRemote : SPTAppRemote ) {
// Connection was successful, you can begin issuing commands
}
func appRemote ( _ appRemote : SPTAppRemote , didFailConnectionAttemptWithError error : Error ? ) {
// Connection failed
}
func appRemote ( _ appRemote : SPTAppRemote , didDisconnectWithError error : Error ? ) {
// Connection disconnected
}
Objective-c
self.appRemote.delegate = self;
[ self .appRemote connect ];
- ( void )appRemoteDidEstablishConnection:(SPTAppRemote *)appRemote
{
// Connection was successful, you can begin issuing commands
}
- ( void )appRemote:(SPTAppRemote *)appRemote didFailConnectionAttemptWithError:( NSError *)error
{
// Connection failed
}
- ( void )appRemote:(SPTAppRemote *)appRemote didDisconnectWithError:(nullable NSError *)error
{
// Connection disconnected
}
設定委託並訂閱玩家狀態:
迅速
self . appRemote . playerAPI ? . delegate = self
appRemote . playerAPI ? . subscribe ( toPlayerState : { result , error in
// Handle Errors
} )
// MARK: SPTAppRemotePlayerStateDelegate
func playerStateDidChange ( _ playerState : SPTAppRemotePlayerState ) {
print ( " track name ( playerState . track . name ) " )
}
Objective-c
appRemote.playerAPI.delegate = self;
[appRemote.playerAPI subscribeToPlayerState: ^( id _Nullable result, NSError * _Nullable error) {
// Handle Errors
}];
- ( void )playerStateDidChange:( id <SPTAppRemotePlayerState>)playerState
{
NSLog ( @" Track name: %@ " , playerState. track . name );
}
出於禮貌,當您的應用程式進入背景狀態時,您應該始終斷開 App Remote 的連線。這告訴 Spotify 禁用活動串流是安全的。如果您的應用程式未正確呼叫斷開連接,Spotify 將無法知道它不應維持連接,這可能會導致將來出現連接問題。
如果您希望應用程式在來電或 Siri 互動等中斷事件發生後自動重新連接,您可以使用willResignActive
和didBecomeActive
回呼來安全地斷開連接和重新連接。如果您不希望直接重新連接,通常只需在didEnterBackground
回呼中關閉連線即可。
迅速
func sceneWillResignActive ( _ scene : UIScene ) {
self . appRemote . disconnect ( )
}
func sceneDidBecomeActive ( _ scene : UIScene ) {
self . appRemote . connect ( )
}
Objective-c
- ( void )applicationWillResignActive:(UIApplication *)application
{
[ self .appRemote disconnect ];
}
- ( void )applicationDidBecomeActive:(UIApplication *)application
{
[ self .appRemote connect ];
}
// If you're using UIWindowSceneDelegate
- ( void )sceneDidBecomeActive:(UIScene *)scene
{
[ self .appRemote connect ];
}
- ( void )sceneWillResignActive:(UIScene *)scene
{
[ self .appRemote disconnect ];
}
為什麼需要播放音樂才能與SPTAppRemote
連結?
當您連接SPTAppRemote
時,音樂必須正在播放,以確保 Spotify 應用程式不會在背景暫停。 iOS 應用程式只能在背景保持活動狀態幾秒鐘,除非它們正在積極執行導航或播放音樂等操作。
SpotifyiOS.framework 線程安全嗎?
不,框架當前期望從主執行緒呼叫。它將把大部分工作卸載到內部後台線程,但對程式碼的回呼也將發生在主線程上。
如果我需要在不開始播放的情況下授權怎麼辦?
還有一種替代授權方法。您可以在這裡找到更多相關資訊。