AFNetworking 使用总结 (用法+JSON解析)转载

来源:互联网 发布:mac设置图标大小 编辑:程序博客网 时间:2024/06/14 04:20

AFNetworking 使用总结 (用法+JSON解析)

   
转载 原文http://blog.sina.com.cn/s/blog_af73e7a70102v0l0.html
  1. 下面这个例子是用来处理json请求的:  
  2. NSURL *url [NSURL URLWithString:@"https://alpha-api.app.net/stream/0/posts/stream/global"];  
  3. NSURLRequest *request [NSURLRequest requestWithURL:url];  
  4. AFJSONRequestOperation *operation [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)  
  5.     NSLog(@"App.net Global Stream: %@"JSON);  
  6. failure:nil];  
  7. [operation start];  
  8.   
  9.   
  10. 使用方法:  
  11. 1.下载AFNetwork,点击下载  
  12. 2.将文件夹名称为AFNetworking拖入到你的工程项目即可  
  13.   
  14. 常见问题:  
  15. 1. AFNetworking作用都有哪些?  
  16. NSURLConnection提供了+sendAsynchronousRequest:queue:completionHandler:和+sendAsynchronousRequest:queue:completionHandler: ,但是AFNetworking提供了更好的功能  
  17. *AFURLConnectionOperation和它的子类继承NSOperation的,允许请求被取消,暂停/恢复和由NSOperationQueue进行管理。  
  18. *AFURLConnectionOperation也可以让你轻松得完成上传和下载,处理验证,监控上传和下载进度,控制的缓存。  
  19. *AFHTTPRequestOperation和它得子类可以基于http状态和内容列下来区分是否成功请求了  
  20. *AFNetworking可以将远程媒体数据类型(NSData)转化为可用的格式,比如如JSON,XML,图像和plist。  
  21. *AFHTTPClient提供了一个方便的网络交互接口,包括默认头,身份验证,是否连接到网络,批量处理操作,查询字符串参数序列化,已经多种表单请求  
  22. *的UIImageView+ AFNetworking增加了一个方便的方法来异步加载图像。  
  23.   
  24. 2. AFNetworking是否支持缓存?  
  25. 可以,NSURLCache及其子类提供了很多高级接口用于处理缓存  
  26. 如果你想将缓存存储再磁盘,推荐使用SDURLCache  
  27.   
  28. 3.如何使用AFNetworking上传一个文件?  
  29. NSData *imageData UIImagePNGRepresentation(image);  
  30. NSURLRequest *request [client multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id  formData)  
  31.   [formData appendPartWithFileData:imageData mimeType:@"image/png" name:@"avatar"];  
  32. }];  
  33.   
  34.   
  35. 4.如何使用AFNetworking下载一个文件?  
  36. 先创建一个AFURLConnectionOperation对象,然后再使用它的属性outputStream进行处理  
  37. operation.outputStream [NSOutputStream outputStreamToFileAtPath:@"download.zip" append:NO];  
  38.   
  39. 5.如何解决:SystemConfiguration framework not found in project  
  40. 请导入:  
  41. #import   
  42. #import   
  43.   
  44. 6.当应用程序退出时,如何保持持续的请求?  
  45. AFURLConnectionOperation有一个叫setShouldExecuteAsBackgroundTaskWithExpirationHandler:的方法用于处理在应用程序进入后台后,进行持续的请求  
  46. [self setShouldExecuteAsBackgroundTaskWithExpirationHandler:^{  
  47. }];  
  48.   
  49.   
  50.   
  51. 一些实例:  
  52. 1.XML 请求  
  53. NSURLRequest *request [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://api.flickr.com/services/rest/?method=flickr.groups.browse&api_key=b6300e17ad3c506e706cb0072175d047&cat_id=34427469792@N01&format=rest"]];  
  54. AFXMLRequestOperation *operation [AFXMLRequestOperation XMLParserRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser)  
  55.   XMLParser.delegate self;  
  56.   [XMLParser parse];  
  57. failure:nil];  
  58. [operation start];  
  59.   
  60.   
  61. 2.图片请求:  
  62. UIImageView *imageView [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)];  
  63. [imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]];  
  64.   
  65. 3.图片上传处理,监测上传状态:  
  66. didiwei  17:28:57  
  67. NSURL *url [NSURL URLWithString:@"http://api-base-url.com"];  
  68. AFHTTPClient *httpClient [[AFHTTPClient alloc] initWithBaseURL:url];  
  69. NSData *imageData UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5);  
  70. NSMutableURLRequest *request [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id formData)  
  71.     [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];  
  72. }];  
  73. AFHTTPRequestOperation *operation [[AFHTTPRequestOperation alloc] initWithRequest:request];  
  74. [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite)  
  75.     NSLog(@"Sent %lld of %lld bytes"totalBytesWritten, totalBytesExpectedToWrite);  
  76. }];  
  77. [operation start];  
  78.   
  79.   
  80. 4.在线流媒体请求  
  81. NSURLRequest *request [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8080/encode"]];  
  82. AFHTTPRequestOperation *operation [[AFHTTPRequestOperation alloc] initWithRequest:request];  
  83. operation.inputStream [NSInputStream inputStreamWithFileAtPath:[[NSBundle mainBundle] pathForResource:@"large-image" ofType:@"tiff"]];  
  84. operation.outputStream [NSOutputStream outputStreamToMemory];  
  85. [operation start];  
142257cszs1i9t18t8btp9.png  

From:http://www.coneboy.com/?p=716

这几天在评论页面的时候发现get请求后加入2个以上的汉字会出现BadURL提示,断点调试发现是多中文字符惹的祸,所以在URL使用以前先转码成UTF-8即可
这里顺便说明下自己使用AFNetworking 的常用方法。

目前我只是用到
#import “AFHTTPClient.h”;
#import “AFHTTPRequestOperation.h”
这两个类

发起一个请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 NSString *URLTmp = @”http://www.coneboy.com”;
NSString *URLTmp1 = [URLTmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  //转码成UTF-8  否则可能会出现错误
URLTmp = URLTmp1;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: URLTmp]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success: %@", operation.responseString);

 

NSString *requestTmp = [NSString stringWithString:operation.responseString];
NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
//系统自带JSON解析
NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@”Failure: %@”, error);
[SVProgressHUD dismissWithError:@"提交失败,请重试"];
}];
[operation start];
}

AFNetworking 下载图片
AFNETWorking 下载图片是异步并且可缓存到cache里面 非常好用不会阻塞主线程。用过的都说好!而且使用也简单!
#import “UIImageView+AFNetworking.h”

1
[imageView setImageWithURL:[NSURL URLWithString:URL]];

 

0 0