17

認証にDeviseを使用するRailsサーバーに接続するiPhoneアプリのネットワークレイヤーとしてAFNetworkingを使用しています。ユーザー名/パスワードを指定して(POST呼び出しで)サインインすると、その後、実行するGETはすべて問題ありません。

(バックグラウンドだけでなく)アプリを閉じると、認証されていないと思われるため、すべてのGETリクエストが失敗します。

したがって、Cookieはどこかに保存されていると思います。NSUserDefaults常にログインしないようにするために、それらをそのような場所に保存する方法はありますか?

4

2 に答える 2

84

を使用する場合は、NSUserDefaultsやキーチェーンラッパーを気にする必要はありませんNSURLCredential。実際、ユーザー名NSURLCredentialパスワードの両方を2行のコードでキーチェーンに保存できるため、はるかに簡単に使用できます。

ユーザーがログインすると、コードは次のようになります。

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すべてのために一度作成されます。このサンプルコードは、このスペースにクレデンシャルが1つしかないことを前提としていることに注意してください。これは、複数のアカウントを管理している場合を除いて、通常は当てはまります。

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 に答える