iOS AFNetworking各种功能封装类代码

 更新时间:2018年01月15日 10:02:39   作者:键盘舞者113  
下面小编就为大家分享一篇iOS AFNetworking各种功能封装类代码,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

这个封装类包含了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各种功能封装类代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Xcode清理缓存和垃圾文件的教程

    Xcode清理缓存和垃圾文件的教程

    下面小编就为大家分享一篇Xcode清理缓存和垃圾文件的教程,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-01-01
  • iOS开发之APP相关

    iOS开发之APP相关

    本文给大家介绍的是IOS开发系列文章的第一篇,给大家分享一些APP相关的知识点,非常的实用,有需要的小伙伴可以参考下
    2016-04-04
  • iOS实现一个可以在屏幕中自由移动的按钮

    iOS实现一个可以在屏幕中自由移动的按钮

    经常在手机上看到可以随意移动的按钮,正巧最近工作遇到了这个需求,索性就写一个,下面这篇文章主要给大家介绍了利用iOS实现一个可以在屏幕中自由移动的按钮的相关资料,需要的朋友可以参考借鉴,下面来一起看看吧。
    2017-07-07
  • iOS 修改alertViewController弹框的字体颜色及字体的方法

    iOS 修改alertViewController弹框的字体颜色及字体的方法

    下面小编就为大家分享一篇iOS 修改alertViewController弹框的字体颜色及字体的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-01-01
  • 将多个字符串高亮显示之TTTAttributedLabel

    将多个字符串高亮显示之TTTAttributedLabel

    本文介绍了将多个字符串高亮显示之TTTAttributedLabel。在此需要对每个字符串进行匹配,可以研究下kmp和bm算法,在这里应用了oc自带的NSRegularExpression 来进行正则表达式匹配,算是比较简单的方法,需要的朋友可以参考下
    2015-07-07
  • 一步一步实现iOS主题皮肤切换效果

    一步一步实现iOS主题皮肤切换效果

    这篇文章主要为大家详细介绍了一步一步实现iOS主题皮肤切换效果的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-09-09
  • iOS中无限循环滚动简单处理实现原理分析

    iOS中无限循环滚动简单处理实现原理分析

    这篇文章主要介绍了iOS中无限循环滚动简单处理实现原理分析,需要的朋友可以参考下
    2017-12-12
  • Unity移动端的复制要这么写示例代码

    Unity移动端的复制要这么写示例代码

    这篇文章主要给大家介绍了关于Unity移动端的复制的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴,下面随着小编来一起学习学习吧
    2018-08-08
  • iOS中关于Taptic-Engine震动反馈的深入解析

    iOS中关于Taptic-Engine震动反馈的深入解析

    这篇文章主要给大家介绍了关于iOS中关于Taptic-Engine震动反馈的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。
    2017-11-11
  • iOS中NSPredicate谓词的使用

    iOS中NSPredicate谓词的使用

    这篇文章主要给大家介绍了关于iOS中NSPredicate谓词的使用方法,文中通过示例代码介绍的非常详细,对各位iOS开发者们具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-01-01

最新评论