您的位置:首页 > 理论基础 > 计算机网络

关于使用ASIHTTPRequest进行断点续传

2015-09-19 13:56 1026 查看
最近项目中用到了ASI的断点续传,把其中遇到的问题和解决方法与大家分享

NSString *bookPath = [RBUtilsObject filePathString:s9id];
ASIHTTPRequest *bookDownloadRequest = [[ASIHTTPRequest alloc]initWithURL:requestURL];
bookDownloadRequest.shouldContinueWhenAppEntersBackground = YES;
[bookDownloadRequest setDownloadDestinationPath:bookPath];
NSString *tmpbookPath = [RBUtilsObject tmpfilePathString:s9id];
[bookDownloadRequest setTemporaryFileDownloadPath:tmpbookPath];
[bookDownloadRequest setAllowResumeForFileDownloads:YES];
bookDownloadRequest.allowCompressedResponse = NO;

__block NSString *currentDownloadBookID = s9id;
__block BOOL isAddToShelf = NO;

[bookDownloadRequest setBytesReceivedBlock:^(unsigned long long size, unsigned long long total) {
if ( total !=0) {
if (isAddToShelf == NO) {
isAddToShelf = YES;
[[NSNotificationCenter defaultCenter]postNotificationName:@(kIsAddToShelf) object:nil userInfo:[NSDictionary dictionaryWithObjectsAndKeys:currentDownloadBookID,@(kCurrentDownloadBookID), nil]];//s9id
}
float progressAmount = (float)((size*1.0)/(total*1.0));
NSLog(@"downloadPercent=%f  s9id= %@",progressAmount,currentDownloadBookID);
//这里的size其实是request接收到的数据的回调block,并不是当前全部已下载的数据,因此在这样不能正确显示下载进度
[[NSNotificationCenter defaultCenter]postNotificationName:currentDownloadBookID object:@(progressAmount)];

}
}];


解决方案如下:找到ASIHTTPRequest的.m文件

- (void)updateDownloadProgress
{
// We won't update download progress until we've examined the headers, since we might need to authenticate
if (![self responseHeaders] || [self needsRedirect] || !([self contentLength] || [self complete])) {
return;
}

unsigned long long bytesReadSoFar = [self totalBytesRead]+[self partialDownloadSize];
unsigned long long value = 0;

if ([self showAccurateProgress] && [self contentLength]) {
value = bytesReadSoFar-[self lastBytesRead];
if (value == 0) {
return;
}
} else {
value = 1;
[self setUpdatedProgress:YES];
}
if (!value) {
return;
}

[ASIHTTPRequest performSelector:@selector(request:didReceiveBytes:) onTarget:&queue withObject:self amount:&value callerToRetain:self];
[ASIHTTPRequest performSelector:@selector(request:didReceiveBytes:) onTarget:&downloadProgressDelegate withObject:self amount:&value callerToRetain:self];

[ASIHTTPRequest updateProgressIndicator:&downloadProgressDelegate withProgress:[self totalBytesRead]+[self partialDownloadSize] ofTotal:[self contentLength]+[self partialDownloadSize]];

#if NS_BLOCKS_AVAILABLE
if (bytesReceivedBlock) {
unsigned long long totalSize = [self contentLength] + [self partialDownloadSize];
//		[self performBlockOnMainThread:^{ if (bytesReceivedBlock) { bytesReceivedBlock(value, totalSize); }}];此处修改为即可将下载进度正确返回
[self performBlockOnMainThread:^{
if (bytesReceivedBlock) {
bytesReceivedBlock(([self totalBytesRead] + [self partialDownloadSize]),totalSize);
}
}];
}
#endif
[self setLastBytesRead:bytesReadSoFar];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息