AFNetworking粗解(解析)

AFNetworking粗解(解析)_第1张图片
111180.png

1.官网文档外加点中文注释
AFNetworking官网(点击进入)

AFNetworking翻译注释
Architecture(结构)
NSURLConnection
• AFURLConnectionOperation
• AFHTTPRequestOperation
• AFHTTPRequestOperationManager
NSURLSession (iOS 7 / Mac OS X 10.9)
• AFURLSessionManager
• AFHTTPSessionManager
Serialization(序列化)

• AFHTTPRequestSerializer
• AFJSONRequestSerializer
• AFPropertyListRequestSerializer

• AFHTTPResponseSerializer
• AFJSONResponseSerializer
• AFXMLParserResponseSerializer
• AFXMLDocumentResponseSerializer (Mac OS X)
• AFPropertyListResponseSerializer
• AFImageResponseSerializer
• AFCompoundResponseSerializer
Additional Functionality
• AFSecurityPolicy
• AFNetworkReachabilityManager
Usage(使用)
HTTP Request Operation Manager(HTTP请求操作管理器)
AFHTTPRequestOperationManager encapsulates the common patterns of communicating with a web application over HTTP, including request creation, response serialization, network reachability monitoring, and security, as well as request operation management.
AFHTTPRequestOperationManager 将通用的与服务器应用交互的操作封装了起来,包括了请求的创建,回复的序列化,网络指示器的监测,安全性,当然还有请求操作的管理。

GET Request(GET请求)

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];[manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {   
 NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {    
NSLog(@"Error: %@", error);
}];
POST URL-Form-Encoded Request(附带表单编码的POST请求)
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
[manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {    
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {   
 NSLog(@"Error: %@", error);
}];
POST Multi-Part Request(复杂的POST请求)
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];NSDictionary *parameters = @{@"foo": @"bar"};
NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id formData) {   
 [formData appendPartWithFileURL:filePath name:@"image" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) { 
   NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {   
 NSLog(@"Error: %@", error);}];

AFURLSessionManager

AFURLSessionManager creates and manages an NSURLSession object based on a specified NSURLSessionConfiguration object, which conforms to , , , and .
AFURLSessionManager 创建了一个管理一个NSURLSession的对象,基于一个指定的NSURLSessionConfiguration对象,它与以下的这些协议融合在一起(, , ,)。
Creating a Download Task(创建一个下载任务)
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {   
 NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];   
 return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {  
  NSLog(@"File downloaded to: %@", filePath);
}];
[downloadTask resume];
Creating an Upload Task(创建一个上传任务)
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {    
if (error) {      
 NSLog(@"Error: %@", error);   
 } else {      
  NSLog(@"Success: %@ %@", response, responseObject);  
  }}];
[uploadTask resume];
Creating an Upload Task for a Multi-Part Request, with Progress(创建一个复杂的请求,并附带进度)
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id formData) {        [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];    } error:nil];   
 AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];   
 NSProgress *progress = nil;  
  NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {       
 if (error) {         
   NSLog(@"Error: %@", error);      
  } else {         
  NSLog(@"%@ %@", response, responseObject);       
 }    }];   
 [uploadTask resume];
Creating a Data Task(创建一个数据任务)
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {   
 if (error) {        
NSLog(@"Error: %@", error);    } else {       
 NSLog(@"%@ %@", response, responseObject); 
   }}];
[dataTask resume];

Request Serialization(请求序列化)

Request serializers create requests from URL strings, encoding parameters as either a query string or HTTP body.
请求序列化器会从URL字符串创建请求,编码参数,查找字符串或者是HTTPbody部分。
NSString *URLString = @"http://example.com";NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};
Query String Parameter Encoding(查询string的编码)
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3
URL Form Parameter Encoding(查询URL表单形式参数的编码)
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];
POST http://example.com/Content-Type: application/x-www-form-urlencodedfoo=bar&baz[]=1&baz[]=2&baz[]=3
JSON Parameter Encoding(查询json参数的编码)
[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];
POST http://example.com/Content-Type: application/json{"foo": "bar", "baz": [1,2,3]}

Network Reachability Manager(监测网络管理器)
AFNetworkReachabilityManager monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.
AFNetworkReachabilityManager 监测域名以及IP地址的畅通性,对于WWAN以及WiFi的网络接口都管用。
Shared Network Reachability(单例形式检测网络畅通性)
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {    NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));}];
HTTP Manager with Base URL(用基本的URL管理HTTP)
When a baseURL is provided, network reachability is scoped to the host of that base URL.
如果提供了一个基本的URL地址,那个基本URL网址的畅通性就会被仔细的监测着。
NSURL *baseURL = [NSURL URLWithString:@"http://example.com/"];AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];NSOperationQueue *operationQueue = manager.operationQueue;[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {    switch (status) {        case AFNetworkReachabilityStatusReachableViaWWAN:        case AFNetworkReachabilityStatusReachableViaWiFi:            [operationQueue setSuspended:NO];            break;        case AFNetworkReachabilityStatusNotReachable:        default:            [operationQueue setSuspended:YES];            break;    }}];

Security Policy

AFSecurityPolicy evaluates server trust against pinned X.509 certificates and public keys over secure connections.
Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled.
Allowing Invalid SSL Certificates(允许不合法的SSL证书)
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production

AFHTTPRequestOperation

