仅仅是基本实现,根据需要进行修改。
大佬勿喷,有错误的地方还请在评论区指出,谢谢
RequestHelper.h
#import <Foundation/Foundation.h> @interface RequestHelper : NSObject //POST请求方法,afnetworking +(void)postNetCallForStr:(NSString*)url paramArray:(NSMutableArray *) paramArray success:(void (^)(NSDictionary * respDic))success fail:(void (^) (NSError * error)) fail; @end
RequestHelper.m
#import "RequestHelper.h" #import "AFNNetworking.h" @implementation RequestHelper +(void)postNetCallForStr:(NSString*)url paramArray:(NSMutableArray *) paramArray success:(void (^)(NSDictionary * respDic))success fail:(void (^) (NSError * error)) fail{ AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; manager.requestSerializer = [AFJSONRequestSerializer serializer]; manager.responseSerializer = [AFHTTPResponseSerializer serializer]; NSString *urlStr=url; NSLog(@"===%@",urlStr); [manager POST:url parameters:paramArray success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { //请求成功返回数据 根据responseSerializer 返回不同的数据格式 NSLog(@"responseObject-->%@",responseObject); NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil]; if(success){ success(dic); } } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { //请求失败 NSLog(@"error-->%@",error); if(fail){ fail(error); } }]; } @end
调用示例
NSString *url=@"http://10.0.0.233:8848/User/login"; NSDictionary* param= @{ @"username":@"xxx", @"password":@"xxxxxxxx" }; [RequestHelper postNetCallForStr:url paramArray:param success:^(NSDictionary *respDic) { NSLog(@"%@",respDic); } fail:^(NSError *error) { NSLog(@"%@",error); }];
微信扫码查看本文
发表评论