基于AFNetworking的封装的工具类MXERequestService

//
//  MXERequestService.h
//  testAFNetWorking
//
//  Created by lujun on 2022/1/6.
//#import <Foundation/Foundation.h>/** 请求类型的枚举 */
typedef NS_ENUM(NSUInteger, MXEHttpRequestType){/** get请求 */MXEHttpRequestTypeGet = 0,/** post请求 */MXEHttpRequestTypePost
};/**http通讯成功的block@param responseObject 返回的数据*/
typedef void (^MXEHTTPRequestSuccessBlock)(id responseObject);/**http通讯失败后的block@param error 返回的错误信息*/
typedef void (^MXEHTTPRequestFailedBlock)(NSError *error);//超时时间
extern NSInteger const kAFNetworkingTimeoutInterval;@interface MXERequestService : NSObject/***  网络请求的实例方法**  @param type         get / post (项目目前只支持这倆中)*  @param urlString    请求的地址*  @param parameters   请求的参数*  @param successBlock 请求成功回调*  @param failureBlock 请求失败回调*/
+ (void)requestWithType:(MXEHttpRequestType)typeurlString:(NSString *)urlStringparameters:(NSDictionary *)parameterssuccessBlock:(MXEHTTPRequestSuccessBlock)successBlockfailureBlock:(MXEHTTPRequestFailedBlock)failureBlock;/**取消队列*/
+(void)cancelDataTask;
+ (void)postRequestWithApi:(NSString *)apiparam:(NSDictionary *)paramsuccess:(void(^)(NSDictionary *rootDict))successfailure:(void(^)(id error))failure;
+ (void)getRequestWithApi:(NSString *)apiparam:(NSDictionary *)paramsuccess:(void(^)(NSDictionary *rootDict))successfailure:(void(^)(id error))failure;@end
//
//  MXERequestService.m
//  testAFNetWorking
//
//  Created by lujun on 2022/1/6.
//#import "MXERequestService.h"
#import <AFNetworking/AFNetworking.h>NSInteger const kAFNetworkingTimeoutInterval = 10;@implementation MXERequestServicestatic AFHTTPSessionManager *aManager;+ (AFHTTPSessionManager *)sharedAFManager {static dispatch_once_t onceToken;dispatch_once(&onceToken, ^{aManager = [AFHTTPSessionManager manager];//以下三项manager的属性根据需要进行配置aManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/xml",@"text/json",@"text/plain",@"text/JavaScript",@"application/json",@"image/jpeg",@"image/png",@"application/octet-stream",nil];aManager.responseSerializer = [AFHTTPResponseSerializer serializer];// 设置超时时间aManager.requestSerializer.timeoutInterval = kAFNetworkingTimeoutInterval;});return aManager;
}+ (void)requestWithType:(MXEHttpRequestType)typeurlString:(NSString *)urlStringparameters:(NSDictionary *)parameterssuccessBlock:(MXEHTTPRequestSuccessBlock)successBlockfailureBlock:(MXEHTTPRequestFailedBlock)failureBlock {if (urlString == nil) {return;}if (@available(iOS 9.0, *)) {urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];}else {urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];}if (type == MXEHttpRequestTypeGet){[[self sharedAFManager] GET:urlString parameters:parameters headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {if (successBlock){id JSON =  [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];successBlock(JSON);}} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {if (error.code !=-999) {if (failureBlock) {failureBlock(error);}}else{NSLog(@"取消队列了");}}];}if (type == MXEHttpRequestTypePost){[[self sharedAFManager] POST:urlString parameters:parameters  headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {id JSON =  [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];if (successBlock){successBlock(JSON);}} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {if (error.code !=-999) {if (failureBlock){failureBlock(error);}}else{NSLog(@"取消队列了");}}];}
}+ (void)cancelDataTask {NSMutableArray *dataTasks = [NSMutableArray arrayWithArray:[self sharedAFManager].dataTasks];for (NSURLSessionDataTask *taskObj in dataTasks) {[taskObj cancel];}
}+ (void)postRequestWithApi:(NSString *)apiparam:(NSDictionary *)paramsuccess:(void (^)(NSDictionary * _Nonnull))successfailure:(void (^)(id _Nonnull))failure {[self requestWithType:MXEHttpRequestTypePost urlString:api parameters:param successBlock:^(id responseObject) {success(responseObject);} failureBlock:^(NSError *error) {failure(error);}];
}+ (void)getRequestWithApi:(NSString *)apiparam:(NSDictionary *)paramsuccess:(void (^)(NSDictionary * _Nonnull))successfailure:(void (^)(id _Nonnull))failure {[self requestWithType:MXEHttpRequestTypeGet urlString:api parameters:param successBlock:^(id responseObject) {success(responseObject);} failureBlock:^(NSError *error) {failure(error);}];
}+ (void)downloadRequestWithApi:(NSString *)urlparam:(NSDictionary *)paramprogress:(void(^)(NSInteger progress))progresssuccess:(void(^)(NSDictionary *rootDict))successfailure:(void(^)(id error))failure{NSURLRequest *requset = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];[[self sharedAFManager] downloadTaskWithRequest:requset progress:^(NSProgress * _Nonnull downloadProgress) {//        progress(downloadProgress.);} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];return [NSURL fileURLWithPath:fullPath];} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {}];
}@end

基于AFNetworking的封装的工具类相关推荐

  1. Redis(七) - 封装Redis工具类

    文章目录 一.封装Redis工具类 1. 使用构造方法注入StringRedisTemplate 2. 方法1:将任意Java对象序列化为json并存储在string类型的key中,并且可以设置TTL ...

  2. Java封装OkHttp3工具类

    点击关注公众号,Java干货及时送达  作者:如漩涡 https://blog.csdn.net/m0_37701381 Java封装OkHttp3工具类,适用于Java后端开发者 说实在话,用过挺多 ...

  3. writeValueAsString封装成工具类

    封装成工具类 [java] view plaincopyprint? <span style="font-family:Microsoft YaHei;">public ...

  4. MySQL数据库学习笔记(十一)----DAO设计模式实现数据库的增删改查(进一步封装JDBC工具类)...

    [声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...

  5. 分页封装实用工具类及其使用方法

    分页封装实用工具类及其使用方法 作者: javaboy2012 Email:yanek@163.com qq:    1046011462 package com.yanek.util; import ...

  6. Java封装redis工具类RedisUtils,以及在@Postconstruct注解中调用redis可能出现redisTemplate空指针异常

    1.封装redis工具类RedisUtils import org.springframework.data.redis.core.RedisTemplate; import org.springfr ...

  7. SpringBoot整合Redis+mybatis,封装RedisUtils工具类等实战(附源码)

    点击上方蓝色字体,选择"标星公众号" 优质文章,第一时间送达 关注公众号后台回复pay或mall获取实战项目资料+视频 作者:陈彦斌 cnblogs.com/chenyanbin/ ...

  8. 装饰器/使用类和对象封装一个工具类

    # coding:utf-8 # 装饰器是以@开头,@结构称为语法糖,装饰器的作用主要是给现有的函数增加一些额外的功能. # @classmethod # @staticmethod # @prope ...

  9. 基于Java封装Groovy工具类

    1.首先在POM文件引入对应核心groovy jar <dependency><groupId>org.codehaus.groovy</groupId><a ...

最新文章

  1. unicode表_Python数据库操作 Mysql数据库表引擎与字符集#学习猿地
  2. Web前端开发css基础样式总结
  3. petshop4.0数据库分析一:数据库概览
  4. 运筹学期末复习2020年
  5. 一分钟开启Tomcat https支持
  6. 【MFC】Windows窗口样式
  7. Android应用的Tab键,来回反复点击会报ANR,是空指针导致的,判空就可以解决
  8. 有关于婚姻经济学的经典对话
  9. ZZULIOJ 1072:青蛙爬井
  10. 计算机二级ppt没弄内容,计算机二级office考试中PPT母版知识考察点有哪些
  11. iphone7 无法连接计算机看照片,iphone7连接电脑没反应怎么解决
  12. js修改伪元素的属性、styleSheets获取样式表,Failed to read the 'cssRules' property from 'CSSStyleSheet' Cannot acces
  13. Matlab的plot函数画线显示空白问题解决
  14. from batchgenerators.transforms import ComposeImportError: cannot import name ‘Compose‘ from ‘batch
  15. Android P HAL层添加HIDL实例(详细实现步骤)
  16. 二年级课程表(4月11日-4月15日)
  17. 最大回撤线性算法实现
  18. Word基础(二)简单排版
  19. 海思3559U-Boot移植(二):更换新的SPI Nand Flash
  20. 数据分析技术:结构方程模型;想要“追求”,了解是第一步

热门文章

  1. java nginx 例子_Nginx配置日志
  2. linux mysql 文件恢复_linux下误删数据文件恢复
  3. 取sql数据乱码_不基于备份和表,生产系统数据误删就能完全恢复
  4. 2021年的芯片市场,骗子太多,傻子不够用
  5. 工作多年,怀才不遇你该怎么办?
  6. Sobel边缘检测算法verilog实现及仿真
  7. python编程基础_月隐学python第一课
  8. java weblogic连接池,Weblogic JNDI 方式连接连接池 (工作中遇到的问题)
  9. jquery的ajax查询数据库,用Jquery和Ajax查询Django数据库
  10. GeneXus笔记本—城市级联下拉