声明:这个类是对AFNetworking的二次封装
1.创建RequestManager类继承自NSObject
> 枚举
>//请求数据成功之后进行回调 返回NSData
typedef void(^Finish)(NSData *data);
> //请求数据失败之后进行回调 返回NSError
typedef void(^Error)(NSError *error);
>// 请求方式的枚举
typedef NS_ENUM(NSInteger, RequestType) {
RequestGET,
RequestPOST
};
声明属性
@property (nonatomic, copy)Finish finish;
@property (nonatomic, copy)Error error;
> 给外界的接口,写成类方法,可以让外界直接调用
+ (void)requestWithUrlString:(NSString *)urlString requestType:(RequestType)requestType parDic:(NSDictionary *)parDic finish:(Finish)finish error:(Error)error;
2.RequestManager.m
>类方法
+ (void)requestWithUrlString:(NSString *)urlString requestType:(RequestType)requestType parDic:(NSDictionary *)parDic finish:(Finish)finish error:(Error)error;
{
RequestManager *request = [[RequestManager alloc] init];
[request requestWithUrlString:urlString requestType:requestType parDic:parDic finish:finish error:error];
}
>方法的实现
- (void)requestWithUrlString:(NSString *)urlString requestType:(RequestType)requestType parDic:(NSDictionary *)parDic finish:(Finish)finish error:(Error)error;
{
// 对block属性进行赋值
self.finish = finish;
self.error = error;
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.timeoutInterval = 10;
// 如果是POST请求
if (requestType == RequestPOST)
{
[request setHTTPMethod:@"POST"];
if (parDic.count > 0) {
[request setHTTPBody:[self parDicToPOSTData:parDic]];
}
}
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
self.error(error);
}
else {
dispatch_async(dispatch_get_main_queue(), ^{
self.finish(data);
});
}
}];
//调用此方法 才是去异步链接
[task resume];
}
//拼接网址
- (NSData *)parDicToPOSTData:(NSDictionary *)parDic
{
NSMutableArray *array = [NSMutableArray array];
for (NSString *key in parDic)
{
NSString *string = [NSString stringWithFormat:@"%@=%@", key, parDic[key]];
[array addObject:string];
}
NSString *postString = [array componentsJoinedByString:@"&"];
return [postString dataUsingEncoding:NSUTF8StringEncoding];
}