iOS利用AFNetworking3.0——实现文件断点下载

利用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来支持断点续传功能。

© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享
评论 抢沙发

请登录后发表评论