需要有关使用NSURLConnection下载数据的帮助

时间:2012-11-15 11:31:08

标签: objective-c ios nsurlconnection nsurlconnectiondelegate

我的应用是一个短信应用,它也可以发送图像文件。我只是在网络服务器上上传图像,另一边只是发送它的网址,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。

问题是它会立即触发,因此当进度视图为下载进度设置动画时,此方法也会执行,如果我在此处删除进度视图,则进度视图将立即消失,并指示完整的下载进度。

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

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

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

否则会毫不拖延地调用相同的方法。