9

I have a spotify login in my app and try to made an autologin:

Login function

func getSpotifyToken(fromController controller: UIViewController, success: (spotifyToken: String?) -> Void, failure: (error: NSError?) -> Void) {

    loginSuccessBlock = success
    loginFailureBlock = failure

    SPTAuth.defaultInstance().clientID        = SpotifyClientID
    SPTAuth.defaultInstance().redirectURL     = NSURL(string: SpotifyRedirectURI)
    SPTAuth.defaultInstance().requestedScopes = [SPTAuthStreamingScope, SPTAuthPlaylistReadPrivateScope]

    let spotifyLoginController = SPTAuthViewController.authenticationViewController()
    spotifyLoginController.delegate = self
    spotifyLoginController.clearCookies { () -> Void in
        controller.presentViewController(spotifyLoginController, animated: true, completion: nil)
    }
}

Check if session exist

private func spotifyConnected() -> Bool {        
    if SPTAuth.defaultInstance().session == nil {
        self.loadSpotifySession()
    }        
    return SPTAuth.defaultInstance().session != nil
}

Save session

private func saveSpotifySession() {
    let sessionData = NSKeyedArchiver.archivedDataWithRootObject(SPTAuth.defaultInstance().session)
    NSUserDefaults.standardUserDefaults().setObject(sessionData, forKey: Spotify_Session_Key)
    NSUserDefaults.standardUserDefaults().synchronize()
}

Load session

private func loadSpotifySession() {        
    if let sessionData = NSUserDefaults.standardUserDefaults().objectForKey(Spotify_Session_Key) as? NSData {
        let session = NSKeyedUnarchiver.unarchiveObjectWithData(sessionData) as! SPTSession
        SPTAuth.defaultInstance().session = session
    }
}

Renew session - call at app start

func renewSpotifySession() {        
    guard spotifyConnected() else {
        return
    }

    SPTAuth.defaultInstance().renewSession(SPTAuth.defaultInstance().session) { (error: NSError!, session: SPTSession!) -> Void in
        if session != nil {
            SPTAuth.defaultInstance().session = session                
        } else {
            print("Failed to refresh spotify session")
        }
    }        
}

renewSession return nil. I saw some info about refreshToken, But I don't know, where I can catch it.

How I can renew spotify session? maybe I made something wrong?

Viktor
  • 840
  • 7
  • 18

1 Answers1

5

In order to renew the session without the user needing to re-authorize your app every 60 minutes, you'll need to have a server-side script running someplace that your app will call. The server side script then talks to the Spotify servers to renew or swap out the token for a new one.

The demo projects directory in the ios-sdk download contains a sample script that you can use locally for development.

Once you have that in place, it's pretty easy. Someplace you'll have some code that configures your swap / refresh URLs:

let auth = SPTAuth.defaultInstance()
auth.clientID = Constant.SPOTIFY_CLIENT_ID;
auth.redirectURL = Constant.SPOTIFY_AUTH_CALLBACK_URL
auth.tokenSwapURL = Constant.SPOTIFY_TOKEN_SWAP_URL
auth.tokenRefreshURL = Constant.SPOTIFY_TOKEN_REFRESH_URL
auth.sessionUserDefaultsKey = Constant.SPOTIFY_SESSION_USER_DEFAULTS_KEY

Then, when you want to login or renew the session, you can have something like this:

func loginOrRenewSession(handler: (loginTriggered: Bool, error: NSError?) -> Void) {
    guard auth.session != nil else {
        print("will trigger login")
        UIApplication.sharedApplication().openURL(auth.loginURL)
        handler(loginTriggered: true, error: nil)
        return
    }

    if auth.session.isValid() {
        print("already have a valid session, nothing to do")
        handler(loginTriggered: false, error: nil)
        return
    }

    print("will renew session")
    auth.renewSession(auth.session) { error, session in
        self.auth.session = session            
        handler(loginTriggered: false, error: error)
    }
}
brki
  • 2,433
  • 1
  • 14
  • 12
  • 1
    As I understand, I need to implement swap & refresh functions on my server and add these url's to SPTAuth(). Spotify will automatically update my tokens using my backend? – Viktor Mar 15 '16 at 09:23
  • I wouldn't say automatically - you still need to periodically check that you have a valid token and refresh it if needed. The tokens expire after 60 minutes. – brki Mar 15 '16 at 22:21
  • Correct me, if I wrong: I add swap & renew functions on by server and add urls for them to STPAuth(). After login, I will receive accessToken with 1h expiration. If I close my client and open it again after 2h and call "loginOrRenewSession" session will be restored? Or I need to periodically manually renew access tokens for all users on server? – Viktor Mar 16 '16 at 09:08
  • 3
    Exactly. The server just acts a certified messenger - accepting requests from the iOS clients, transmitting them to the Spotify server, authenticated with your spotify client key + secret, and returning the response from the server (after encrypting the token). It's done like this so that you don't need to include your Spotify client secret key in the iOS app. – brki Mar 17 '16 at 07:44
  • @brki are you using `SPTAuth.loginURL` to get `loginURL` ? – mcatach Sep 08 '18 at 17:51