我创建了一个UIProgressView。但是我用NSTimerUIProgressView's进程。现在,当URL正在加载时,我需要集成UIProgressView进程。 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函数中或在代码中的其他地方)

不要忘记在类中添加保存字节数的变量!

我希望这有帮助..

编辑:这是您可以实现委托(delegate)以更新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];
 }

关于ios - 在UIProgressView上添加NSURLConnection加载过程,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4255261/

10-10 21:10