デリゲートの使い方や細かい処理方法を忘れるのでメモとして書きとどめておきます。
NSURLConnection
NSURLConnectionには同期処理と非同期処理があります。
同期的な処理については以前書いた記事内で使っている(sendSynchronousRequest:returningResponse:error:
メソッド)のでそちらを見ていただくとして、今回はデリゲートを使った非同期処理についてのメモです。
NSURLConnectionDataDelegateに準拠する
非同期処理の場合は、NSURLConnectionDataDelegate
プロトコロに準拠して、適切にメソッドを実装します。
実装すべきメソッドは以下のもの。
実装するデリゲートメソッド
メソッド | 説明 |
---|---|
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response | リクエストしたレスポンスを取得する。(データ本体ではない)※1 |
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data | データを受信する度に呼び出される。受信データは完全な形ではなく断片で届くため、このメソッド内で適切にデータを保持し結合する必要がある |
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error | エラー時に呼び出される |
- (void)connectionDidFinishLoading:(NSURLConnection *)connection | データの受信が完全に終わった際に呼び出される |
※1 ... 受け取るレスポンス内容
{
URL: http://example.com/
status code: 200
headers {
"Accept-Ranges" = bytes;
Connection = "Keep-Alive";
"Content-Length" = 38939;
"Content-Type" = "text/html";
Date = "Tue, 22 Apr 2014 00:44:54 GMT";
Etag = "\"dce3e36-981b-4ef2ed2eb1b40\"";
"Keep-Alive" = "timeout=5, max=20";
"Last-Modified" = "Sun, 05 Jan 2014 01:11:33 GMT";
Server = "Apache/2.2.25";
}
}
簡単な実装例
// AnyWrapperClass.h
@interface AnyWrapperClass : NSObject <NSURLConnectionDataDelegate>
@end
// AnyWrapperClass.m
@interface AnyWrapperClass ()
@property (strong, nonatomic) NSMutableData *receivedData;
@end
//////////////////////////////////////////////////////////////
@implementation AnyWrapperClass
- (void)connection:(NSURLConnection *)connection
didReceiveResponse:(NSURLResponse *)response
{
// データの長さを0で初期化
[self.receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection
didReceiveData:(NSData *)data
{
// 受信したデータを追加していく
[self.receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error
{
NSLog(@"Error!");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"Did finish loading!");
NSLog(@"data: \n%@", [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding]);
}
@end