大文件下載
方案一:應用NSURLConnection和它的代理辦法,及NSFileHandle(IOS9後不建議運用)
相關變量:
@property (nonatomic,strong) NSFileHandle *writeHandle; @property (nonatomic,assign) long long totalLength;
1>發送懇求
// 創立一個懇求 NSURL *url = [NSURL URLWithString:@""]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 運用NSURLConnection發起一個異步懇求 [NSURLConnection connectionWithRequest:request delegate:self];
2>在代理辦法中處置服務器前往的數據
/** 在接納到服務器的呼應時調用上面這個代理辦法
1.創立一個空文件
2.用一個句柄對象關聯這個空文件,目的是方便在空文件前面寫入數據
*/
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(nonnull NSURLResponse *)response
{
// 創立文件途徑
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
NSString *filePath = [caches stringByAppendingPathComponent:@"videos.zip"];
// 創立一個空的文件到沙盒中
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr createFileAtPath:filePath contents:nil attributes:nil];
// 創立一個用來寫數據的文件句柄
self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
// 取得文件的總大小
self.totalLength = response.expectedContentLength;
}
/** 在接納到服務器前往的文件數據時調用上面這個代理辦法
應用句柄對象往文件的最前面追加數據
*/
- (void)connection:(NSURLConnection *)connection didReceiveData:(nonnull NSData *)data
{
// 挪動到文件的最前面
[self.writeHandle seekToEndOfFile];
// 將數據寫入沙盒
[self.writeHandle writeData:data];
}
/**
在一切數據接納終了時,封閉句柄對象
*/
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// 封閉文件並清空
[self.writeHandle closeFile];
self.writeHandle = nil;
}
方案二:運用NSURLSession的NSURLSessionDownloadTask和NSFileManager
NSURLSession *session = [NSURLSession sharedSession];
NSURL *url = [NSURL URLWithString:@""];
// 可以用來下載大文件,數據將會存在沙盒裡的tmp文件夾
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// location :暫時文件寄存的途徑(下載好的文件)
// 創立存儲文件途徑
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
// response.suggestedFilename:建議運用的文件名,普通跟服務器端的文件名分歧
NSString *file = [caches stringByAppendingPathComponent:response.suggestedFilename];
/**將暫時文件剪切或許復制到Caches文件夾
AtPath :剪切前的文件途徑
toPath :剪切後的文件途徑
*/
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr moveItemAtPath:location.path toPath:file error:nil];
}];
[task resume];
方案三:運用NSURLSessionDownloadDelegate的代理辦法和NSFileManger
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// 創立一個下載義務並設置代理
NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSURL *url = [NSURL URLWithString:@""];
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url];
[task resume];
}
#pragma mark -
/**
下載終了後調用
參數:lication 暫時文件的途徑(下載好的文件)
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location{
// 創立存儲文件途徑
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
// response.suggestedFilename:建議運用的文件名,普通跟服務器端的文件名分歧
NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
/**將暫時文件剪切或許復制到Caches文件夾
AtPath :剪切前的文件途徑
toPath :剪切後的文件途徑
*/
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr moveItemAtPath:location.path toPath:file error:nil];
}
/**
每當下載完一局部時就會調用(能夠會被調用屢次)
參數:
bytesWritten 這次調用下載了多少
totalBytesWritten 累計寫了多少長度到沙盒中了
totalBytesExpectedToWrite 文件總大小
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
// 這裡可以做些顯示進度等操作
}
/**
恢復下載時運用
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes
{
// 用於斷點續傳
}
斷點下載
方案一:
1>在方案一的根底上新增兩個變量和按扭
@property (nonatomic,assign) long long currentLength; @property (nonatomic,strong) NSURLConnection *conn;
2>在接納到服務器前往數據的代理辦法中添加如下代碼
// 記載斷點,累計文件長度 self.currentLength += data.length;
3>點擊按鈕開端(持續)或暫停下載
- (IBAction)download:(UIButton *)sender {
sender.selected = !sender.isSelected;
if (sender.selected) { // 持續(開端)下載
NSURL *url = [NSURL URLWithString:@""];
// ****關鍵點是運用NSMutableURLRequest,設置懇求頭Range
NSMutableURLRequest *mRequest = [NSMutableURLRequest requestWithURL:url];
NSString *range = [NSString stringWithFormat:@"bytes=%lld-",self.currentLength];
[mRequest setValue:range forHTTPHeaderField:@"Range"];
// 下載
self.conn = [NSURLConnection connectionWithRequest:mRequest delegate:self];
}else{
[self.conn cancel];
self.conn = nil;
}
}
4>在承受到服務器呼應執行的代理辦法中第一行添加上面代碼,避免反復創立空文件
if (self.currentLength) return;
方案二:運用NSURLSessionDownloadDelegate的代理辦法
所需變量
@property (nonatomic,strong) NSURLSession *session; @property (nonatomic,strong) NSData *resumeData; //包括了持續下載的開端地位和下載的url @property (nonatomic,strong) NSURLSessionDownloadTask *task;
辦法
// 懶加載session
- (NSURLSession *)session
{
if (!_session) {
NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
self.session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
}
return _session;
}
- (IBAction)download:(UIButton *)sender {
sender.selected = !sender.isSelected;
if (self.task == nil) { // 開端(持續)下載
if (self.resumeData) { // 原先無數據則恢復
[self resume];
}else{
[self start]; // 原先沒無數據則開端
}
}else{ // 暫停
[self pause];
}
}
// 從零開端
- (void)start{
NSURL *url = [NSURL URLWithString:@""];
self.task = [self.session downloadTaskWithURL:url];
[self.task resume];
}
// 暫停
- (void)pause{
__weak typeof(self) vc = self;
[self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
//resumeData : 包括了持續下載的開端地位和下載的url
vc.resumeData = resumeData;
vc.task = nil;
}];
}
// 恢復
- (void)resume{
// 傳入上次暫停下載前往的數據,就可以回復下載
self.task = [self.session downloadTaskWithResumeData:self.resumeData];
// 開端義務
[self.task resume];
// 清空
self.resumeData = nil;
}
#pragma mark - NSURLSessionDownloadDelegate
/**
下載終了後調用
參數:lication 暫時文件的途徑(下載好的文件)
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location{
// 創立存儲文件途徑
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
// response.suggestedFilename:建議運用的文件名,普通跟服務器端的文件名分歧
NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
/**將暫時文件剪切或許復制到Caches文件夾
AtPath :剪切前的文件途徑
toPath :剪切後的文件途徑
*/
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr moveItemAtPath:location.path toPath:file error:nil];
}
/**
每當下載完一局部時就會調用(能夠會被調用屢次)
參數:
bytesWritten 這次調用下載了多少
totalBytesWritten 累計寫了多少長度到沙盒中了
totalBytesExpectedToWrite 文件總大小
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
// 這裡可以做些顯示進度等操作
}
/**
恢復下載時運用
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes
{
}
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支持本站。
【iOS開發-完成大文件下載與斷點下載思緒】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!