您的位置:首页 > 理论基础 > 计算机网络

iOS 封装网络请求任务

2015-08-20 10:36 441 查看
  很多时候我们要用到网络发起任务时,每次都要创建NSRUL、NSMutableURLRequest、NSURLSession...这些对象未免太麻烦,这些对象每次创建时方式几乎是一样的,所以可以考虑把它们封装起来,下次再用时就不必再一个个创建,直接调用已封装好的方法,只需要把不同的地方修改下即可(例如URL网址、请求参数等...),具体的方法现实如下:

// __________WXDataService.h__________

#define Base_URL @"http://www.weather.com.cn/data/sk/"    // 宏定义使用重复的网址

typedef void (^CompletionBlock)(id jsonData);   // block


// __________WXDataService.m__________

+ (void)requestWithURLCityID:(NSString *)IDString withHTTPMethod:(NSString *)method withAllHTTPHeaderFields:(NSDictionary *)HTTPHeaderField withHTTPBody:(NSData *)HTTPBody completion:(CompletionBlock)block {

// 网络请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSStringstringWithFormat:@"%@%@.html",Base_URL,IDString]] cachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:60];

// 判断请求方式
if ([method isEqualToString:@"GET"]) {
request.HTTPMethod = @"GET";

}else if ([method isEqualToString:@"POST"]) {
request.HTTPMethod = @"POST";
}

request.allHTTPHeaderFields = HTTPHeaderField;  // 请求头
request.HTTPBody = HTTPBody;    // 请求体

// 网络数据任务
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

if (error != nil) {
NSLog(@"错误 = %@",error);
return ;    // 如果有错误block返回到这里结束
}

// 读取文件
NSError *jsonError = nil;   // 错误信息
id jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainerserror:&jsonError];

// 回到主线程执行操作
dispatch_async(dispatch_get_main_queue(), ^{
block(jsonData);    // 拿到解析好的jsonData数据
});
}];

[task resume];  //发送网络数据任务
}


// __________ViewController.m__________

  // 这样回到主方法ViewController.m中调用,传入需要的参数即可:
[WXDataService requestWithURLCityID:cityID withHTTPMethod:@"GET" withAllHTTPHeaderFields:nil withHTTPBody:nilcompletion:^(id jsonData) {
[self refreshUIData:jsonData[@"weatherinfo"]];
}];

  // 有类似于这种重复的网络任务请求,也可以参照此方法封装起来。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: