欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS基于AFNetworking的post、get方法的封装及获取当前网络状态的实现

程序员文章站 2023-01-24 19:13:25
afnetworking是一个常用的网络请求库,每个项目的网络请求和返回格式不同,afnetworking返回的通用型的,我们可以封装一层,让其更适合我们自己的项目。 实现代码: #import...

afnetworking是一个常用的网络请求库,每个项目的网络请求和返回格式不同,afnetworking返回的通用型的,我们可以封装一层,让其更适合我们自己的项目。
实现代码:

#import 
typedef void (^requestcompleteblock)(id response);
typedef void (^requesterrorblock)(nserror *error);

@interface bzhttprequesthelper : nsobject


/**
 post请求

 @param url 接口地址
 @param params 入参
 @param completeblock 成功回调
 @param errorblock 失败回调
 */
+(void)postwithurl:(nsstring *)url
params:(nsdictionary *)params
 complete:(requestcompleteblock)completeblock
 error:(requesterrorblock)errorblock;



/**
 get请求

 @param url 接口地址
 @param params 入参
 @param completeblock 成功回调
 @param errorblock 失败回调
 */
+(void)getwithurl:(nsstring *)url
params:(nsdictionary *)params
complete:(requestcompleteblock)completeblock
error:(requesterrorblock)errorblock;

@end
#import "bzhttprequesthelper.h"
#import "afnetworking.h"
//根据服务器返回的格式定义的基础返回模型
#import "bzhttpresponse.h"
//网络状态判断
#import "bznetworkstatusmanager.h"

@implementation bzhttprequesthelper

+(afhttpsessionmanager *)sharehttpsessionmanager{
 static afhttpsessionmanager * manager = nil;
 static dispatch_once_t oncetoken;
 dispatch_once(&oncetoken, ^{
  manager = [afhttpsessionmanager manager];
  manager.requestserializer = [afhttprequestserializer serializer];
  manager.responseserializer = [afjsonresponseserializer serializer];
  manager.requestserializer.timeoutinterval = 30;
 });
 return manager;
}

+(void)postwithurl:(nsstring *)url params:(nsdictionary *)params complete:(requestcompleteblock)completeblock error:(requesterrorblock)errorblock{
 //判断当前网络状态,如果是无网络状态可直接提示用户,且放弃网络请求
 if (![bznetworkstatusmanager sharenetworkstatusmanagerinstance].isnetworkavailable) {
  [bzhttprequesthelper shownetworkunavailable];
  return;
 }
 [[bzhttprequesthelper sharehttpsessionmanager] post:url parameters:params progress:^(nsprogress * _nonnull uploadprogress) {

 } success:^(nsurlsessiondatatask * _nonnull task, id  _nullable responseobject) {
  //拿到返回数据后做相应的处理,下面的是根据服务器定义的一些错误码来判断请求是否成功返回
  bzhttpresponse * responsemodel = [[bzhttpresponse alloc] init];
  nserror * error;
  if ([responseobject iskindofclass:[nsdictionary class]]) {
[responsemodel setvaluesforkeyswithdictionary:responseobject];
if (responsemodel.code == 0) {
 if (completeblock) {
  if (responsemodel.data) {
completeblock(responsemodel.data);
  }else{
completeblock(responsemodel);
  }

 }
}else{
 if (responsemodel.code  == 7) {
  //token失效,退出登录
  [[nsnotificationcenter defaultcenter] postnotificationname:current_user_kickout object:nil];
 }else{
  error = [nserror errorwithdomain:responsemodel.message code:responsemodel.code userinfo:nil];
 }
 if (errorblock) {
  errorblock(error);
 }
}
  }else{
error = [nserror errorwithdomain:@"服务器数据结构错误" code:-100 userinfo:nil];
if (errorblock) {
 errorblock(error);
}
  }

 } failure:^(nsurlsessiondatatask * _nullable task, nserror * _nonnull error) {
  nslog(@"error == %@",error);
  if (errorblock) {
errorblock(error);
  }
 }];
}

+(void)getwithurl:(nsstring *)url params:(nsdictionary *)params complete:(requestcompleteblock)completeblock error:(requesterrorblock)errorblock{
 if (![bznetworkstatusmanager sharenetworkstatusmanagerinstance].isnetworkavailable) {
  [bzhttprequesthelper shownetworkunavailable];
  return;
 }
 [[bzhttprequesthelper sharehttpsessionmanager] get:url parameters:params progress:^(nsprogress * _nonnull downloadprogress) {

 } success:^(nsurlsessiondatatask * _nonnull task, id  _nullable responseobject) {
  if (completeblock) {
completeblock(responseobject);
  }
 } failure:^(nsurlsessiondatatask * _nullable task, nserror * _nonnull error) {
  if (errorblock) {
errorblock(error);
  }
 }];
}

+(void)shownetworkunavailable{
 dispatch_async(dispatch_get_main_queue(), ^{
  uiwindow * window = [[[uiapplication sharedapplication] delegate] window];
  [window maketoast:@"当前网络不可用,请检查网络稍后再试" duration:1.5 position:cstoastpositionbottom];
 });
}

@end

获取当前网络状态:

#import 

@interface bznetworkstatusmanager : nsobject

+(instancetype)sharenetworkstatusmanagerinstance;
@property(nonatomic,assign) bool isnetworkavailable;

@end
#import "bznetworkstatusmanager.h"
#import "afnetworking.h"

@implementation bznetworkstatusmanager

+(instancetype)sharenetworkstatusmanagerinstance{
 static bznetworkstatusmanager * manager = nil;
 static dispatch_once_t oncetoken; 
 dispatch_once(&oncetoken, ^{
  manager = [[bznetworkstatusmanager alloc] init];
 });
 return manager;
}

-(instancetype)init{
 self = [super init];
 if (self) {
  [self monitornetworking];
 }
 return self;
}

-(void)monitornetworking{
 [[afnetworkreachabilitymanager sharedmanager] startmonitoring];
 [[afnetworkreachabilitymanager sharedmanager] setreachabilitystatuschangeblock:^(afnetworkreachabilitystatus status) {
  switch (status) {
case -1:
 nslog(@"未知网络");
 break;
case 0:
 nslog(@"网络不可达");
 break;
case 1:
 nslog(@"gprs网络");
 break;
case 2:
 nslog(@"wifi网络");
 break;
default:
 break;
  }
  if (status == afnetworkreachabilitystatusreachableviawwan || status == afnetworkreachabilitystatusreachableviawifi) {
nslog(@"有网");
self.isnetworkavailable = yes;
  }else{
nslog(@"没网");
self.isnetworkavailable = no;
  }
 }];
}

@end