ios 在下载html代码的时候,如何显示下载的进度

本文介绍了一种使用NSURLConnection结合多线程技术实现图片下载的方法,包括创建连接、接收数据、更新进度及错误处理。通过设置线程特定资源、利用NSURLConnection的delegate方法接收响应和数据,并在主线程更新UI。同时,展示了如何从HTTP返回的response中获取下载文件的总大小,从而计算下载进度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里以下载图片举例。
1,首先创建一个cconnection
downloadImage是一个线程函数,在子线程中下载图片。



//url 图片的url地址
- (void) downloadImage:(NSString*)url{  
    self.uploadPool = [[NSAutoreleasePool alloc] init];
    self.characterBuffer = [NSMutableData data];
    done = NO;
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    
    self.connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    [self performSelectorOnMainThread:@selector(httpConnectStart) withObject:nil waitUntilDone:NO];
    if (connection != nil) {
        do {
            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        } while (!done);
    }
    
    self.photo = [UIImage imageWithData:characterBuffer];
    
    [self performSelectorOnMainThread:@selector(fillPhoto) withObject:nil waitUntilDone:NO];
    
    // Release resources used only in this thread.
    self.connection = nil;
    [uploadPool release];
    self.uploadPool = nil;
}



2, 在NSURLConnection的delegate中接收数据
// Forward errors to the delegate.
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    done = YES;
    [self performSelectorOnMainThread:@selector(httpConnectEnd) withObject:nil waitUntilDone:NO];
    //NSLog(@"%@",[error localizedDescription]);
    [characterBuffer setLength:0];
    
}


// Called when a chunk of data has been downloaded.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // Process the downloaded chunk of data.
    
    //NSLog(@"%d", [data length]);
    
    received_ += [data length];
    [self performSelectorOnMainThread:@selector(updateProgress) withObject:nil waitUntilDone:NO];
    
    [characterBuffer appendData:data];
    
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    
    //NSLog(@"%lld", received_);
    
    [self performSelectorOnMainThread:@selector(httpConnectEnd) withObject:nil waitUntilDone:NO];
    // Set the condition which ends the run loop.
    done = YES; 
}



上面三个方法,第一个是连接出错的情况,第二个是接收数据,reveived_纪录一共接收了多少子节的数据。第三个是连接结束。


还有一个方法,我们可以从http返回的response中拿到一些连接的信息。这里我拿到了要下载的数据的大小,保存在"Content-Length"的字段中,详细的理论见HTTP协议。

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    if(httpResponse && [httpResponse respondsToSelector:@selector(allHeaderFields)]){
        NSDictionary *httpResponseHeaderFields = [httpResponse allHeaderFields];
        
        total_ = [[httpResponseHeaderFields objectForKey:@"Content-Length"] longLongValue];
        
        //NSLog(@"%lld", total_);
    }
}





有了要下载的数据的总大小,和已经下载的大小,进度自然就出来了。

//**************************************************************************************************************

还有一种方法

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

//得到要下载文件的文件大小、文件名称

long length=[response expectedContentLength];

self.Myfilenmame=[response suggestedFilename];

self.Myfilelength=length;

//将文件名显示

self.label.text=Myfilenmame;

long firstleng = self.Myfilelength/3;

for (int i=0; i<2; i++) {

[self.r release];

self.r = [[NSMutableURLRequest alloc] initWithURL: url];

NSString *range = [[NSString alloc] initWithFormat:@"bytes=%d-%d", i*firstleng, (i+1)*firstleng];

[self.r setValue:range forHTTPHeaderField:@"Range"];

[range release];

NSString *tempname = [[NSString alloc] initWithFormat:@"%@%d.tmp", self.Myfilenmame, i];

TheardDown *threadload = [[TheardDown alloc] init];

[threadload init_all:tempname controllers:self mylength:firstleng myrequest:self.r];

[theards addObject:threadload];

[threadload release];

[tempname release];

}

self.r = [[NSMutableURLRequest alloc] initWithURL: url];

NSString *range = [[NSString alloc] initWithFormat:@"bytes=%d-", 2*firstleng];

[self.r setValue:range forHTTPHeaderField:@"Range"];

[range release];

TheardDown *threadload = [[TheardDown alloc] init];

NSString *tempname = [[NSString alloc] initWithFormat:@"%@%d.tmp", self.Myfilenmame, 2];

[threadload init_all:tempname controllers:self mylength:(self.Myfilelength - 2*firstleng) myrequest:self.r];

[theards addObject:threadload];

[threadload release];

[tempname release];

//设置几根线程在下载

self.count = 3;

[self.connection cancel];


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值