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

iOS AFNetworking各种功能封装类代码

程序员文章站 2023-12-19 12:24:16
这个封装类包含了get请求,post请求,上传图片,上传多张图片,下载图片,判断网络是否可用等功能。 #import

这个封装类包含了get请求,post请求,上传图片,上传多张图片,下载图片,判断网络是否可用等功能。

#import <foundation/foundation.h>
@interface httputil : nsobject

typedef ns_enum(nsinteger, networkreachabilitystatus) { networkreachabilitystatusunknown   = -1, networkreachabilitystatusnotreachable  = 0, networkreachabilitystatusreachableviawwan = 1, networkreachabilitystatusreachableviawifi = 2,
};

// get请求
+ (void)getwithurlstring:(nsstring *)urlstring
    parameters:(id)parameters
     success:(void (^)(id))success
     failure:(void (^)(nserror * error))failure;

// post请求
+ (void)postwithurlstring:(nsstring *)urlstring
    parameters:(id)parameters
     success:(void (^)(id))success
     failure:(void (^)(nserror *))failure;
// 上传图片
+ (void)uploadwithurlstring:(nsstring *)urlstring
     parameters:(id)parameters
     uploaddata:(nsdata *)uploaddata
     uploadname:(nsstring *)uploadname
     success:(void (^)())success
     failure:(void (^)(nserror *))failure;
// 上传多张图片
+ (void)uploadmostimagewithurlstring:(nsstring *)urlstring
       parameters:(id)parameters
       uploaddatas:(nsarray *)uploaddatas
       uploadname:(nsstring *)uploadname
        success:(void (^)())success
        failure:(void (^)(nserror *))failure;
+(void)downloadwithurlstring:(nsstring *)urlstring
     parameters:(id)parameters
     progress:(void (^)(id))progress
      success:(void(^)(nsurl *filepath))success;

+(void)setreachabilitystatuschangeblock:(void(^)(networkreachabilitystatus status))block;
+(void)stopmonitoring;

