网络请求基于对AFNetWorking的一个二次封装

2016-06-16  本文已影响171人  天涯海角我爱你

#import

// 这个类是基于对AFNetWorking的一个二次封装

// 之前我们请求的方式是用NSURLSession 现在我们请求的方式变成AFNetWorking

// 请求方式的枚举

typedef NS_ENUM(NSInteger, RequestType) {

RequestGET, // GET请求

RequestPOST // POST请求

};

// 请求成功回调的block

typedef void(^Finish)(NSData *data);

// 请求失败回调的block

typedef void(^Error)(NSError *error);

@interface RequestManager : NSObject

// block属性

@property (nonatomic, copy)Finish finish;

@property (nonatomic, copy)Error error;

// 给controller提供的接口 传进来字符串网址 字典 请求类型 成功block 失败blcok

+ (void)requestWithUrlString:(NSString *)urlString parDic:(NSDictionary *)parDic requestType:(RequestType)requestType finish:(Finish)finish error:(Error)error;

@end

#import "RequestManager.h"

@implementation RequestManager

+ (void)requestWithUrlString:(NSString *)urlString parDic:(NSDictionary *)parDic requestType:(RequestType)requestType finish:(Finish)finish error:(Error)error

{

RequestManager *manager = [[RequestManager alloc] init];

[manager requestWithUrlString:urlString parDic:parDic requestType:requestType finish:finish error:error];

}

- (void)requestWithUrlString:(NSString *)urlString parDic:(NSDictionary *)parDic requestType:(RequestType)requestType finish:(Finish)finish error:(Error)error

{

// block赋值

self.finish = finish;

self.error = error;

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

manager.responseSerializer = [AFHTTPResponseSerializer serializer];

if (requestType == RequestGET)

{

[manager GET:urlString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

[self finishRequestReturnMainThread:responseObject];

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

self.error(error);

}];

return;

}

[manager POST:urlString parameters:parDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

[self finishRequestReturnMainThread:responseObject];

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

self.error(error);

}];

}

- (void)finishRequestReturnMainThread:(NSData *)data

{

dispatch_async(dispatch_get_main_queue(), ^{

self.finish(data);

});

}

@end

上一篇下一篇

猜你喜欢

热点阅读