网上针对af的封装也有好多了,其实封装主要是为了我们能够更好的复用,减少不必要的代码量!更多的好处就不多说了,话不多说直接上代码。
1、新建一个LsxNetManager的工具类,继承自NSObject;
2.使用类方法创建两个GET 和 POST请求函数;
/** 对AFHTTPSessionManager的GET请求方法进行了封装 */
+ (id)GET:(NSString *)path parameters:(NSDictionary *)params complationHandle:(void(^)(id responseObject, NSError *error))completed;
/** 对AFHTTPSessionManager的POST请求方法进行了封装 */
+ (id)POST:(NSString *)path parameters:(NSDictionary *)params complationHandle:(void(^)(id responseObject, NSError *error))completed;
3.在.m 中#import “AFNetworking/AFNetworking.h”,并实现.h中定义的两个函数;
static AFHTTPSessionManager *manager = nil;
/** 单例一个AFHTTPSessionManager */
+ (AFHTTPSessionManager *)defaultManager {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [AFHTTPSessionManager manager];
// 设置接受解析的内容类型
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/json",@"text/plain",@"text/javascript",@"application/json", nil];
});
return manager;
}
+ (id)GET:(NSString *)path parameters:(NSDictionary *)params complationHandle:(void (^)(id, NSError *))completed {
NSLog(@"Request Path: %@, params %@", path, params);
return [[self defaultManager] GET:path parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
completed(responseObject,nil);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[SVProgressHUD dismiss];
NSLog(@"GET ERROR: %@",error.userInfo);
}];
}
+ (id)POST:(NSString *)path parameters:(NSDictionary *)params complationHandle:(void (^)(id, NSError *))completed {
return [[self defaultManager] POST:path parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
completed(responseObject,nil);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[SVProgressHUD dismiss];
NSLog(@"POST ERROR: %@",error.userInfo);
}];
}
4.接下来是它的使用方法
(1)导入头文件
#import "LsxNetManager.h"
(2)直接调用
[BaseNetManager POST:[NSString stringWithFormat:@"%s/appa/company/collectUserList",URLL] parameters:params complationHandle:^(id responseObject, NSError *error){
NSLog(@"服务器返回的数据:%@----------出错信息:%@",responseObject,error);
}];