AFHTTPRequestOperation is a subclass of AFURLConnectionOperation for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request.
Although AFHTTPRequestOperationManager is usually the best way to go about making requests, AFHTTPRequestOperation can be used by itself.
AFHTTPRequestOperation继承自AFURLConnectionOperation,使用HTTP以及HTTPS协议来处理网络请求。它封装成了一个可以令人接受的代码形式。当然AFHTTPRequestOperationManager 目前是最好的用来处理网络请求的方式,但AFHTTPRequestOperation 也有它自己的用武之地。
GET with AFHTTPRequestOperation(使用AFHTTPRequestOperation)
NSURL *URL = [NSURL URLWithString:@"http://example.com/resources/123.json"];NSURLRequest *request = [NSURLRequest requestWithURL:URL];AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];op.responseSerializer = [AFJSONResponseSerializer serializer];[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {    NSLog(@"JSON: %@", responseObject);} failure:^(AFHTTPRequestOperation *operation, NSError *error) {    NSLog(@"Error: %@", error);}];[[NSOperationQueue mainQueue] addOperation:op];
Batch of Operations(许多操作一起进行)
NSMutableArray *mutableOperations = [NSMutableArray array];for (NSURL *fileURL in filesToUpload) {    NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id formData) {        [formData appendPartWithFileURL:fileURL name:@"images[]" error:nil];    }];    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];    [mutableOperations addObject:operation];}NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:@[...] progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {    NSLog(@"%lu of %lu complete", numberOfFinishedOperations, totalNumberOfOperations);} completionBlock:^(NSArray *operations) {    NSLog(@"All operations in batch complete");}];[[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];

2.官网文档外加点中文注释

原创翻译微博(点击可进入)

AFNetworking 2.0
AFNetworking 是当前 iOS 和 OS X 开发中最广泛使用的开源项目之一。它帮助了成千上万叫好又叫座的应用,也为其它出色的开源库提供了基础。这个项目是社区里最活跃、最有影响力的项目之一,拥有 8700 个 star、2200 个 fork 和 130 名贡献者。
从各方面来看,AFNetworking 几乎已经成为主流。
但你有没有听说过它的新版呢? AFNetworking 2.0。
这一周的 NSHipster:独家揭晓 AFNetworking 的未来。
声明:NSHipster 由 AFNetworking 的作者 撰写,所以这并不是对 AFNetworking 及它的优点的客观看法。你能看到的是个人关于 AFNetworking 目前及未来版本的真实看法。
AFNetworking 的大体思路
始于 2011 年 5 月,AFNetworking 作为一个已死的 LBS 项目中对 Apple 范例代码的延伸,它的成功更是由于时机。彼时 ASIHTTPRequest 是网络方面的主流方案,AFNetworking 的核心思路使它正好成为开发者渴求的更现代的方案。
NSURLConnection + NSOperation
NSURLConnection 是 Foundation URL 加载系统的基石。一个 NSURLConnection 异步地加载一个NSURLRequest 对象,调用 delegate 的 NSURLResponse / NSHTTPURLResponse 方法,其 NSData 被发送到服务器或从服务器读取;delegate 还可用来处理 NSURLAuthenticationChallenge、重定向响应、或是决定 NSCachedURLResponse 如何存储在共享的 NSURLCache 上。
NSOperation 是抽象类,模拟单个计算单元,有状态、优先级、依赖等功能,可以取消。
AFNetworking 的第一个重大突破就是将两者结合。AFURLConnectionOperation 作为 NSOperation 的子类,遵循 NSURLConnectionDelegate 的方法,可以从头到尾监视请求的状态,并储存请求、响应、响应数据等中间状态。
Blocks
iOS 4 引入的 block 和 Grand Central Dispatch 从根本上改善了应用程序的开发过程。相比于在应用中用 delegate 乱七八糟地实现逻辑,开发者们可以用 block 将相关的功能放在一起。GCD 能够轻易来回调度工作,不用面对乱七八糟的线程、调用和操作队列。
更重要的是,对于每个 request operation,可以通过 block 自定义 NSURLConnectionDelegate 的方法(比如,通过 setWillSendRequestForAuthenticationChallengeBlock: 可以覆盖默认的connection:willSendRequestForAuthenticationChallenge: 方法)。
现在,我们可以创建 AFURLConnectionOperation 并把它安排进 NSOperationQueue,通过设置NSOperation 的新属性 completionBlock,指定操作完成时如何处理 response 和 response data(或是请求过程中遇到的错误)。
序列化 & 验证
更深入一些,request operation 操作也可以负责验证 HTTP 状态码和服务器响应的内容类型,比如,对于 application/json MIME 类型的响应,可以将 NSData 序列化为 JSON 对象。
从服务器加载 JSON、XML、property list 或者图像可以抽象并类比成潜在的文件加载操作,这样开发者可以将这个过程想象成一个 promise 而不是异步网络连接。
介绍 AFNetworking 2.0
AFNetworking 胜在易于使用和可扩展之间取得的平衡,但也并不是没有提升的空间。
在第二个大版本中,AFNetworking 旨在消除原有设计的怪异之处,同时为下一代 iOS 和 OS X 应用程序增加一些强大的新架构。
动机

兼容 NSURLSession - NSURLSession 是 iOS 7 新引入的用于替代 NSURLConnection 的类。NSURLConnection 并没有被弃用,今后一段时间应该也不会,但是 NSURLSession 是 Foundation 中网络的未来,并且是一个美好的未来,因为它改进了之前的很多缺点。(参考 WWDC 2013 Session 705 “What’s New in Foundation Networking”,一个很好的概述)。起初有人推测,NSURLSession 的出现将使 AFNetworking 不再有用。但实际上,虽然它们有一些重叠,AFNetworking 还是可以提供更高层次的抽象。AFNetworking 2.0 不仅做到了这一点,还借助并扩展 NSURLSession 来铺平道路上的坑洼,并最大程度扩展了它的实用性。

模块化 - 对于 AFNetworking 的主要批评之一是笨重。虽然它的构架使在类的层面上是模块化的,但它的包装并不允许选择独立的一些功能。随着时间的推移,AFHTTPClient尤其变得不堪重负(其任务包括创建请求、序列化 query string 参数、确定响应解析行为、生成和管理 operation、监视网络可达性)。 在 AFNetworking 2.0 中,你可以挑选并通过 CocoaPods subspecs 选择你所需要的组件。

实时性 - 在新版本中,AFNetworking 尝试将实时性功能提上日程。在接下来的 18 个月,实时性将从最棒的 1% 变成用户都期待的功能。 AFNetworking 2.0 采用 Rocket技术,利用 Server-Sent Event 和 JSON Patch 等网络标准在现有的 REST 网络服务上构建语义上的实时服务。

演员阵容
NSURLConnection 组件 (iOS 6 & 7)

AFURLConnectionOperation - NSOperation 的子类,负责管理 NSURLConnection 并且实现其 delegate 方法。

AFHTTPRequestOperation - AFURLConnectionOperation 的子类,用于生成 HTTP 请求,可以区别可接受的和不可接受的状态码及内容类型。2.0 版本中的最大区别是,你可以直接使用这个类,而不用继承它,原因可以在“序列化”一节中找到。

AFHTTPRequestOperationManager - 包装常见 HTTP web 服务操作的类,通过AFHTTPRequestOperation 由 NSURLConnection 支持。
NSURLSession 组件 (iOS 7)

AFURLSessionManager - 创建、管理基于 NSURLSessionConfiguration 对象的NSURLSession 对象的类,也可以管理 session 的数据、下载/上传任务,实现 session 和其相关联的任务的 delegate 方法。因为 NSURLSession API 设计中奇怪的空缺,任何和NSURLSession 相关的代码都可以用 AFURLSessionManager 改善。

AFHTTPSessionManager - AFURLSessionManager 的子类,包装常见的 HTTP web 服务操作,通过 AFURLSessionManager 由 NSURLSession 支持。

总的来说:为了支持新的 NSURLSession API 以及旧的未弃用且还有用的NSURLConnection,AFNetworking 2.0 的核心组件分成了 request operation 和 session 任务。AFHTTPRequestOperationManager 和 AFHTTPSessionManager 提供类似的功能,在需要的时候(比如在 iOS 6 和 7 之间转换),它们的接口可以相对容易的互换。
之前所有绑定在 AFHTTPClient的功能,比如序列化、安全性、可达性,被拆分成几个独立的模块,可被基于 NSURLSession 和 NSURLConnection 的 API 使用。

序列化
AFNetworking 2.0 新构架的突破之一是使用序列化来创建请求、解析响应。可以通过序列化的灵活设计将更多业务逻辑转移到网络层,并更容易定制之前内置的默认行为。

- 符合这个协议的对象用于处理请求,它将请求参数转换为 query string 或是 entity body 的形式,并设置必要的 header。那些不喜欢 AFHTTPClient使用 query string 编码参数的家伙,你们一定喜欢这个。

- 符合这个协议的对象用于验证、序列化响应及相关数据,转换为有用的形式,比如 JSON 对象、图像、甚至基于 Mantle 的模型对象。相比没完没了地继承 AFHTTPClient,现在 AFHTTPRequestOperation 有一个 responseSerializer 属性,用于设置合适的 handler。同样的,再也没有没用的受 NSURLProtocol 启发的 request operation 类注册,取而代之的还是很棒的 responseSerializer 属性。谢天谢地。

安全性
感谢 Dustin Barker、Oliver Letterer、Kevin Harwood 等人做出的贡献,AFNetworking 现在带有内置的 SSL pinning 支持,这对于处理敏感信息的应用是十分重要的。
AFSecurityPolicy - 评估服务器对安全连接针对指定的固定证书或公共密钥的信任。tl;dr 将你的服务器证书添加到 app bundle,以帮助防止 中间人攻击。

可达性
从 AFHTTPClient 解藕的另一个功能是网络可达性。现在你可以直接使用它,或者使用AFHTTPRequestOperationManager / AFHTTPSessionManager 的属性。
AFNetworkReachabilityManager - 这个类监控当前网络的可达性,提供回调 block 和 notificaiton,在可达性变化时调用。

实时性
AFEventSource - EventSource DOM API 的 Objective-C 实现。建立一个到某主机的持久 HTTP 连接,可以将事件传输到事件源并派发到听众。传输到事件源的消息的格式为JSON Patch 文件,并被翻译成 AFJSONPatchOperation 对象的数组。可以将这些 patch operation 应用到之前从服务器获取的持久性数据集。

{objective-c} NSURL *URL = [NSURL URLWithString:@"http://example.com"]; AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:URL]; [manager GET:@"/resources" parameters:nil success:NSURLSessionDataTask *task, id responseObject { [resources addObjectsFromArray:responseObject[@"resources"]];

[manager SUBSCRIBE:@"/resources" usingBlock:NSArray *operations, NSError *error { for (AFJSONPatchOperation *operation in operations) { 
switch (operation.type) { 
case AFJSONAddOperationType: [resources addObject:operation.value]; break; default: break;
 } }
 } error:nil]; 
} failure:nil]; 

