如何续订Spotify会话?

时间:2015-07-12 04:18:36

标签: ios iphone swift session spotify

我有一个应用程序,允许用户从spotify流式传输歌曲。因此,为了实现这一点,每当用户想要从spotify流式传输歌曲时,我需要不时更新会话。我正在使用最新的spotify sdk(beta-9),我目前正在关注https://www.youtube.com/watch?v=GeO00YdJ3cE的教程。在该教程中,我们需要刷新令牌交换,但是当我从https://developer.spotify.com/technologies/spotify-ios-sdk/tutorial/查看时,无需刷新令牌交换。

我最终没有使用令牌交换,当我刷新我的会话然后用更新的会话播放歌曲时,我得到以下错误:

  

错误Domain = com.spotify.ios-sdk.playback代码= 8“由于凭据无效,登录Spotify失败。” UserInfo = 0x7f840bf807b0 {NSLocalizedDescription =由于凭据无效,登录Spotify失败。}

我正在使用下面的代码来续订我的会话:

 let userDefaults = NSUserDefaults.standardUserDefaults()

    if let sessionObj : AnyObject = NSUserDefaults.standardUserDefaults().objectForKey("spotifySession") {

        let sessionDataObj : NSData = sessionObj as! NSData
        let session = NSKeyedUnarchiver.unarchiveObjectWithData(sessionDataObj) as! SPTSession
        self.playUsingSession(session)

        if !session.isValid() {

            SPTAuth.defaultInstance().renewSession(session, callback: { (error : NSError!, newsession : SPTSession!) -> Void in

                if error == nil {

                    let sessionData = NSKeyedArchiver.archivedDataWithRootObject(session)
                    userDefaults.setObject(sessionData, forKey: "spotifySession")
                    userDefaults.synchronize()

                    self.session = newsession

                    self.playUsingSession(newsession)

                }else{

                    println("renew session having problerm >>>>> \(error)")

                }
            })
        }else{

            println("session is still valid")
            self.playUsingSession(session)

        }

    }else{

        spotifyLoginButton.hidden = false

    }

和以下代码来流式化歌曲:

func playUsingSession(sessionObj:SPTSession!){

    if spotifyPlayer == nil {

        spotifyPlayer = SPTAudioStreamingController(clientId: kSpotifyClientID)

    }

    spotifyPlayer?.loginWithSession(sessionObj, callback: { (error : NSError!) -> Void in
        if error != nil {

            println("enabling playback got error : \(error)")

            return

        }
        var spotifyTrackUri : NSURL = NSURL(string: "spotify:track:3FREWTEY2uFxOorJZMmZPX")!
        self.spotifyPlayer!.playURIs([spotifyTrackUri], fromIndex: 0, callback: { (error : NSError!) -> Void in
            if error != nil {

                println("\(error)")

            }
        })

    })

}

我还需要为最新的sdk刷新令牌交换吗?或者我的代码中缺少什么东西?

2 个答案:

答案 0 :(得分:10)

默认情况下,除非您使用授权代码流,否则用户需要每小时登录一次使用Spotify SDK的应用。要使用此流程,您需要设置服务器来处理令牌交换和刷新。

  1. 使用此一键式部署到Heroku https://github.com/adamontherun/SpotifyTokenRefresh

  2. 设置免费服务器
  3. 使用上面创建的服务器的URL在配置SPTAuth.defaultInstance()时添加以下内容:

    SPTAuth.defaultInstance()。tokenSwapURL = URL(字符串:" https://YOURSERVERNAME.herokuapp.com/swap")         SPTAuth.defaultInstance()。tokenRefreshURL = URL(字符串:" https://YOURSERVERNAME.herokuapp.com/refresh")

  4. 在使用会话之前,请检查它是否有效:

    如果SPTAuth.defaultInstance()。session.isValid()

  5. 如果不打电话

    SPTAuth.defaultInstance().renewSession(SPTAuth.defaultInstance().session, callback: { (error, session) in
                            if let session = session {
                                SPTAuth.defaultInstance().session = session
                            } 
                        })
    

