SPLoginViewController以记住凭据



在CocoaLibSpotify中,如何让SPLoginViewController存储凭据,以便用户以后可以通过[[SPSession sharedSession]attemptLoginWithStoredCredentials:]自动登录?

您没有。

相反,实现SPSessionDelegate方法-session:didGenerateLoginCredentials:forUserName:,并将凭据存储在NSUserDefaults或其他任何方法中(给定的凭据已经加密并且可以安全地存储在明文中)。

下次启动应用程序时,如果您有可用凭据,请完全跳过SPLoginViewController,并使用SPSessionattemptLoginWithUserName:existingCredential:rememberCredentials:方法登录。如果这会生成登录错误,则令牌已失效,您需要要求用户再次登录——如果用户在生成令牌后更改了密码,则可能会发生失效。

请注意,rememberCredentials:参数和旧的attemptLoginWithStoredCredentials:做事方式现在被认为是弃用的,并且很快就会消失。

前面的答案也不再相关,因为attemptLoginWithUserName:existingCredential:rememberCredentials:方法不再存在(尽管SPSession.h的注释中仍然引用了它)

获取设置:

  1. 从github获取最新的cocalibspotify并在Xcode中构建:https://github.com/spotify/cocoalibspotify
  2. 构建并放入您的项目中:

自动登录或提示用户身份验证(如果以前未登录):

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]];
}

登录时存储凭据的回调方法:

-(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];
}

相关内容

  • 没有找到相关文章

最新更新