OCNet
轻量级的网络请求库,不依赖任何第三方框架。基于NSURLSession,支持iOS7及以上。
支持的功能
- GET、POST、Upload、Download
- 支持Chain、Group形式的组合请求
- 支持请求重试
- 支持JSON解析
- 支持Form、JSON参数提交
- 支持大文件断点下载(OCBlobDownloadRequest)
- 新增网络状态监听类(OCReachability)
OCNetPrintDecodeJSON
方法为格式化打印JSON,并转换Unicode编码,方便的显示中文。
注意
所有任务回调均不在主线程回调(方便调用者异步处理后续操作),除了进度回调(Progress Block)、Notification。
使用
1、基本使用,导入OCNet.h
头文件
GET请求,返回NSData
[OCSessionManager GET:@"" parameter:nil completionBlock:^(NSURLSessionDataTask * _Nonnull task, NSData * _Nullable data, NSError * _Nullable error) {
if (error) {
NSLog(@"%@", error);
} else {
NSLog(@"respons=>%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}
}];
POST请求,返回NSData
+ (NSURLSessionDataTask *)POST:(NSString *)urlString parameter:(NSDictionary * _Nullable)parameter completionBlock:(OCSessionManagerCompletionBlock _Nullable)completionBlock;
文件上传,progressBlock上传进度
+ (NSURLSessionUploadTask *)upload:(NSString *)urlString parameter:(NSDictionary * _Nullable)parameter data:(NSData *)data field:(NSString *)field fileName:(NSString *)fileName mimeType:(NSString *)mimeType progressBlock:(OCSessionManagerProgressBlock _Nullable)progressBlock completionBlock:(OCSessionManagerCompletionBlock _Nullable)completionBlock;
文件下载,destinationBlock返回的URL为保存文件的地址
+ (NSURLSessionDownloadTask *)download:(NSString *)urlString destinationBlock:(NSURL *(^)(void))destinationBlock progressBlock:(OCSessionManagerProgressBlock _Nullable)progressBlock completionBlock:(OCSessionManagerCompletionBlock _Nullable)completionBlock;
2、自定义
继承OCHttpRequest
类,该类提供了自定义的属性来满足业务需求。开始请求调用startWithCompletionBlock
方法,停止请求调用stopRequestWithBlock
方法。
子类重写requestSerializerClass
方法返回自定义的请求序列化对象。
子类重写responseObject
方法返回自定义的响应序列化对象。
3、请求重试
OCHttpRetryRequest
类提供了retryCount
和retryTimeIntervals
属性来实现重试机制。
retryCount
:用于控制重试的次数。
retryTimeIntervals
:用于设置每次重试请求的间隔。如果数组的长度小于retryCount,那么之后的所有的重试请求间隔将使用数组的最后一个元素的值。如果数组没有元素,将会使用默认值1秒。
retryRequestCount
:属性统计重试请求的次数。
onRetryBlock
:重试请求回调block,返回YES继续重试,否则停止请求
示例:
OCHttpRetryRequest *request = [[OCHttpRetryRequest alloc] initWithMethod:OCHttpRequestMethodGET urlString:@"https://suggest.taobao.com/sug" parameter:@{@"code":@"utf-8",@"q":@"女装"}];
request.retryTimeIntervals = @[@(3.0), @(2.0)];
request.responseType = OCHttpResponseTypeJSON;
[request setOnRetryBlock:^BOOL(__kindof OCHttpRetryRequest * _Nonnull request) {
if (request.retryRequestCount > 1) {
NSLog(@"%ld %ld", request.retryCount, request.retryRequestCount);
return NO;
}
return YES;
}];
[request startWithCompletionBlock:^(__kindof OCHttpRequest * _Nonnull request, __kindof OCHttpResponse * _Nonnull response) {
if (response.error) {
NSLog(@"%@", response.error);
} else {
id json = [(OCJSONResponse *)response json];
if (response.error) {
NSLog(@"%@", response.error);
} else {
NSLog(@"%@", OCNetPrintDecodeJSON(json));
}
}
}];
4、序列化
默认提供Form、JSON、data实现,如果需要自定义序列化,继承OCRequestSerializer
类,重写URLRequest
和prepareRequestBody
方法。
5、代理
如果需要自定义处理NSURLSession的生命周期事件,请设置OCSessionManager
类的sessionDelegate
属性。如果sessionDelegate实现了NSURLSession生命周期事件,OCSessionManager将不会触发任何通知和回调代理动作。
进阶
导入OCRequestQueue.h
。注意:需要持有OCChainRequestQueue
和OCGroupRequestQueue
初始化后的对象。
1、需求:需要同时发送多个请求,每个请求按照添加顺序执行,并获取结果。 通过添加的顺序来确定每个请求任务的优先级和依赖关系。示例:
OCChainRequestQueue *chainQueue = [[OCChainRequestQueue alloc] init];
__weak typeof(chainQueue) weakQueue = chainQueue;
for (int i = 0; i < 10; i++) {
OCHttpRequest *request = [[OCHttpRequest alloc] initWithMethod:OCHttpRequestMethodGET urlString:@"https://suggest.taobao.com/sug" parameter:@{@"code":@"utf-8",@"q":[NSString stringWithFormat:@"女装+%d", i],@"callback":@"cb"}];
[request setCompletionBlock:^(OCHttpRequest *request, OCHttpResponse *response){
NSLog(@"request index=>%ld", weakQueue.currentIndex);
}];
[chainQueue entryRequest:request];
}
// 是否允许下一个请求执行
[_chainQueue setOnNextBlock:^BOOL(OCChainRequestQueue * _Nonnull queue, __kindof OCHttpRequest * _Nonnull request1, __kindof OCHttpRequest * _Nonnull request2) {
if (queue.currentIndex > 4) {
return NO;
}
return YES;
}];
[chainQueue startWithCompletionBlock:^(__kindof OCAbstractRequestQueue * _Nonnull requestQueue, NSError * _Nullable error) {
if (error) {
NSLog(@"执行%ld 错误=>%@", requestQueue.currentIndex, error);
} else {
NSLog(@"全部任务执行完成");
}
}];
2、需求:需要同时发送多个请求,不确定任务的执行顺序,所有请求完成后,并获取结果。示例:
OCGroupRequestQueue *groupQueue = [[OCGroupRequestQueue alloc] init];
__weak typeof(groupQueue) weakQueue = groupQueue;
for (int i = 0; i < 10; i++) {
OCHttpRequest *request = [[OCHttpRequest alloc] initWithMethod:OCHttpRequestMethodGET urlString:@"https://suggest.taobao.com/sug" parameter:@{@"code":@"utf-8",@"q":[NSString stringWithFormat:@"女装+%d", i],@"callback":@"cb"}];
[request setCompletionBlock:^(OCHttpRequest *request, OCHttpResponse *response){
NSLog(@"request index=>%ld", weakQueue.currentIndex);
}];
[groupQueue entryRequest:request];
}
[groupQueue startWithCompletionBlock:^(__kindof OCAbstractRequestQueue * _Nonnull requestQueue, NSError * _Nullable error) {
if (error) {
NSLog(@"执行%ld 错误=>%@", requestQueue.currentIndex, error);
} else {
NSLog(@"全部任务执行完成");
}
}];
3、大文件下载
示例:
OCBlobDownloadRequest *request = [[OCBlobDownloadRequest alloc] initWithURLString:@"http://wcy.dzryycs.com/vscode-osx.zip"];
request.saveFilePath = [NSString stringWithFormat:@"/Users/xxx/Desktop/%@", request.urlString.lastPathComponent];
request.tempFilePath = [NSString stringWithFormat:@"/Users/xxx/Desktop/temp-%@", request.urlString.lastPathComponent];
NSLog(@"saveFilePath=>%@", request.saveFilePath);
NSLog(@"tempFilePath=>%@", request.tempFilePath);
[request setProgressBlock:^(OCHttpRequest * _Nonnull request, float progress, int64_t completedUnitCount, int64_t totalUnitCount) {
NSLog(@"%.2fM %.2f", totalUnitCount / 1024.0 / 1024.0, progress);
}];
[request startWithCompletionBlock:^(OCHttpRequest *request, OCHttpResponse *response) {
if (response.error) {
NSLog(@"%@", response.error);
} else {
NSLog(@"下载成功");
}
}];
致谢
AFNetworkingUtils、User-Agent的代码来自AFNetworking
。
OCReachability修改Apple提供的Reachability类源码,并在此基础上增加了移动网络类型判断。