自己封装的一个网络请求 以类方法的形式调用 基于AFNetworking
在.h中声明
+ (void)PostData:(NSDictionary*)para url:(NSString*)url success:(void (^)(id responseDic))success fail:(void (^)(NSError *error))fail;
+ (void)GetData:(NSDictionary*)para url:(NSString*)url success:(void (^)(id responseDic))success fail:(void (^)(NSError *error))fail;
在.m中实现
+ (void)PostData:(NSDictionary*)para url:(NSString*)url success:(void (^)(id responseDic))success fail:(void (^)(NSError *error))fail{
AFHTTPSessionManager *Postmanager = [AFHTTPSessionManager manager];
// 设置返回格式
Postmanager.responseSerializer = [AFHTTPResponseSerializer serializer];
Postmanager.requestSerializer = [AFJSONRequestSerializer serializer];
//超时时间
[Postmanager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
[Postmanager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
Postmanager.requestSerializer.timeoutInterval = 12;
//设置token
[Postmanager.requestSerializer setValue:[TokenStore sharedData].token forHTTPHeaderField:@"token"];
//post请求
[Postmanager POST:url parameters:para progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
success(dict);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"error = %@",error.localizedDescription);
fail(error);
}];
}
+ (void)GetData:(NSDictionary*)para url:(NSString*)url success:(void (^)(id responseDic))success fail:(void (^)(NSError *error))fail{
AFHTTPSessionManager *Getmanager = [AFHTTPSessionManager manager];;
// 设置返回格式
Getmanager.responseSerializer = [AFHTTPResponseSerializer serializer];
Getmanager.requestSerializer = [AFHTTPRequestSerializer serializer];
//设置token
[Getmanager.requestSerializer setValue:[TokenStore sharedData].token forHTTPHeaderField:@"token"];
//设置超时时间
[Getmanager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
[Getmanager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
Getmanager.requestSerializer.timeoutInterval = 12;
//get请求
[Getmanager GET:url parameters:para progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
success(dict);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"error = %@",error.localizedDescription);
fail(error);
}];
}
引入头文件调用类方法即可使用,例如:
[NetManage PostData:nil url:self.url success:^(id responseDic) {
//数据解析
} fail:^(NSError *error) {
NSLog(@"失败");
}];