3

NSDatainitWithContentsOfURLを使用して、URL から画像を読み込みます。ただ、画像のサイズが事前にわからないので、レスポンスが一定サイズを超えたら接続を停止または失敗させたいです。

iPhone 3.0でこれを行う方法はありますか?

前もって感謝します。

4

1 に答える 1

10

NSData を介して直接行うことはできませんが、NSURLConnectionは画像を非同期的にロードし、connection:didReceiveData:を使用して受信したデータ量を確認することで、そのようなことをサポートします。制限を超えた場合は、キャンセルメッセージを NSURLConnection に送信してリクエストを停止してください。

簡単な例: (receivedData はヘッダーで NSMutableData として定義されています)

@implementation TestConnection

- (id)init {
    [self loadURL:[NSURL URLWithString:@"http://stackoverflow.com/content/img/so/logo.png"]];
    return self;
}

- (BOOL)loadURL:(NSURL *)inURL {
    NSURLRequest *request = [NSURLRequest requestWithURL:inURL];
    NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];

    if (conn) {
        receivedData = [[NSMutableData data] retain];
    } else {
        return FALSE;
    }

    return TRUE;
}

- (void)connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)response {
    [receivedData setLength:0]; 
}

- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data {
    [receivedData appendData:data];

    if ([receivedData length] > 5120) { //5KB
        [conn cancel];
    }
}

- (void)connectionDidFinishLoading:(NSURLConnection *)conn {
    // do something with the data
    NSLog(@"Succeeded! Received %d bytes of data", [receivedData length]);

    [receivedData release];
}

@end
于 2009-07-23T03:48:12.920 に答える