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 线程安全吗?
不,框架当前期望从主线程调用。它将把大部分工作卸载到内部后台线程,但对代码的回调也将发生在主线程上。
如果我需要在不开始播放的情况下授权怎么办?
还有一种替代授权方法。您可以在这里找到更多相关信息。