HTTP通信

恐らくiOSを使ったアプリケーションでは必須の処理であろうHTTP通信だが、Foundationの標準的なクラスであっても、書き方によってバリエーションがあるようだ。

    • 同期通信

通信開始を明示的に実行し、結果が戻るまでブロックする同期通信処理

NSURL* url = [NSURL URLWithString:@"http://〜"];
NSURLRequest* req = [NSURLRequest requestWithURL:url];
NSURLResponse* resp = nil;
NSError* error = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:req returningResponse:&resp error : &error];
    • 非同期通信

通信のイベントコールバックをデリゲートで処理する非同期通信処理。同期処理とはNSURLConnectionの使い方に違いがある。

NSURL* url = [NSURL URLWithString:@"http://〜"];
NSURLRequest* req = [NSURLRequest requestWithURL:url];
NSURLConnection* con = [[NSURLConnection alloc] initWithRequest:req delegate:self];

//レスポンス受信直後に呼ばれる(ヘッダなどを処理できる)
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse *)response
{
}
//データ受信直後に呼ばれる
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
}
//エラー発生時呼ばれる
- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error 
{
}
//データの受信完了直後に呼ばれる
- (void)connectionDidFinishLoading:(NSURLConnection*)connection 
{
}

どちらも一長一短だが、既に非同期処理用のクラス(BBAsyncTask)を作っているので、シンプルな同期処理用のイディオムを使うことにしよう。