In CocoaLibSpotify, how do I get SPLoginViewController to store credentials, so users later can login automatically via [[SPSession sharedSession] attemptLoginWithStoredCredentials:]?
The way to do this usually is to not store the username/password at all, but a GUID/hash that identifies the users session, and then let that session be persisted. That way, even if somebody else gets access to the session, they won't have the username/password.
You don't.
Instead, implement the SPSessionDelegate
method -session:didGenerateLoginCredentials:forUserName:
and store the credentials in NSUserDefaults
or whatever (the given credentials are already encrypted and safe for storing in cleartext).
Next time your app launches, if you have available credentials skip SPLoginViewController
entirely and login using SPSession
's attemptLoginWithUserName:existingCredential:rememberCredentials:
method. If this generates a login error, the token has been invalidated and you need to ask the user to login again — invalidation can happen if the user changes their password since the token was generated.
Note that the rememberCredentials:
parameters and the old attemptLoginWithStoredCredentials:
way of doing things is now considered deprecated and will be going away soon.
The previous answer is also no longer relevant as the attemptLoginWithUserName:existingCredential:rememberCredentials: method no longer exists (despite it still being referred to in the comments of SPSession.h)
To get setup:
To login automatically or prompt for user auth if not previously logged in:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *storedCredentials = [defaults valueForKey:@"SpotifyUsers"];
if (storedCredentials == nil)
[self performSelector:@selector(showLogin) withObject:nil afterDelay:0.0];
else
{
NSString *u = [storedCredentials objectForKey:@"LastUser"] ;
[[SPSession sharedSession] attemptLoginWithUserName:u existingCredential:[storedCredentials objectForKey:u]];
}
Callback method for storing credentials when logged in:
-(void)session:(SPSession *)aSession didGenerateLoginCredentials:(NSString *)credential forUserName:(NSString *)userName
{
NSLog(@"stored credentials");
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *storedCredentials = [[defaults valueForKey:@"SpotifyUsers"] mutableCopy];
if (storedCredentials == nil)
storedCredentials = [NSMutableDictionary dictionary];
[storedCredentials setValue:credential forKey:userName];
[storedCredentials setValue:userName forKey:@"LastUser"];
[defaults setValue:storedCredentials forKey:@"SpotifyUsers"];
[defaults synchronize];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With