1

我的应用程序是一个消息应用程序,它也可以发送图像文件。我只是在网络服务器上作为图像上传,而在另一端只是发送它的 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:NSURLConnection 的连接。

问题是它立即触发,所以当进度视图动画下载进度时,此方法也会执行,如果我在这里删除进度视图,进度视图将立即消失,而不指示完整的下载进度。

如何解决这个问题?

4

1 回答 1

0

定义一个移除进度条的方法,然后在你的- (void)connectionDidFinishLoading:(NSURLConnection *)connection实现中,如果资源长度小于你决定的一定数量,延迟调用remove方法:

[self performSelector:@selector(removeProgressBar) withObject:nil afterDelay:2];

否则立即调用相同的方法。

于 2012-11-15T12:22:54.880 回答