关于ios 网络请求之MKNetworkKit库的使用
项目导入MK库之后,还需要导入三个框架文件:
SystemConfiguration.framework
CFNetwork.framework
Security.framework
新的MK支持ARC机制,所以如果项目没有使用ARC的话需要告诉编译器这个库是支持ARC的:
@interface HttpService : MKNetworkEngine
创建一个类,继承MKNetworkEngine
获取单例对象:
+(HttpService*) shareEngine;
+(HttpService*)shageEngine
{
@synchronized(self)
{
if(engine == nil)
{
engine = [[self alloc] initWithHostName:HOST_URL];
//HOST——URL是被发送请求的主机地址
}
}
return engine;
}
请求方法:
typedef void(^ResponseBlock) (Info *info);
-(MKNetworkOperation*)getLogin:(ResponseBlock) info//请求成功Block
onError:(MKNKResponseErrorBlock) error//请求失败Block
andAction:(NSString*)aAction//请求参数
andCardNum:(NSString*)aCardNum//请求参数
andCardCode:(NSString*) aCardCode; //请求参数
实现
-(MKNetworkOperation*)getLogin:(ResponseBlock)infoonError:(MKNKResponseErrorBlock)error
andAction:(NSString*)aAction
andCardNum:(NSString*)aCardNum
andCardCode:(NSString*)aCardCode
{
//网络接口
NSString *url = [NSStringstringWithFormat:@"DeliveryService.aspx"];
//创建一个存放参数的可变字典
NSMutableDictionary *dic =[NSMutableDictionary dictionaryWithCapacity:0];
//将请求的参数存入字典
[dic setObject:aAction forKey:@"action"];
[dic setObject:aCardNumforKey:@"CardNum"];
[dic setObject:aCardCodeforKey:@"CardCode"];
//创建一个MKNetworkOperation 对象
MKNetworkOperation *op = [selfoperationWithPath:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]params:dic httpMethod:@"POST"];
//发送请求
[op addCompletionHandler:^(MKNetworkOperation*completedOperation){
//请求成功时执行
//completedOperation 请求成功的数据
NSString *resStr = [completedOperationresponseString];
NSLog(@"%@",resStr);
NSDictionary *d = [str objectFromJSONString];
Info *aInfo = [[Info alloc] initInfoWithDic:d];
//回调
info(aInfo);
}errorHandler:^(MKNetworkOperation*completedOperation,NSError *error){
//请求失败时执行
}];
[self enqueueOperation:op];
return op;
}