Spotify iOS 프레임워크를 사용하면 애플리케이션이 사용자 기기의 백그라운드에서 실행되는 Spotify 앱과 상호 작용할 수 있습니다. 기능에는 승인, 현재 재생 중인 트랙 및 컨텍스트에 대한 메타데이터 가져오기, 재생 명령 실행이 포함됩니다.
참고: Spotify 개발자 도구를 사용하면 개발자 이용 약관에 동의하게 됩니다.
Spotify iOS SDK는 Spotify 앱과 연결되어 이를 제어할 수 있는 경량 개체 세트로, 재생의 모든 무거운 작업을 Spotify 앱 자체로 오프로드합니다. Spotify 앱은 재생, 네트워킹, 오프라인 캐싱 및 OS 음악 통합을 처리하므로 사용자는 사용자 경험에 집중할 수 있습니다. 앱에서 Spotify 앱으로 또는 그 반대로 이동하는 것은 재생과 메타데이터가 항상 동기화되는 효율적인 환경입니다.
주요 특징
버그 신고
구성요소
앱 원격 통화는 어떻게 작동하나요?
이용약관
지도 시간
자주 묻는 질문
우리는 개발자 커뮤니티의 피드백을 환영합니다. 문제 추적기에 누락된 기능이나 버그가 있으면 언제든지 제출해 주세요. 새 이슈를 생성하기 전에 기존 이슈를 검색했는지 확인하세요.
오픈 버그 티켓 | 기능 요청 열기
Spotify iOS 프레임워크에는 iOS 12 이상의 배포 대상이 필요합니다. SDK에서는 다음 아키텍처가 지원됩니다.
SPTAppRemoteAlbum
SPTAppRemoteArtist
SPTAppRemoteLibraryState
SPTAppRemotePlaybackRestrictions
SPTAppRemotePlaybackOptions
SPTAppRemotePlayerState
SPTAppRemoteTrack
SPTAppRemoteContentItem
SPTAppRemoteUserCapabilities
SPTAppRemoteImageRepresentable
SPTConfiguration
Spotify 앱에 연결하고 API 구성 요소를 검색하는 기본 진입점입니다. 이를 사용하여 연결을 설정, 모니터링 및 종료합니다.
다음과 같은 재생 관련 명령을 보냅니다.
SPTAppRemoteImageRepresentable
에 대한 이미지 가져오기
다음과 같은 사용자 관련 데이터 가져오기/구독/설정:
SPTAppRemoteUserCapabilities
가져오기 및/또는 구독사용자에게 추천 콘텐츠를 가져옵니다.
App Remote API와 상호 작용할 때 예상 결과 항목 또는 작업이 실패한 경우 NSError
와 함께 호출되는 SPTAppRemoteCallback
블록을 전달합니다. Spotify 앱이 명령을 수신한 후(또는 연결을 설정할 수 없는 경우) 차단이 트리거됩니다.
다음은 SPTRemotePlayerAPI
를 사용하여 노래를 건너뛰는 예입니다.
[appRemote.playerAPI skipToNext: ^( id _Nullable result, NSError * _Nullable error) {
if (error) {
// Operation failed
} else {
// Operation succeeded
}
}];
DemoProjects 폴더에서 iOS 프레임워크를 시작하는 데 도움이 되는 몇 가지 샘플 프로젝트를 제공합니다. 각 샘플의 기능에 대한 자세한 내용은 DemoProjects 폴더의 Readme를 참조하세요.
Spotify 앱과 통신하려면 애플리케이션이 먼저 App Remote에 대한 내장 인증을 사용하여 재생을 제어할 수 있는 사용자 권한을 얻어야 합니다. 그렇게 하려면 Spotify에 연결할 때 승인 보기를 요청해야 합니다. 프레임워크는 자동으로 app-remote-control
범위를 요청하고 사용자가 아직 동의하지 않은 경우 인증 보기를 표시합니다.
Spotify 개발자 도구를 사용하면 개발자 이용 약관에 동의하게 됩니다.
이 튜토리얼에서는 Spotify iOS SDK를 사용하여 오디오 트랙을 재생하고 플레이어 상태를 구독하는 간단한 앱을 만드는 과정을 단계별로 안내합니다. 승인 흐름을 안내합니다.
다음 단계에 따라 코딩을 시작할 준비가 되었는지 확인하세요.
프로젝트에 SpotifyiOS 패키지를 추가하세요. SPM(Swift Package Manager)을 통해 이 작업을 수행하거나 Xcode 프로젝트에 SpotifyiOS.xcframework
직접 추가하여 수행할 수 있습니다.
info.plist에 내 애플리케이션에 등록한 리디렉션 URI를 추가하세요. "URL 유형" 및 "URL 구성표" 아래에 리디렉션 URI를 추가해야 합니다. 고유한 "URL 식별자"도 설정해야 합니다.
소스 파일에 라이브러리를 추가합니다.
스위프트
import SpotifyiOS
목표-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 " ) !
)
목표-c
SPTConfiguration *configuration = [[SPTConfiguration alloc ] initWithClientID: @" your_client_id "
redirectURL: [ NSURL URLWithString: @" your_redirect_uri " ]];
SPTConfiguration
사용하여 SPTAppRemote
초기화
스위프트
self . appRemote = SPTAppRemote ( configuration : configuration , logLevel : . debug )
목표-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.
*/
}
}
목표-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.
*/
}
}];
application:openURL:options:
에서 accessToken을 구문 분석하도록 AppDelegate
구성하고 SPTAppRemote
연결 매개변수에 설정합니다.
목표-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
}
목표-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 ) " )
}
목표-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 ( )
}
목표-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
에 연결하려면 왜 음악을 재생해야 합니까?
Spotify 앱이 백그라운드에서 일시 중지되지 않도록 SPTAppRemote
와 연결할 때 음악이 재생되고 있어야 합니다. iOS 애플리케이션은 탐색이나 음악 재생과 같은 작업을 적극적으로 수행하지 않는 한 몇 초 동안만 백그라운드에서 활성 상태를 유지할 수 있습니다.
SpotifyiOS.framework 스레드는 안전합니까?
아니요, 프레임워크는 현재 기본 스레드에서 호출될 것으로 예상합니다. 대부분의 작업을 내부적으로 백그라운드 스레드로 오프로드하지만 코드에 대한 콜백도 기본 스레드에서 발생합니다.
재생을 시작하지 않고 인증해야 하면 어떻게 되나요?
대체 인증 방법이 있습니다. 이에 대한 자세한 내용은 여기에서 확인할 수 있습니다.