在 Spotify iOS SDK 中设置身份验证令牌

Posted

技术标签:

【中文标题】在 Spotify iOS SDK 中设置身份验证令牌【英文标题】:Setting Auth Tokens in Spotify iOS SDK 【发布时间】:2017-10-30 07:33:37 【问题描述】:

Spotify ios SDK 全部在 Objective-c 中,截至今天,看起来任何使用 SDK 的请求都需要令牌。当我尝试搜索歌曲时,出现此错误:

["error": 
    message = "No token provided";
    status = 401;
]

这是我的 appDelegate 代码:

var auth = SPTAuth()
var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool 
    //Neccessary Spotify stuff
    auth.redirectURL = URL(string: "my_redirect_url")
    auth.sessionUserDefaultsKey = "current session"

    FIRApp.configure()

    window = UIWindow(frame: UIScreen.main.bounds)
    window?.makeKeyAndVisible()
    window?.rootViewController = CustomTabBarController()

    return true


// 1
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool 
    // 2- check if app can handle redirect URL
    if auth.canHandle(auth.redirectURL) 
        // 3 - handle callback in closure
        auth.handleAuthCallback(withTriggeredAuthURL: url, callback:  (error, session) in
            // 4- handle error
            if error != nil 
                print("error!")
            
            // 5- Add session to User Defaults
            let userDefaults = UserDefaults.standard
            let sessionData = NSKeyedArchiver.archivedData(withRootObject: session as Any)
            userDefaults.set(sessionData, forKey: "SpotifySession")
            userDefaults.synchronize()
            // 6 - Tell notification center login is successful
            NotificationCenter.default.post(name: Notification.Name(rawValue: "loginSuccessfull"), object: nil)
        )
        return true
    
    return false

如何在 Swift 中设置令牌?

【问题讨论】:

【参考方案1】:
var auth = SPTAuth.defaultInstance()!
var session:SPTSession!

首先设置重定向 URL 和客户端 ID:

            let redirectURL = "xyz://" // put your redirect URL here
            auth.redirectURL     = URL(string: redirectURL)
            auth.clientID        = kClientId
            auth.requestedScopes = [SPTAuthStreamingScope, SPTAuthPlaylistReadPrivateScope, SPTAuthPlaylistModifyPublicScope, SPTAuthPlaylistModifyPrivateScope]
            loginUrl = auth.spotifyWebAuthenticationURL()

然后使用登录方式:

        if UIApplication.shared.openURL(loginUrl!) 

            if auth.canHandle(auth.redirectURL) 
                // To do - build in error handling
            
        

如果您需要更多帮助,请告诉我。我在 Swift 中配置并在我的当前应用程序中使用它。

【讨论】:

【参考方案2】:

在您的 AppDelegate 中:

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool 

            let auth: SPTAuth = SPTAuth.defaultInstance()
            auth.clientID = "Your-Client-Id"
            auth.redirectURL = URL(string: "Your-Callback-URL")
            auth.sessionUserDefaultsKey = "current session"

            return true
  

  func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool 
        let auth:SPTAuth = SPTAuth.defaultInstance()

        let authCallback: SPTAuthCallback =  error, session in
            if let error = error 
                print(error.localizedDescription)
                return
            
            auth.session = session

            NotificationCenter.default.post(name: NSNotification.Name("sessionUpdated"), object: nil)
        

        if auth.canHandle(url) 
            auth.handleAuthCallback(withTriggeredAuthURL: url, callback: authCallback)
            return true
        

        return false
  

在您的初始视图控制器中,您的登录方法应该是这样的:

func loginToSpotify 
        let auth:SPTAuth = SPTAuth.defaultInstance()

//check if first time login

        if auth.session != nil 
            if auth.session.isValid() 
                //to your search page
                return
            
//refresh token
            renewTokenAndShowSearchVC()
            return
        

        if SPTAuth.supportsApplicationAuthentication() 
            UIApplication.shared.open(auth.spotifyAppAuthenticationURL(), options: [:], completionHandler: nil)
         else 
            let safari = SFSafariViewController(url: auth.spotifyWebAuthenticationURL())
            present(safari, animated: true, completion: nil)
        
    

func renewTokenAndShowSearchVC() 

        print("Refreshing token...")

        let auth:SPTAuth = SPTAuth.defaultInstance()
        auth.renewSession(auth.session)  (error, session) in
            auth.session = session

            if let error = error 
                print("Refreshing token failed.")
                print(error.localizedDescription)
                return
            
            //to your search page
        
    

然后.. 在您的 View Controller 或 Model View 的某个地方,您可以通过从 SPTSession 调用 accessToken 来获取令牌,例如,如果您想搜索曲目(名称、艺术家和专辑):

   struct Track: 
            let name: String
            let artist: String
            let album: String

            init(name: String, artist: String, album: String) 
                self.name = name
                self.artist = artist
                self.album = album
            
        

     func search(query: String, callback: @escaping ([Track]) -> Void) -> Void 

            let auth: SPTAuth = SPTAuth.defaultInstance()
            let token = auth.session.accessToken

            SPTSearch.perform(withQuery: query, queryType: .queryTypeTrack, accessToken: token, market: "Country_Code")  (error, result) in
                if let error = error 
                    print(error.localizedDescription)
                    return
                

                if let listPage = result as? SPTListPage, 
                let items = listPage.items as? [SPTPartialTrack], 
                let artist = items.first?.artists.first as? SPTPartialArtist 

                     let tracks = items.compactMap( (pTrack) -> Track in

                            let name: String = pTrack.name
                            let artist: String = artist.name
                            let album: String = pTrack.album.name

                            return Track(name: name , artist: artist, album: album)
                        )

                        callback(tracks)
                    
                
            

【讨论】:

以上是关于在 Spotify iOS SDK 中设置身份验证令牌的主要内容,如果未能解决你的问题,请参考以下文章

React-Native Spotify SDK iOS:关闭身份验证窗口

Spotify 身份验证流程 SDK 中的未知错误

在 druid 中设置基本身份验证

在 Android Studio 中设置 Spotify API

使用来自 django-allauth 的访问令牌登录 Spotify iOS SDK

Spotify iOS sdk 使用现有访问令牌连接到 Spotify 远程应用程序