AFNetworking导入工程
网络请求类名NetworkTool继承AFHTTPSessionManager
NetworkTool.h
#import "AFHTTPSessionManager.h"
@interface NetworkTool : AFHTTPSessionManager
/**
* 网络请求工具类全局访问点
*
* @return AFHTTPSessionManager的实例
*/
+ (instancetype)sharedNetworkTool;
/**
* 网络请求工具类请求的主方法
*
* @param URLString 请求地址
* @param success 成功的回调
* @param failure 失败的回调
*/
+ (void)POSTWithURLString:(NSString *)URLString parameters:(NSMutableDictionary *)parameters
success:(void(^)(id responseObject))success faile:(void(^)(NSError *error))failure;
@end
NetworkTool.m
#import "NetworkTool.h"
#import "AFNetworking.h"
@implementation NetworkTool
+ (instancetype)sharedNetworkTool
{
static NetworkTool *instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// 设置相对路径
NSURL *BaseURL = [NSURL URLWithString:@""];
// 实例化Manager
instance = [[self alloc] initWithBaseURL:BaseURL];
// 增加AFN支持的文件类型
instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
});
return instance;
}
//网络请求方法
+ (void)POSTWithURLString:(NSString *)URLString parameters:(NSMutableDictionary *)parameters
success:(void(^)(id responseObject))success faile:(void(^)(NSError *error))failure
{
//大P为key,由接口决定,也可不需要
NSData *data = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:nil];
NSString *JsonStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSMutableDictionary *parameterDic = [[NSMutableDictionary alloc]init];
[parameterDic setObject:JsonStr forKey:@"P"];
AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
sessionManager.requestSerializer.timeoutInterval = 15.f;
sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
[sessionManager POST:URLString parameters:parameterDic progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog((@"\n[函数名:%s]\n" "[行号:%d]\n" "参数%@\n"), __FUNCTION__, __LINE__,parameters);
NSLog((@"\n[函数名:%s]\n" "[行号:%d]\n" "地址%@\n"), __FUNCTION__, __LINE__,URLString);
NSLog((@"\n[函数名:%s]\n" "[行号:%d]\n" "返回%@\n"), __FUNCTION__, __LINE__,responseObject);
success(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure(error);
NSLog((@"该接口返回错误==%@\n参数是==%@\n错误是==%@\n"),URLString,parameters,error);
[self testNetwork];//查询当前网络
}];
}
+(void)testNetwork
{
// 监测网络环境
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
/*
status
AFNetworkReachabilityStatusUnknown = -1, 不知道监测的是什么
AFNetworkReachabilityStatusNotReachable = 0, 没有检测到网络
AFNetworkReachabilityStatusReachableViaWWAN = 1, 蜂窝网
AFNetworkReachabilityStatusReachableViaWiFi = 2, WIFI
*/
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
if (status == 0) {
//没有检测到网络!
}
}];
[manager startMonitoring];
}
网友评论