UIKit 扩展
`
之前 AFNetworking 中的所有 UIKit category 都被保留并增强,还增加了一些新的 category。

AFNetworkActivityIndicatorManager:在请求操作开始、停止加载时,自动开始、停止状态栏上的网络活动指示图标。

UIImageView+AFNetworking:增加了 imageResponseSerializer 属性,可以轻松地让远程加载到 image view 上的图像自动调整大小或应用滤镜。比如,AFCoreImageSerializer可以在 response 的图像显示之前应用 Core Image filter。

UIButton+AFNetworking (新):与 UIImageView+AFNetworking 类似,从远程资源加载image 和 backgroundImage。

UIActivityIndicatorView+AFNetworking (新):根据指定的请求操作和会话任务的状态自动开始、停止 UIActivityIndicatorView。

UIProgressView+AFNetworking (新):自动跟踪某个请求或会话任务的上传/下载进度。
UIWebView+AFNetworking (新): 为加载 URL 请求提供了更强大的API,支持进度回调和内容转换。
`

于是终于要结束 AFNetworking 旋风之旅了。为下一代应用设计的新功能,结合为已有功能设计的全新架构,有很多东西值得兴奋。
旗开得胜
将下列代码加入 Podfile 就可以开始把玩 AFNetworking 2.0 了:
platform :ios, '7.0'pod "AFNetworking", "2.0.0"

