十年網(wǎng)站開發(fā)經(jīng)驗(yàn) + 多家企業(yè)客戶 + 靠譜的建站團(tuán)隊(duì)
量身定制 + 運(yùn)營維護(hù)+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
大文件下載

發(fā)展壯大離不開廣大客戶長期以來的信賴與支持,我們將始終秉承“誠信為本、服務(wù)至上”的服務(wù)理念,堅(jiān)持“二合一”的優(yōu)良服務(wù)模式,真誠服務(wù)每家企業(yè),認(rèn)真做好每個(gè)細(xì)節(jié),不斷完善自我,成就企業(yè),實(shí)現(xiàn)共贏。行業(yè)涉及成都混凝土攪拌站等,在網(wǎng)站建設(shè)公司、全網(wǎng)營銷推廣、WAP手機(jī)網(wǎng)站、VI設(shè)計(jì)、軟件開發(fā)等項(xiàng)目上具有豐富的設(shè)計(jì)經(jīng)驗(yàn)。
方案一:利用NSURLConnection和它的代理方法,及NSFileHandle(iOS9后不建議使用)
相關(guān)變量:
@property (nonatomic,strong) NSFileHandle *writeHandle; @property (nonatomic,assign) long long totalLength;
1>發(fā)送請(qǐng)求
// 創(chuàng)建一個(gè)請(qǐng)求 NSURL *url = [NSURL URLWithString:@""]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 使用NSURLConnection發(fā)起一個(gè)異步請(qǐng)求 [NSURLConnection connectionWithRequest:request delegate:self];
2>在代理方法中處理服務(wù)器返回的數(shù)據(jù)
/** 在接收到服務(wù)器的響應(yīng)時(shí)調(diào)用下面這個(gè)代理方法
1.創(chuàng)建一個(gè)空文件
2.用一個(gè)句柄對(duì)象關(guān)聯(lián)這個(gè)空文件,目的是方便在空文件后面寫入數(shù)據(jù)
*/
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(nonnull NSURLResponse *)response
{
// 創(chuàng)建文件路徑
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
NSString *filePath = [caches stringByAppendingPathComponent:@"videos.zip"];
// 創(chuàng)建一個(gè)空的文件到沙盒中
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr createFileAtPath:filePath contents:nil attributes:nil];
// 創(chuàng)建一個(gè)用來寫數(shù)據(jù)的文件句柄
self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
// 獲得文件的總大小
self.totalLength = response.expectedContentLength;
}
/** 在接收到服務(wù)器返回的文件數(shù)據(jù)時(shí)調(diào)用下面這個(gè)代理方法
利用句柄對(duì)象往文件的最后面追加數(shù)據(jù)
*/
- (void)connection:(NSURLConnection *)connection didReceiveData:(nonnull NSData *)data
{
// 移動(dòng)到文件的最后面
[self.writeHandle seekToEndOfFile];
// 將數(shù)據(jù)寫入沙盒
[self.writeHandle writeData:data];
}
/**
在所有數(shù)據(jù)接收完畢時(shí),關(guān)閉句柄對(duì)象
*/
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// 關(guān)閉文件并清空
[self.writeHandle closeFile];
self.writeHandle = nil;
}
方案二:使用NSURLSession的NSURLSessionDownloadTask和NSFileManager
NSURLSession *session = [NSURLSession sharedSession];
NSURL *url = [NSURL URLWithString:@""];
// 可以用來下載大文件,數(shù)據(jù)將會(huì)存在沙盒里的tmp文件夾
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// location :臨時(shí)文件存放的路徑(下載好的文件)
// 創(chuàng)建存儲(chǔ)文件路徑
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
// response.suggestedFilename:建議使用的文件名,一般跟服務(wù)器端的文件名一致
NSString *file = [caches stringByAppendingPathComponent:response.suggestedFilename];
/**將臨時(shí)文件剪切或者復(fù)制到Caches文件夾
AtPath :剪切前的文件路徑
toPath :剪切后的文件路徑
*/
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr moveItemAtPath:location.path toPath:file error:nil];
}];
[task resume]; 方案三:使用NSURLSessionDownloadDelegate的代理方法和NSFileManger
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event { // 創(chuàng)建一個(gè)下載任務(wù)并設(shè)置代理 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 - /** 下載完畢后調(diào)用 參數(shù):lication 臨時(shí)文件的路徑(下載好的文件) */ - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{ // 創(chuàng)建存儲(chǔ)文件路徑 NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject]; // response.suggestedFilename:建議使用的文件名,一般跟服務(wù)器端的文件名一致 NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename]; /**將臨時(shí)文件剪切或者復(fù)制到Caches文件夾 AtPath :剪切前的文件路徑 toPath :剪切后的文件路徑 */ NSFileManager *mgr = [NSFileManager defaultManager]; [mgr moveItemAtPath:location.path toPath:file error:nil]; } /** 每當(dāng)下載完一部分時(shí)就會(huì)調(diào)用(可能會(huì)被調(diào)用多次) 參數(shù): bytesWritten 這次調(diào)用下載了多少 totalBytesWritten 累計(jì)寫了多少長度到沙盒中了 totalBytesExpectedToWrite 文件總大小 */ - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{ // 這里可以做些顯示進(jìn)度等操作 } /** 恢復(fù)下載時(shí)使用 */ - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes { // 用于斷點(diǎn)續(xù)傳 }
斷點(diǎn)下載
方案一:
1>在方案一的基礎(chǔ)上新增兩個(gè)變量和按扭
@property (nonatomic,assign) long long currentLength; @property (nonatomic,strong) NSURLConnection *conn;
2>在接收到服務(wù)器返回?cái)?shù)據(jù)的代理方法中添加如下代碼
// 記錄斷點(diǎn),累計(jì)文件長度 self.currentLength += data.length;
3>點(diǎn)擊按鈕開始(繼續(xù))或暫停下載
- (IBAction)download:(UIButton *)sender {
sender.selected = !sender.isSelected;
if (sender.selected) { // 繼續(xù)(開始)下載
NSURL *url = [NSURL URLWithString:@""];
// ****關(guān)鍵點(diǎn)是使用NSMutableURLRequest,設(shè)置請(qǐng)求頭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>在接受到服務(wù)器響應(yīng)執(zhí)行的代理方法中第一行添加下面代碼,防止重復(fù)創(chuàng)建空文件
if (self.currentLength) return;
方案二:使用NSURLSessionDownloadDelegate的代理方法
所需變量
@property (nonatomic,strong) NSURLSession *session; @property (nonatomic,strong) NSData *resumeData; //包含了繼續(xù)下載的開始位置和下載的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) { // 開始(繼續(xù))下載
if (self.resumeData) { // 原先有數(shù)據(jù)則恢復(fù)
[self resume];
}else{
[self start]; // 原先沒有數(shù)據(jù)則開始
}
}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 : 包含了繼續(xù)下載的開始位置和下載的url
vc.resumeData = resumeData;
vc.task = nil;
}];
}
// 恢復(fù)
- (void)resume{
// 傳入上次暫停下載返回的數(shù)據(jù),就可以回復(fù)下載
self.task = [self.session downloadTaskWithResumeData:self.resumeData];
// 開始任務(wù)
[self.task resume];
// 清空
self.resumeData = nil;
}
#pragma mark - NSURLSessionDownloadDelegate
/**
下載完畢后調(diào)用
參數(shù):lication 臨時(shí)文件的路徑(下載好的文件)
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location{
// 創(chuàng)建存儲(chǔ)文件路徑
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
// response.suggestedFilename:建議使用的文件名,一般跟服務(wù)器端的文件名一致
NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
/**將臨時(shí)文件剪切或者復(fù)制到Caches文件夾
AtPath :剪切前的文件路徑
toPath :剪切后的文件路徑
*/
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr moveItemAtPath:location.path toPath:file error:nil];
}
/**
每當(dāng)下載完一部分時(shí)就會(huì)調(diào)用(可能會(huì)被調(diào)用多次)
參數(shù):
bytesWritten 這次調(diào)用下載了多少
totalBytesWritten 累計(jì)寫了多少長度到沙盒中了
totalBytesExpectedToWrite 文件總大小
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
// 這里可以做些顯示進(jìn)度等操作
}
/**
恢復(fù)下載時(shí)使用
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes
{
}
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。