1.AFNetWorking简介
AFNetworking是一个在IOS开发中使用非常多网络开源库,适用于iOS以及Mac OS X. 它构建于(apple iOS开发文档)NSURLConnection, NSOperation,以及其他熟悉的Foundation技术之上。它拥有良好的架构,丰富的API,以及模块化构建方式,使得使用起来非常轻松.
AFURLConnectionOperation:继承自 NSOperation 实现了NSURLConnection 的代理方法.
AFHTTPRequestOperation: 继承自 AFURLConnectionOperation的子类,当request请求使用的协议为HTTP和HTTPS时使用,它封装了用于决定request是否成功的状态码和内容类型.
AFJSONRequestOperation: 继承自AFHTTPRequestOperation,用于下载和处理json response数据.
AFXMLRequestOperation:继承自AFHTTPRequestOperation,用于下载和处理xml response数据.
AFPropertyListRequestOperation:继承自AFHTTPRequestOperation,用于下载和处理property list response数据.
AFHTTPClient:是一个封装了基于http协议的网络应用程序的公共交流模式.包含
(1).发起基于根路径的使用基本的url相关路径来只做request
(2).为request自动添加设置http headers.
(3).使用http 基础证书或者OAuth来验证request
(4).为由client制作的requests管理一个NSOperationQueue
(5).从NSDictionary生成一个查询字符串或http bodies.
(6).从request中构建多部件
(7).自动的解析http response数据为相应的表现数据
(8).在网络可达性测试用监控和响应变化.
AFNetWorking的下载地址:https://github.com/AFNetworking/AFNetworking
2.AFNetWorking的使用
(1) 将AFNetWorking文件夹导入项目
(2) 添加类库 Security.framework、MobileCoreServices.framework、SystemConfiguration.framework
(3) 在使用的地方 #import "AFNetworking.h"
(4)解决编译时警告:
//Prefix.pch文件中加入
#import <SystemConfiguration/SystemConfiguration.h>
#import <MobileCoreServices/MobileCoreServices.h>
注:AFNetWorking采用ARC ,在不使用ARC项目中使用时,对AFNetWorking的所有.m文件添加“-fobjc-arc”
在使用ARC项目中,使用“不使用ARC”的类库时,对类库的.m文件添加“-fno-objc-arc”
(5)
static NSString*const BaseURLString = @"http://www.raywenderlich.com/downloads/weather_sample/";
NSString *weatherUrl = [NSStringstringWithFormat:@"%@weather.php?format=json",BaseURLString];
NSURL *url = [NSURLURLWithString:weatherUrl];
NSURLRequest *request = [NSURLRequestrequestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperationJSONRequestOperationWithRequest:request success:^(NSURLRequest*request, NSHTTPURLResponse *response, id JSON) {
NSDictionary*dicWeather = (NSDictionary *)JSON;
NSLog(@"result:%@",dicWeather);
} failure:^(NSURLRequest*request, NSHTTPURLResponse *response, NSError *error, id JSON) {
UIAlertView*alertView = [[UIAlertView alloc] initWithTitle:@"Error RetrievingWeather" message:[NSStringstringWithFormat:@"%@",error] delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alertView show];}];
[operation start];
1)根据基本的URL构造除完整的一个URL,然后通过这个完整的URL获得一个NSURL对象,然后根据这个url获得一个NSURLRequest。
2)AFJSONRequestOperation是一个完整的类,整合了从网络中获取数据并对JSON进行解析。
3)当请求成功,则运行成功块。在本例中,把解析出来的天气数据从JSON变量转换为一个字典(dictionary),并将其存储在字典中。
4)如果运行出问题了,则运行失败块(failure block),比如网络不可用。如果failure block被调用了,将会通过提示框显示错误信息。
(6).AFNetWorking异步加载图片
#import “UIImageView+AFNetworking.h”
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(40, 80, 40, 40)];
__weak UIImageView *_imageView = imageView;
[imageViewsetImageWithURLRequest:[[NSURLRequest alloc] initWithURL:[NSURLURLWithString:@"http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png"]] placeholderImage:[UIImage imageNamed:@"placeholder.png"] success:^(NSURLRequest *request,NSHTTPURLResponse *response, UIImage *image) {
_imageView.image = image;
[_imageView setNeedsDisplay];
} failure:^(NSURLRequest *request, NSHTTPURLResponse*response, NSError *error) { }];
[self.view addSubview:imageView];
(7).GET 和POST请求
1).构建一个baseURL,以及一个参数字典,并将这两个变量传给AFHTTPClient.
2).将AFJSONRequestOperation注册为HTTP的操作, 这样就可以跟之前的示例一样,可以获得解析好的JSON数据。
3).做了一个GET请求,这个请求有一对block:success和failure。
4).POST请求跟GET一样
AFHTTPClient *client= [[AFHTTPClient alloc] initWithBaseURL:baseURL];
[clientregisterHTTPOperationClass:[AFJSONRequestOperation class]];
[clientsetDefaultHeader:@"Accept" value:@"application/json"];
[client postPath:@"weather.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.weather =responseObject;
self.title = @"HTTPPOST";
[self.tableViewreloadData]; } failure:^(AFHTTPRequestOperation *operation, NSError*error) {
UIAlertView *av =[[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather" message:[NSStringstringWithFormat:@"%@",error] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[av show];
[client getPath:@"weather.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.weather =responseObject;
self.title = @"HTTP GET";
[self.tableViewreloadData]; } failure:^(AFHTTPRequestOperation *operation, NSError*error) { UIAlertView *av =[[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather" message:[NSStringstringWithFormat:@"%@",error] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[av show];
}]; <strong> </strong>
(8)状态栏设置
在Appdelegate里面- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 方法中添加 [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];//用来给用户做出网络访问的提示。
(9)请求超时设置
timeout和参数都是在NSURLRequest/NSMutableURLRequest设置的
NSMutableURLRequest *request = [client requestWithMethod:@"GET" path:@"/" parameters:nil];//这里的parameters:参数就是你的第二个问题如何设置参数
[request setTimeoutInterval:120];
AFHTTPRequestOperation *operation = [client HTTPRequestOperationWithRequest:request success:^{...} failure:^{...}];
[client enqueueHTTPRequestOperation:operation];
如果你是继承了AFHTTPClient
就需要override一个方法requestWithMethod
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method path:(NSString *)path parameters:(NSDictionary *)parameters{
NSMutableURLRequest *request = [super requestWithMethod:method path:path parameters:parameters];
[request setTimeoutInterval:15];
return request;
}
[self postPath:@"" parameters:nil //参数
success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (success) {
success((AFJSONRequestOperation *)operation, responseObject);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (failure) {
failure((AFJSONRequestOperation *)operation, error);
}
}];
转载两篇其他大师的博文:
AFNetWorking2.0的使用:http://blog.csdn.net/daiyelang/article/details/38421341
AFNetWorking2.5的使用:http://blog.csdn.net/daiyelang/article/details/38434023
AFNetWorking2.0新特性讲解之AFHTTPSessionManager:http://www.360doc.com/content/13/1217/09/14615320_337780262.shtml
AFNetWorking框架使用浅析:http://wenku.baidu.com/link?url=RbK27v4ZabX1ezY6FXn8gvcIFJXpVesi-zZHFP2DQ_cuv7cT1pIr13GzOdpUBo7B30BC0N2TjvnnSKi3u_BMJ9jlZ5ZC_gEfPqepOtsFsAu