3.中文详细解析
(点击进入)
AFNetworking2.0源码解析<一>
AFNetworking2.0源码解析<二>
AFNetworking2.0源码解析<三>

4.源代码

可以下载的URL:

#define Pictureurl @"http://x1.zhuti.com/down/2012/11/29-win7/3D-1.jpg"
#define imagurl @"http://pic.cnitblog.com/avatar/607542/20140226182241.png"
#define Musicurl @"http://bcs.duapp.com/chenwei520/media/music.mp3"
#define Zipurl @"http://example.com/download.zip"
#define Jsonurl @"https://api.douban.com/v2/movie/us_box"
#define Xmlurl @"http://flash.weather.com.cn/wmaps/xml/beijing.xml"
#define Movieurl @"http://bcs.duapp.com/chenwei520/media/mobile_vedio.mp4"

interface中需要创建的UI
[objc] view plaincopyprint?

1.  
@interface ViewController () 
2.  
3.  @end 
4.  
5.  @implementation ViewController{ 
6.  
7.  UIProgressView *_progressView; 
8.  UIActivityIndicatorView *_activitView; 
9.  AFURLSessionManager *SessionManage; 
10. 
11. } 
12. 
13. - (void)viewDidLoad 
14. { 
15. [super viewDidLoad]; 
16. _progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault]; 
17. _progressView.frame = CGRectMake(0,100,320,20); 
18. _progressView.tag = 2014; 
19. _progressView.progress = 0.0; 
20. [self.view addSubview:_progressView]; 
21. 
22. _activitView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; 
23. _activitView.frame = CGRectMake(160, 140, 0, 0); 
24. _activitView.backgroundColor = [UIColor yellowColor]; 
25. [self.view addSubview:_activitView]; 
26. 
27. //添加下载任务 
28. UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
29. button.frame = CGRectMake(140, 60, 40, 20); 
30. [button setTitle:@"下载" forState:UIControlStateNormal]; 
31. button.backgroundColor = [UIColor orangeColor]; 
32. 
33. [button addTarget:self action:@selector(addDownloadTask:) forControlEvents:UIControlEventTouchUpInside]; 
34. [self.view addSubview:button]; 
@interface ViewController ()@end@implementation ViewController{    UIProgressView *_progressView;    UIActivityIndicatorView *_activitView;    AFURLSessionManager *SessionManage;}- (void)viewDidLoad{    [super viewDidLoad];    _progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];    _progressView.frame = CGRectMake(0,100,320,20);    _progressView.tag = 2014;    _progressView.progress = 0.0;    [self.view addSubview:_progressView];        _activitView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];    _activitView.frame = CGRectMake(160, 140, 0, 0);    _activitView.backgroundColor = [UIColor yellowColor];    [self.view addSubview:_activitView];        //添加下载任务    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];    button.frame = CGRectMake(140, 60, 40, 20);    [button setTitle:@"下载" forState:UIControlStateNormal];    button.backgroundColor = [UIColor orangeColor];        [button addTarget:self action:@selector(addDownloadTask:) forControlEvents:UIControlEventTouchUpInside];    [self.view addSubview:button];

//AFHTTPRequestOperationManager无参数的GET请求(成功)
[objc] view plaincopyprint?

