AFNetworking 2.0(2.3.1)使用详解
在项目中使用AFNetworking最好的做法是使用Cocopods将三方框架集成到项目中。
使用方式:Podfile文件中键入如下内容即可。
platform :ios, '7.0' pod "AFNetworking", "~> 2.0"
下面进入正题:
AFNetworking Architecture(架构)
NSURLConnection
AFURLConnectionOperation
AFHTTPRequestOperation
AFHTTPRequestOperationManager
NSURLSession (iOS 7 / Mac OS X 10.9)
AFURLSessionManager
AFHTTPSessionManager
<AFURLRequestSerialization>
AFHTTPRequestSerializer
AFJSONRequestSerializer
AFPropertyListRequestSerializer
<AFURLResponseSerialization>
AFHTTPResponseSerializer
AFJSONResponseSerializer
AFXMLParserResponseSerializer
AFXMLDocumentResponseSerializer
(Mac OS X)AFPropertyListResponseSerializer
AFImageResponseSerializer
AFCompoundResponseSerializer
AFSecurityPolicy
AFNetworkReachabilityManager
各个类的简单说明及用法:
1. AFHTTPRequestOperationManager
封装与Web应用程序通过HTTP交互,包括请求的创建,响应序列化,网络可达性监控和安全,以及请求操作管理的常见沟通模式。
GET请求:
1 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 2 [manager GET:@"http://example.com/resources.json" 3 parameters:nil 4 success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"JSON: %@", responseObject); } 5 failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error: %@", error); }];
附带表单编码的POST请求
1 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 2 NSDictionary *parameters = @{@"foo": @"bar"}; 3 [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请求,如上传)
1 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 2 NSDictionary *parameters = @{@"foo": @"bar"}; 3 NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];//上传的图片 4 [manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { [formData appendPartWithFileURL:filePath name:@"image" error:nil]; } success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"Success: %@", responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error: %@", error); }];
2. AFURLSessionManager
创建了并管理基于一个指定的NSURLSessionConfiguration对象的NSURLSession对象,它与以下协议配合使用(<NSURLSessionTaskDelegate>,<NSURLSessionDataDelegate>, <NSURLSessionDownloadDelegate>,<NSURLSessionDelegate>)
创建一个下载任务
1 NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 2 AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; 3 NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"]; NSURLRequest *request = [NSURLRequest requestWithURL:URL]; NSURLSessionDownloadTask *downloadTask =
[manager downloadTaskWithRequest:request 4 progress:nil 5 destination:^NSURL *(NSURL *targetPath, NSURLResponse *response)
{ NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; 6 return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]]; } 7 completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { NSLog(@"File downloaded to: %@", filePath); }]; 8 [downloadTask resume];
创建一个上传任务
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];
为一个复杂请求(MULTI-PART REQUEST)创建上传任务,并附带进度条
1 NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://ex ample.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { [formData appendPartWithFileURL :[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil]; } error:nil]; 2 AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessio nConfiguration]]; 3 NSProgress *progress = nil; 4 NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLR esponse *response, id responseObject, NSError *error) { if (error) { NSLog(@"Error: %@", error); } else { NSLog(@"%@ %@" , response, responseObject); } }]; 5 [uploadTask resume];
创建一个数据任务(Data Task)
1 NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 2 AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; 3 NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"]; 4 NSURLRequest *request = [NSURLRequest requestWithURL:URL]; //上传数据的任务 5 NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { if (error) { NSLog(@"Error: %@", error); } else { NSLog(@"%@ %@", response, responseObject); } }]; 6 [dataTask resume];
3. 请求序列化
请求序列化器会根据提供的URL strings和请求参数pramaters去创建相应的查询请求或HTTP body(请求体),如:
1 NSString *URLString = @"http://example.com"; 2 NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]}; 3 //查询GET“请求编码” 4 [[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil]; 5 // GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3 6 //查询POST表单提交请求编码 7 [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters]; 8 /* POST http://example.com/ Content-Type: application/x-www-form-urlencoded foo=bar&baz[]=1&baz[]=2&baz[]=3 */ 9 //查询JSON格式请求编码 10 [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters]; 11 /* POST http://example.com/ Content-Type: application/json {"foo": "bar", "baz": [1,2,3]} */
4. AFNetworkReachabilityManager(网络监测管理器)
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status)); }];
1 NSURL *baseURL = [NSURL URLWithString:@"http://example.com/"]; 2 AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL]; 3 NSOperationQueue *operationQueue = manager.operationQueue; 4 [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { 5 switch (status) { 6 case AFNetworkReachabilityStatusReachableViaWWAN: 7 case AFNetworkReachabilityStatusReachableViaWiFi: 8 [operationQueue setSuspended:NO]; 9 break; 10 case AFNetworkReachabilityStatusNotReachable: 11 default: 12 [operationQueue setSuspended:YES]; 13 break; } 14 }];
1 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 2 manager.securityPolicy.allowInvalidCertificates = YES; 3 // not recommended for production
1 NSURL *URL = [NSURL URLWithString:@"http://example.com/resources/123.json"]; 2 NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 3 AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 4 op.responseSerializer = [AFJSONResponseSerializer serializer];//提交JSON格式数据 5 [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"JSON: %@", responseObject); } 6 failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error: %@", error); }]; 7 [[NSOperationQueue mainQueue] addOperation:op];
1 NSMutableArray *mutableOperations = [NSMutableArray array]; 2 for (NSURL *fileURL in filesToUpload) { 3 NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example. com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { [formData appendPartWithFileURL:fileU RL name:@"images[]" error:nil]; }]; 4 AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 5 [mutableOperations addObject:operation]; 6 } 7 NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:@[...] 8 progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) { NSLog(@"%lu of %lu complete", numbe rOfFinishedOperations, totalNumberOfOperations); } completionBlock:^(NSArray *operations) { NSLog(@"All operations in batch comp lete"); 9 }]; 10 [[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];