常用请求框架AFN的进一步封装,个人感觉好用

自己没事时候在afn的基础上又进行了一层封装,一行代码解决get/post请求,自我感觉良好,有用的朋友可以下载下来看看---推荐

先说一下环境的吧,先建一个项目,然后导入afn库,可以直接导入包,也可以通过cocoapods导入,这个简单的操作就不说了,后面我会介绍怎么安装cocoapods的,下面直接上代码:

1.新建一个类为WNHttpRequest

.h中:

#importtypedef void(^SuccessBlock)(id responseBody);

typedef void(^FailureBlock)(NSString *error);

@interface WNHttpRequest : NSObject

+(void)reqWithUrl:(NSString *)url parameters:(id)parameter reqMethod:(NSString *)method body:(NSString *)body successBlock:(SuccessBlock)successBlock failureBlock:(FailureBlock)failureBlock;

@end

.m中

#import "WNHttpRequest.h"#import "AFNetworking.h"#import@implementation WNHttpRequest

#pragma mark - 服务器请求

+(void)reqWithUrl:(NSString *)url parameters:(id)parameter reqMethod:(NSString *)method body:(NSString *)body successBlock:(SuccessBlock)successBlock failureBlock:(FailureBlock)failureBlock

{

AFHTTPSessionManager *manager=[[[self class] alloc]init];

NSString *uppercaseReqMethod=[method uppercaseString];

NSLog(@"%@",uppercaseReqMethod);

if ([uppercaseReqMethod isEqualToString:@"POST"]) {

[manager POST:url parameters:parameter success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

successBlock(responseObject);

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

failureBlock([error localizedDescription]);

}];

}

else if([uppercaseReqMethod isEqualToString:@"GET"])

{

[manager GET:url parameters:parameter success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

successBlock(responseObject);

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

failureBlock([error localizedDescription]);

}];

}

}

@end

2.在ViewController.m中

#import "ViewController.h"

#import "WNHttpRequest.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

NSDictionary *parameters = @{参数};

[WNHttpRequest reqWithUrl:url parameters:parameters reqMethod:@"POST/GET" body:nil successBlock:^(id responseBody) {

NSLog(@"%@",responseBody);

} failureBlock:^(NSString *error) {

NSLog(@"%@",error);

}];

}

- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

源代码demo的下载地址https://github.com/wangningsai/WNHttpRequest

直接把WNHttpRequest这个类拉到项目中即可

你可能感兴趣的:(常用请求框架AFN的进一步封装,个人感觉好用)