本文主要是介绍AFNetworking 2.0使用(持续更新),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
导入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];// 根据网址信息拼接成一个完整的文件存储路径并返回给blockreturn [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error){// 结束后移除掉这个progress [progress removeObserver:selfforKeyPath:@"fractionCompleted"context:NULL];}];// 设置这个progress的唯一标示符[progress setUserInfoObject:@"someThing" forKey:@"Y.X."];[downloadTask resume];// 给这个progress添加监听任务 [progress addObserver:selfforKeyPath:@"fractionCompleted"options:NSKeyValueObservingOptionNewcontext: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:@"http://images.cnitblog.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 {// 组织URLNSURL *URL = [NSURL URLWithString:@"http://pic.cnitblog.com/avatar/607542/20140226182241.png"];// 组织请求NSURLRequest *request = [NSURLRequest requestWithURL:URL];// 给SessionManager管理器添加一个下载任务NSURLSessionDownloadTask *downloadTask = \[manager downloadTaskWithRequest:requestprogress:nildestination:^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); }
这篇关于AFNetworking 2.0使用(持续更新)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!