基于AFN封装的带缓存的网络请求

给大家分享一个基于AFN封装的网络请求

git: https://github.com/zhouxihi/NVNetworking

#带缓存机制的网络请求

各类请求有分带缓存 , 不带缓存, 可自定义, 默认请求头和解析头等几种方式

#没有缓存机制的网络请求库

##初始化

//测试初始化
_nvNetworking = [NVNetworking shareInstance];

//测试设置beseUrl
[_nvNetworking setBaseUrl:@"http://xdf-new-test.novasoftware.cn/api"];

//测试设置需要授权
[_nvNetworking setAuthorizationRequired:true];

//检测网络监听
[_nvNetworking startMonitorNetworkWithBlock:^(NVNetworkStatus status) {

  NSLog(@"status: %lu", status);
}];

##默认请求样式

//使用默认请求样式:
[_nvNetworking get:@"/open/ads" parameters:nil progress:^(NSProgress *downloadProgress) {

NSLog(@"进度: %f", downloadProgress.fractionCompleted);
} callback:^(ApiResult *result, id responseObject) {

  if (result.success) {

    NSLog(@"%@", result.data);
}

NSLog(@"请求结束后网络请求个数: %lu", (unsigned long)[[_nvNetworking getAllTask] count]);
}];

NSLog(@"请求结束前网络请求个数: %lu", (unsigned long)[[_nvNetworking getAllTask] count]);

##取消所有任务

[_nvNetworking cancelAllTask];

##取消特定api的请求

[_nvNetworking cancelTaskWithApi:@"open/ads"];

##带任务返回的请求Get/Post

NVNetworking *manager = [NVNetworking shareInstance];
_task = [manager nv_get:@"/pushMessage/GetpushMessages?phonenumber=18502329837" parameters:nil progress:nil callback:^(ApiResult *result, id responseObject) {

  if (result.success) {

    NSLog(@"回调: %@", result.data);
    NSDictionary *dict = [result.data mj_keyValues];
    NSLog(@"dict: %@", dict);
  } else {

    NSLog(@"失败回调: %@", responseObject);
    NSLog(@"失败code: %i", result.error.code);
  }
}];

##取消任务

[_task cancel];

##自定义请求样式

AFHTTPRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
AFHTTPResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializer];

[_nvNetworking get:@"/open/ads" parameters:nil requestSerializer:requestSerializer responseSerializer:responseSerializer header:nil progress:^(NSProgress *downloadProgress) {

NSLog(@"%f", downloadProgress.fractionCompleted);
} callback:^(ApiResult *result, id responseObject) {

  NSLog(@"请求结束后网络请求个数: %lu", (unsigned long)[[_nvNetworking getAllTask] count]);
  if (result.success) {

  NSLog(@"%@", result.data);
  }
}];

##网络监听

[_nvNetworking startMonitorNetworkWithBlock:^(NVNetworkStatus status) {

  switch (status) {
    case k3GNetwork:
      NSLog(@"3G网");
      break;

    case kWiFiNetwork:
      NSLog(@"wifi");
      break;

    case kNoNetwork:
      NSLog(@"没有网");
      break;

    default:
      break;
  }
}];

##单个文件上传

UploadParam *uploadParam = [[UploadParam alloc] init];
uploadParam.data = UIImagePNGRepresentation([UIImage imageNamed:@"1.png"]);
uploadParam.name = @"1.png";
uploadParam.fileName = @"1.png";
uploadParam.mimeType = @"image/png";

NVNetworking *manager = [NVNetworking shareInstance];
[manager upload:@"/file/upload" parameters:nil uploadParam:uploadParam progress:^(NSProgress *progress) {

  NSLog(@"上传进度: %f", progress.fractionCompleted);
} callback:^(ApiResult *result, id responseObject) {

  NSLog(@"结果: %@", responseObject);

  if (result.success) {

    NSLog(@"回调: %@", result.data);
    NSDictionary *dict = [result.data mj_keyValues];
    NSLog(@"dict: %@", dict);
  } else {

    NSLog(@"失败回调: %@", responseObject);
    NSLog(@"失败code: %i", result.error.code);
  }
}];

##取消上传任务可以用

NVNetworking *manager = [NVNetworking shareInstance];
[manager cancelTaskWithApi:@"/file/upload"];

##多任务上传

UploadParam *uploadParam = [[UploadParam alloc] init];
uploadParam.data = UIImagePNGRepresentation([UIImage imageNamed:@"1.png"]);
uploadParam.name = @"1.png";
uploadParam.fileName = @"1.png";
uploadParam.mimeType = @"image/png";

UploadParam *uploadParam1 = [[UploadParam alloc] init];
uploadParam1.data = UIImagePNGRepresentation([UIImage imageNamed:@"1.png"]);
uploadParam1.name = @"1.png";
uploadParam1.fileName = @"1.png";
uploadParam1.mimeType = @"image/png";

NSArray *array = @[uploadParam, uploadParam1];
NVNetworking *manager = [NVNetworking shareInstance];

[manager upload:@"/file/upload" parameters:nil uploadParams:array progress:^(NSProgress *progress, NSInteger completeCount, NSInteger totalCount, NSInteger failCount, BOOL taskCompleted) {

NSLog(@"progress: %f, completeCount: %li, totalCount: %li, failCount: %li, taskCompleted: %@", progress.fractionCompleted, (long)completeCount, (long)totalCount, (long)failCount, taskCompleted ? @"YES": @"NO");
} callback:^(NSInteger completeCount, NSInteger totalCount, NSInteger failCount, BOOL taskCompleted) {

NSLog(@"completeCount: %li, totalCount: %li, failCount: %li, taskCompleted: %@", (long)completeCount, (long)totalCount, (long)failCount, taskCompleted ? @"YES": @"NO");

}];

