https://github.com/AFNetworking/AFNetworking

与asi-http-request功能类似的网络库,不过是基于NSURLConnection 和 NSOperation 的,同样支持iOS与MacOS双平台。目前的更新比较频繁,适合新项目使用,而且使用起来也更简单。

操作JSON

- (IBAction)jsonTapped:(id)sender {
// 1
NSString *weatherUrl = [NSString stringWithFormat:@"%@weather.php?format=json", BaseURLString];
NSURL *url = [NSURL URLWithString:weatherUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 2
AFJSONRequestOperation *operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest:request
// 3
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
self.weather = (NSDictionary *)JSON;
self.title = @"JSON Retrieved";
[self.tableView reloadData];
}
// 4
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
message:[NSString stringWithFormat:@"%@",error]
delegate:nil
cancelButtonTitle:@"OK" otherButtonTitles:nil];
[av show];
}]; // 5
[operation start];
}
  1. 根据基本的URL构造出完整的一个URL。然后通过这个完整的URL获得一个NSURL对象,然后根据这个url获得一个NSURLRequest.
  2. AFJSONRequestOperation 是一个功能完整的类(all-in-one)— 整合了从网络中获取数据并对JSON进行解析。
  3. 当请求成功,则运行成功块(success block)。在本示例中,把解析出来的天气数据从JSON变量转换为一个字典(dictionary),并将其存储在属性 weather 中.
  4. 如果运行出问题了,则运行失败块(failure block),比如网络不可用。如果failure block被调用了,将会通过提示框显示出错误信息。

操作Property Lists(plists)

 -(IBAction)plistTapped:(id)sender{
NSString *weatherUrl = [NSString stringWithFormat:@"%@weather.php?format=plist",BaseURLString];
NSURL *url = [NSURL URLWithString:weatherUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url]; AFPropertyListRequestOperation *operation =
[AFPropertyListRequestOperation propertyListRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList) {
self.weather = (NSDictionary *)propertyList;
self.title = @"PLIST Retrieved";
[self.tableView reloadData];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id propertyList) {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
message:[NSString stringWithFormat:@"%@",error]
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[av show];
}]; [operation start];
}

上面的代码几乎与JSON版的一致,只不过将操作(operation)的类型从AFJSONOperation 修改为 AFPropertyListOperation.

操作XML

- (IBAction)xmlTapped:(id)sender{
NSString *weatherUrl = [NSString stringWithFormat:@"%@weather.php?format=xml",BaseURLString];
NSURL *url = [NSURL URLWithString:weatherUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url]; AFXMLRequestOperation *operation =
[AFXMLRequestOperation XMLParserRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
//self.xmlWeather = [NSMutableDictionary dictionary];
XMLParser.delegate = self;
[XMLParser setShouldProcessNamespaces:YES];
[XMLParser parse];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser) {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
message:[NSString stringWithFormat:@"%@",error]
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[av show];
}]; [operation start];
}

到现在为止,这看起来跟之前处理JSON和plist很类似。最大的改动就是在成功块(success block)中, 在这里不会传递给你一个预处理好的NSDictionary对象. 而是AFXMLRequestOperation实例化的NSXMLParse对象,这个对象将用来处理繁重的XML解析任务。

NSXMLParse对象有一组delegate方法是你需要实现的 — 用来获得XML数据。注意,在上面的代码中我将XMLParser的delegate设置为self, 因此WTTableViewController将用来处理XML的解析任务。

下载图片

UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)];
[imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]];
- (IBAction)updateBackgroundImage:(id)sender {

    //Store this image on the same server as the weather canned files
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.scott-sherwood.com/wp-content/uploads/2013/01/scene.png"]];
AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request
imageProcessingBlock:nil
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
self.backgroundImageView.image = image;
[self saveImage:image withFilename:@"background.png"];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(@"Error %@",error);
}];
[operation start];
}
-(void)saveImage:(UIImage *)image withFilename:(NSString *)filename{

    NSString *path;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"WeatherHTTPClientImages/"]; BOOL isDir; if(![[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir]){
if(!isDir){
NSError *error;
[[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error]; NSLog(@"%@",error);
}
} path = [path stringByAppendingPathComponent:filename];
NSData *imageData = UIImagePNGRepresentation(image);
NSLog(@"Written: %d",[imageData writeToFile:path atomically:YES]);
}

AFHTTPClient

AFHTTPClient一般是给它设置一个基本的URL,然后用AFHTTPClient进行多个请求(而不是像之前的那样,每次请求的时候,都创建一个AFHTTPClient)。

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{

    if(buttonIndex==0){
NSURL *baseURL = [NSURL URLWithString:[NSString stringWithFormat:BaseURLString]];
NSDictionary *parameters = [NSDictionary dictionaryWithObject:@"json" forKey:@"format"]; AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
[client registerHTTPOperationClass:[AFJSONRequestOperation class]];
[client setDefaultHeader:@"Accept" value:@"application/json"]; [client postPath:@"weather.php"
parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.weather = responseObject;
self.title = @"HTTP POST";
[self.tableView reloadData];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
message:[NSString stringWithFormat:@"%@",error]
delegate:nil
cancelButtonTitle:@"OK" otherButtonTitles:nil];
[av show]; }
];
}
else if (buttonIndex==1){
NSURL *baseURL = [NSURL URLWithString:[NSString stringWithFormat:BaseURLString]];
NSDictionary *parameters = [NSDictionary dictionaryWithObject:@"json" forKey:@"format"]; AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
[client registerHTTPOperationClass:[AFJSONRequestOperation class]];
[client setDefaultHeader:@"Accept" value:@"application/json"]; [client getPath:@"weather.php"
parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.weather = responseObject;
self.title = @"HTTP GET";
[self.tableView reloadData];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
message:[NSString stringWithFormat:@"%@",error]
delegate:nil
cancelButtonTitle:@"OK" otherButtonTitles:nil];
[av show]; }
];
}
}
  1. 构建一个baseURL,以及一个参数字典,并将这两个变量传给AFHTTPClient.
  2. 将AFJSONRequestOperation注册为HTTP的操作, 这样就可以跟之前的示例一样,可以获得解析好的JSON数据。
  3. 做了一个GET请求,这个请求有一对block:success和failure。
  4. POST请求跟GET一样。

上传一个文件

NSURL *url = [NSURL URLWithString:@"http://api-base-url.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
}]; AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[httpClient enqueueHTTPRequestOperation:operation];

下载一个文件

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8080/encode"]];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.inputStream = [NSInputStream inputStreamWithFileAtPath:[[NSBundle mainBundle] pathForResource:@"large-image" ofType:@"tiff"]];
operation.outputStream = [NSOutputStream outputStreamToMemory];
[operation start];

参考:

http://www.raywenderlich.com/zh-hans/36079/afnetworking%E9%80%9F%E6%88%90%E6%95%99%E7%A8%8B%EF%BC%881%EF%BC%89

