を使用する場合は、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];