1 将AFNetWorking文件夹导入项目
2 添加类库 Security.framework、MobileCoreServices.framework、SystemConfiguration.framework
3 在使用的地方 #import "AFNetworking.h"
4.解决编译警告:
<span style="font-size:14px;"><em>Prefix.pch文件中加入
#import <SystemConfiguration/SystemConfiguration.h>
#import <MobileCoreServices/MobileCoreServices.h></em></span>
5.JSON数据解析
(1)根据基本的URL构造出完整的一个URL, 让后通过这个完整的URL获得一个NSURL对象,然后根据这个url获得一个NSURLRequest。
(2)AFNJSONRequestOperation是一个完整的类,整合了送网络中获取数据并对JSON进行解析。
(3)当请求成功,则运行成功块,在本例子中将一个JSON变量转换为一个字典,并将其存在字典中。
(4)如果失败,则运行失败块,比如网络不可用
<pre name="code" class="objc"><span style="font-size:14px;">static NSString *const BaseURLString = @"http://www.raywenderlich.com/downloads/weather_sample";
/*1*/
NSString *weatherUrl = [NSString stringWithFormat:@"%@weather.php?format=json", BaseURLString];
NSURL *url = [NSURL URLWithString:weatherUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
/*2.3.4*/
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:requestsuccess:^(NSURLRequest * request, NSHTTPURLResponse *response, id JSON) {
NSDictonary *dicWeather = (NSDictonary *)JSON; NSLog(@"result:%@", dicWeather); } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *rror, id JSON) { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error RetrievingWether" message:[NSString stringWithFormat :@"%@", error] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alertView show]; }]; [operation start];</span>
6.AFNetworking异步加载图片
<span style="font-size:14px;">// 1
#imptort "UIImageView+AFNetworking.h"
// 2
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(40, 80, 40, 40)];
__weak UIImageView *_imageView;
[imageView setImageWithURLRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.worldweatheronline.com/images/wsymbols01_png_64/wstmbol_0001_sunny.png"]] placeholderImage:[UIImage imageNamed:@"placeholder.png"] success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
_imageView.image;
[_imageView setNeedsDisplay];
} failure:^(NSURLRequest *request, NSHTTPURLResponse Response, NSError *error) {
}];
[self.view addSubview:imageView];
</span>
7.GET和POST请求
(1)构建一个baseURL,以及一个参数字典,并将这两个变脸传给AFHTTPClient。
(2)将AFJSONRequestOpreation注册为HTTP的操作,这样就可以和之前示例一样,获得解析好的JSON数据
(3)做一个GET请求,这个请求有一对block:success和failure。
(4)POST请求和GET一样
<span style="font-size:14px;">AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
[client registerHTTPOperationClass:[AFJSONRequestOperation class]];
[client setDefeultHeader:@"Accept" value:@"application/json"];
[client postPath:@"weather.php" parameters:parameters success:^(AFNHTTPRequestOperation *operation, id responseObject) {
self.weather = responseObject;
self.title = @"HTTPPOST";
[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];
}];
[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];
}];</span>
8.状态栏设置
在Appdelegate里面的- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 方法中添加
[AFNetworkActivityIndicatorManager shareManager] setEnabled:YES]; // 用来给用户做出网络访问提示。
9.请求超时设置
(1)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];
(2)如果你是继承了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) {
succes((AFJSONRequestOperation *)operation, responseObject);
}
} failure:^(AFJSONRequestOperation *operation, NSError *error) {
if (failure) {
failure((SFJSONRequestOperation *)operation, error);
}
}];