1.  - (void)GETTask1{//下载成功 
2.  
3.  NSString *url = Musicurl; 
4.  
5.  AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 
6.  
7.  manager.responseSerializer = [AFHTTPResponseSerializer serializer];//不对数据解析 
8.  
9.  //无参数的GET请求下载parameters:nil,也可以带参数 
10. AFHTTPRequestOperation *operation = [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) { 
11. 
12. //下载完成后打印这个 
13. NSLog(@"下载完成"); 
14. 
15. _progressView.hidden = YES; 
16. 
17. } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
18. 
19. NSLog(@"下载失败"); 
20. 
21. }]; 
22. 
23. //定义下载路径 
24. NSString *filePath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@",[url lastPathComponent]]; 
25. 
26. NSLog(@"%@",filePath); 
27. 
28. ///Users/mac1/Library/Application Support/iPhone Simulator/7.1/Applications/787B2D0B-A400-4177-9914-25DA7F40A54B/Documents/music.mp3 
29. 
30. //创建下载文件 
31. if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { 
32. 
33. //会自动将数据写入文件 
34. [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil]; 
35. 
36. } 
37. 
38. //加载进度视图 
39. [_activitView setAnimatingWithStateOfOperation:operation]; 
40. 
41. //使用AF封装好的类目UIProgressView+AFNetworking.h 
42. if (operation != nil) { 
43. //下载进度 
44. [_progressView setProgressWithDownloadProgressOfOperation:operation animated:YES]; 
45. } 
46. 
47. //设置下载的输出流,而此输出流写入文件,这里可以计算传输文件的大小 
48. operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:YES]; 
49. 
50. __weak ViewController *weakSelf = self; 
51. 
52. //监听的下载的进度 
53. /* 
54. * 
55. * bytesRead 每次传输的数据包大小 
56. * totalBytesRead 已下载的数据大小 
57. * totalBytesExpectedToRead 总大小 
58. * 
59. */ 
60. 
61. //调用Block监听下载传输情况 
62. [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) { 
63. 
64. CGFloat progess = totalBytesRead/(CGFloat)totalBytesExpectedToRead; 
65. 
66. __strong ViewController *strongSelf = weakSelf; 
67. 
68. strongSelf->_progressView.progress = progess; 
69. 
70. }]; 
71. 
72. } 
- (void)GETTask1{//下载成功        NSString *url = Musicurl;        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];        manager.responseSerializer = [AFHTTPResponseSerializer serializer];//不对数据解析        //无参数的GET请求下载parameters:nil,也可以带参数    AFHTTPRequestOperation *operation = [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {                //下载完成后打印这个        NSLog(@"下载完成");                _progressView.hidden = YES;            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {                NSLog(@"下载失败");            }];        //定义下载路径    NSString *filePath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@",[url lastPathComponent]];        NSLog(@"%@",filePath);        ///Users/mac1/Library/Application Support/iPhone Simulator/7.1/Applications/787B2D0B-A400-4177-9914-25DA7F40A54B/Documents/music.mp3        //创建下载文件    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {                //会自动将数据写入文件        [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];            }        //加载进度视图    [_activitView setAnimatingWithStateOfOperation:operation];        //使用AF封装好的类目UIProgressView+AFNetworking.h    if (operation != nil) {        //下载进度        [_progressView setProgressWithDownloadProgressOfOperation:operation animated:YES];    }        //设置下载的输出流,而此输出流写入文件,这里可以计算传输文件的大小    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:YES];        __weak ViewController *weakSelf = self;        //监听的下载的进度    /*     *     * bytesRead                每次传输的数据包大小     * totalBytesRead           已下载的数据大小     * totalBytesExpectedToRead 总大小     *     */        //调用Block监听下载传输情况    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {                CGFloat progess = totalBytesRead/(CGFloat)totalBytesExpectedToRead;                __strong ViewController *strongSelf = weakSelf;                strongSelf->_progressView.progress = progess;            }];    }

//AFHTTPRequestOperationManager附带表单编码的POST请求-------URL-Form-Encoded(成功)

[objc] view plaincopyprint?

1.  - (void)POSTTask1{//发送微博成功 
2.  
3.  NSMutableDictionary *params = [NSMutableDictionary dictionary]; 
4.  [params setValue:@"正在发微博" forKey:@"status"];//发送微博的类容 
5.  [params setValue:@"xxxxxx" forKey:@"access_token"];//XXXXX自己注册新浪微博开发账号得到的令牌 
6.  
7.  NSString *urlstring = @"https://api.weibo.com/2/statuses/updata.json"; 
8.  
9.  AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 
10. AFHTTPRequestOperation *operation = nil; 
11. 
12. operation = [manager POST:urlstring parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { 
13. 
14. NSLog(@"发送成功:%@",responseObject); 
15. 
16. } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
17. 
18. NSLog(@"网络请求失败:%@",error); 
19. 
20. }]; 
21. 
22. } 
- (void)POSTTask1{//发送微博成功    NSMutableDictionary *params = [NSMutableDictionary dictionary];    [params setValue:@"正在发微博" forKey:@"status"];//发送微博的类容    [params setValue:@"xxxxxx" forKey:@"access_token"];//XXXXX自己注册新浪微博开发账号得到的令牌        NSString *urlstring = @"https://api.weibo.com/2/statuses/updata.json";        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];    AFHTTPRequestOperation *operation = nil;        operation = [manager POST:urlstring parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {                NSLog(@"发送成功:%@",responseObject);            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {                NSLog(@"网络请求失败:%@",error);            }];}

//AFHTTPRequestOperationManager复杂的POST请求--------Multi-Part(成功)

[objc] view plaincopyprint?

1.  - (void)POSTTask2{ 
2.  
3.  //file://本地文件传输协议,file:// + path就是完整路径,可以用浏览器打开 
4.  //file:///Users/mac1/Desktop/whrite.png 
5.  
6.  AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 
7.  AFHTTPRequestOperation *operation = nil; 
8.  
9.  NSMutableDictionary *params = [NSMutableDictionary dictionary]; 
10. [params setValue:@"带图片哦" forKey:@"status"]; 
11. [params setValue:@"XXXXXX" forKey:@"access_token"]; 
12. 
13. 
14. //方式一(拖到编译器中的图片) 
15. //UIImage *_sendImg = [UIImage imageNamed:@"whrite.png"]; 
16. //NSData *data = UIImageJPEGRepresentation(_sendImg, 1); 
17. //NSData *data = UIImagePNGRepresentation(_sendImg); 
18. 
19. //方式二(程序包中的图片) 
20. //NSString *theImagePath = [[NSBundle mainBundle] pathForResource:@"whrite"ofType:@"png"];//文件包路径,在程序包中 
21. //NSURL *Imagefile = [NSURL fileURLWithPath:theImagePath]; 
22. 
23. //方式三,沙盒中的图片 
24. NSString *pathstring = [NSHomeDirectory() stringByAppendingPathComponent:@"/Documents/whrite.png"];//从沙盒中找到文件,沙盒中需要有这个whrite.png图片 
25. NSURL *urlfile = [NSURL fileURLWithPath:pathstring]; 
26. 
27. operation = [manager POST:@"https://api.weibo.com/2/statuses/upload.json" parameters:params constructingBodyWithBlock:^(id formData) {//multipart/form-data编码方式 
28. 
29. //方式二和三调用的方法,给的是URL 
30. [formData appendPartWithFileURL:urlfile name:@"pic" error:nil];//name:@"pic"新浪微博要求的名字,去阅读新浪的API文档 
31. 
32. //方式三调用的方法,给的是Data 
33. //[formData appendPartWithFileData:data name:@"pic" fileName:@"pic" mimeType:@"image/png"]; 
34. 
35. 
36. } success:^(AFHTTPRequestOperation *operation, id responseObject) { 
37. NSLog(@"Success: %@", responseObject); 
38. 
39. } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
40. NSLog(@"Error: %@", error); 
41. }]; 
42. 
43. //监听进度 
44. [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) { 
45. 
46. CGFloat progress = totalBytesWritten/(CGFloat)totalBytesExpectedToWrite; 
47. NSLog(@"进度:%.1f",progress); 
48. 
49. }]; 
50. 
51. } 
- (void)POSTTask2{      
  //file://本地文件传输协议,
file:// + path就是完整路径,可以用浏览器打开    
//file:///Users/mac1/Desktop/whrite.png        
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 
   AFHTTPRequestOperation *operation = nil;       
 NSMutableDictionary *params = [NSMutableDictionary dictionary];   
 [params setValue:@"带图片哦" forKey:@"status"];    [params setValue:@"XXXXXX" forKey:@"access_token"];           
 //方式一(拖到编译器中的图片)   
 //UIImage *_sendImg = [UIImage imageNamed:@"whrite.png"];   
 //NSData *data = UIImageJPEGRepresentation(_sendImg, 1);    
//NSData *data = UIImagePNGRepresentation(_sendImg);       
//方式二(程序包中的图片)    
//NSString *theImagePath = [[NSBundle mainBundle] pathForResource:@"whrite"ofType:@"png"];
//文件包路径,在程序包中     
//NSURL *Imagefile = [NSURL fileURLWithPath:theImagePath];      
 //方式三,沙盒中的图片   
 NSString *pathstring = [NSHomeDirectory() stringByAppendingPathComponent:@"/Documents/whrite.png"];
//从沙盒中找到文件,沙盒中需要有这个whrite.png图片    
NSURL *urlfile = [NSURL fileURLWithPath:pathstring];       
 operation = [manager POST:@"https://api.weibo.com/2/statuses/upload.json" parameters:params constructingBodyWithBlock:^(id formData) {
//multipart/form-data编码方式               
 //方式二和三调用的方法,给的是URL      
  [formData appendPartWithFileURL:urlfile name:@"pic" error:nil];
//name:@"pic"新浪微博要求的名字,去阅读新浪的API文档             
   //方式三调用的方法,给的是Data      
 //[formData appendPartWithFileData:data name:@"pic" fileName:@"pic" mimeType:@"image/png"];           
 } success:^(AFHTTPRequestOperation *operation, id responseObject) {       
 NSLog(@"Success: %@", responseObject);          
  } failure:^(AFHTTPRequestOperation *operation, NSError *error) {       
 NSLog(@"Error: %@", error);    }];        
//监听进度  
  [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {                
CGFloat progress = totalBytesWritten/(CGFloat)totalBytesExpectedToWrite;        
NSLog(@"进度:%.1f",progress);            }];  
 }