答案 1 :(得分:0)

我建议您按照本教程https://medium.com/@brianhans/getting-started-with-the-spotify-ios-sdk-435607216ecc和本教程:https://medium.com/@brianhans/spotify-ios-sdk-authentication-b2c35cd4affb

完成后,您将看到创建了一个名为“ Constants.swift”的文件,如下所示:

import Foundation

struct Constants {
  static let clientID = "XXXXXXXXXXXXXXXXXXXX"
  static let redirectURI = URL(string: "yourappname://")!
  static let sessionKey = "spotifySessionKey"
}

然后,您可以按照Heroku中的步骤进行操作(不要慌张输入很简单):

https://github.com/adamontherun/SpotifyTokenRefresh

几乎准备就绪,当服务器“运行”时,回到Xcode项目,并在“ Constants.swift”文件中添加两个静态常量,如下所示:

import Foundation

struct Constants {
  static let clientID = "XXXXXXXXXXXXXXXXXXXX"
  static let redirectURI = URL(string: "yourappname://")!
  static let sessionKey = "spotifySessionKey"
  static let tokenSawp = URL(string: "https://yourappname.herokuapp.com/swap")
  static let tokenRefresh = URL(string:"https://yourappname.herokuapp.com/refresh")
}

最后,请转到AppDelegate.swift并搜索“ func setupSpotify()”。添加新的两个常量,您的函数应如下所示:

func setupSpotify() {
    SPTAuth.defaultInstance().clientID = Constants.clientID
    SPTAuth.defaultInstance().redirectURL = Constants.redirectURI
    SPTAuth.defaultInstance().sessionUserDefaultsKey = Constants.sessionKey
    SPTAuth.defaultInstance().tokenSwapURL = Constants.tokenSawp //new constant added
    SPTAuth.defaultInstance().tokenRefreshURL = Constants.tokenRefresh //new constant added

    SPTAuth.defaultInstance().requestedScopes = [SPTAuthStreamingScope]

    do {
        try SPTAudioStreamingController.sharedInstance().start(withClientId: Constants.clientID)


    } catch {
        fatalError("Couldn't start Spotify SDK")
    }
}

最后一步,只需在signInSpotify函数中添加SPTAuth.defaultInstance()。renewSession,应如下所示:

    @IBAction func SignInSpotify(_ sender: Any) {
    if SPTAuth.defaultInstance().session == nil {

        let appURL = SPTAuth.defaultInstance().spotifyAppAuthenticationURL()
        let webURL = SPTAuth.defaultInstance().spotifyWebAuthenticationURL()!

        // Before presenting the view controllers we are going to start watching for the notification
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(receievedUrlFromSpotify(_:)),
                                               name: NSNotification.Name.Spotify.authURLOpened,
                                               object: nil)

        if SPTAuth.supportsApplicationAuthentication() {
            UIApplication.shared.open(appURL!, options: [:], completionHandler: nil)
        } else {
            let webVC = SFSafariViewController(url: webURL)
            present(webVC, animated: true, completion: nil)
        }

    } else if SPTAuth.defaultInstance().session.isValid() == true {
        print("YOUR SESSION IS VALID")
        self.successfulLogin()
    } else {
        print("YOUR SESSION IS NOT VALID / NEED RENEW")
        //Every 60 minutes the token need a renew https://github.com/spotify/ios-sdk

        SPTAuth.defaultInstance().renewSession(SPTAuth.defaultInstance().session, callback: { (error, session) in
            if let session = session {
                SPTAuth.defaultInstance().session = session
                self.successfulLogin()
                print("RENEW OK")
            }

            if let error = error {
                print("RENEW NOT OK \(error)")
            }
        })
    }
}

祝你好运!