AFNetworking和Cookies

Ema*_*lli 17 afnetworking

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

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

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

Phi*_*hil 84

如果使用,您不需要打扰NSUserDefaults或任何钥匙串包装器NSURLCredential.的确NSURLCredential更易于使用,因为它可以让你在钥匙串两个用户名和密码存储在两行代码.

一旦用户登录,您的代码就是这样的代码:

NSURLCredential *credential;

credential = [NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistencePermanent];
[[NSURLCredentialStorage sharedCredentialStorage] setCredential:credential forProtectionSpace:self.loginProtectionSpace];
Run Code Online (Sandbox Code Playgroud)

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

NSURLCredential *credential;
NSDictionary *credentials;

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

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

NSURLCredential *credential;
NSDictionary *credentials;

credentials = [[NSURLCredentialStorage sharedCredentialStorage] credentialsForProtectionSpace:self.loginProtectionSpace];
credential = [credentials.objectEnumerator nextObject];
[[NSURLCredentialStorage sharedCredentialStorage] removeCredential:credential forProtectionSpace:self.loginProtectionSpace];
Run Code Online (Sandbox Code Playgroud)

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];
Run Code Online (Sandbox Code Playgroud)

  • 我已经用如何创建NSURLProtectionSpace的示例更新了我的答案.请使用您自己的URL替换URL,并使用服务器使用的身份验证方法更新身份验证方法参数. (4认同)

mat*_*ttt 10

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

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

// Getting
NSString *username = [[NSUserDefaults standardDefaults] objectForKey:@"username"];
Run Code Online (Sandbox Code Playgroud)

您可能希望与此结合使用,AFHTTPClient以便将您的凭据与AuthorizationHTTP标头中的每个请求一起发送.

  • 实际上,请不要在NSUserDefaults中存储用户名和密码.请改用钥匙串.Apple发布的KeychainWrapper基本上做同样的事情,但更安全. (28认同)