1

我想显示一个 UIProgressView,指示在我使用 touchJSON 请求 JSON 数据时收到的数据量。我想知道是否有办法监听接收到的数据的大小。

我使用以下命令请求数据:

- (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 回答