一般的に、完了ハンドラー ブロックを使用して NSURL の 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];
}
}