at_yasu's blog

ロード的なことを

NSURLConnectionとBasic Authentication

NSURLConnectionで基本認証をする方法。一つに、ヘッダーにbase64にしたユーザ名パスワードを入れる方法がありますが、あまりスマートではないし、ドキュメントをちゃんと読んでいないのがバレますので非推奨。

して、このドキュメントには NSURLAuthenticationChallenge を使う方法が書いています。


手順としてはこんな感じ。詳しくはここのHandling Authentication Challengesを読むべし

  • NSURLConnection/NSURLDownloadは、指定されたURLへ接続します。
  • HTTPでの認証が必要な場合、delegateオブジェクトにconnection:didReceiveAuthenticationChallenge: / download: connection:didReceiveAuthenticationChallenge: メッセージを送ります。この時に、ユーザにユーザ名とパスワードを入力するように求めます。
  • 認証を取り消した場合は、 connection:didCancelAuthenticationChallenge: へメッセージを送ります。

簡単なサンプルコード。

-(void)connection:(NSURLConnection *)connection
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    if ([challenge previousFailureCount] == 0)
	{
        NSURLCredential *newCredential;
        newCredential=[NSURLCredential credentialWithUser:_username
                                                 password:_password
                                              persistence:NSURLCredentialPersistenceNone];
        [[challenge sender] useCredential:newCredential
               forAuthenticationChallenge:challenge];
    }
	else
	{
        [[challenge sender] cancelAuthenticationChallenge:challenge];
        // inform the user that the user name and password
        // in the preferences are incorrect
    }
}