封装网络请求是因为项目中需要与服务器进行交互的次数非常多,封装好之后可以节省很多代码,也方便调用.
//Get请求的封装, 在.h文件里声明方法;
- (void)httpGetUrlNoToken:(NSString *)url
params:(NSDictionary *)paramsDict
success:(void(^)(NSDictionary *))success
failure:(void(^)(NSError *))failure;
//在.m里实现方法,有参数上传参数,没参数传nil.
- (void)httpGetUrlNoToken:(NSString *)url
params:(NSDictionary *)paramsDict
success:(void (^)(NSDictionary *))success
failure:(void (^)(NSError *))failure
{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:url parameters:paramsDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject){
success(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure(error);
}];
}
通常我会建一个单例类.这个方法放进去,方便调用.