iosswiftcore-dataspotifyspotify-app

How do I create, save, and pass a valid SPTSession once I am logged in Spotify?


I'm having trouble with Spotify beta 9. All the tutorials seem phased out regarding saving a SPTSession and updating(refreshing) with the RefreshTokenURL. This is how I'm getting the AuthViewController....

        let spotifyAuthenticationViewController = SPTAuthViewController.authenticationViewController()
        spotifyAuthenticationViewController.delegate = self
        spotifyAuthenticationViewController.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext
        spotifyAuthenticationViewController.definesPresentationContext = true
        presentViewController(spotifyAuthenticationViewController, animated: true, completion: nil)

Now I need to create a session, save, and periodically refresh. I would like to save in CoreData. Please help if you've done this before or have any good tips


Solution

  • You have to store it in NSUserDefaults:

    SPTAuth *auth = [SPTAuth defaultInstance];
    id sessionData = [[NSUserDefaults standardUserDefaults] objectForKey:auth.sessionUserDefaultsKey];
    SPTSession *sessionUserDefault = [NSKeyedUnarchiver unarchiveObjectWithData:sessionData];
    
    auth.tokenRefreshURL = [NSURL URLWithString:kTokenRefreshServiceURL];
    
        if (![sessionUserDefault isValid] && [auth hasTokenRefreshService]) {
            [auth renewSession:sessionUserDefault callback:^(NSError *error, SPTSession *renewedSession) {
                if (error != nil)
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"spotifySessionNotOK" object:renewedSession];
    
                if(renewedSession)
                    self.session = renewedSession;
    
            }];
        }
        else {
            self.session = sessionUserDefault;
        }
    
      [auth setSessionUserDefaultsKey:auth.sessionUserDefaultsKey];
    }