Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to renew spotify session?

I have an application that allow users to stream songs from spotify. So to achieve that I need to renew session from time to time whenever users want to stream song from spotify. I'm using latest spotify sdk (beta-9), and I'm currently following tutorial from https://www.youtube.com/watch?v=GeO00YdJ3cE. In that tutorial we need to refresh token swap but when I looked from https://developer.spotify.com/technologies/spotify-ios-sdk/tutorial/ there is no need to refresh token swap.

and I end up not using the token swap, when I refresh my session then play song with renewed session, I got below error:

Error Domain=com.spotify.ios-sdk.playback Code=8 "Login to Spotify failed because of invalid credentials." UserInfo=0x7f840bf807b0 {NSLocalizedDescription=Login to Spotify failed because of invalid credentials.}

And I'm using this code below, for renewing my session:

 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

    }

and below code to stream spotify songs:

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)")

            }
        })

    })

}

Do I still need to refresh token swap for latest sdk? Or is there something missing with my code?

like image 552
Ega Setya Putra Avatar asked Jul 12 '15 04:07

Ega Setya Putra


1 Answers

By default, users need to login once per hour for apps using the Spotify SDK unless you use the Authorization Code flow. To use this flow you'll need to setup a server to handle token swap and refresh.

  1. Setup a free server with this one-click-deploy to Heroku https://github.com/adamontherun/SpotifyTokenRefresh

  2. Using the URL of the server created above add the following when configuring your SPTAuth.defaultInstance():

    SPTAuth.defaultInstance().tokenSwapURL = URL(string: "https://YOURSERVERNAME.herokuapp.com/swap") SPTAuth.defaultInstance().tokenRefreshURL = URL(string: "https://YOURSERVERNAME.herokuapp.com/refresh")

  3. Before using your session check if it is valid:

    if SPTAuth.defaultInstance().session.isValid()

and if it isn't call

SPTAuth.defaultInstance().renewSession(SPTAuth.defaultInstance().session, callback: { (error, session) in
                        if let session = session {
                            SPTAuth.defaultInstance().session = session
                        } 
                    })
like image 150
Adamontherun Avatar answered Sep 30 '22 01:09

Adamontherun