由于ASIHTTPRequest已经没人去维护了,所以为了应对不断更新的ios版本,所以需要用一些其他的库来简化网络操作,本文首先看一下AFNetworking,简单介绍一下用法。
1. 启动
首先当然是获取到最新的库,github地址。另附,官方文档地址:http://cocoadocs.org/docsets/AFNetworking/2.0.0-RC1/。
解压后的目录结构如图。
然后加入需要的类库,
CoreLocation.framework, MobileCoreServices.framework, SystemConfiguration.framework, Security.framework
最后在预编译头文件加入
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <Security/Security.h>
#import "AFNetworking.h"
编译一下,没问题就好了。
2. 发送请求与解析数据
这里先给出返回数据是Json的情况,请求如何发出。
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:WEATHERAPI, cityCode]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];
AFJSONRequestOperation *operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSDictionary *result = [(NSDictionary *)JSON objectForKey:@"weatherinfo"];
self.cityLabel.text = [result objectForKey:@"city"];
self.tempLabel.text = [result objectForKey:@"temp"];
self.timeLabel.text = [result objectForKey:@"time"];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@"Error with: %@", error);
}];
[operation start];
我获取请求的webservice是中国国家气象局天气预报信息接口:
http://www.weather.com.cn/data/sk/101010100.html
注意在发请求之前
[AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];
不加这句话的话会报一个error:
Error Domain=AFNetworkingErrorDomain Code=-1016....
AFNetworking通过网络来加载和处理结构化的数据是非常智能的,普通的HTTP请求也一样。尤其是它支持JSON, XML 和 Property Lists (plists)。
未完待续。。。。