一、引入MKNetworkKit
1,添加MKNetworkKit的到工程目录。
2,添加的CFNetwork.Framework,SystemConfiguration.framework,Security.framework和ImageIO.Framework。
3,PCH文件包含MKNetworkKit.h
4,如果您正在构建针对iOS,删除NSAlert + MKNetworkKitAdditions.h文件。
5,如果您正在构建的Mac,删除UIAlertView + MKNetworkKitAdditions.h文件。
二、MKNetworkKit类
1,MKNetworkOperation
2,MKNetworkEngine
3,辅助类(apple' Reachability) and categories,网络以及扩展
1.1 -(MKStoreKit添加应用内购买)对于使用MKNetworkKit,你需要知道的方法由两个类MKNetworkOperation MKNetworkEngine。MKNetworkOperation与ASIHttpRequest相似。这是一个NSOperation的子类,包装你的请求和响应类。创建一个MKNetworkOperation用于管理应用内请求时序等问题。
2.1 -MKNetworkEngine是一个伪单例类,负责管理你的app的网络队列。因此,简单的请求时,你应该直接使用MKNetworkEngine的方法。在更为复杂的定制中,你应该继承它。每一个MKNetworkEngine的子类都有他自己的Reachability对象来通知服务器的连通情况。可以考虑为特别的REST服务器请求都通过继承MKNetworkEngine。因为是伪单例模式,每一个单独的子类的请求,都会通过仅有的队列发送。
MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:@"192.168.2.176:9502/api"
customHeaderFields:nil];
MKNetworkOperation *op = [engine operationWithPath:@"login.php?userid=admin&userpwd=123" params:nil httpMethod:@"GET"];
[op onCompletion:^(MKNetworkOperation *operation){
NSLog(@"request string: %@",[op responseString]);
}
onError:^(NSError *error){
}];
[engine enqueueOperation:op];
//post
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
[dic setValue:@"admin" forKey:@"username"];
[dic setValue:@"123" forKey:@"password"];
MKNetworkOperation *op = [engine operationWithPath:@"user.do" params:dic httpMethod:@"POST"];
[op onCompletion:^(MKNetworkOperation *operation) {
NSLog(@"post response string :%@",[op responseString]);
} onError:^(NSError *error) {
DLog(@"%@", error);
}];
[engine enqueueOperation:op];
解析json
//接口使用的是天气接口
static MKNetworkEngine *engine;
+(MKNetworkEngine *)defaultEngine{
if (engine == nil) {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
engine = [[MKNetworkEngine alloc] initWithHostName:@"m.weather.com.cn"
customHeaderFields:nil];//initWithHostName 只写主机名,不要加http//,代码会自动加上
});
}
return engine;
}
MKNetworkOperation *operation = [engine operationWithPath:@"/data/101010100.html" params:nil httpMethod:@"GET"];
//operationWithPath 写后缀名 使用GET方法
[operation addCompletionHandler:^(MKNetworkOperation *completedOperation) {
//******** 返回json 直接解析json
id json = [completedOperation responseJSON]; //有现成的返回json方法可直接调用
NSDictionary *weatherDic = (NSDictionary *)json;//json里面本身就是字典,所以直接把json转换成dictionary
NSDictionary *weatherInfo = [weatherDic objectForKey:@"weatherinfo"];
NSString *city = [weatherInfo objectForKey:@"city"];
NSString *date_y = [weatherInfo objectForKey:@"date_y"];
NSString *fl1 = [weatherInfo objectForKey:@"fl1"];
NSString *fl2 = [weatherInfo objectForKey:@"fl2"];
self.textlable.text = [NSString stringWithFormat:@"%@ \n %@ \n %@ \n %@",city,date_y,fl1,fl2]; //赋值
//
NSLog(@"%@",[completedOperation responseJSON]); //返回json
} errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
}];
[engine enqueueOperation:op];
}