iOSアプリ開発の逆引き辞典

iPhone/iPadで使えるアプリ開発のTipsをまとめてみました

NSURLConnectionクラスを使ってダイジェスト認証をおこなう

NSURLConnectionクラスを使ってダイジェスト認証をおこなう方法をご紹介します。

以下のサンプルコードでは、サンプルページ付きで紹介されている「htaccess によるアクセス制限「Digest認証」ダイジェスト認証 BIG-server.com 簡単スクリプト集」のURLを使わせていただいております。

ボタンがクリックされるとNSURLConnectionクラスを使ってコンテンツを取得しようとします。

-(IBAction) ClickedButton
{
  NSURL *URL = [NSURL URLWithString:@"http://www.maido3.com/server/script/digest/"];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    NSURLConnection *connection 
        = [NSURLConnection connectionWithRequest:request delegate:self];
    [connection start];
}

対象に認証が掛かっている場合にデリゲートdidReceiveAuthenticationChallenge:メソッドが呼ばれ、このメソッドでユーザー名とパスワードを指定して認証をおこないます。

正しく認証されるとレスポンスデータの受信を開始します。

#define USER_NAME @"big-server"
#define PASSWORD @"test"

// 認証
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 
{
    if ([challenge previousFailureCount] == 0) {
        NSURLCredential* newCredential = [NSURLCredential credentialWithUser:USER_NAME 
                                                                    password:PASSWORD 
                                                                 persistence:NSURLCredentialPersistenceNone];
        [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
    } else {
        [[challenge sender] cancelAuthenticationChallenge:challenge];
    }
}

// レスポンスデータの受信
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSString* content = [NSString stringWithUTF8String:[data bytes]];
    NSLog(@"%@", content);
}