2010-11-19 61 views
1

我想顯示一個UIProgressView,指出使用touchJSON請求JSON數據時接收的數據量。我想知道是否有方法來收聽收到的數據的大小。iOS:TouchJSON&檢索的數據大小

我請使用以下數據:

- (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; 
} 

回答

1

你將不得不推出更多的代碼,包括下載狀態指示條。目前您下載的數據爲[NSData dataWithConentsOfURL:...]。相反,您將創建一個使用NSURLConnection對象的類來下載數據,將這些數據存儲在MSMutableData對象中,並相應地更新您的UI。您應該能夠使用ContentLength HTTP標頭和- (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 
} 

我個人認爲,要做到這一點最簡單的方法是創建一個實現上述方法做一般的數據下載和接口與類的類。

這應該足以讓你得到你所需要的東西。