NSURLCredential
を使用する場合、NSUserDefaultsやキーチェーンラッパーを気にする必要はありません。 実際には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回作成されます。このサンプルコードでは、このスペースには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];
おかげで、はい、これは私が古い資格情報を保つために何をすべきかです。 私が避けたいのは、すべてのアプリの再起動時のログインの初期POSTです。私は、AFNetworkingで処理されるクッキーの有効期間を延長できるかどうか疑問に思っていました。 –
実際には、NSUserDefaultsにユーザ名とパスワードを保存しないでください。代わりにキーチェーンを使用してください。 AppleはKeychainWrapperを配布していますが、これは基本的に同じことですが、より安全です。 – eddieroger