//AFHTTPRequestOperation(构建request,使用setCompletionBlockWithSuccess)(成功)
[objc] view plaincopyprint?

1.  - (void)SimpleGETTaskOperation{//使用AFHTTPRequestOperation,不带参数,无需指定请求的类型 
2.  
3.  NSURL *URL = [NSURL URLWithString:Pictureurl]; 
4.  
5.  NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 
6.  
7.  AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 
8.  
9.  // 进行操作的配置,设置解析序列化方式 
10. 
11. //Json 
12. //op.responseSerializer = [AFJSONResponseSerializer serializer]; 
13. //op.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingMutableContainers]; 
14. 
15. //Image 
16. operation.responseSerializer = [AFImageResponseSerializer serializer]; 
17. 
18. //XML 
19. //operation.responseSerializer = [AFXMLParserResponseSerializer serializer]; 
20. 
21. [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 
22. 
23. NSLog(@"responseObject = %@", responseObject);//返回的是对象类型 
24. 
25. } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
26. NSLog(@"Error: %@", error); 
27. }]; 
28. 
29. //[[NSOperationQueue mainQueue] addOperation:operation]; 
30. [operation start]; 
31. 
32. } 
- (void)SimpleGETTaskOperation{
//使用AFHTTPRequestOperation,不带参数,无需指定请求的类型       
 NSURL *URL = [NSURL URLWithString:Pictureurl];       
 NSURLRequest *request = [NSURLRequest requestWithURL:URL];     
   AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];       
 // 进行操作的配置,设置解析序列化方式      
  //Json    
//op.responseSerializer = [AFJSONResponseSerializer serializer];  
 //op.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingMutableContainers];        
//Image   
 operation.responseSerializer = [AFImageResponseSerializer serializer];     
   //XML   
 //operation.responseSerializer = [AFXMLParserResponseSerializer serializer];     
  [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {               
NSLog(@"responseObject = %@", responseObject);//返回的是对象类型           
 } failure:^(AFHTTPRequestOperation *operation, NSError *error) {       
NSLog(@"Error: %@", error);    }];      
  //[[NSOperationQueue mainQueue] addOperation:operation];   
 [operation start];  
  }

//AFHTTPRequestOperation(许多操作一起进行)(未成功)
[objc] view plaincopyprint?