+(boolean)judgenetisconnect;
@end
#import "httputil.h"
#import "afnetworking.h"
@implementation httputil
#pragma mark -- get请求 --
+ (void)getwithurlstring:(nsstring *)urlstring
    parameters:(id)parameters
     success:(void (^)(id))success
     failure:(void (^)(nserror * error))failure {
 afhttpsessionmanager *manager = [afhttpsessionmanager manager];
 manager.requestserializer.timeoutinterval = 10;
 manager.responseserializer.acceptablecontenttypes = [nsset setwithobjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];
 [manager get:urlstring parameters:parameters progress:nil success:^(nsurlsessiondatatask * _nonnull task, id _nullable responseobject) {
  if (responseobject) {
   success(responseobject);
  }
 } failure:^(nsurlsessiondatatask * _nullable task, nserror * _nonnull error) {
  if (error) {
   failure(error);
  }
 }];
}
#pragma mark -- post请求 --
+ (void)postwithurlstring:(nsstring *)urlstring
    parameters:(id)parameters
     success:(void (^)(id))success
     failure:(void (^)(nserror *))failure {
 afhttpsessionmanager *manager = [afhttpsessionmanager manager];
// manager.requestserializer.httpmethodsencodingparametersinuri = [nsset setwitharray:@[@"post", @"get", @"head"]];
 manager.requestserializer.timeoutinterval = 10;
 manager.responseserializer.acceptablecontenttypes = [nsset setwithobjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];
 [manager post:urlstring parameters:parameters progress:nil success:^(nsurlsessiondatatask * _nonnull task, id _nullable responseobject) {
  if (success) {
   success(responseobject);
  }
 } failure:^(nsurlsessiondatatask * _nullable task, nserror * _nonnull error) {
  if (failure) {
   failure(error);
  }
 }];
}
#pragma mark -- 上传图片 --
+ (void)uploadwithurlstring:(nsstring *)urlstring
     parameters:(id)parameters
     uploaddata:(nsdata *)uploaddata
     uploadname:(nsstring *)uploadname
     success:(void (^)())success
     failure:(void (^)(nserror *))failure {
 afhttpsessionmanager *manager = [afhttpsessionmanager manager];
 manager.responseserializer.acceptablecontenttypes = [nsset setwithobjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];
 [manager post:urlstring parameters:parameters constructingbodywithblock:^(id< afmultipartformdata > _nonnull formdata) {
  [formdata appendpartwithfiledata:uploaddata name:uploadname filename:uploadname mimetype:@"image/png"];
 } progress:nil success:^(nsurlsessiondatatask * _nonnull task, id _nullable responseobject) {
  if (success) {
   success(responseobject);
  }
 } failure:^(nsurlsessiondatatask * _nullable task, nserror * _nonnull error) {
  if (failure) {
   failure(error);
  }
 }];
}
// 上传多张图片 uploaddatas 图片的data集合
// uploadname 文件名称 最好以xxx1 xxx2 表示 image1 image2
+ (void)uploadmostimagewithurlstring:(nsstring *)urlstring
       parameters:(id)parameters
       uploaddatas:(nsarray *)uploaddatas
       uploadname:(nsstring *)uploadname
        success:(void (^)())success
        failure:(void (^)(nserror *))failure{
 afhttpsessionmanager *manager = [afhttpsessionmanager manager];
 manager.responseserializer.acceptablecontenttypes = [nsset setwithobjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];
 [manager post:urlstring parameters:parameters constructingbodywithblock:^(id< afmultipartformdata > _nonnull formdata) {
  for (int i=0; uploaddatas.count; i++) {
   nsstring *imagename = [nsstring stringwithformat:@"%@[%i]", uploadname, i];
   [formdata appendpartwithfiledata:uploaddatas[i] name:uploadname filename:imagename mimetype:@"image/png"];
  }
 } progress:nil success:^(nsurlsessiondatatask * _nonnull task, id _nullable responseobject) {
  if (success) {
   success(responseobject);
  }
 } failure:^(nsurlsessiondatatask * _nullable task, nserror * _nonnull error) {
  if (failure) {
   failure(error);
  }
 }];
}
+(void)downloadwithurlstring:(nsstring *)urlstring
     parameters:(id)parameters
     progress:(void (^)(id))progress
      success:(void(^)(nsurl *filepath))success
{
 //1.创建管理者对象
 afhttpsessionmanager *manager = [afhttpsessionmanager manager];
 urlstring=[self downloadurlwithparams:urlstring withnsdictionaryparams:parameters];
 nslog(@"downloadfileurl %@",urlstring);
 nsurl *url = [nsurl urlwithstring:urlstring];
 //3.创建请求对象
 nsurlrequest *request = [nsurlrequest requestwithurl:url];
 //下载任务
 nsurlsessiondownloadtask *task = [manager downloadtaskwithrequest:request progress:^(nsprogress * _nonnull downloadprogress) {
  if (progress) {
   progress(downloadprogress);
  }
 } destination:^nsurl * _nonnull(nsurl * _nonnull targetpath, nsurlresponse * _nonnull response) {
  //  //下载地址
  //  //设置下载路径,通过沙盒获取缓存地址,最后返回nsurl对象
  nsstring *filepath = [nssearchpathfordirectoriesindomains(nscachesdirectory, nsuserdomainmask, yes)lastobject];
  filepath=[filepath stringbyappendingpathcomponent:@"dfu.zip"];
  return [nsurl fileurlwithpath:filepath];
 } completionhandler:^(nsurlresponse * _nonnull response, nsurl * _nullable filepath, nserror * _nullable error) {
  if (success) {
   success(filepath);
  }
 }];
 //开始启动任务
 [task resume];
}
//因为下载的方法不能够直接填写dict参数进去,所以只有使用这种方法拼接参数进去
+(nsstring *)downloadurlwithparams:(nsstring*)url withnsdictionaryparams:(nsdictionary *)params{
 // 初始化参数变量
 nsstring *body=@"";
 // 快速遍历参数数组
 nsstring* appendurl;
 for(id key in params) {
  nslog(@"key :%@ value :%@", key, [params objectforkey:key]);
  body = [body stringbyappendingstring:key];
  body = [body stringbyappendingstring:@"="];
  body = [body stringbyappendingstring:[params objectforkey:key]];
  body = [body stringbyappendingstring:@"&"];
 }
 // 处理多余的&以及返回含参url
 if (body.length > 1) {
  // 去掉末尾的&
  body = [body substringtoindex:body.length - 1];
  // 返回含参url
 }
 appendurl=[url stringbyappendingstring:body];
 return appendurl;
}

+(void)setreachabilitystatuschangeblock:(void(^)(networkreachabilitystatus status))block{ //监测网络状态
 afnetworkreachabilitymanager *netman = [afnetworkreachabilitymanager sharedmanager];
 [netman setreachabilitystatuschangeblock:^(afnetworkreachabilitystatus status) {
  switch (status) {
    // 未知网络
   case afnetworkreachabilitystatusunknown:
    if (block) {
     block(networkreachabilitystatusunknown);
    }
    break;
    // 没有网络
   case afnetworkreachabilitystatusnotreachable:
    if (block) {
     block(networkreachabilitystatusnotreachable);
    }
    break;
    // 手机自带网络
   case afnetworkreachabilitystatusreachableviawwan:
    if (block) {
     block(networkreachabilitystatusreachableviawwan);    }
    break;
    // wifi
   case afnetworkreachabilitystatusreachableviawifi:
    if (block) {
     block(networkreachabilitystatusreachableviawifi);    }
    break;
  }
 }];
 [netman startmonitoring];}

+(void)stopmonitoring{
 afnetworkreachabilitymanager *netman = [afnetworkreachabilitymanager sharedmanager];
 [netman stopmonitoring];
}

+(boolean)judgenetisconnect{
 nsstring *urlstr=wuchebaseurl;
 nsurlrequest *request=[nsurlrequest requestwithurl:[nsurl urlwithstring:urlstr]
           cachepolicy:nsurlrequestuseprotocolcachepolicy
          timeoutinterval:5.0];
 nsdata *response = [nsurlconnection sendsynchronousrequest:request returningresponse:nil error:nil];
 if (response!=null) {
  return yes;
 }
 return no;
}

@end

以上这篇ios afnetworking各种功能封装类代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

上一篇:

下一篇: