将UIProgressView添加到TableView单元格

时间:2012-03-12 23:54:06

标签: iphone asynchronous download tableview uiprogressview

我有一个应用程序,显示不同文件的表视图。我已将其设置为异步下载,并希望所选单元格显示进度条。我整个下午都在网上看过,到目前为止我发现的一切似乎都不完整,如何做到这一点。这是我目前为止下载的代码,并设置为具有progressview show下载状态。

代码:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
NSURL *url = [NSURL URLWithString:entry.articleUrl];    
self.nameit = entry.articleTitle;
NSURLRequest *theRequest = [NSURLRequest requestWithURL:url         cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];   
receivedData = [[NSMutableData alloc] initWithLength:0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self     startImmediately:YES];
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
progress.hidden = NO;
[receivedData setLength:0];
expectedBytes = [response expectedContentLength];
}

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
float progressive = (float)[receivedData length] / (float)expectedBytes;
[progress setProgress:progressive];


}

 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[connection release];
}

- (NSCachedURLResponse *) connection:(NSURLConnection *)connection willCacheResponse:    (NSCachedURLResponse *)cachedResponse {
  return nil;
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:[currentURL stringByAppendingString:@".mp3"]];
NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[receivedData writeToFile:pdfPath atomically:YES];
progress.hidden = YES;
[connection release];
}

1 个答案:

答案 0 :(得分:6)

首先,向您的界面添加一个UIProgressView变量,以便您可以从类中的任何方法引用它。

然后,当用户选择它时。你必须初始化它

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    UITableViewCell *cell =[tableView cellForRowAtIndexPath:indexPath];

    progress = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleBar];
    progress.frame = CGRectMake(10, 10, 30, 30);
    progress.progress = 0.0;

    progress.center = CGPointMake(23,21);

    [cell.contentView addSubview:progress];


}

现在,您可以在文件下载时更新progressBar,然后再发送[progress removeFromSuperView]

就是这样!