之前写项目时一直用第三方AFNet进行网络请求,对于原生的网络请求模式很久没有涉猎。所以趁着最近有空对原生的网络请求进行了一个封装,算是一个复习吧。
苹果推荐使用NSURLSession框架进行网络请求,所以封装是在NSURLSession的基础上进行的封装。本次封装的主文件在为NetWorkingHelper类,由于为了方面进行数据转换和检查还引入了两个类OWInstrument和NSURL+CheckUrl。
NetWorkingHelper.h
#import <Foundation/Foundation.h>
@interface NetWorkingHelper : NSObject
+(void)getDataWithUrlStr:(NSString *)url
successBlock:(void (^)(id obj))success
failueBlock:(void (^)(id obj))failue;
+(void)postDataWithParamer:(id)paramer
url:(NSString *)urlStr
successBlock:(void (^)(id obj))success
failueBlock:(void (^)(id obj))failue;
@end
NetWorkingHelper.m
//get请求
+(void)getDataWithUrlStr:(NSString *)url
successBlock:(void (^)(id))success
failueBlock:(void (^)(id))failue {
NetWorkingHelper *helper = [NetWorkingHelper shareDefault];
//对url进行转码,防止有中文产生
NSString *urlStr = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSURLSessionDataTask *dataTask = [helper.session dataTaskWithURL:[NSURL URLWithString:urlStr] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (!error) {
success(data);
}else {
failue(error);
}
});
}];
[dataTask resume];
});
}
//post请求
+(void)postDataWithParamer:(id)paramer url:(NSString *)urlStr successBlock:(void (^)(id))success failueBlock:(void (^)(id))failue {
NetWorkingHelper *helper = [NetWorkingHelper shareDefault];
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// //设置请求超时时间
// request.timeoutInterval = 0.5;
// //设置缓存策略
// request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
// //设置请求方式
request.HTTPMethod = @"POST";
//设置请求头
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//设置请求体
request.HTTPBody = [NetWorkingHelper requestDataWithObj:paramer];
//将网络请求放到子线程去执行
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSURLSessionDataTask *dataTask = [helper.session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
dispatch_async(dispatch_get_main_queue(), ^{
//在主线程回传数据并处理
if (!error) {
success(data);
}else {
failue(error);
}
});
}];
[dataTask resume];
});
}
对于请求数据体的封装需要进行一个一个简单的封装,否则会出现数据错误问题,我这边用这个方法进行处理
//苹果官方的请求体最终封装成字符串类型
+(NSData *)requestDataWithObj:(id)paramer {
NSString *dataStr = @"";
if ([paramer isKindOfClass:[NSString class]]) {
dataStr = [paramer mutableCopy];
}else if ([paramer isKindOfClass:[NSDictionary class]]) {
NSArray *keys = [paramer allKeys];
for (NSString *key in keys) {
NSString *value = [paramer objectForKey:key];
NSString *valueAll = [key stringByAppendingString:[NSString stringWithFormat:@"=%@",value]];
dataStr = [dataStr stringByAppendingString:valueAll];
}
}else {
}
return [dataStr dataUsingEncoding:NSUTF8StringEncoding];
}
以上只简单封装了get和post请求,后续还会进行一些改动,有需要的朋友可以去看demo。