在UIProgressView上添加NSURLConnection加载过程

Vel*_*gan 5 nsurlconnection uiprogressview ios

我创造了一个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];
}
Run Code Online (Sandbox Code Playgroud)

Hle*_*ess 15

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

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

现在,为了将进度条设置为正确的大小,您可以简单地执行以下操作: MyProgressBar.progress = _receivedDataBytes / (float)_totalFileSize

(在didReceiveData函数中或代码中的其他位置)

不要忘记将包含字节数的变量添加到您的类中!

我希望这有帮助..

编辑:这是你如何实现代表以更新进度视图

-(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];
 }
Run Code Online (Sandbox Code Playgroud)