IOS网络访问之使用AFNetworking

IOS网络访问之使用AFNetworking

  AFNetworking是IOS上常用的第三方网络访问库,我们可以在github上下载它,同时github上有它详细的使用说明,最新的AFNetworing2.0与1.0有很大的变化,这里仅对2.0常用的使用方法进行总结

  基于NSURLConnection的API

  提交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);

  }];

   上面代码中responseObject代表了返回的值,当网络返回json或者xml之类的数据时,它们的本质都是字符串,我们需要通过一定操作才能 把字符串转成希望的对象,AFNetWorking通过设置AFHTTPRequestOperationManager对象的 responseSerializer属性替我们做了这些事。

  如果返回的数据时json格式,那么我们设定

  manager.responseSerializer = [[AFJSONResponseSerializer alloc] init],responseObject就是获得的json的根对象(NSDictionary或者NSArray)

//manager.responseSerializer = [AFHTTPResponseSerializer serializer]; //这句也可以,很重要,去掉就容易遇到错误,暂时还未了解更加详细的原因

  如果返回的是plist格式我们就用AFPropertyListResponseSerializer解析器

  如果返回的是xml格式我们就用AFXMLParserResponseSerializer解析器,responseObject代表了NSXMLParser对像

  如果返回的是图片,可以使用AFImageResponseSerializer

  如果只是希望获得返回二进制格式,那么可以使用AFHTTPResponseSerializer

  AFRequestSerializer

  AFHTTPRequestOperationManager还可以通过设置requestSeializer属性设置请求的格式

  有如下的请求地址与参数

  NSString *URLString = @"http://example.com";

  NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};

  我们使用AFHTTPRequestSerializer的GET提交方式

  [[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];

  GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3

  我们使用AFHTTPRequestSerializer的POST提交方式

  [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];

  POST http://example.com/

  Content-Type: application/x-www-form-urlencoded

  foo=bar&baz[]=1&baz[]=2&baz[]=3

  我们使用AFJSONRequestSerializer

  [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];

  POST http://example.com/

  Content-Type: application/json

  {"foo": "bar", "baz": [1,2,3]}

  默认提交请求的数据是二进制(AFHTTPRequestSerializer)的,返回格式是JSON(AFJSONResponseSerializer)

提交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请求时附带文件


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<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);

}];

  也可以通过appendPartWithFileData上传NSData数据的文件

  AFHTTPRequestOperation

  除了使用AFHTTPRequestOperationManager访问网络外还可以通过AFHTTPRequestOperation,AFHTTPRequestOperation继承自AFURLConnectionOperation,

  AFURLConnectionOperation继承自NSOperation,所以可以通过AFHTTPRequestOperation定义了一个网络请求任务,然后添加到队列中执行。


NSMutableArray *mutableOperations = [NSMutableArray array];

for (NSURL *fileURL in filesToUpload) {

NSURLRequest
*request = [[AFHTTPRequestSerializer serializer]
multipartFormRequestWithMethod:@"POST"
URLString:@"http://example.com/upload" parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> 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];

  批量任务处理


NSMutableArray *mutableOperations = [NSMutableArray array];

for (NSURL *fileURL in filesToUpload) {

NSURLRequest
*request = [[AFHTTPRequestSerializer serializer]
multipartFormRequestWithMethod:@"POST"
URLString:@"http://example.com/upload" parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> 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];

  上面的API是基于NSURLConnection,IOS7之后AFNetWorking还提供了基于NSURLSession的API

  基于NSURLSession的API

  下载任务


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];

  文件上传任务


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];

  带进度的文件上传


NSMutableURLRequest
*request = [[AFHTTPRequestSerializer serializer]
multipartFormRequestWithMethod:@"POST"
URLString:@"http://example.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];

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];

NSURLSessionDataTask

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];

  查看网络状态

  苹果官方提供Reachablity用来查看网络状态,AFNetWorking也提供这方面的API


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;

}

}];

//开始监控

[manager.reachabilityManager startMonitoring];

时间: 2024-08-06 16:04:16

IOS网络访问之使用AFNetworking的相关文章

IOS网络访问之使用AFNetworking&lt;2&gt;

