在UIProgressView上添加NSURLConnection加载过程

我创build了一个UIProgressView 。 但是我用NSTimerUIProgressView's过程。 现在我需要整合UIProgressView过程,当URL加载。 UIProgressView's大小将取决于NSURLConnection's数据。

我用下面的代码来NSURLConnection

 -(void)load { NSURL *myURL = [NSURL URLWithString:@"http://feeds.epicurious.com/newrecipes"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60]; [[NSURLConnection alloc] initWithRequest:request delegate:self]; } -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { responseData = [[NSMutableData alloc] init]; } -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [responseData appendData:data]; } -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { [connection release]; UIAlertView *alert = [[UIAlertView alloc] init]; [alert setTitle:@"Warning"]; [alert setMessage:@"Network Connection Failed?"]; [alert setDelegate:self]; [alert addButtonWithTitle:@"Yes"]; [alert show]; [alert release]; NSLog(@"Error"); } -(void)connectionDidFinishLoading:(NSURLConnection *)connection { responsetext = [[[NSString alloc] initWithData:responseData encoding: NSASCIIStringEncoding] autorelease]; } 

在你的didReceiveResponse函数中,你可以得到如下的总文件大小: _totalFileSize = response.expectedContentLength;

在您的didReceiveData函数中,您可以添加总共收到的字节计数器: _receivedDataBytes += [data length];

现在为了设置进度条到正确的大小,你可以简单地做: MyProgressBar.progress = _receivedDataBytes / (float)_totalFileSize

(在didReceiveData函数或代码中的其他地方)

不要忘记将保存字节数的variables添加到您的类中!

我希望这有帮助..

编辑:这是如何实现代表为了更新progressview

 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { _totalFileSize = response.expectedContentLength; responseData = [[NSMutableData alloc] init]; } -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { _receivedDataBytes += [data length]; MyProgressBar.progress = _receivedDataBytes / (float)_totalFileSize; [responseData appendData:data]; }