##取消多任务上传

NVNetworking *manager = [NVNetworking shareInstance];
[manager cancelUploadFile];

##缓存策略有以下几种

    kReturnCacheDataThenLoad = 0,   //有缓存先返回缓存, 并同步请求
    kReloadIgnoringLocalCacheData,  //忽略缓存, 直接请求
    kReturnCacheDataElseLoad,       //有缓存就返回缓存, 没有缓存再请求
    kReturnCacheDataNotLoad         //有缓存就返回缓存, 没有缓存也不请求

##带缓存策略 get请求

/**
 带进度回调 缓存策略的 normal get请求

 @param api api
 @param parameters object参数
 @param cachePolicy 缓存策略
 @param progresss 进度回调
 @param callback 回调方法
 */
- (void)get:(NSString *)api
            parameters:(id)parameters
                cachePolicy:(NVCachePolicy)cachePolicy
                    progress:(ProgressCallback)progresss
                        callback:(NetworkCallback)callback;

##带缓存策略 任务返回的 get请求

/**
/**
 带任务返回 进度回调 缓存策略的 get请求

 @param api api
 @param parameters object参数
 @param cachePolicy 缓存策略
 @param progresss 进度回调
 @param callback 回调方法
 @return 本次请求的task
 */
- (NSURLSessionTask *)nv_get:(NSString *)api
                        parameters:(id)parameters
                            cachePolicy:(NVCachePolicy)cachePolicy
                                progress:(ProgressCallback)progresss
                                    callback:(NetworkCallback)callback;

##带缓存策略的 自定义get请求

/**
 带进度回调的 自定义 带缓存策略的 get请求

 @param api api
 @param parameters object参数
 @param requestSerializer 请求样式
 @param responseSerializer 响应样式
 @param header 请求头数据(字典)
 @param cachePolicy 缓存策略
 @param progresss 进度回调
 @param callback 回调方法
 */
- (void)get:(NSString *)api
            parameters:(id)parameters
                requestSerializer:(AFHTTPRequestSerializer *)requestSerializer
                    responseSerializer:(AFHTTPResponseSerializer *)responseSerializer
                        header:(NSDictionary *)header
                            cachePolicy:(NVCachePolicy)cachePolicy
                                progress:(ProgressCallback)progresss
                                    callback:(NetworkCallback)callback;

##带任务返回 缓存策略的 自定义get请求

/**
 带任务返回 进度回调 缓存策略的 自定义 get请求

 @param api api
 @param parameters object参数
 @param requestSerializer 请求样式
 @param responseSerializer 响应样式
 @param header 请求头数据(字典)
 @param cachePolicy 缓存策略
 @param progresss 进度回调
 @param callback 回调方法
 @return 本次请求的task
 */
- (NSURLSessionTask *)nv_get:(NSString *)api
                  parameters:(id)parameters
           requestSerializer:(AFHTTPRequestSerializer *)requestSerializer
          responseSerializer:(AFHTTPResponseSerializer *)responseSerializer
                      header:(NSDictionary *)header
                 cachePolicy:(NVCachePolicy)cachePolicy
                    progress:(ProgressCallback)progresss
                    callback:(NetworkCallback)callback;

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏Android 技术栈

一款Android WebView进度条显示控件,使其加载进度平滑过渡。

此类是从项目Justson/AgentWeb-WebIndicator中将处理WebView进度条剥离出来的,在此基础上进行优化后合并为一个类,便于导入到自己的...

19030
来自专栏微信公众号【Java技术江湖】

SVN与Git比较的优缺点差异

1. Subversion属于集中式的版本控制系统 集中式的版本控制系统都有一个单一的集中管理的服务器,保存所有文件的修订版本,而协同工作的人们都通过客户端连到...

33430
来自专栏bigsai

Springboot+shiro基于url身份认证和授权认证

三个核心组件:Subject, SecurityManager 和 Realms.

7420
来自专栏Java技术栈

大牛总结的 Git 使用技巧,写得太好了!

本文是参考廖雪峰老师的Git资料再加上我自己对Git的理解,记录我的Git学习历程,作下此文是为以后学习,工作,开发中如果遇到问题可以回过头来参考参考。因为水平...

15750
来自专栏机器学习与统计学

如何轻松阅读 GitHub 上的项目源码 ?

作者:牛岱 link:https://www.zhihu.com/question/27821340/answer/808399749

24560
来自专栏运维经验分享

HTTP 502: Whoops, GitLab is taking too much time to respond.

2、看到错误第一时间想到的是 Baidu(没其他意思),找找 logpath 先看日志不好吗?

14130
来自专栏bigsai

全排列的两种实现方式(java)-poj2718

上述方法虽然能够实现全排列,但是方法的复杂度还是很高。指数级别增长。因为要遍历很多没用的情况。所以当数据较大并不能高速处理。所以换一种思路处理。 设[a,b,c...

9430
来自专栏运维经验分享

Gitlab+Jenkins实现自动部署

©著作权归作者所有:来自51CTO博客作者三和梁朝伟的原创作品,如需转载,请注明出处,否则将追究法律责任

11330
来自专栏Python空间

寓教于乐,用玩游戏的方式学习 Git!

从刚接触电脑时的打字练习软件 金山打字通,到程序猿写代码的利器 Vim 都有小游戏(金山打字通游戏、VIM Adventures)来帮助我们入门。

8330
来自专栏运维经验分享

ssh-keygen -t rsa -C"your_email@youremail.com"

ssh-keygen -t rsa -C"your_email@youremail.com"

10320

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励