【发布时间】:2012-11-04 00:01:07
【问题描述】:
我的应用程序是一个消息应用程序,它也可以发送图像文件。我只是在网络服务器上作为图像上传,而在另一端只是发送它的 url,使用 NSURLConnection 我正在尝试使用 UIProgressView 作为下载指示器下载图像,这是我的代码:
点击uitableview中的下载按钮时调用该方法,删除下载按钮,添加uiprogressview并开始下载
-(void)downloadImage:(UIButton *)link
{
UITableViewCell *cell = (UITableViewCell*)[link superview];
NSIndexPath *pathToCell = [tView indexPathForCell:cell];
NSMutableDictionary *checkItHasFile = [messages objectAtIndex:pathToCell.row];
NSString *str = [checkItHasFile objectForKey:@"hasFile"];
if([str isEqualToString:@"1"])
{
progress = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleBar];
progress.frame = CGRectMake(10, 50, 160, 30);
progress.progress = 0.0;
//progress.center = CGPointMake(23,21);
[cell addSubview:progress];
}
UIButton *view = [[UIButton alloc]init];
NSArray *subviews = [cell subviews];
for (view in subviews)
{
if([view isKindOfClass:[UIButton class]])
{
[view removeFromSuperview];
}
}
//
NSString *linkToPass = [NSString stringWithFormat:@"THE URL"];
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:linkToPass]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection)
{
nsmd = [[NSMutableData alloc]init];
}
else
{
NSLog(@"Connection to server failed!");
}
...
这个方法是一个 NSURLConnection 代表来表示响应,在这个我计算响应大小
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.resourceData setLength:0];
self.filesize = [NSNumber numberWithLongLong:[response expectedContentLength]];
}
此方法是一个 NSURLConnection 委托,用于指示接收到的数据,我正在通过一些计算来更新进度条
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
resourceData = [[NSMutableData alloc]init];
[self.resourceData appendData:data];
NSNumber *resourceLength = [NSNumber numberWithUnsignedInteger:[self.resourceData length]];
[self.progress setProgress:[resourceLength floatValue] / [self.filesize floatValue] animated:YES];
}
我想知道下载何时完成,因此我还可以删除进度视图,因为委托方法是 connectionDidFinishLoading:connection of NSURLConnection。
问题是它立即触发,所以当进度视图动画下载进度时,此方法也会执行,如果我在这里删除进度视图,进度视图将立即消失,而不指示完整的下载进度。
如何解决这个问题?
【问题讨论】:
-
例如,如果图像只有 5kb,您的数据连接会突然下载它。尝试下载一个大图像,它现在的行为是否相同。然后我认为你需要在 didReceiveResponse: 本身中设置 Progress: 方法。这样你就可以显示进度条了。
-
让我试试这个.. 谢谢你的回复 :)
-
似乎我现有的带有大文件的代码无法正常工作,我正在记录下载数据,进度条没有正确增加或在下载所有数据时在中间停止:( ...什么做什么?
-
在下载 gui 之前也会冻结.. 它都是异步的,那么为什么 gui 冻结...
标签: objective-c ios nsurlconnection nsurlconnectiondelegate