導入AFNetworking 2.0 文件夾,引入頭文件AFNetworking.h
---------------
*使用NSURLSessionDownloadTask來下載一張圖片,並帶有下載進度(以下兩段代碼是一起的,注意)
NSProgress為iOS7新增加的類
// 定義一個progress指針 NSProgress *progress; // 創建一個URL鏈接 NSURL *url = [NSURL URLWithString:\ @"http://wallpapers.wallbase.cc/rozne/wallpaper-3020771.jpg"]; // 初始化一個請求 NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 獲取一個Session管理器 AFHTTPSessionManager *session = [AFHTTPSessionManager manager]; // 開始下載任務 NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { // 拼接一個文件夾路徑 NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; // 根據網址信息拼接成一個完整的文件存儲路徑並返回給block return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]]; } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { // 結束后移除掉這個progress [progress removeObserver:self forKeyPath:@"fractionCompleted" context:NULL]; }]; // 設置這個progress的唯一標示符 [progress setUserInfoObject:@"someThing" forKey:@"Y.X."]; [downloadTask resume]; // 給這個progress添加監聽任務 [progress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew context:NULL];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([keyPath isEqualToString:@"fractionCompleted"] && [object isKindOfClass:[NSProgress class]]) { NSProgress *progress = (NSProgress *)object; NSLog(@"Progress is %f", progress.fractionCompleted); // 打印這個唯一標示符 NSLog(@"%@", progress.userInfo); } }
*使用AFHTTPRequestOperation下載圖片的操作,不過,沒有進度顯示(源碼中也沒有相關方法-_-!)
// 組織一個請求 NSURLRequest *request = \ [NSURLRequest requestWithURL:\ [NSURL URLWithString:@"https://images0.cnblogs.com/i/607542/201404/050759358125578.png"]]; // 建立請求操作 AFHTTPRequestOperation *requestOperation = \ [[AFHTTPRequestOperation alloc] initWithRequest:request]; // 進行操作的配置(下載圖片,還有其他的類型) requestOperation.responseSerializer = [AFImageResponseSerializer serializer]; // 設置獲取數據的block [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { // 源碼中為並發線程池返回了主線程 NSLog(@"Response: %@", responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { // 源碼中為並發線程池返回了主線程 NSLog(@"Image error: %@", error); }]; // 開始執行 [requestOperation start];
*下載隊列,且能在后台下載,關閉了應用后還繼續下載(這個功能好^_^)
Upload and download tasks in background sessions are performed by an external daemon instead of by the app itself. As a result, the transfers continue in the background even if the app is suspended, exits, or crashes.
在后台進行上傳或者下載任務的會話,是被系統的程序管理而不是應用本身來管理的.所以呢,當app掛了,推出了甚至崩潰了,這個下載還是繼續着的
@interface DownloadsViewController () { AFURLSessionManager *manager; } @end
// 配置后台下載會話配置 NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"downloads"]; // 初始化SessionManager管理器 manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; // 獲取添加到該SessionManager管理器中的下載任務 NSArray *downloadTasks = [manager downloadTasks]; // 如果有下載任務 if (downloadTasks.count) { NSLog(@"downloadTasks: %@", downloadTasks); // 繼續全部的下載鏈接 for (NSURLSessionDownloadTask *downloadTask in downloadTasks) { [downloadTask resume]; } }
按按鈕添加一個下載任務到manager中
- (void)addDownloadTask:(id)sender { // 組織URL NSURL *URL = [NSURL URLWithString:@"http://pic.cnitblog.com/avatar/607542/20140226182241.png"]; // 組織請求 NSURLRequest *request = [NSURLRequest requestWithURL:URL]; // 給SessionManager管理器添加一個下載任務 NSURLSessionDownloadTask *downloadTask = \ [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { NSURL *documentsDirectoryPath = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]]; return [documentsDirectoryPath URLByAppendingPathComponent:[targetPath lastPathComponent]]; } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { NSLog(@"File downloaded to: %@", filePath); }]; [downloadTask resume]; // 打印下載的標示 NSLog(@"%d", downloadTask.taskIdentifier); }