在请求时使用NSURLCredentialPersistenceForSession然后在注销时清除凭据仍然会保留cerdentials

我在登录时在NSURLConnection委托方法的NSURLCredentialPersistenceForSession中使用NSURLCredentialPersistenceForSession 。 现在当我注销并使用此代码清除存储时..

 NSURLCredentialStorage *credentialStorage = [NSURLCredentialStorage sharedCredentialStorage]; NSDictionary *credentialsDicationary = [credentialStorage allCredentials]; NSLog(@"credentialsDicationary..%@",[credentialsDicationary description]); for (NSURLProtectionSpace *space in [credentialsDicationary allKeys]) { NSDictionary *spaceDictionary = [credentialsDicationary objectForKey:space]; NSLog(@"spaceDictionary..%@",[spaceDictionary description]); for (id userName in [spaceDictionary allKeys]) { NSURLCredential *credential = [spaceDictionary objectForKey:userName]; [credentialStorage removeCredential:credential forProtectionSpace:space]; } } 

但是当我在注销后突然再次登录时,登录时会出现错误的凭据。 请让我知道如何清除缓存。 如果我在5秒钟后重新登录,它就能工作。

在此先感谢.. AJ

如果您正在使用NSURLSession,请使会话无效并创建一个新会话,例如:

 [self.session invalidateAndCancel]; self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil]; 

这将清除会话范围的凭据。

如果您使用NSURLCredentialPersistenceForSession创建凭证,则应用程序会存储整个会话的凭据,直到应用程序关闭为止。

您可以通过以下方式解决此问题:

  • 更改url(如将“#”附加到url末尾)
  • 使用NSURLCredentialPersistenceNone并为每个nsurlrequest提供凭据
  • 将身份validation信息附加到url( http:// username:password@mywebsite.com ),而不是使用信用卡
  • 将身份validation信息附加到请求标头,而不是使用creds

     //Pseudo code for appending to header: NSString *authString = [NSString stringWithFormat:@"%@:%@", self.loginCreds.username, self.loginCreds.password]; NSData *stringData = [authString dataUsingEncoding:NSUTF8StringEncoding]; authString = [NSString stringWithFormat:@"Basic %@", [stringData base64EncodedString]]; [[self requestHeader] setValue:authString forHTTPHeaderField:@"Authorization"]; 

可以删除凭证,但在实际删除之前可能需要几分钟。 但是,我不记得它是如何完成的……它要么按照你在问题中提到的方式,要么通过钥匙串完成。

我有同样的问题,我尝试清除凭据存储,与url关联的cookie,甚至尝试重置会话,但似乎没有任何工作,最后我只是使用随机查询字符串值添加到url的末尾,这样做我的诀窍

 // Random number calculated. NSInteger randomNumber = arc4random() % 16; NSURL* apiURL = [NSURL URLWithString:@"https://localhost/api/"]; [[RKObjectManager sharedManager] getObjectsAtPath:[NSString stringWithFormat:@"%@getUser?randomNumber=%d",apiURL,randomNumber] parameters:nil success:successBlock failure:failureBlock]; 

因此,不要尝试删除当前缓存的凭据(这似乎是不可能的),只需使用“新鲜”URL,这样就不会有任何与之关联的缓存对象。

我遇到了同样的问题,现在可以了。

使用NSURLConnection可以通过在URL末尾添加一个随机数来轻松修复此问题:

因此,搜索您的URLRequest并将随机数附加到URLRequest

 NSInteger randomNumber = arc4random() % 999; NSString *requestURL = [NSString stringWithFormat:@"%@?cache=%ld",yourURL,(long)randomNumber]; NSURL *URLRequest = [NSURL URLWithString:requestURL]; 

并确保在您呼叫的所有URL的末尾都有一个随机数。