https://github.com/AFNetworking/AFNetworking

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

操作JSON

  1. - (IBAction)jsonTapped:(id)sender {
  2. // 1
  3. NSString *weatherUrl = [NSString stringWithFormat:@"%@weather.php?format=json", BaseURLString];
  4. NSURL *url = [NSURL URLWithString:weatherUrl];
  5. NSURLRequest *request = [NSURLRequest requestWithURL:url];
  6.  
  7. // 2
  8. AFJSONRequestOperation *operation =
  9. [AFJSONRequestOperation JSONRequestOperationWithRequest:request
  10. // 3
  11. success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
  12. self.weather = (NSDictionary *)JSON;
  13. self.title = @"JSON Retrieved";
  14. [self.tableView reloadData];
  15. }
  16. // 4
  17. failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
  18. UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
  19. message:[NSString stringWithFormat:@"%@",error]
  20. delegate:nil
  21. cancelButtonTitle:@"OK" otherButtonTitles:nil];
  22. [av show];
  23. }];
  24.  
  25. // 5
  26. [operation start];
  27. }
  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)

  1. -(IBAction)plistTapped:(id)sender{
  2. NSString *weatherUrl = [NSString stringWithFormat:@"%@weather.php?format=plist",BaseURLString];
  3. NSURL *url = [NSURL URLWithString:weatherUrl];
  4. NSURLRequest *request = [NSURLRequest requestWithURL:url];
  5.  
  6. AFPropertyListRequestOperation *operation =
  7. [AFPropertyListRequestOperation propertyListRequestOperationWithRequest:request
  8. success:^(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList) {
  9. self.weather = (NSDictionary *)propertyList;
  10. self.title = @"PLIST Retrieved";
  11. [self.tableView reloadData];
  12. }
  13. failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id propertyList) {
  14. UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
  15. message:[NSString stringWithFormat:@"%@",error]
  16. delegate:nil
  17. cancelButtonTitle:@"OK"
  18. otherButtonTitles:nil];
  19. [av show];
  20. }];
  21.  
  22. [operation start];
  23. }

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

操作XML

  1. - (IBAction)xmlTapped:(id)sender{
  2. NSString *weatherUrl = [NSString stringWithFormat:@"%@weather.php?format=xml",BaseURLString];
  3. NSURL *url = [NSURL URLWithString:weatherUrl];
  4. NSURLRequest *request = [NSURLRequest requestWithURL:url];
  5.  
  6. AFXMLRequestOperation *operation =
  7. [AFXMLRequestOperation XMLParserRequestOperationWithRequest:request
  8. success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
  9. //self.xmlWeather = [NSMutableDictionary dictionary];
  10. XMLParser.delegate = self;
  11. [XMLParser setShouldProcessNamespaces:YES];
  12. [XMLParser parse];
  13. }
  14. failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser) {
  15. UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
  16. message:[NSString stringWithFormat:@"%@",error]
  17. delegate:nil
  18. cancelButtonTitle:@"OK"
  19. otherButtonTitles:nil];
  20. [av show];
  21. }];
  22.  
  23. [operation start];
  24. }

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

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

下载图片

  1. UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)];
  2. [imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]];
  1. - (IBAction)updateBackgroundImage:(id)sender {
  2.  
  3. //Store this image on the same server as the weather canned files
  4. NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.scott-sherwood.com/wp-content/uploads/2013/01/scene.png"]];
  5. AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request
  6. imageProcessingBlock:nil
  7. success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
  8. self.backgroundImageView.image = image;
  9. [self saveImage:image withFilename:@"background.png"];
  10. }
  11. failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
  12. NSLog(@"Error %@",error);
  13. }];
  14. [operation start];
  15. }
  1. -(void)saveImage:(UIImage *)image withFilename:(NSString *)filename{
  2.  
  3. NSString *path;
  4. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  5. path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"WeatherHTTPClientImages/"];
  6.  
  7. BOOL isDir;
  8.  
  9. if(![[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir]){
  10. if(!isDir){
  11. NSError *error;
  12. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
  13.  
  14. NSLog(@"%@",error);
  15. }
  16. }
  17.  
  18. path = [path stringByAppendingPathComponent:filename];
  19. NSData *imageData = UIImagePNGRepresentation(image);
  20. NSLog(@"Written: %d",[imageData writeToFile:path atomically:YES]);
  21. }

AFHTTPClient

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

  1. - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
  2.  
  3. if(buttonIndex==0){
  4. NSURL *baseURL = [NSURL URLWithString:[NSString stringWithFormat:BaseURLString]];
  5. NSDictionary *parameters = [NSDictionary dictionaryWithObject:@"json" forKey:@"format"];
  6.  
  7. AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
  8. [client registerHTTPOperationClass:[AFJSONRequestOperation class]];
  9. [client setDefaultHeader:@"Accept" value:@"application/json"];
  10.  
  11. [client postPath:@"weather.php"
  12. parameters:parameters
  13. success:^(AFHTTPRequestOperation *operation, id responseObject) {
  14. self.weather = responseObject;
  15. self.title = @"HTTP POST";
  16. [self.tableView reloadData];
  17. }
  18. failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  19. UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
  20. message:[NSString stringWithFormat:@"%@",error]
  21. delegate:nil
  22. cancelButtonTitle:@"OK" otherButtonTitles:nil];
  23. [av show];
  24.  
  25. }
  26. ];
  27. }
  28. else if (buttonIndex==1){
  29. NSURL *baseURL = [NSURL URLWithString:[NSString stringWithFormat:BaseURLString]];
  30. NSDictionary *parameters = [NSDictionary dictionaryWithObject:@"json" forKey:@"format"];
  31.  
  32. AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
  33. [client registerHTTPOperationClass:[AFJSONRequestOperation class]];
  34. [client setDefaultHeader:@"Accept" value:@"application/json"];
  35.  
  36. [client getPath:@"weather.php"
  37. parameters:parameters
  38. success:^(AFHTTPRequestOperation *operation, id responseObject) {
  39. self.weather = responseObject;
  40. self.title = @"HTTP GET";
  41. [self.tableView reloadData];
  42. }
  43. failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  44. UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
  45. message:[NSString stringWithFormat:@"%@",error]
  46. delegate:nil
  47. cancelButtonTitle:@"OK" otherButtonTitles:nil];
  48. [av show];
  49.  
  50. }
  51. ];
  52. }
  53. }
  1. 构建一个baseURL,以及一个参数字典,并将这两个变量传给AFHTTPClient.
  2. 将AFJSONRequestOperation注册为HTTP的操作, 这样就可以跟之前的示例一样,可以获得解析好的JSON数据。
  3. 做了一个GET请求,这个请求有一对block:success和failure。
  4. POST请求跟GET一样。

上传一个文件

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

下载一个文件

  1. NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8080/encode"]];
  2.  
  3. AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
  4. operation.inputStream = [NSInputStream inputStreamWithFileAtPath:[[NSBundle mainBundle] pathForResource:@"large-image" ofType:@"tiff"]];
  5. operation.outputStream = [NSOutputStream outputStreamToMemory];
  6. [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. WCF 学习文摘

    WCF:Windows Communication Foundation 1.概念 WCF是一个用于搭建面向服务的框架,可以通过它从一个服务终端以异步消息的方式发送数据到其他服务: WCF是一个基于消 ...

  2. 多线程pre

    body, table{font-family: 微软雅黑; font-size: 13.5pt} table{border-collapse: collapse; border: solid gra ...

  3. VScode+Flutter 开发继续踩坑

    运行慢解决方法1:修改build.gradle,注释掉jcenter(),google().使用阿里的镜像.原因是jcenter google库无法访问到导致的问题.虽然我有万能的爬墙工具,开启全局代 ...

  4. CF1082G:G. Petya and Graph(裸的最大闭合权图)

    Petya has a simple graph (that is, a graph without loops or multiple edges) consisting of n n vertic ...

  5. Idea 使用 Maven 搭建 Web 项目

    传送门: 袁咩咩的小小博客 Maven项目对象模型(POM),可以通过一小段描述信息来管理项目的构建,报告和文档的软件项目管理工具. 使用它来搭建项目可以省去很多操作,它不仅有依赖管理.自动生成项目站 ...

  6. deno学习二 基本代码

    deno 介绍是安全的ts 运行时 简单的代码 使用js(app.js) console.log("demoapp") 输出 dalongdemo 使用ts(app.ts) con ...

  7. MSMQ向远程服务器发送消息----错误总结

    一:路径错误(Path)错误 如果向远程服务器发送消息,请使用格式名的形式,如: FormatName:Direct=TCP:121.0.0.1\\private$\\queueFormatName: ...

  8. jQuery因mouseover,mouseout冒泡产生的闪烁问题

    由于浏览器的冒泡行为.造成如果在一个DIV元素上同时定义了mouseover,mouseout的时候,当鼠标移动到DIV中的child子元素的时候,就会同时执行了两个操作mouseover和mouse ...

  9. Mysql5.6 buffer_pool预热功能

    通常在mysql重启服务后,需要通过手工执行SQL来预热buffer_pool,在mysql5.6中,有如下参数可以无需人工干预. innodb_buffer_pool_dump_at_shutdow ...

  10. CentOS7 tomcat systemctl脚本

    1,centos7 使用 systemctl 替换了 service命令 参考:redhat文档: https://access.redhat.com/documentation/en-US/Red_ ...