利用AFNetworking 3.0可以实现文件的断点下载。主要分以下几步:
1. 创建文件管理器,获取下载文件信息
NSFileManager *fileManager = [NSFileManager defaultManager]; NSString *downloadPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *tempPath = [downloadPath stringByAppendingPathComponent:tempName]; NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:tempPath error:nil]; NSUInteger fileSize = [fileAttributes fileSize]; NSUInteger downloadedSize = 0;
2. 创建下载任务,判断是否断点继续下载
NSURLSessionDownloadTask *downloadTask;
if (fileSize > 0) { // 存在临时下载文件,进行断点下载
    NSURL *url = [NSURL URLWithString:downloadUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    downloadTask = [session downloadTaskWithResumeData:resumeData completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
       // ...
    }];
} else { // 重新下载
    downloadTask = [session downloadTaskWithURL:[NSURL URLWithString:downloadUrl] completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
       // ...
    }];
}
[downloadTask resume];
3. 下载过程中获取下载进度并存储到沙盒
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask 
       didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten 
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    
    downloadedSize += bytesWritten;
    float progress = (float)downloadedSize/fileSize;
    
    // 存储下载进度到沙盒
    NSString *progressPath = [downloadPath stringByAppendingPathComponent:@"progress.progress"];
    [fileManager createFileAtPath:progressPath contents:[NSData dataWithBytes:&progress length:sizeof(progress)] attributes:nil];
}
4. 下载完成合并临时文件
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask 
didFinishDownloadingToURL:(NSURL *)location{
    
    NSString *tempPath = [downloadPath stringByAppendingPathComponent:tempName];
    NSString *filePath = [downloadPath stringByAppendingPathComponent:fileName];
    [fileManager moveItemAtPath:tempPath toPath:filePath error:nil];
}
以上就是利用AFNetworking实现文件的断点下载思路与示例代码。需要注意的是要针对不同的后端,选择恰当的HTTP Header来支持断点续传功能。
© 版权声明
本文刊载的所有内容,包括文字、图片、音频、视频、软件、程序、以及网页版式设计等部门来源于互联网,版权均归原作者所有!本网站提供的内容服务于个人学习、研究或欣赏,以及其他非商业性或非盈利性用途,但同时应遵守著作权法及其他相关法律的规定,不得侵犯本网站及相关权利人的合法权利。
联系信息:邮箱aoxolcom@163.com或见网站底部。
联系信息:邮箱aoxolcom@163.com或见网站底部。
THE END
    



















请登录后发表评论
注册
社交帐号登录