1.  - (void)CompleTaskOperation{ 
2.  
3.  NSMutableArray *mutableOperations = [NSMutableArray array]; 
4.  
5.  NSArray *filesToUpload = nil; 
6.  for (NSURL *fileURL in filesToUpload) { 
7.  
8.  NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id formData) { 
9.  
10. [formData appendPartWithFileURL:fileURL name:@"images[]" error:nil]; 
11. }]; 
12. 
13. AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 
14. 
15. [mutableOperations addObject:operation]; 
16. } 
17. 
18. NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:@[@"一个",@"两个"] progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) { 
19. 
20. NSLog(@"%lu of %lu complete", (unsigned long)numberOfFinishedOperations, (unsigned long)totalNumberOfOperations); 
21. 
22. } completionBlock:^(NSArray *operations) { 
23. 
24. NSLog(@"All operations in batch complete"); 
25. }]; 
26. 
27. [[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO]; 
28. 
29. } 
- (void)CompleTaskOperation{   
 NSMutableArray *mutableOperations = [NSMutableArray array];       
 NSArray *filesToUpload = nil;   
 for (NSURL *fileURL in filesToUpload) {               
 NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id formData) {                       
 [formData appendPartWithFileURL:fileURL name:@"images[]" error:nil];    
   }];                
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];            
    [mutableOperations addObject:operation];   
 }      
  NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:@[@"一个",@"两个"] progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {               
 NSLog(@"%lu of %lu complete", (unsigned long)numberOfFinishedOperations, (unsigned long)totalNumberOfOperations);           
 } completionBlock:^(NSArray *operations) {               
 NSLog(@"All operations in batch complete");    }];       
 [[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];
}

//创建一个下载任务---------downloadTaskWithRequest(成功)
[objc] view plaincopyprint?

1.  - (void)DownloadTask{//下载成功 
2.  
3.  // 定义一个progress指针 
4.  NSProgress *progress = nil; 
5.  
6.  // 创建一个URL链接 
7.  NSURL *url = [NSURL URLWithString:Pictureurl]; 
8.  
9.  // 初始化一个请求 
10. NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
11. 
12. // 获取一个Session管理器 
13. AFHTTPSessionManager *session = [AFHTTPSessionManager manager]; 
14. 
15. // 开始下载任务 
16. NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) 
17. { 
18. // 拼接一个文件夹路径 
19. NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; 
20. 
21. NSLog(@"不完整路径%@",documentsDirectoryURL); 
22. //下载成后的路径,这个路径在自己电脑上的浏览器能打开 
23. //file:///Users/mac1/Library/Application%20Support/iPhone%20Simulator/7.1/Applications/787B2D0B-A400-4177-9914-25DA7F40A54B/Documents/ 
24. 
25. // 根据网址信息拼接成一个完整的文件存储路径并返回给block 
26. return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]]; 
27. 
28. //----------可与写入沙盒中------------- 
29. 
30. 
31. } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) 
32. { 
33. // 结束后移除掉这个progress 
34. [progress removeObserver:self 
35. forKeyPath:@"fractionCompleted" 
36. context:NULL]; 
37. }]; 
38. 
39. // 设置这个progress的唯一标示符 
40. [progress setUserInfoObject:@"someThing" forKey:@"Y.X."]; 
41. 
42. [downloadTask resume]; 
43. 
44. // 给这个progress添加监听任务 
45. [progress addObserver:self 
46. forKeyPath:@"fractionCompleted" 
47. options:NSKeyValueObservingOptionNew 
48. context:NULL]; 
49. } 
50. //监听进度的方法(没调用) 
51. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(voidvoid *)context 
52. { 
53. if ([keyPath isEqualToString:@"fractionCompleted"] && [object isKindOfClass:[NSProgress class]]) { 
54. NSProgress *progress = (NSProgress *)object; 
55. NSLog(@"Progress is %f", progress.fractionCompleted); 
56. 
57. // 打印这个唯一标示符 
58. NSLog(@"%@", progress.userInfo); 
59. } 
60. } 
- (void)DownloadTask{
//下载成功       
 // 定义一个progress指针    
NSProgress *progress = nil;        
// 创建一个URL链接    
NSURL *url = [NSURL URLWithString:Pictureurl];        
// 初始化一个请求    
NSURLRequest *request = [NSURLRequest requestWithURL:url];       
 // 获取一个Session管理器    
AFHTTPSessionManager *session = [AFHTTPSessionManager manager];        
// 开始下载任务    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response)        {                                                 
// 拼接一个文件夹路径                                                  
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];                                                                                                    NSLog(@"不完整路径%@",documentsDirectoryURL);                                                  
//下载成后的路径,这个路径在自己电脑上的浏览器能打开                                                  //file:///Users/mac1/Library/Application%20Support/iPhone%20Simulator/7.1/Applications/787B2D0B-A400-4177-9914-25DA7F40A54B/Documents/                                                                                                    // 根据网址信息拼接成一个完整的文件存储路径并返回给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);   
 }}

//AFURLSessionManager下载队列,且能在后台下载,关闭了应用后还继续下载(成功)
[objc] view plaincopyprint?

