AFNetworking 网络请求
static AFHTTPSessionManager *_manager = nil
+(AFHTTPSessionManager *)defaultHTTPManager{
static dispatch_once_t onceToken;
dispatch_once(&onceToken,^{
_manager = [AFHTTPSessionManager manager];
_manager .responseSerializer= [AFHTTPResponseSerializer serializer];
_manager.requesetSerializer .timeoutInterval = 30.0;
});
return _manager;
}
方法:
+(void) getMessageWithParameters :(NSDictionary *)parameters complete:(void(^)(NSArray *dataArray))complete{
AFHTTPSessionManager *manager = [self defaulHTTPManager];
NSMutableArray *dataArray = [[NSMutableArray alloc] initWithCapacity:0];
[manager POST:KClassURL parameters:parameters progress:nil success:^(NSURLSessionDataTask *_Nonnull task,id _Nullable responseObjiect){
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
id data = dic[@"data"];
if([data isKindofClass:[NSarray claas]]){
NSArray *mesageArray = dic[@"data"];
for (NSDictionary *messDic in messageArray){
MyModel *model = [Mymodel alloc] initClassMyModelWithDictionary:messDic];
[dataArray addobject:model];
}
complete(dataArray);
}else if ([data isKindofClass:[NSDictionary class]]){
NSDictionary *messageDic = dic[@"data"];
MyModel *model = [Mymodel alloc] initClassMyModelWithDictionary:messDic];
[dataArray addobject:model];
complete(dataArray);
else{
complete(dataArray):
}
}failure:^(NSURLSessionDataTask *_Nullabel task,NSError *_Nonnull error){
}];
+(void) getMessageWithParameters :(NSDictionary *)parameters success:(void(^)(BOOL success)) success{
AFHTTPSessionManager *manager = [self defaulHTTPManager];
[manager POST:KClassURL parameters:parameters progress:nil success:^(NSURLSessionDataTask *_Nonnull task,id _Nullable responseObjiect){
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
if([dic[@"data"] integerValue == 1{
success (YES);
}esle{
success(NO):
}
}failure:^(NSURLSessionDataTask *_Nullabel task,NSError *_Nonnull error){
success(NO);
}];
}
使用AFNetworking出现报错:
error=Error Domain=com.alamofire.error.serialization.response Code=-1016
处理:
刚开始只添加了"text/html",继续报错,后来搞了老半天,才找到这个坑,后来返回的是无文本属性的文档,所以需要添加"text/plain"属性。
_manager.responseSerializer.acceptableContentTypes= [NSSetsetWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",@"text/plain",nil];