17

我使用 AFNetworking 作为我的 iPhone 应用程序的网络层,该应用程序连接到使用 Devise 进行身份验证的 Rails 服务器。如果我登录(通过 POST 调用)提供用户名/密码,那么之后我执行的任何 GET 都可以。

如果我关闭应用程序(不仅仅是后台),那么我所有的 GET 请求都会失败,因为我猜它们没有经过身份验证。

所以我认为cookies存储在某个地方;有没有办法将它们保存在NSUserDefaults或类似的地方以避免一直登录?

4

2 回答 2

84

如果您使用NSURLCredential. Indeed使用起来NSURLCredential简单得多,因为它允许您在两行代码中将用户名和密码存储在钥匙串中。

用户登录后,您的代码将类似于:

NSURLCredential *credential;

credential = [NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistencePermanent];
[[NSURLCredentialStorage sharedCredentialStorage] setCredential:credential forProtectionSpace:self.loginProtectionSpace];

然后,每次启动应用程序时,您可以通过搜索任何凭据来检查您的用户是否已经登录,以便自动重新登录您的用户(如果需要):

NSURLCredential *credential;
NSDictionary *credentials;

credentials = [[NSURLCredentialStorage sharedCredentialStorage] credentialsForProtectionSpace:self.loginProtectionSpace];
credential = [credentials.objectEnumerator nextObject];
NSLog(@"User %@ already connected with password %@", credential.user, credential.password);

当用户想要注销时,您还需要清除凭据:

NSURLCredential *credential;
NSDictionary *credentials;

credentials = [[NSURLCredentialStorage sharedCredentialStorage] credentialsForProtectionSpace:self.loginProtectionSpace];
credential = [credentials.objectEnumerator nextObject];
[[NSURLCredentialStorage sharedCredentialStorage] removeCredential:credential forProtectionSpace:self.loginProtectionSpace];

loginProtectionSpace一劳永逸地创建。请注意,此示例代码假定此空间中只有一个凭据,除非您管理多个帐户,否则通常是这种情况。

下面是一个如何创建 的示例NSURLProtectionSpace

NSURL *url = [NSURL URLWithString:@"http://www.example.com"];
self.loginProtectionSpace = [[NSURLProtectionSpace alloc] initWithHost:url.host
                                                                  port:[url.port integerValue]
                                                              protocol:url.scheme
                                                                 realm:nil
                                                  authenticationMethod:NSURLAuthenticationMethodHTTPDigest];
于 2013-08-01T15:13:23.620 回答
10

对于特定服务器上的任何后续请求,Cookie 确实会在应用程序的整个生命周期内自动存储。一个好的策略是将用户名和密码存储在钥匙串中或NSUserDefaults像这样:

// Setting
[[NSUserDefaults standardDefaults] setObject:username forKey:@"username"];
[[NSUserDefaults standardDefaults] synchronize];

// Getting
NSString *username = [[NSUserDefaults standardDefaults] objectForKey:@"username"];

您可能希望将其与HTTP 标头AFHTTPClient中的每个请求一起发送您的凭据。Authorization

于 2011-12-24T21:41:09.820 回答