1.  - (void)DownloadTaskbackaAndqueue{ 
2.  
3.  // 配置后台下载会话配置 
4.  NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"downloads"]; 
5.  
6.  // 初始化SessionManager管理器 
7.  SessionManage = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; 
8.  
9.  // 获取添加到该SessionManager管理器中的下载任务 
10. NSArray *downloadTasks = [SessionManage downloadTasks]; 
11. 
12. // 如果有下载任务 
13. if (downloadTasks.count) 
14. { 
15. NSLog(@"downloadTasks: %@", downloadTasks); 
16. 
17. // 继续全部的下载链接 
18. for (NSURLSessionDownloadTask *downloadTask in downloadTasks) 
19. { 
20. [downloadTask resume]; 
21. } 
22. } 
23. } 
24. 
25. //点击按钮添加下载任务 
26. - (void)addDownloadTask:(id)sender 
27. { 
28. // 组织URL 
29. NSURL *URL = [NSURL URLWithString:imagurl]; 
30. 
31. // 组织请求 
32. NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 
33. 
34. // 给SessionManager管理器添加一个下载任务 
35. NSURLSessionDownloadTask *downloadTask = 
36. [SessionManage downloadTaskWithRequest:request 
37. progress:nil 
38. destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { 
39. 
40. //下载文件路径 
41. NSURL *documentsDirectoryPath = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]]; 
42. return [documentsDirectoryPath URLByAppendingPathComponent:[targetPath lastPathComponent]]; 
43. 
44. } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { 
45. NSLog(@"File downloaded to: %@", filePath); 
46. 
47. //file:///Users/mac1/Library/Application%20Support/iPhone%20Simulator/7.1/Applications/787B2D0B-A400-4177-9914-25DA7F40A54B/Documents/CFNetworkDownload_NWLWU6.tmp 
48. 
49. }]; 
50. [downloadTask resume]; 
51. 
52. // 打印下载的标示 
53. NSLog(@"%d", downloadTask.taskIdentifier); 
54. } 
- (void)DownloadTaskbackaAndqueue{       
 // 配置后台下载会话配置    
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"downloads"];        
// 初始化SessionManager管理器    
SessionManage = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];        // 获取添加到该SessionManager管理器中的下载任务    
NSArray *downloadTasks = [SessionManage downloadTasks];       
 // 如果有下载任务  
  if (downloadTasks.count)    {       
 NSLog(@"downloadTasks: %@", downloadTasks);                
// 继续全部的下载链接       
 for (NSURLSessionDownloadTask *downloadTask in downloadTasks)  {        
    [downloadTask resume];    
    }  
  }}

//点击按钮添加下载任务

- (void)addDownloadTask:(id)sender{    
// 组织URL   
 NSURL *URL = [NSURL URLWithString:imagurl];        
// 组织请求    
NSURLRequest *request = [NSURLRequest requestWithURL:URL];        
// 给SessionManager管理器添加一个下载任务    
NSURLSessionDownloadTask *downloadTask =    [SessionManage 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);                                                                      //file:///Users/mac1/Library/Application%20Support/iPhone%20Simulator/7.1/Applications/787B2D0B-A400-4177-9914-25DA7F40A54B/Documents/CFNetworkDownload_NWLWU6.tmp                                                                  }];   
 [downloadTask resume];        
// 打印下载的标示    
NSLog(@"%d", downloadTask.taskIdentifier);
}

//创建一个数据任务(成功)

[objc] view plaincopyprint?
1.  - (void)GreatDataTask{//下载成功 
2.  
3.  NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 
4.  
5.  AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; 
6.  
7.  NSURL *URL = [NSURL URLWithString:Jsonurl]; 
8.  
9.  NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 
10. 
11. //创建一个数据任务 
12. NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { 
13. if (error) { 
14. NSLog(@"Error: %@", error); 
15. } else { 
16. //能将Json数据打印出来 
17. NSLog(@"*************** response = %@ \n************** responseObject = %@", response, responseObject); 
18. } 
19. }]; 
20. [dataTask resume]; 
21. 
22. } 
- (void)GreatDataTask{
//下载成功    
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];       
 AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];        
NSURL *URL = [NSURL URLWithString:Jsonurl];       
 NSURLRequest *request = [NSURLRequest requestWithURL:URL];      
  //创建一个数据任务   
 NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {        
if (error) {           
 NSLog(@"Error: %@", error);       
 } else {            
//能将Json数据打印出来            
NSLog(@"*************** response = %@ \n************** responseObject = %@", response, responseObject);       
 }   
 }];  
  [dataTask resume];   
 }

//创建一个上传的任务(尚未成功)

[objc] view plaincopyprint?
1.  - (void)UploadTask{ 
2.  
3.  NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 
4.  AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; 
5.  
6.  NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"]; 
7.  NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 
8.  
9.  NSURL *filePath = [NSURL fileURLWithPath:@"/Users/mac1/Library/Application Support/iPhone Simulator/7.1/Applications/787B2D0B-A400-4177-9914-25DA7F40A54B/Documents/whrite.png"];//给的是沙盒路径下的图片 
10. 
11. NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { 
12. if (error) { 
13. NSLog(@"Error: %@", error); 
14. } else { 
15. NSLog(@"Success: %@ %@", response, responseObject); 
16. } 
17. }]; 
18. [uploadTask resume]; 
19. 
20. } 
- (void)UploadTask{    
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];    
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];       
 NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];   
 NSURLRequest *request = [NSURLRequest requestWithURL:URL];       
 NSURL *filePath = [NSURL fileURLWithPath:@"/Users/mac1/Library/Application Support/iPhone Simulator/7.1/Applications/787B2D0B-A400-4177-9914-25DA7F40A54B/Documents/whrite.png"];
//给的是沙盒路径下的图片        
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {        if (error) {            
NSLog(@"Error: %@", error);       
 } else {            
NSLog(@"Success: %@ %@", response, responseObject);       
 }   
 }];    
[uploadTask resume];
}

//创建一个复杂的请求(尚未成功)

[objc] view plaincopyprint?
1.  - (void)GreatComplexTask{ 
2.  
3.  NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id formData) { 
4.  [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil]; 
5.  } error:nil]; 
6.  
7.  AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; 
8.  NSProgress *progress = nil; 
9.  
10. NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { 
11. if (error) { 
12. NSLog(@"Error: %@", error); 
13. } else { 
14. NSLog(@"%@ %@", response, responseObject); 
15. } 
16. }]; 
17. 
18. [uploadTask resume]; 
19. 
20. }

你可能感兴趣的:(AFNetworking粗解(解析))