iOS 文件下載、斷點(diǎn)下載

AFNetworking下載文件

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
// 1. 創(chuàng)建會話管理者
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
// 2. 創(chuàng)建下載路徑和請求對象
NSURL *URL = [NSURL URLWithString:@"http://dldir1.qq.com/qqfile/QQforMac/QQ_V5.4.0.dmg"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
// 3.創(chuàng)建下載任務(wù)
/**
 * 第一個參數(shù) - request:請求對象
 * 第二個參數(shù) - progress:下載進(jìn)度block
 *      其中: downloadProgress.completedUnitCount:已經(jīng)完成的大小
 *            downloadProgress.totalUnitCount:文件的總大小
 * 第三個參數(shù) - destination:自動完成文件剪切操作
 *      其中: 返回值:該文件應(yīng)該被剪切到哪里
 *            targetPath:臨時(shí)路徑 tmp NSURL
 *            response:響應(yīng)頭
 * 第四個參數(shù) - completionHandler:下載完成回調(diào)
 *      其中: filePath:真實(shí)路徑 == 第三個參數(shù)的返回值
 *            error:錯誤信息
 */
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress *downloadProgress) {
        
    // 下載進(jìn)度
    self.progressView.progress = 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
    self.progressLabel.text = [NSString stringWithFormat:@"當(dāng)前下載進(jìn)度:%.2f%%",100.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount];
        
} destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        
    NSURL *path = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
    return [path URLByAppendingPathComponent:@"QQ_V5.4.0.dmg"]; 
      
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {        
    NSLog(@"File downloaded to: %@", filePath);
}];

// 4. 開啟下載任務(wù)
[downloadTask resume];

AFNetworking斷點(diǎn)下載,離線下載

@interface ViewController ()

/** 下載進(jìn)度條 */
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
/** 下載進(jìn)度條Label */
@property (weak, nonatomic) IBOutlet UILabel *progressLabel;

/** AFNetworking斷點(diǎn)下載(支持離線)需用到的屬性 **********/
/** 文件的總長度 */
@property (nonatomic, assign) NSInteger fileLength;
/** 當(dāng)前下載長度 */
@property (nonatomic, assign) NSInteger currentLength;
/** 文件句柄對象 */
@property (nonatomic, strong) NSFileHandle *fileHandle;

/** 下載任務(wù) */
@property (nonatomic, strong) NSURLSessionDataTask *downloadTask;
/* AFURLSessionManager */
@property (nonatomic, strong) AFURLSessionManager *manager;

@end

/**
 * manager的懶加載
 */
- (AFURLSessionManager *)manager {
    if (!_manager) {
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        // 1. 創(chuàng)建會話管理者
        _manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    }
    return _manager;
}

/**
 * downloadTask的懶加載
 */
- (NSURLSessionDataTask *)downloadTask {
    if (!_downloadTask) {
        // 創(chuàng)建下載URL
        NSURL *url = [NSURL URLWithString:@"http://dldir1.qq.com/qqfile/QQforMac/QQ_V5.4.0.dmg"];
        
        // 2.創(chuàng)建request請求
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        
        // 設(shè)置HTTP請求頭中的Range
        NSString *range = [NSString stringWithFormat:@"bytes=%zd-", self.currentLength];
        [request setValue:range forHTTPHeaderField:@"Range"];
        
        __weak typeof(self) weakSelf = self;
        _downloadTask = [self.manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
            NSLog(@"dataTaskWithRequest");
            
            // 清空長度
            weakSelf.currentLength = 0;
            weakSelf.fileLength = 0;
            
            // 關(guān)閉fileHandle
            [weakSelf.fileHandle closeFile];
            weakSelf.fileHandle = nil;
            
        }];
        
        [self.manager setDataTaskDidReceiveResponseBlock:^NSURLSessionResponseDisposition(NSURLSession * _Nonnull session, NSURLSessionDataTask * _Nonnull dataTask, NSURLResponse * _Nonnull response) {
            NSLog(@"NSURLSessionResponseDisposition");
            
            // 獲得下載文件的總長度:請求下載的文件長度 + 當(dāng)前已經(jīng)下載的文件長度
            weakSelf.fileLength = response.expectedContentLength + self.currentLength;
            
            // 沙盒文件路徑
            NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"QQ_V5.4.0.dmg"];
            
            NSLog(@"File downloaded to: %@",path);
            
            // 創(chuàng)建一個空的文件到沙盒中
            NSFileManager *manager = [NSFileManager defaultManager];
            
            if (![manager fileExistsAtPath:path]) {
                // 如果沒有下載文件的話,就創(chuàng)建一個文件。如果有下載文件的話,則不用重新創(chuàng)建(不然會覆蓋掉之前的文件)
                [manager createFileAtPath:path contents:nil attributes:nil];
            }
            
            // 創(chuàng)建文件句柄
            weakSelf.fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
            
            // 允許處理服務(wù)器的響應(yīng),才會繼續(xù)接收服務(wù)器返回的數(shù)據(jù)
            return NSURLSessionResponseAllow;
        }];
        
        [self.manager setDataTaskDidReceiveDataBlock:^(NSURLSession * _Nonnull session, NSURLSessionDataTask * _Nonnull dataTask, NSData * _Nonnull data) {
            NSLog(@"setDataTaskDidReceiveDataBlock");
            
            // 指定數(shù)據(jù)的寫入位置 -- 文件內(nèi)容的最后面
            [weakSelf.fileHandle seekToEndOfFile];
            
            // 向沙盒寫入數(shù)據(jù)
            [weakSelf.fileHandle writeData:data];
            
            // 拼接文件總長度
            weakSelf.currentLength += data.length;
            
            // 獲取主線程,不然無法正確顯示進(jìn)度。
            NSOperationQueue* mainQueue = [NSOperationQueue mainQueue];
            [mainQueue addOperationWithBlock:^{
                // 下載進(jìn)度
                if (weakSelf.fileLength == 0) {
                    weakSelf.progressView.progress = 0.0;
                    weakSelf.progressLabel.text = [NSString stringWithFormat:@"當(dāng)前下載進(jìn)度:00.00%%"];
                } else {
                    weakSelf.progressView.progress =  1.0 * weakSelf.currentLength / weakSelf.fileLength;
                    weakSelf.progressLabel.text = [NSString stringWithFormat:@"當(dāng)前下載進(jìn)度:%.2f%%",100.0 * weakSelf.currentLength / weakSelf.fileLength];
                }
               
            }];
        }];
    }
    return _downloadTask;
}
/**
 * 點(diǎn)擊按鈕 -- 使用AFNetworking斷點(diǎn)下載(支持離線)
 */
- (IBAction)OfflinResumeDownloadBtnClicked:(UIButton *)sender {
    // 按鈕狀態(tài)取反
    sender.selected = !sender.isSelected;
    
    if (sender.selected) { // [開始下載/繼續(xù)下載]
        // 沙盒文件路徑
        NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"QQ_V5.4.0.dmg"];
        
        NSInteger currentLength = [self fileLengthForPath:path];
        if (currentLength > 0) {  // [繼續(xù)下載]
            self.currentLength = currentLength;
        }
        
        [self.downloadTask resume];
        
    } else {
        [self.downloadTask suspend];
        self.downloadTask = nil;
    }
}

/**
 * 獲取已下載的文件大小
 */
- (NSInteger)fileLengthForPath:(NSString *)path {
    NSInteger fileLength = 0;
    NSFileManager *fileManager = [[NSFileManager alloc] init]; // default is not thread safe
    if ([fileManager fileExistsAtPath:path]) {
        NSError *error = nil;
        NSDictionary *fileDict = [fileManager attributesOfItemAtPath:path error:&error];
        if (!error && fileDict) {
            fileLength = [fileDict fileSize];
        }
    }
    return fileLength;
}

直接下載NSData

// 創(chuàng)建下載路徑
NSURL *url = [NSURL URLWithString:@"http://pics.sc.chinaz.com/files/pic/pic9/201508/apic14052.jpg"];

// 使用NSData的dataWithContentsOfURL:方法下載
NSData *data = [NSData dataWithContentsOfURL:url];

// 如果下載的是將要顯示的圖片,則可以顯示出來
// 如果下載的是其他文件,然后可以將data轉(zhuǎn)存為本地文件

NSURLSession下載
如果想要監(jiān)聽下載進(jìn)度,我們就需要用到NSURLSessionDownloadDelegate。
具體使用方式就是使用代理的方法創(chuàng)建下載任務(wù),并且實(shí)現(xiàn)對應(yīng)的代理方法。

// 創(chuàng)建下載路徑
NSURL *url = [NSURL URLWithString:@"http://dldir1.qq.com/qqfile/QQforMac/QQ_V5.4.0.dmg"];
    
// 創(chuàng)建NSURLSession對象,并設(shè)計(jì)代理方法。其中NSURLSessionConfiguration為默認(rèn)配置
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    
// 創(chuàng)建任務(wù)
NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:url];
    
// 開始任務(wù)
[downloadTask resume];
#pragma mark <NSURLSessionDownloadDelegate> 實(shí)現(xiàn)方法
/**
 *  文件下載完畢時(shí)調(diào)用
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
    // 文件將要移動到的指定目錄
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    
    // 新文件路徑
    NSString *newFilePath = [documentsPath stringByAppendingPathComponent:@"QQ_V5.4.0.dmg"];
    
    NSLog(@"File downloaded to: %@",newFilePath);
    
    // 移動文件到新路徑
    [[NSFileManager defaultManager] moveItemAtPath:location.path toPath:newFilePath error:nil];
    
}

/**
 *  每次寫入數(shù)據(jù)到臨時(shí)文件時(shí),就會調(diào)用一次這個方法??稍谶@里獲得下載進(jìn)度
 *
 *  @param bytesWritten              這次寫入的文件大小
 *  @param totalBytesWritten         已經(jīng)寫入沙盒的文件大小
 *  @param totalBytesExpectedToWrite 文件總大小
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    
    // 下載進(jìn)度
    self.progressView.progress = 1.0 * totalBytesWritten / totalBytesExpectedToWrite;
    self.progressLabel.text = [NSString stringWithFormat:@"當(dāng)前下載進(jìn)度:%.2f%%",100.0 * totalBytesWritten / totalBytesExpectedToWrite];
}

/**
 *  恢復(fù)下載后調(diào)用
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes
{
    
}

NSURLSession 斷點(diǎn)下載,不支持離線
NSURLSession斷點(diǎn)下載(不支持離線)實(shí)現(xiàn)斷點(diǎn)下載的步驟如下:

在實(shí)現(xiàn)斷點(diǎn)下載的[開始/暫停]按鈕中添加以下步驟:
設(shè)置一個downloadTask、session以及resumeData的全局變量
如果開始下載,就創(chuàng)建一個新的downloadTask,并啟動下載
如果暫停下載,調(diào)用取消下載的函數(shù),并在block中保存本次的resumeData到全局resumeData中。
如果恢復(fù)下載,將上次保存的resumeData加入到任務(wù)中,并啟動下載。

@interface ViewController () <NSURLSessionDownloadDelegate>

/** 下載進(jìn)度條 */
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
/** 下載進(jìn)度條Label */
@property (weak, nonatomic) IBOutlet UILabel *progressLabel;

/** NSURLSession斷點(diǎn)下載(不支持離線)需用到的屬性 **********/
/** 下載任務(wù) */
@property (nonatomic, strong) NSURLSessionDownloadTask *downloadTask;
/** 保存上次的下載信息 */
@property (nonatomic, strong) NSData *resumeData;

/** session */
@property (nonatomic, strong) NSURLSession *session;

@end
/**
 * 點(diǎn)擊按鈕 -- 使用NSURLSession斷點(diǎn)下載(不支持離線)
 */
- (IBAction)resumeDownloadBtnClicked:(UIButton *)sender {
    // 按鈕狀態(tài)取反
    sender.selected = !sender.isSelected;
    
    if (nil == self.downloadTask) { // [開始下載/繼續(xù)下載]
        if (self.resumeData) { // [繼續(xù)下載]
            // 傳入上次暫停下載返回的數(shù)據(jù),就可以恢復(fù)下載
            self.downloadTask = [self.session downloadTaskWithResumeData:self.resumeData];
            
            // 開始任務(wù)
            [self.downloadTask resume];
            
            self.resumeData = nil;
        }else{ // [開始下載]:從0開始下載
            NSURL* url = [NSURL URLWithString:@"http://dldir1.qq.com/qqfile/QQforMac/QQ_V5.4.0.dmg"];
            
            // 創(chuàng)建任務(wù)
            self.downloadTask = [self.session downloadTaskWithURL:url];
            
            // 開始任務(wù)
            [self.downloadTask resume];
        }
        
    }else{ // [暫停下載]
        __weak typeof(self) weakSelf = self;
        [self.downloadTask cancelByProducingResumeData:^(NSData *resumeData) {
            // resumeData:包含了繼續(xù)下載的位置\下載的路徑
            weakSelf.resumeData = resumeData;
            weakSelf.downloadTask = nil;
        }];
    }
}

NSURLSession(斷點(diǎn)下載 | 支持離線)

@interface ViewController () <NSURLSessionDataDelegate>

/** 下載進(jìn)度條 */
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
/** 下載進(jìn)度條Label */
@property (weak, nonatomic) IBOutlet UILabel *progressLabel;

/** NSURLSession斷點(diǎn)下載(支持離線)需用到的屬性 **********/
/** 文件的總長度 */
@property (nonatomic, assign) NSInteger fileLength;
/** 當(dāng)前下載長度 */
@property (nonatomic, assign) NSInteger currentLength;
/** 文件句柄對象 */
@property (nonatomic, strong) NSFileHandle *fileHandle;

/** 下載任務(wù) */
@property (nonatomic, strong) NSURLSessionDataTask *downloadTask;
/** session */
@property (nonatomic, strong) NSURLSession *session;

@end
/**
 * session的懶加載
 */
- (NSURLSession *)session
{
    if (!_session) {
        _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
    return _session;
}

/**
 * downloadTask的懶加載,這里設(shè)置請求頭中的Range
 */
- (NSURLSessionDataTask *)downloadTask {
    if (!_downloadTask) {
        // 創(chuàng)建下載URL
        NSURL *url = [NSURL URLWithString:@"http://dldir1.qq.com/qqfile/QQforMac/QQ_V5.4.0.dmg"];
        
        // 2.創(chuàng)建request請求
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        
        // 設(shè)置HTTP請求頭中的Range
        NSString *range = [NSString stringWithFormat:@"bytes=%zd-", self.currentLength];
        [request setValue:range forHTTPHeaderField:@"Range"];
        
        // 3. 下載
        _downloadTask = [self.session dataTaskWithRequest:request];
    }
    return _downloadTask;
}

/**
 * 點(diǎn)擊按鈕 -- 使用NSURLSession斷點(diǎn)下載(支持離線)
 */
- (IBAction)OfflinResumeDownloadBtnClicked:(UIButton *)sender {
    // 按鈕狀態(tài)取反
    sender.selected = !sender.isSelected;
    
    if (sender.selected) { // [開始下載/繼續(xù)下載]
        // 沙盒文件路徑
        NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"QQ_V5.4.0.dmg"];
        
        NSInteger currentLength = [self fileLengthForPath:path];
        if (currentLength > 0) {  // [繼續(xù)下載]
            self.currentLength = currentLength;
        }
        
        [self.downloadTask resume];
        
    } else {
        [self.downloadTask suspend];
        self.downloadTask = nil;
    }
}

/**
 * 獲取已下載的文件大小
 */
- (NSInteger)fileLengthForPath:(NSString *)path {
    NSInteger fileLength = 0;
    NSFileManager *fileManager = [[NSFileManager alloc] init]; // default is not thread safe
    if ([fileManager fileExistsAtPath:path]) {
        NSError *error = nil;
        NSDictionary *fileDict = [fileManager attributesOfItemAtPath:path error:&error];
        if (!error && fileDict) {
            fileLength = [fileDict fileSize];
        }
    }
    return fileLength;
}
#pragma mark - <NSURLSessionDataDelegate> 實(shí)現(xiàn)方法
/**
 * 接收到響應(yīng)的時(shí)候:創(chuàng)建一個空的沙盒文件
 */
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    // 獲得下載文件的總長度:請求下載的文件長度 + 當(dāng)前已經(jīng)下載的文件長度
    self.fileLength = response.expectedContentLength + self.currentLength;
    
    // 沙盒文件路徑
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"QQ_V5.4.0.dmg"];
    
    NSLog(@"File downloaded to: %@",path);
    
    // 創(chuàng)建一個空的文件到沙盒中
    NSFileManager *manager = [NSFileManager defaultManager];
    
    if (![manager fileExistsAtPath:path]) {
        // 如果沒有下載文件的話,就創(chuàng)建一個文件。如果有下載文件的話,則不用重新創(chuàng)建(不然會覆蓋掉之前的文件)
        [manager createFileAtPath:path contents:nil attributes:nil];
    }
    
    // 創(chuàng)建文件句柄
    self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];

    // 允許處理服務(wù)器的響應(yīng),才會繼續(xù)接收服務(wù)器返回的數(shù)據(jù)
    completionHandler(NSURLSessionResponseAllow);
}

/**
 * 接收到具體數(shù)據(jù):把數(shù)據(jù)寫入沙盒文件中
 */
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    // 指定數(shù)據(jù)的寫入位置 -- 文件內(nèi)容的最后面
    [self.fileHandle seekToEndOfFile];
    
    // 向沙盒寫入數(shù)據(jù)
    [self.fileHandle writeData:data];
    
    // 拼接文件總長度
    self.currentLength += data.length;
    
    NSLog(@"%ld",self.currentLength);
    
    __weak typeof(self) weakSelf = self;
    // 獲取主線程,不然無法正確顯示進(jìn)度。
    NSOperationQueue* mainQueue = [NSOperationQueue mainQueue];
    [mainQueue addOperationWithBlock:^{
        // 下載進(jìn)度
        weakSelf.progressView.progress =  1.0 * weakSelf.currentLength / weakSelf.fileLength;
        weakSelf.progressLabel.text = [NSString stringWithFormat:@"當(dāng)前下載進(jìn)度:%.2f%%",100.0 * self.currentLength / self.fileLength];
    }];
}

/**
 *  下載完文件之后調(diào)用:關(guān)閉文件、清空長度
 */
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    // 關(guān)閉fileHandle
    [self.fileHandle closeFile];
    self.fileHandle = nil;
    
    // 清空長度
    self.currentLength = 0;
    self.fileLength = 0;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容