1

touchJSON を使用して JSON データを要求したときに、受信したデータの量を示す UIProgressView を表示したいと考えています。受信しているデータのサイズを聞く方法があるかどうか疑問に思っていました。

以下を使用してデータをリクエストします。

- (NSDictionary *)requestData
{   
    NSData          *data       =   [NSData dataWithContentsOfURL:[NSURL URLWithString:apiURL]];
    NSError         *error      =   nil;
    NSDictionary    *result     =   [[CJSONDeserializer deserializer] deserializeAsDictionary:data error:&error];

    if(error != NULL)
        NSLog(@"Error: %@", error);

    return result;
}
4

1 に答える 1

1

ダウンロード ステータス インジケーター バーを含めるには、さらにコードを導入する必要があります。現時点では、でデータをダウンロードします[NSData dataWithConentsOfURL:...]。代わりに、NSURLConnectionオブジェクトを使用してデータをダウンロードし、そのデータを MSMutableData オブジェクトに蓄積し、それに応じて UI を更新するクラスを作成します。ContentLengthHTTP ヘッダーと- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;更新を使用して、ダウンロードのステータスを判断できるはずです。

関連するメソッドを次に示します。

- (void) startDownload
{
    downloadedData = [[NSMutableData alloc] init];
    connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
}

- (void)connection:(NSURLConnection *)c didReceiveResponse:(NSURLResponse *)response
{
    totalBytes = [response expectedContentLength];
}

// assume you have an NSMutableData instance variable named downloadedData
- (void)connection:(NSURLConnection *)c didReceiveData:(NSData *)data
{
    [downloadedData appendData: data];
    float proportionSoFar = (float)[downloadedData length] / (float)totalBytes;
    // update UI with proportionSoFar
}

 - (void)connection:(NSURLConnection *)c didFailWithError:(NSError *)error
{
    [connection release];
    connection = nil;
    // handle failure
}

- (void)connectionDidFinishLoading:(NSURLConnection *)c
{
    [connection release];
    connection = nil;
    // handle data upon success
}

個人的には、これを行う最も簡単な方法は、上記のメソッドを実装するクラスを作成して、汎用データのダウンロードとそのクラスとのインターフェイスを行うことだと思います。

これは、必要なものを取得するのに十分なはずです。

于 2010-11-19T19:05:03.307 に答える