一般に、NSURLのsendAsynchronousRequestクラスメソッドでは、完了ハンドラブロックを使用して「起動し忘れて」いるだけですが、認証が必要な場合はオプションではないようです。NSURLConnectionでの認証完了ハンドラでのsendAsynchronousRequest
このような完了ハンドラスタイルの要求を使用して:
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.mysite.com/"]]
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
//Do Stuff
}];
認証を処理するための適切な方法は何ですか? NSURLConnectionを割り当てて初期化し、このクラスメソッドスタイルを使用する代わりにデリゲートを設定する必要がありますか?私はデリゲート関数で正しく認証する方法を理解していると思うが、私はそれをcompletionHandlerブロックに含めることができるかどうか、またはこれを行うより良い方法があるかどうかを調べようとしている。
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if ([challenge previousFailureCount] > 0) {
NSLog(@"Authentication Failure");
[connection cancel];
}
else
{
NSURLCredential *credential = [NSURLCredential credentialWithUser:self.username
password:self.password
persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}
}
' AFBase64EncodedStringFromString'がAで私的な機能であり、それ自体で使用することは意図されていません。代わりに 'AFHTTPClient setAuthorizationHeaderWithUsername:password:'を実行し、 '-requestWithMethod:path:parameters:'で 'NSURLRequest'を作成します(または単に生成されたリクエストから認証ヘッダーをコピーしてください)。 – mattt
サードパーティのライブラリ... – dan