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

网络---大文件的下载(NSURLSession)

2016-02-25 22:48 387 查看
小文件的下载相对比较简单,但往往大文件的下载会比较常见,也相对来说比较复杂

利用NSUrlSession

NSURLSession * session = [NSURLSession sharedSession];

NSURL * url = [NSURL URLWithString:@"下载地址"];

[[session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {

// cache路径(保存在Library下的caches中)
NSString * caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

// 拼接文件路径
NSString * filePath = [caches stringByAppendingPathComponent:response.suggestedFilename];

// 下载完成后将文件移动到 filePath 上
NSFileManager * fileMgr = [NSFileManager defaultManager];

[fileMgr moveItemAtPath:location.path toPath:filePath error:nil];

}] resume];


注意:使用此方法并不能查看下载进度,如果想要实现下载进度,需使用下面方法

NSURLSessionConfiguration * config = [NSURLSessionConfiguration defaultSessionConfiguration];
// 通过设置代理的方法来实现
NSURLSession * session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];

NSURL * url = [NSURL URLWithString:@"下载地址"];

[[session downloadTaskWithURL:url] resume];


#pragma mark --- NSURLSessionDownloadDelegate 代理方法

/**
*  下载完毕后调用
*
*  @param location     临时文件的路径(下载好的文件)
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
// location : 临时文件的路径(下载好的文件)

NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
// response.suggestedFilename : 建议使用的文件名,一般跟服务器端的文件名一致

NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];

// 将临时文件剪切或者复制Caches文件夹
NSFileManager *mgr = [NSFileManager defaultManager];

// AtPath : 剪切前的文件路径
// ToPath : 剪切后的文件路径
[mgr moveItemAtPath:location.path toPath:file error:nil];
}

/**
*  恢复下载时调用
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{

}

/**
*  每当下载完(写完)一部分时就会调用(可能会被调用多次)
*
*  @param bytesWritten              这次调用写了多少
*  @param totalBytesWritten         累计写了多少长度到沙盒中了
*  @param totalBytesExpectedToWrite 文件的总长度
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
double progress = (double)totalBytesWritten / totalBytesExpectedToWrite;
NSLog(@"下载进度---%f", progress);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: