AFNetworking下載文件
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
// 1. 創(chuàng)建會(huì)話管理者
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
// 2. 創(chuàng)建下載路徑和請(qǐng)求對(duì)象
NSURL *URL = [NSURL URLWithString:@"http://dldir1.qq.com/qqfile/QQforMac/QQ_V5.4.0.dmg"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
// 3.創(chuàng)建下載任務(wù)
/**
* 第一個(gè)參數(shù) - request:請(qǐng)求對(duì)象
* 第二個(gè)參數(shù) - progress:下載進(jìn)度block
* 其中: downloadProgress.completedUnitCount:已經(jīng)完成的大小
* downloadProgress.totalUnitCount:文件的總大小
* 第三個(gè)參數(shù) - destination:自動(dòng)完成文件剪切操作
* 其中: 返回值:該文件應(yīng)該被剪切到哪里
* targetPath:臨時(shí)路徑 tmp NSURL
* response:響應(yīng)頭
* 第四個(gè)參數(shù) - completionHandler:下載完成回調(diào)
* 其中: filePath:真實(shí)路徑 == 第三個(gè)參數(shù)的返回值
* error:錯(cuò)誤信息
*/
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)下載(支持離線)需用到的屬性 **********/
/** 文件的總長(zhǎng)度 */
@property (nonatomic, assign) NSInteger fileLength;
/** 當(dāng)前下載長(zhǎng)度 */
@property (nonatomic, assign) NSInteger currentLength;
/** 文件句柄對(duì)象 */
@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)建會(huì)話管理者
_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請(qǐng)求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 設(shè)置HTTP請(qǐng)求頭中的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");
// 清空長(zhǎng)度
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");
// 獲得下載文件的總長(zhǎng)度:請(qǐng)求下載的文件長(zhǎng)度 + 當(dāng)前已經(jīng)下載的文件長(zhǎ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)建一個(gè)空的文件到沙盒中
NSFileManager *manager = [NSFileManager defaultManager];
if (![manager fileExistsAtPath:path]) {
// 如果沒有下載文件的話赚导,就創(chuàng)建一個(gè)文件茬缩。如果有下載文件的話,則不用重新創(chuàng)建(不然會(huì)覆蓋掉之前的文件)
[manager createFileAtPath:path contents:nil attributes:nil];
}
// 創(chuàng)建文件句柄
weakSelf.fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
// 允許處理服務(wù)器的響應(yīng)吼旧,才會(huì)繼續(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];
// 拼接文件總長(zhǎng)度
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)對(duì)應(yīng)的代理方法。
// 創(chuàng)建下載路徑
NSURL *url = [NSURL URLWithString:@"http://dldir1.qq.com/qqfile/QQforMac/QQ_V5.4.0.dmg"];
// 創(chuàng)建NSURLSession對(duì)象昵济,并設(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
{
// 文件將要移動(dòng)到的指定目錄
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
// 新文件路徑
NSString *newFilePath = [documentsPath stringByAppendingPathComponent:@"QQ_V5.4.0.dmg"];
NSLog(@"File downloaded to: %@",newFilePath);
// 移動(dòng)文件到新路徑
[[NSFileManager defaultManager] moveItemAtPath:location.path toPath:newFilePath error:nil];
}
/**
* 每次寫入數(shù)據(jù)到臨時(shí)文件時(shí),就會(huì)調(diào)用一次這個(gè)方法访忿∏评酰可在這里獲得下載進(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è)置一個(gè)downloadTask海铆、session以及resumeData的全局變量
如果開始下載迹恐,就創(chuàng)建一個(gè)新的downloadTask,并啟動(dòng)下載
如果暫停下載卧斟,調(diào)用取消下載的函數(shù)殴边,并在block中保存本次的resumeData到全局resumeData中。
如果恢復(fù)下載珍语,將上次保存的resumeData加入到任務(wù)中锤岸,并啟動(dòng)下載。
@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)下載(支持離線)需用到的屬性 **********/
/** 文件的總長(zhǎng)度 */
@property (nonatomic, assign) NSInteger fileLength;
/** 當(dāng)前下載長(zhǎng)度 */
@property (nonatomic, assign) NSInteger currentLength;
/** 文件句柄對(duì)象 */
@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è)置請(qǐng)求頭中的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請(qǐng)求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 設(shè)置HTTP請(qǐng)求頭中的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)建一個(gè)空的沙盒文件
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
// 獲得下載文件的總長(zhǎng)度:請(qǐng)求下載的文件長(zhǎng)度 + 當(dāng)前已經(jīng)下載的文件長(zhǎ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)建一個(gè)空的文件到沙盒中
NSFileManager *manager = [NSFileManager defaultManager];
if (![manager fileExistsAtPath:path]) {
// 如果沒有下載文件的話,就創(chuàng)建一個(gè)文件募逞。如果有下載文件的話蛋铆,則不用重新創(chuàng)建(不然會(huì)覆蓋掉之前的文件)
[manager createFileAtPath:path contents:nil attributes:nil];
}
// 創(chuàng)建文件句柄
self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
// 允許處理服務(wù)器的響應(yīng),才會(huì)繼續(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];
// 拼接文件總長(zhǎng)度
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)閉文件、清空長(zhǎng)度
*/
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
// 關(guān)閉fileHandle
[self.fileHandle closeFile];
self.fileHandle = nil;
// 清空長(zhǎng)度
self.currentLength = 0;
self.fileLength = 0;
}