#import "NetWorkingHelper.h"
@implementation NetWorkingHelper
+(NSData*)dicTransformDataWithDic:(NSDictionary*)dic{
NSMutableArray* mArray=[NSMutableArray array];
if (dic && dic.count) {
for (NSString* key in dic) {
NSString* str=[NSString stringWithFormat:@"%@=%@",key,dic[key]];
[mArray addObject:str];
}
NSString* resultStr=[mArray componentsJoinedByString:@"&"];
return [resultStr dataUsingEncoding:NSUTF8StringEncoding];
}else{
return nil;
}
}
//外部调用的方法
+(void)requestWithType:(RequestType)type url:(NSString*)url parameters:(NSDictionary*)parameters success:(Success)success failure:(Failure)failure{
//会话管理对象
NSURLSession* session=[NSURLSession sharedSession];
NSMutableURLRequest* req=nil;
NSURLSessionDataTask* task=nil;
//设置请求参数
if (type==GET) {
NSString* parString=[[NSString alloc] initWithData:[self dicTransformDataWithDic:parameters] encoding:NSUTF8StringEncoding ];
if (parString) {
url=[url stringByAppendingFormat:@"?%@",parString];
}
req=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
req.HTTPMethod=@"GET";
}else{
req.HTTPMethod=@"POST";
req=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
req.HTTPBody=[self dicTransformDataWithDic:parameters];
}
task=[session dataTaskWithRequest:req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
if (failure) {
//请求失败
failure(task,error);
}
}else{
//请求成功
id result=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
if (success) {
success(task,result);
}
}
}];
//启动任务
[task resume];
}
@end
在其他类中调用即可,例如:
- (void)viewDidLoad {
[super viewDidLoad];
NSString* url=@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
[NetWorkingHelper requestWithType:GET url:url parameters:nil success:^(NSURLSessionTask *task, id responseObject) {
if (responseObject) {
NSLog(@"请求成功----%@",responseObject);
}
} failure:^(NSURLSessionTask *task, NSError *error) {
if (error) {
NSLog(@"请求失败---%@",error.description);
}
}];
}