iOS开源项目:AFNetworking----写得非常好的更多相关文章

  1. GitHub上有很多不错的iOS开源项目

    GitHub上有很多不错的iOS开源项目,个人认为不错的,有这么几个:1. ReactiveCocoa:ReactiveCocoa/ReactiveCocoa · GitHub:GitHub自家的函数 ...

  2. 推荐大家在GitHub 上值得关注学习的 iOS 开源项目

    GitHub上有很多不错的iOS开源项目,和大家特别推荐以下几个项目: 1. ReactiveCocoa GitHub链接:ReactiveCocoa/ReactiveCocoa GitHub自家的函 ...

  3. 直接拿来用!最火的iOS开源项目

    1. AFNetworking 在众多iOS开源项目中,AFNetworking可以称得上是最受开发者欢迎的库项目.AFNetworking是一个轻量级的iOS.Mac OS X网络通信类库,现在是G ...

  4. (转)直接拿来用!最火的iOS开源项目(一)

    1. AFNetworking 在众多iOS开源项目中,AFNetworking可以称得上是最受开发者欢迎的库项目.AFNetworking是一个轻量级的iOS.Mac OS X网络通信类库,现在是G ...

  5. 【转】GitHub平台最火的iOS开源项目——2013-08-25 17

    http://www.cnblogs.com/lhming/category/391396.html 今天,我们将介绍20个在GitHub上非常受开发者欢迎的iOS开源项目,你准备好了吗? 1. AF ...

  6. iOS开源项目

    在结束了GitHub平台上“最受欢迎的Android开源项目”系列盘点之后,我们正式迎来了“GitHub上最受欢迎的iOS开源项目”系列盘点.今天,我们将介绍20个在GitHub上非常受开发者欢迎的i ...

  7. GitHub上最火的40个iOS开源项目

    1. AFNetworking 在众多iOS开源项目中,AFNetworking可以称得上是最受开发者欢迎的库项目.AFNetworking是一个轻量级的iOS. Mac OS X网络通信类库,现在是 ...

  8. 直接拿来用!最火的iOS开源项目(一)

    直接拿来用!最火的iOS开源项目(一) 发表于2013-06-05 10:17| 39373次阅读| 来源CSDN| 100 条评论| 作者唐小引 iOS开源项目GitHub移动开发最受欢迎的开源项目 ...

  9. GitHub上最受欢迎的iOS开源项目TOP20

    AFNetworking 在众多iOS开源项目中,AFNetworking可以称得上是最受开发者欢迎的库项目.AFNetworking是一个轻量级的iOS.Mac OS X网络通信类库,现在是GitH ...

  10. 直接拿来用!最火的iOS开源项目(一~三)

    结束了GitHub平台上“最受欢迎的Android开源项目”系列盘点之后,我们正式迎来了“GitHub上最受欢迎的iOS开源项目”系列盘点.今天,我们将介绍20个在GitHub上非常受开发者欢迎的iO ...

随机推荐

  1. 在Firefox中发现一个在Linux下查看chm文档的插件

    在Firefox浏览器插件中搜索插件chmfox插件,安装后就可以在linux下通过Firefox浏览器阅读chm文档了.

  2. RabbitMQ三种Exchange模式

    RabbitMQ中,所有生产者提交的消息都由Exchange来接受,然后Exchange按照特定的策略转发到Queue进行存储 RabbitMQ提供了四种Exchange:fanout,direct, ...

  3. bzoj3862

    题解: 这一道题目和模板有不同的地方就是在于可以修改只有一条边和i相邻 于是我们还要记录与这个点相邻的点有没有改变 代码: #pragma GCC optimize(2) #include<bi ...

  4. Delphi 简体 繁体 转换

    http://delphi.ktop.com.tw/board.php?cid=30&fid=69&tid=104986 試看看 這個是豬寶寶從網路上抄來的 檢視純文字版列印? fun ...

  5. Sublime 中文标题乱码

    ---title:Sublime 中文标题乱码--- #markdown语法(非Github Flavored) #解决办法: 在用户设置里添加一项,强制不根据 dpi 缩放dpi_scale: 1. ...

  6. c++的关联容器入门(map and set)

    目录 std::map std::set C++的关联容器主要是两大类map和set 我们知道谈到C++容器时,我们会说到 顺序容器(Sequence containers),关联容器(Associa ...

  7. 怎么定位bug

    测试发现bug,怎么定位?不同领域不同的测试对象,具体定位方法都不一样.自己定位bug的方法通常是以下过程: 1.发现bug,首先要查看bug的详细信息,根据描述初步分析是哪个模块哪段代码的问题 2. ...

  8. swift3.0 创建经典界面的九宫图

    网络上很多例子都是早期的 Object-C的效果,现在用到Swift3.0开发,故把网络上的例子翻译过来,达到基本的效果.可是现在这个还不算很满意,再下次继续进行优化 override func vi ...

  9. 【maven】mvn 命令

    ===========maven参数打包================== 在使用mvn package进行编译.打包时,Maven会执行src/test/java中的JUnit测试用例,有时为了跳 ...

  10. 重新学习之spring第三个程序,整合struts2+spring

    第一步:导入Struts2jar包+springIOC的jar包和Aop的Jar包 第二步:建立applicationContext.xml文件+struts.xml文件+web.xml文件 web. ...