IOS网络访问之使用AFNetworking AFNetworking是IOS上常用的第三方网络访问库,我们可以在github上下载它,同时github上有它详细的使用说明,最新的AFNetworing2.0与1.0有很大的变化,这里仅对2.0常用的使用方法进行总结 基于NSURLConnection的API 提交GET请求 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; [man

IOS网络访问之NSURLConnection

IOS网络访问主要建立在http协议上 IOS提供了几个重要的对象完成http请求响应 NSURLRequest:代表一个请求,通过NSURLRequest可以设置请求的URL地址以及缓存策略 NSMutableURLRequest:NSURLRequest的子类,可以方便地设置请求头的各种信息以及请求方式 NSURLConnection:网络访问对象,可以通过同步或者异步的方式发送请求 - (void)viewDidLoad { [super viewDidLoad]; // Do any a

ios网络访问接口-NSURLSession与NSURLConnection的区别

AFNetworking是日常开发中最常用的网络框架,现在我们使用的版本是3.0版,3.0与2.0版最大的区别就是,AFNetworking 2.0使用NSURLConnection的基础API ,而3.0是完全基于NSURLSession的API,已经抛弃了NSURLConnection.而NSURLSession可以看作是是NSURLConnection 的替代者,在2013年苹果全球开发者大会(WWDC2013)随ios7一起发布,是对NSURLConnection进行了重构优化后的新的网

IOS网络访问之NSURLSession

NSURLSession是IOS7中新添加的网络访问接口,作用与NSURLConnection一致,在程序在前台时,NSURLSession与NSURLConnection可以互为替代工作.如果用户强制将程序关闭,NSURLSession会断掉. NSURLSession中关键类有下面几种 1:NSURLSessionConfiguration:用于配置NSURLSession工作模式以及网络设置 工作模式分为下面三种: 普通模式(default):可以使用缓存 + (NSURLSessionC

IOS网络访问之获取网络状态

苹果设备的网络状况多变,既可能有网,也可能网络断开,既可能通过wifi联网,也可能通过蜂窝数据联网,很多时候我们需要获知程序当前运行在何种网络状况下 我们可以在苹果官方下载工具类Reachability,解压后将Reachability.h和Reachability.m添加到我们的项目中 示例1:查看当前的网络环境(通过访问一个页面测试网络状况) Reachability *reach = [Reachability reachabilityWithHostName:@"http://www.c

对比iOS网络组件:AFNetworking VS ASIHTTPRequest

对比iOS网络组件:AFNetworking VS ASIHTTPRequest 在开发iOS应用过程中,如何高效的与服务端API进行数据交换,是一个常见问题.一般开发者都会选择一个第三方的网络组件作为服务,以提高开发效率和稳定性.这些组件把复杂的网络底层操作封装成友好的类和方法,并且加入异常处理等. 那么,大家最常用的组件是什么?这些组件是如何提升开发效率和稳定性的?哪一款组件适合自己,是 AFNetworking(AFN)还是 ASIHTTPRequest(ASI)?几乎每一个iOS互联网应

对比iOS网络组件:AFNetworking VS ASIHTTPRequest(转载)

在开发iOS应用过程中,如何高效的与服务端API进行数据交换,是一个常见问题.一般开发者都会选择一个第三方的网络组件作为服务,以提高开发效率和稳定性.这些组件把复杂的网络底层操作封装成友好的类和方法,并且加入异常处理等. 那么,大家最常用的组件是什么?这些组件是如何提升开发效率和稳定性的?哪一款组件适合自己,是 AFNetworking(AFN)还是 ASIHTTPRequest(ASI)?几乎每一个iOS互联网应用开发者都会面对这样的选择题,要从这两个最常用的组件里选出一个好的还真不是那么容易

iOS网络编程(7) 第三方开源库-----&gt;AFNetworking

AFNetworking是一个为 iOS 和 Mac OSX 制作的令人愉快的网络库,它建立在URL 装载系统框架的顶层,内置在Cocoa里,扩展了强有力的高级网络抽象.它的模块架构被良好的设计,拥有丰富的功能,因此,使用起来,必定赏心悦目. @原文链接https://github.com/AFNetworking/AFNetworking,我在此基础上了点配置修改 @介绍 1.支持HTTP请求和基于REST的网络服务(包括GET.POST. PUT.DELETE等) 2.支持ARC 3.要求i

iOS HTTP访问网络受限

HTTP访问网络受限,只需要在项目工程里的Info.plist添加 <key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict> 就能进行网络访问