├── .DS_Store ├── WB_NeiApiManager ├── .DS_Store ├── Http │ ├── .DS_Store │ ├── WB_Request.h │ ├── WB_ArgumentFilterProtocol.h │ ├── WB_UploadImageRequest.h │ ├── WB_BatchUploadImgRequest.h │ ├── WB_BaseRequest.h │ ├── WB_Request.m │ ├── WB_BaseRequest.m │ ├── WB_BatchUploadImgRequest.m │ ├── WB_UploadImageRequest.m │ └── WB_ArgumentFilterProtocol.m ├── WB_NetApiConstant.h ├── WB_NetApiMacro.h ├── WB_NetApiConstant.m ├── AFNetworking │ ├── AFNetworking.h │ ├── AFSecurityPolicy.h │ ├── AFNetworkReachabilityManager.h │ ├── AFNetworkReachabilityManager.m │ ├── AFURLResponseSerialization.h │ ├── AFSecurityPolicy.m │ ├── AFHTTPSessionManager.m │ └── AFHTTPSessionManager.h └── YTKNetwork │ ├── YTKBatchRequestAgent.h │ ├── YTKChainRequestAgent.h │ ├── YTKNetworkAgent.h │ ├── YTKBatchRequestAgent.m │ ├── YTKChainRequestAgent.m │ ├── YTKNetwork.h │ ├── YTKNetworkConfig.m │ ├── YTKNetworkPrivate.h │ ├── YTKChainRequest.h │ ├── YTKNetworkConfig.h │ ├── YTKRequest.h │ ├── YTKBatchRequest.h │ ├── YTKChainRequest.m │ ├── YTKBatchRequest.m │ ├── YTKBaseRequest.m │ ├── YTKNetworkPrivate.m │ ├── YTKBaseRequest.h │ └── YTKRequest.m ├── WB_NetApiManager使用说明.md └── README.md /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/weibo1314/WB_NeiApiManager/HEAD/.DS_Store -------------------------------------------------------------------------------- /WB_NeiApiManager/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/weibo1314/WB_NeiApiManager/HEAD/WB_NeiApiManager/.DS_Store -------------------------------------------------------------------------------- /WB_NeiApiManager/Http/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/weibo1314/WB_NeiApiManager/HEAD/WB_NeiApiManager/Http/.DS_Store -------------------------------------------------------------------------------- /WB_NeiApiManager/Http/WB_Request.h: -------------------------------------------------------------------------------- 1 | // 2 | // WB_Request.h 3 | // WB_iOS_FrameWork 4 | // 5 | // Created by weibo on 2017/9/26. 6 | // Copyright © 2017年 WWB_iOS. All rights reserved. 7 | // 获取数据API的基类,所有获取数据的API 都需要继承于这个方法 8 | 9 | #import "WB_BaseRequest.h" 10 | 11 | @interface WB_Request : WB_BaseRequest 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /WB_NeiApiManager/WB_NetApiConstant.h: -------------------------------------------------------------------------------- 1 | // 2 | // WB_NetApiConstant.h 3 | // WB_iOS_FrameWork 4 | // 5 | // Created by weibo on 2017/9/26. 6 | // Copyright © 2017年 WWB_iOS. All rights reserved. 7 | // 定义全局常量 启动api 8 | 9 | #import 10 | 11 | @interface WB_NetApiConstant : NSObject 12 | 13 | + (WB_NetApiConstant *)sharedInstance; 14 | 15 | //图片上传地址 前缀 16 | @property(nonatomic,copy)NSString *imageUpLoadPrefix; 17 | 18 | 19 | 20 | @end 21 | -------------------------------------------------------------------------------- /WB_NeiApiManager/Http/WB_ArgumentFilterProtocol.h: -------------------------------------------------------------------------------- 1 | // 2 | // WB_ArgumentFilterProtocol.h 3 | // WB_iOS_FrameWork 4 | // 5 | // Created by weibo on 2017/9/26. 6 | // Copyright © 2017年 WWB_iOS. All rights reserved. 7 | // 配置共有参数 8 | 9 | #import 10 | 11 | #import "YTKNetworkConfig.h" 12 | 13 | /// 给url追加arguments,用于全局参数,比如AppVersion, ApiVersion等 14 | @interface WB_ArgumentFilterProtocol : NSObject 15 | 16 | + (WB_ArgumentFilterProtocol *)filterWithArguments:(NSDictionary *)arguments; 17 | 18 | - (NSString *)filterUrl:(NSString *)originUrl withRequest:(YTKBaseRequest *)request; 19 | @end 20 | -------------------------------------------------------------------------------- /WB_NeiApiManager/Http/WB_UploadImageRequest.h: -------------------------------------------------------------------------------- 1 | // 2 | // WB_UploadImageRequest.h 3 | // WB_iOS_FrameWork 4 | // 5 | // Created by weibo on 2017/9/26. 6 | // Copyright © 2017年 WWB_iOS. All rights reserved. 7 | // 上传图片API的基类,所有上传图片的API 都需要继承于这个方法 8 | 9 | #import "WB_Request.h" 10 | 11 | #import 12 | 13 | @interface WB_UploadImageRequest : WB_Request 14 | 15 | @property(nonatomic,strong)UIImage *image; 16 | 17 | - (id)initWithImage:(UIImage *)image; 18 | 19 | //获取上传进度 20 | @property(nonatomic,copy)void(^uploadProgressBlock)(WB_UploadImageRequest *currentApi, NSProgress * progress); 21 | 22 | 23 | 24 | @end 25 | -------------------------------------------------------------------------------- /WB_NeiApiManager/Http/WB_BatchUploadImgRequest.h: -------------------------------------------------------------------------------- 1 | // 2 | // WB_BatchUploadImgRequest.h 3 | // WB_iOS_FrameWork 4 | // 5 | // Created by weibo on 2017/9/26. 6 | // Copyright © 2017年 WWB_iOS. All rights reserved. 7 | // 批量上传图片api 8 | 9 | #import "YTKBatchRequest.h" 10 | 11 | #import 12 | @protocol UpLoadProgressDelegate 13 | 14 | //获取批量上传图片进度回调 15 | -(void)upBatchRequestProgressWithApiTag:(NSInteger )apiTag andProgress:(NSProgress *)progress; 16 | 17 | @end 18 | 19 | @interface WB_BatchUploadImgRequest : YTKBatchRequest 20 | 21 | //批量上传图片 22 | -(instancetype)initWithImgArray:(NSMutableArray *)imgArray; 23 | 24 | @property (nonatomic,weak)idmDelegate; 25 | 26 | 27 | 28 | @end 29 | -------------------------------------------------------------------------------- /WB_NeiApiManager/Http/WB_BaseRequest.h: -------------------------------------------------------------------------------- 1 | // 2 | // WB_BaseRequest.h 3 | // WB_iOS_FrameWork 4 | // 5 | // Created by weibo on 2017/9/26. 6 | // Copyright © 2017年 WWB_iOS. All rights reserved. 7 | // 网络请求基类 所有的网络请求继承这个方法 8 | 9 | #import "YTKRequest.h" 10 | 11 | typedef NS_ENUM(NSInteger,ZorasunRefreshCacheTimeType) 12 | { 13 | kZorasunRequestCacheTimeTypeNone=1, 14 | kZorasunRequestCacheTimeTypeShort=2, 15 | kZorasunRequestCacheTimeTypeLong=3 16 | }; 17 | 18 | @interface WB_BaseRequest : YTKRequest 19 | /** 20 | * 获取状态码 21 | */ 22 | -(NSInteger )getCodeStatus; 23 | /** 24 | * 获取消息 25 | */ 26 | -(NSString * )getMsg; 27 | /** 28 | * 获取content 29 | */ 30 | -(id)getContent; 31 | /** 32 | * 缓存时间,二次请求的时候不真的发起请求 defalut 1 none 33 | */ 34 | @property(nonatomic,assign)ZorasunRefreshCacheTimeType cacheTimeType; 35 | @end 36 | -------------------------------------------------------------------------------- /WB_NeiApiManager/WB_NetApiMacro.h: -------------------------------------------------------------------------------- 1 | // 2 | // WB_NetApiMacro.h 3 | // WB_iOS_FrameWork 4 | // 5 | // Created by weibo on 2017/9/25. 6 | // Copyright © 2017年 WWB_iOS. All rights reserved. 7 | // 8 | 9 | #ifndef WB_NetApiMacro_h 10 | #define WB_NetApiMacro_h 11 | 12 | /* 13 | *  NSlog替代宏 debug调试打印 14 | */ 15 | #ifdef DEBUG 16 | #define WBLog(...) NSLog(@"%@",[NSString stringWithFormat:__VA_ARGS__]) 17 | #endif 18 | 19 | 20 | //网络请求方式 21 | #define GETORPOST 1 // 0 GET 1 POST 22 | 23 | /* 24 | * 正式服务器接口 25 | */ 26 | ////////数据请求 27 | #define WB_BASEURL @"http://11.11.111/" 28 | ///////图片上传 29 | #define WB_BASEUPLOADIMGURL @"http://11.11.111/" 30 | 31 | /* 32 | * 测试服务器接口 33 | */ 34 | //////////数据请求 35 | //#define WB_BASEURL @"http://47.94.116.6/" 36 | /////////图片上传 37 | //#define WB_BASEUPLOADIMGURL @"http://47.94.116.6/" 38 | 39 | 40 | #endif /* WB_NetApiMacro_h */ 41 | -------------------------------------------------------------------------------- /WB_NeiApiManager/WB_NetApiConstant.m: -------------------------------------------------------------------------------- 1 | // 2 | // WB_NetApiConstant.m 3 | // WB_iOS_FrameWork 4 | // 5 | // Created by weibo on 2017/9/26. 6 | // Copyright © 2017年 WWB_iOS. All rights reserved. 7 | // 8 | 9 | #import "WB_NetApiConstant.h" 10 | 11 | #import "YTKNetworkConfig.h" 12 | 13 | @implementation WB_NetApiConstant 14 | static WB_NetApiConstant *Const = nil; 15 | + (WB_NetApiConstant *)sharedInstance 16 | { 17 | static dispatch_once_t once; 18 | dispatch_once(&once, ^{ 19 | 20 | Const = [[self alloc] init]; 21 | 22 | }); 23 | return Const; 24 | } 25 | -(instancetype)init 26 | { 27 | self=[super init]; 28 | if (self) { 29 | YTKNetworkConfig *config = [YTKNetworkConfig sharedConfig]; 30 | //请求的基础url前缀 31 | config.baseUrl = WB_BASEURL; 32 | //图片上传url前缀 33 | _imageUpLoadPrefix = WB_BASEUPLOADIMGURL; 34 | } 35 | return self; 36 | } 37 | 38 | 39 | @end 40 | -------------------------------------------------------------------------------- /WB_NeiApiManager/Http/WB_Request.m: -------------------------------------------------------------------------------- 1 | // 2 | // WB_Request.m 3 | // WB_iOS_FrameWork 4 | // 5 | // Created by weibo on 2017/9/26. 6 | // Copyright © 2017年 WWB_iOS. All rights reserved. 7 | // 8 | 9 | #import "WB_Request.h" 10 | 11 | @implementation WB_Request 12 | -(long )getCodeStatus 13 | { 14 | return [[[self responseJSONObject] objectForKey:@"code"]longValue]; 15 | } 16 | -(NSString * )getMsg 17 | { 18 | return [[self responseJSONObject] objectForKey:@"msg"]; 19 | } 20 | -(id)getContent 21 | { 22 | return [[self responseJSONObject] objectForKey:@"data"]; 23 | } 24 | #pragma mark 请求方式 25 | - (YTKRequestMethod)requestMethod { 26 | if (GETORPOST == 1) { 27 | return YTKRequestMethodPOST; 28 | }else{ 29 | return YTKRequestMethodGET; 30 | } 31 | } 32 | #pragma mark 添加请求头 33 | -(NSDictionary *)requestHeaderFieldValueDictionary 34 | { 35 | NSMutableDictionary *headParams=[[NSMutableDictionary alloc]init]; 36 | // [headParams setObject:@"31" forKey:@"accountId"]; 37 | // [headParams setObject:@"2" forKey:@"isUser"]; 38 | return headParams; 39 | } 40 | @end 41 | -------------------------------------------------------------------------------- /WB_NeiApiManager/Http/WB_BaseRequest.m: -------------------------------------------------------------------------------- 1 | // 2 | // WB_BaseRequest.m 3 | // WB_iOS_FrameWork 4 | // 5 | // Created by weibo on 2017/9/26. 6 | // Copyright © 2017年 WWB_iOS. All rights reserved. 7 | // 8 | 9 | #import "WB_BaseRequest.h" 10 | 11 | @implementation WB_BaseRequest 12 | -(id)init 13 | { 14 | self=[super init]; 15 | if (self) { 16 | if (self.cacheTimeType == 0) { 17 | self.cacheTimeType=kZorasunRequestCacheTimeTypeNone; 18 | } 19 | } 20 | return self; 21 | } 22 | -(NSInteger )getCodeStatus 23 | { 24 | return 0; 25 | } 26 | -(NSString * )getMsg 27 | { 28 | return nil; 29 | } 30 | -(id)getContent 31 | { 32 | return nil; 33 | } 34 | #pragma mark 缓存时间,二次请求的时候不真的发起请求 ,如果需要其他缓存时间的请求,进行覆盖 35 | -(NSInteger)cacheTimeInSeconds 36 | { 37 | NSInteger seconds=0; 38 | switch (_cacheTimeType) { 39 | case kZorasunRequestCacheTimeTypeLong: 40 | seconds=60*5; 41 | break; 42 | case kZorasunRequestCacheTimeTypeShort: 43 | seconds= 60*1; 44 | break; 45 | case kZorasunRequestCacheTimeTypeNone: 46 | default: 47 | break; 48 | } 49 | return seconds; 50 | } 51 | 52 | @end 53 | -------------------------------------------------------------------------------- /WB_NeiApiManager/Http/WB_BatchUploadImgRequest.m: -------------------------------------------------------------------------------- 1 | // 2 | // WB_BatchUploadImgRequest.m 3 | // WB_iOS_FrameWork 4 | // 5 | // Created by weibo on 2017/9/26. 6 | // Copyright © 2017年 WWB_iOS. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | #import "WB_BatchUploadImgRequest.h" 12 | 13 | #import "WB_UploadImageRequest.h" 14 | 15 | @interface WB_BatchUploadImgRequest() 16 | 17 | @end 18 | 19 | @implementation WB_BatchUploadImgRequest 20 | -(instancetype)initWithImgArray:(NSMutableArray *)imgArray 21 | { 22 | NSMutableArray *apiArr = [NSMutableArray new]; 23 | for (NSInteger i = 0; i < imgArray.count; i ++) { 24 | WB_UploadImageRequest *api = [[WB_UploadImageRequest alloc] initWithImage:imgArray[i]]; 25 | api.tag = i + 1; 26 | 27 | #pragma mark api获取上传进度的block不能写在这里... 28 | 29 | [apiArr addObject:api]; 30 | } 31 | self = [[WB_BatchUploadImgRequest alloc] initWithRequestArray:apiArr]; 32 | //添加上传进度回调 33 | [self getBatchProgress]; 34 | return self; 35 | } 36 | -(void)getBatchProgress 37 | { 38 | for (WB_UploadImageRequest *api in self.requestArray) { 39 | api.uploadProgressBlock = ^(WB_UploadImageRequest *currentApi, NSProgress *progress) { 40 | if (_mDelegate&&[_mDelegate respondsToSelector:@selector(upBatchRequestProgressWithApiTag:andProgress:)]) 41 | { 42 | [_mDelegate upBatchRequestProgressWithApiTag:currentApi.tag andProgress:progress]; 43 | } 44 | }; 45 | } 46 | } 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | @end 56 | -------------------------------------------------------------------------------- /WB_NeiApiManager/AFNetworking/AFNetworking.h: -------------------------------------------------------------------------------- 1 | // AFNetworking.h 2 | // 3 | // Copyright (c) 2013 AFNetworking (http://afnetworking.com/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | #import 25 | #import 26 | 27 | #ifndef _AFNETWORKING_ 28 | #define _AFNETWORKING_ 29 | 30 | #import "AFURLRequestSerialization.h" 31 | #import "AFURLResponseSerialization.h" 32 | #import "AFSecurityPolicy.h" 33 | 34 | #if !TARGET_OS_WATCH 35 | #import "AFNetworkReachabilityManager.h" 36 | #endif 37 | 38 | #import "AFURLSessionManager.h" 39 | #import "AFHTTPSessionManager.h" 40 | 41 | #endif /* _AFNETWORKING_ */ 42 | -------------------------------------------------------------------------------- /WB_NeiApiManager/YTKNetwork/YTKBatchRequestAgent.h: -------------------------------------------------------------------------------- 1 | // 2 | // YTKBatchRequestAgent.h 3 | // 4 | // Copyright (c) 2012-2016 YTKNetwork https://github.com/yuantiku 5 | // 6 | // Permission is hereby granted, free of charge, to any person obtaining a copy 7 | // of this software and associated documentation files (the "Software"), to deal 8 | // in the Software without restriction, including without limitation the rights 9 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | // copies of the Software, and to permit persons to whom the Software is 11 | // furnished to do so, subject to the following conditions: 12 | // 13 | // The above copyright notice and this permission notice shall be included in 14 | // all copies or substantial portions of the Software. 15 | // 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | // THE SOFTWARE. 23 | 24 | #import 25 | 26 | NS_ASSUME_NONNULL_BEGIN 27 | 28 | @class YTKBatchRequest; 29 | 30 | /// YTKBatchRequestAgent handles batch request management. It keeps track of all 31 | /// the batch requests. 32 | @interface YTKBatchRequestAgent : NSObject 33 | 34 | - (instancetype)init NS_UNAVAILABLE; 35 | + (instancetype)new NS_UNAVAILABLE; 36 | 37 | /// Get the shared batch request agent. 38 | + (YTKBatchRequestAgent *)sharedAgent; 39 | 40 | /// Add a batch request. 41 | - (void)addBatchRequest:(YTKBatchRequest *)request; 42 | 43 | /// Remove a previously added batch request. 44 | - (void)removeBatchRequest:(YTKBatchRequest *)request; 45 | 46 | @end 47 | 48 | NS_ASSUME_NONNULL_END 49 | -------------------------------------------------------------------------------- /WB_NeiApiManager/YTKNetwork/YTKChainRequestAgent.h: -------------------------------------------------------------------------------- 1 | // 2 | // YTKChainRequestAgent.h 3 | // 4 | // Copyright (c) 2012-2016 YTKNetwork https://github.com/yuantiku 5 | // 6 | // Permission is hereby granted, free of charge, to any person obtaining a copy 7 | // of this software and associated documentation files (the "Software"), to deal 8 | // in the Software without restriction, including without limitation the rights 9 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | // copies of the Software, and to permit persons to whom the Software is 11 | // furnished to do so, subject to the following conditions: 12 | // 13 | // The above copyright notice and this permission notice shall be included in 14 | // all copies or substantial portions of the Software. 15 | // 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | // THE SOFTWARE. 23 | 24 | #import 25 | 26 | NS_ASSUME_NONNULL_BEGIN 27 | 28 | @class YTKChainRequest; 29 | 30 | /// YTKChainRequestAgent handles chain request management. It keeps track of all 31 | /// the chain requests. 32 | @interface YTKChainRequestAgent : NSObject 33 | 34 | - (instancetype)init NS_UNAVAILABLE; 35 | + (instancetype)new NS_UNAVAILABLE; 36 | 37 | /// Get the shared chain request agent. 38 | + (YTKChainRequestAgent *)sharedAgent; 39 | 40 | /// Add a chain request. 41 | - (void)addChainRequest:(YTKChainRequest *)request; 42 | 43 | /// Remove a previously added chain request. 44 | - (void)removeChainRequest:(YTKChainRequest *)request; 45 | 46 | @end 47 | 48 | NS_ASSUME_NONNULL_END 49 | -------------------------------------------------------------------------------- /WB_NeiApiManager/Http/WB_UploadImageRequest.m: -------------------------------------------------------------------------------- 1 | // 2 | // WB_UploadImageRequest.m 3 | // WB_iOS_FrameWork 4 | // 5 | // Created by weibo on 2017/9/26. 6 | // Copyright © 2017年 WWB_iOS. All rights reserved. 7 | // 8 | 9 | #import "WB_UploadImageRequest.h" 10 | 11 | #import "AFNetworking.h" 12 | 13 | #import "WB_NetApiConstant.h" 14 | 15 | @implementation WB_UploadImageRequest 16 | - (id)initWithImage:(UIImage *)image { 17 | self = [super init]; 18 | if (self) { 19 | self.image = image; 20 | self.resumableDownloadProgressBlock = [self resumableUploadProgressBlock]; 21 | } 22 | return self; 23 | } 24 | -(NSString *)baseUrl 25 | { 26 | return [[WB_NetApiConstant sharedInstance] imageUpLoadPrefix]; 27 | } 28 | - (YTKRequestMethod)requestMethod { 29 | if (GETORPOST == 1) { 30 | return YTKRequestMethodPOST; 31 | }else{ 32 | return YTKRequestMethodGET; 33 | } 34 | } 35 | - (NSString *)requestUrl { 36 | return @"home/upImg"; 37 | } 38 | //设置上传图片 所需要的 HTTP HEADER 39 | - (AFConstructingBlock)constructingBodyBlock { 40 | return ^(id formData) { 41 | NSData *data=UIImagePNGRepresentation(_image); 42 | NSString *name = @"urlfile"; 43 | NSString *fileName=@""; 44 | NSDate* date = [NSDate date]; 45 | NSDateFormatter *dateformatter = [[NSDateFormatter alloc]init]; 46 | [dateformatter setDateFormat:@"yyyyMMddHHmmss"]; 47 | NSString *timeStr=[dateformatter stringFromDate:date]; 48 | fileName=[NSString stringWithFormat:@"%@.png",timeStr]; 49 | NSString *type = @"image/png"; 50 | [formData appendPartWithFileData:data name:name fileName:fileName mimeType:type]; 51 | }; 52 | } 53 | #pragma mark 上传进度 54 | - (AFURLSessionTaskProgressBlock) resumableUploadProgressBlock 55 | { 56 | AFURLSessionTaskProgressBlock block = ^void(NSProgress * progress){ 57 | if (_uploadProgressBlock) { 58 | _uploadProgressBlock(self,progress); 59 | } 60 | }; 61 | return block; 62 | } 63 | 64 | @end 65 | -------------------------------------------------------------------------------- /WB_NeiApiManager/Http/WB_ArgumentFilterProtocol.m: -------------------------------------------------------------------------------- 1 | // 2 | // WB_ArgumentFilterProtocol.m 3 | // WB_iOS_FrameWork 4 | // 5 | // Created by weibo on 2017/9/26. 6 | // Copyright © 2017年 WWB_iOS. All rights reserved. 7 | // 8 | 9 | #import "WB_ArgumentFilterProtocol.h" 10 | 11 | #import "AFURLRequestSerialization.h" 12 | 13 | 14 | @implementation WB_ArgumentFilterProtocol 15 | { 16 | NSDictionary *_arguments; 17 | } 18 | + (WB_ArgumentFilterProtocol *)filterWithArguments:(NSDictionary *)arguments { 19 | return [[self alloc] initWithArguments:arguments]; 20 | } 21 | 22 | - (id)initWithArguments:(NSDictionary *)arguments { 23 | self = [super init]; 24 | if (self) { 25 | _arguments = arguments; 26 | } 27 | return self; 28 | } 29 | 30 | - (NSString *)filterUrl:(NSString *)originUrl withRequest:(YTKBaseRequest *)request { 31 | return [self urlStringWithOriginUrlString:originUrl appendParameters:_arguments]; 32 | } 33 | - (NSString *)urlStringWithOriginUrlString:(NSString *)originUrlString appendParameters:(NSDictionary *)parameters { 34 | NSString *paraUrlString = AFQueryStringFromParameters(parameters); 35 | 36 | if (!(paraUrlString.length > 0)) { 37 | return originUrlString; 38 | } 39 | 40 | BOOL useDummyUrl = NO; 41 | static NSString *dummyUrl = nil; 42 | NSURLComponents *components = [NSURLComponents componentsWithString:originUrlString]; 43 | if (!components) { 44 | useDummyUrl = YES; 45 | if (!dummyUrl) { 46 | dummyUrl = [YTKNetworkConfig sharedConfig].baseUrl; 47 | } 48 | components = [NSURLComponents componentsWithString:dummyUrl]; 49 | } 50 | 51 | NSString *queryString = components.query ?: @""; 52 | NSString *newQueryString = [queryString stringByAppendingFormat:queryString.length > 0 ? @"&%@" : @"%@", paraUrlString]; 53 | 54 | components.query = newQueryString; 55 | 56 | if (useDummyUrl) { 57 | return [components.URL.absoluteString substringFromIndex:dummyUrl.length - 1]; 58 | } else { 59 | return components.URL.absoluteString; 60 | } 61 | } 62 | @end 63 | -------------------------------------------------------------------------------- /WB_NeiApiManager/YTKNetwork/YTKNetworkAgent.h: -------------------------------------------------------------------------------- 1 | // 2 | // YTKNetworkAgent.h 3 | // 4 | // Copyright (c) 2012-2016 YTKNetwork https://github.com/yuantiku 5 | // 6 | // Permission is hereby granted, free of charge, to any person obtaining a copy 7 | // of this software and associated documentation files (the "Software"), to deal 8 | // in the Software without restriction, including without limitation the rights 9 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | // copies of the Software, and to permit persons to whom the Software is 11 | // furnished to do so, subject to the following conditions: 12 | // 13 | // The above copyright notice and this permission notice shall be included in 14 | // all copies or substantial portions of the Software. 15 | // 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | // THE SOFTWARE. 23 | 24 | #import 25 | 26 | NS_ASSUME_NONNULL_BEGIN 27 | 28 | @class YTKBaseRequest; 29 | 30 | /// YTKNetworkAgent is the underlying class that handles actual request generation, 31 | /// serialization and response handling. 32 | @interface YTKNetworkAgent : NSObject 33 | 34 | - (instancetype)init NS_UNAVAILABLE; 35 | + (instancetype)new NS_UNAVAILABLE; 36 | 37 | /// Get the shared agent. 38 | + (YTKNetworkAgent *)sharedAgent; 39 | 40 | /// Add request to session and start it. 41 | - (void)addRequest:(YTKBaseRequest *)request; 42 | 43 | /// Cancel a request that was previously added. 44 | - (void)cancelRequest:(YTKBaseRequest *)request; 45 | 46 | /// Cancel all requests that were previously added. 47 | - (void)cancelAllRequests; 48 | 49 | /// Return the constructed URL of request. 50 | /// 51 | /// @param request The request to parse. Should not be nil. 52 | /// 53 | /// @return The result URL. 54 | - (NSString *)buildRequestUrl:(YTKBaseRequest *)request; 55 | 56 | @end 57 | 58 | NS_ASSUME_NONNULL_END 59 | -------------------------------------------------------------------------------- /WB_NeiApiManager/YTKNetwork/YTKBatchRequestAgent.m: -------------------------------------------------------------------------------- 1 | // 2 | // YTKBatchRequestAgent.m 3 | // 4 | // Copyright (c) 2012-2016 YTKNetwork https://github.com/yuantiku 5 | // 6 | // Permission is hereby granted, free of charge, to any person obtaining a copy 7 | // of this software and associated documentation files (the "Software"), to deal 8 | // in the Software without restriction, including without limitation the rights 9 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | // copies of the Software, and to permit persons to whom the Software is 11 | // furnished to do so, subject to the following conditions: 12 | // 13 | // The above copyright notice and this permission notice shall be included in 14 | // all copies or substantial portions of the Software. 15 | // 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | // THE SOFTWARE. 23 | 24 | #import "YTKBatchRequestAgent.h" 25 | #import "YTKBatchRequest.h" 26 | 27 | @interface YTKBatchRequestAgent() 28 | 29 | @property (strong, nonatomic) NSMutableArray *requestArray; 30 | 31 | @end 32 | 33 | @implementation YTKBatchRequestAgent 34 | 35 | + (YTKBatchRequestAgent *)sharedAgent { 36 | static id sharedInstance = nil; 37 | static dispatch_once_t onceToken; 38 | dispatch_once(&onceToken, ^{ 39 | sharedInstance = [[self alloc] init]; 40 | }); 41 | return sharedInstance; 42 | } 43 | 44 | - (instancetype)init { 45 | self = [super init]; 46 | if (self) { 47 | _requestArray = [NSMutableArray array]; 48 | } 49 | return self; 50 | } 51 | 52 | - (void)addBatchRequest:(YTKBatchRequest *)request { 53 | @synchronized(self) { 54 | [_requestArray addObject:request]; 55 | } 56 | } 57 | 58 | - (void)removeBatchRequest:(YTKBatchRequest *)request { 59 | @synchronized(self) { 60 | [_requestArray removeObject:request]; 61 | } 62 | } 63 | 64 | @end 65 | -------------------------------------------------------------------------------- /WB_NeiApiManager/YTKNetwork/YTKChainRequestAgent.m: -------------------------------------------------------------------------------- 1 | // 2 | // YTKChainRequestAgent.m 3 | // 4 | // Copyright (c) 2012-2016 YTKNetwork https://github.com/yuantiku 5 | // 6 | // Permission is hereby granted, free of charge, to any person obtaining a copy 7 | // of this software and associated documentation files (the "Software"), to deal 8 | // in the Software without restriction, including without limitation the rights 9 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | // copies of the Software, and to permit persons to whom the Software is 11 | // furnished to do so, subject to the following conditions: 12 | // 13 | // The above copyright notice and this permission notice shall be included in 14 | // all copies or substantial portions of the Software. 15 | // 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | // THE SOFTWARE. 23 | 24 | #import "YTKChainRequestAgent.h" 25 | #import "YTKChainRequest.h" 26 | 27 | @interface YTKChainRequestAgent() 28 | 29 | @property (strong, nonatomic) NSMutableArray *requestArray; 30 | 31 | @end 32 | 33 | @implementation YTKChainRequestAgent 34 | 35 | + (YTKChainRequestAgent *)sharedAgent { 36 | static id sharedInstance = nil; 37 | static dispatch_once_t onceToken; 38 | dispatch_once(&onceToken, ^{ 39 | sharedInstance = [[self alloc] init]; 40 | }); 41 | return sharedInstance; 42 | } 43 | 44 | - (instancetype)init { 45 | self = [super init]; 46 | if (self) { 47 | _requestArray = [NSMutableArray array]; 48 | } 49 | return self; 50 | } 51 | 52 | - (void)addChainRequest:(YTKChainRequest *)request { 53 | @synchronized(self) { 54 | [_requestArray addObject:request]; 55 | } 56 | } 57 | 58 | - (void)removeChainRequest:(YTKChainRequest *)request { 59 | @synchronized(self) { 60 | [_requestArray removeObject:request]; 61 | } 62 | } 63 | 64 | @end 65 | -------------------------------------------------------------------------------- /WB_NeiApiManager/YTKNetwork/YTKNetwork.h: -------------------------------------------------------------------------------- 1 | // 2 | // YTKNetwork.h 3 | // 4 | // Copyright (c) 2012-2016 YTKNetwork https://github.com/yuantiku 5 | // 6 | // Permission is hereby granted, free of charge, to any person obtaining a copy 7 | // of this software and associated documentation files (the "Software"), to deal 8 | // in the Software without restriction, including without limitation the rights 9 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | // copies of the Software, and to permit persons to whom the Software is 11 | // furnished to do so, subject to the following conditions: 12 | // 13 | // The above copyright notice and this permission notice shall be included in 14 | // all copies or substantial portions of the Software. 15 | // 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | // THE SOFTWARE. 23 | 24 | #import 25 | 26 | #ifndef _YTKNETWORK_ 27 | #define _YTKNETWORK_ 28 | 29 | #if __has_include() 30 | 31 | FOUNDATION_EXPORT double YTKNetworkVersionNumber; 32 | FOUNDATION_EXPORT const unsigned char YTKNetworkVersionString[]; 33 | 34 | #import 35 | #import 36 | #import 37 | #import 38 | #import 39 | #import 40 | #import 41 | #import 42 | 43 | #else 44 | 45 | #import "YTKRequest.h" 46 | #import "YTKBaseRequest.h" 47 | #import "YTKNetworkAgent.h" 48 | #import "YTKBatchRequest.h" 49 | #import "YTKBatchRequestAgent.h" 50 | #import "YTKChainRequest.h" 51 | #import "YTKChainRequestAgent.h" 52 | #import "YTKNetworkConfig.h" 53 | 54 | #endif /* __has_include */ 55 | 56 | #endif /* _YTKNETWORK_ */ 57 | -------------------------------------------------------------------------------- /WB_NeiApiManager/YTKNetwork/YTKNetworkConfig.m: -------------------------------------------------------------------------------- 1 | // 2 | // YTKNetworkConfig.m 3 | // 4 | // Copyright (c) 2012-2016 YTKNetwork https://github.com/yuantiku 5 | // 6 | // Permission is hereby granted, free of charge, to any person obtaining a copy 7 | // of this software and associated documentation files (the "Software"), to deal 8 | // in the Software without restriction, including without limitation the rights 9 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | // copies of the Software, and to permit persons to whom the Software is 11 | // furnished to do so, subject to the following conditions: 12 | // 13 | // The above copyright notice and this permission notice shall be included in 14 | // all copies or substantial portions of the Software. 15 | // 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | // THE SOFTWARE. 23 | 24 | #import "YTKNetworkConfig.h" 25 | #import "YTKBaseRequest.h" 26 | 27 | #if __has_include() 28 | #import 29 | #else 30 | #import "AFNetworking.h" 31 | #endif 32 | 33 | @implementation YTKNetworkConfig { 34 | NSMutableArray> *_urlFilters; 35 | NSMutableArray> *_cacheDirPathFilters; 36 | } 37 | 38 | + (YTKNetworkConfig *)sharedConfig { 39 | static id sharedInstance = nil; 40 | static dispatch_once_t onceToken; 41 | dispatch_once(&onceToken, ^{ 42 | sharedInstance = [[self alloc] init]; 43 | }); 44 | return sharedInstance; 45 | } 46 | 47 | - (instancetype)init { 48 | self = [super init]; 49 | if (self) { 50 | _baseUrl = @""; 51 | _cdnUrl = @""; 52 | _urlFilters = [NSMutableArray array]; 53 | _cacheDirPathFilters = [NSMutableArray array]; 54 | _securityPolicy = [AFSecurityPolicy defaultPolicy]; 55 | _debugLogEnabled = NO; 56 | } 57 | return self; 58 | } 59 | 60 | - (void)addUrlFilter:(id)filter { 61 | [_urlFilters addObject:filter]; 62 | } 63 | 64 | - (void)clearUrlFilter { 65 | [_urlFilters removeAllObjects]; 66 | } 67 | 68 | - (void)addCacheDirPathFilter:(id)filter { 69 | [_cacheDirPathFilters addObject:filter]; 70 | } 71 | 72 | - (void)clearCacheDirPathFilter { 73 | [_cacheDirPathFilters removeAllObjects]; 74 | } 75 | 76 | - (NSArray> *)urlFilters { 77 | return [_urlFilters copy]; 78 | } 79 | 80 | - (NSArray> *)cacheDirPathFilters { 81 | return [_cacheDirPathFilters copy]; 82 | } 83 | 84 | #pragma mark - NSObject 85 | 86 | - (NSString *)description { 87 | return [NSString stringWithFormat:@"<%@: %p>{ baseURL: %@ } { cdnURL: %@ }", NSStringFromClass([self class]), self, self.baseUrl, self.cdnUrl]; 88 | } 89 | 90 | @end 91 | -------------------------------------------------------------------------------- /WB_NeiApiManager/YTKNetwork/YTKNetworkPrivate.h: -------------------------------------------------------------------------------- 1 | // 2 | // YTKNetworkPrivate.h 3 | // 4 | // Copyright (c) 2012-2016 YTKNetwork https://github.com/yuantiku 5 | // 6 | // Permission is hereby granted, free of charge, to any person obtaining a copy 7 | // of this software and associated documentation files (the "Software"), to deal 8 | // in the Software without restriction, including without limitation the rights 9 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | // copies of the Software, and to permit persons to whom the Software is 11 | // furnished to do so, subject to the following conditions: 12 | // 13 | // The above copyright notice and this permission notice shall be included in 14 | // all copies or substantial portions of the Software. 15 | // 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | // THE SOFTWARE. 23 | 24 | #import 25 | #import "YTKRequest.h" 26 | #import "YTKBaseRequest.h" 27 | #import "YTKBatchRequest.h" 28 | #import "YTKChainRequest.h" 29 | #import "YTKNetworkAgent.h" 30 | #import "YTKNetworkConfig.h" 31 | 32 | NS_ASSUME_NONNULL_BEGIN 33 | 34 | FOUNDATION_EXPORT void YTKLog(NSString *format, ...) NS_FORMAT_FUNCTION(1,2); 35 | 36 | @class AFHTTPSessionManager; 37 | 38 | @interface YTKNetworkUtils : NSObject 39 | 40 | + (BOOL)validateJSON:(id)json withValidator:(id)jsonValidator; 41 | 42 | + (void)addDoNotBackupAttribute:(NSString *)path; 43 | 44 | + (NSString *)md5StringFromString:(NSString *)string; 45 | 46 | + (NSString *)appVersionString; 47 | 48 | + (NSStringEncoding)stringEncodingWithRequest:(YTKBaseRequest *)request; 49 | 50 | + (BOOL)validateResumeData:(NSData *)data; 51 | 52 | @end 53 | 54 | @interface YTKRequest (Getter) 55 | 56 | - (NSString *)cacheBasePath; 57 | 58 | @end 59 | 60 | @interface YTKBaseRequest (Setter) 61 | 62 | @property (nonatomic, strong, readwrite) NSURLSessionTask *requestTask; 63 | @property (nonatomic, strong, readwrite, nullable) NSData *responseData; 64 | @property (nonatomic, strong, readwrite, nullable) id responseJSONObject; 65 | @property (nonatomic, strong, readwrite, nullable) id responseObject; 66 | @property (nonatomic, strong, readwrite, nullable) NSString *responseString; 67 | @property (nonatomic, strong, readwrite, nullable) NSError *error; 68 | 69 | @end 70 | 71 | @interface YTKBaseRequest (RequestAccessory) 72 | 73 | - (void)toggleAccessoriesWillStartCallBack; 74 | - (void)toggleAccessoriesWillStopCallBack; 75 | - (void)toggleAccessoriesDidStopCallBack; 76 | 77 | @end 78 | 79 | @interface YTKBatchRequest (RequestAccessory) 80 | 81 | - (void)toggleAccessoriesWillStartCallBack; 82 | - (void)toggleAccessoriesWillStopCallBack; 83 | - (void)toggleAccessoriesDidStopCallBack; 84 | 85 | @end 86 | 87 | @interface YTKChainRequest (RequestAccessory) 88 | 89 | - (void)toggleAccessoriesWillStartCallBack; 90 | - (void)toggleAccessoriesWillStopCallBack; 91 | - (void)toggleAccessoriesDidStopCallBack; 92 | 93 | @end 94 | 95 | @interface YTKNetworkAgent (Private) 96 | 97 | - (AFHTTPSessionManager *)manager; 98 | - (void)resetURLSessionManager; 99 | - (void)resetURLSessionManagerWithConfiguration:(NSURLSessionConfiguration *)configuration; 100 | 101 | - (NSString *)incompleteDownloadTempCacheFolder; 102 | 103 | @end 104 | 105 | NS_ASSUME_NONNULL_END 106 | 107 | -------------------------------------------------------------------------------- /WB_NeiApiManager/YTKNetwork/YTKChainRequest.h: -------------------------------------------------------------------------------- 1 | // 2 | // YTKChainRequest.h 3 | // 4 | // Copyright (c) 2012-2016 YTKNetwork https://github.com/yuantiku 5 | // 6 | // Permission is hereby granted, free of charge, to any person obtaining a copy 7 | // of this software and associated documentation files (the "Software"), to deal 8 | // in the Software without restriction, including without limitation the rights 9 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | // copies of the Software, and to permit persons to whom the Software is 11 | // furnished to do so, subject to the following conditions: 12 | // 13 | // The above copyright notice and this permission notice shall be included in 14 | // all copies or substantial portions of the Software. 15 | // 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | // THE SOFTWARE. 23 | 24 | #import 25 | 26 | NS_ASSUME_NONNULL_BEGIN 27 | 28 | @class YTKChainRequest; 29 | @class YTKBaseRequest; 30 | @protocol YTKRequestAccessory; 31 | 32 | /// The YTKChainRequestDelegate protocol defines several optional methods you can use 33 | /// to receive network-related messages. All the delegate methods will be called 34 | /// on the main queue. Note the delegate methods will be called when all the requests 35 | /// of chain request finishes. 36 | @protocol YTKChainRequestDelegate 37 | 38 | @optional 39 | /// Tell the delegate that the chain request has finished successfully. 40 | /// 41 | /// @param chainRequest The corresponding chain request. 42 | - (void)chainRequestFinished:(YTKChainRequest *)chainRequest; 43 | 44 | /// Tell the delegate that the chain request has failed. 45 | /// 46 | /// @param chainRequest The corresponding chain request. 47 | /// @param request First failed request that causes the whole request to fail. 48 | - (void)chainRequestFailed:(YTKChainRequest *)chainRequest failedBaseRequest:(YTKBaseRequest*)request; 49 | 50 | @end 51 | 52 | typedef void (^YTKChainCallback)(YTKChainRequest *chainRequest, YTKBaseRequest *baseRequest); 53 | 54 | /// YTKBatchRequest can be used to chain several YTKRequest so that one will only starts after another finishes. 55 | /// Note that when used inside YTKChainRequest, a single YTKRequest will have its own callback and delegate 56 | /// cleared, in favor of the batch request callback. 57 | @interface YTKChainRequest : NSObject 58 | 59 | /// All the requests are stored in this array. 60 | - (NSArray *)requestArray; 61 | 62 | /// The delegate object of the chain request. Default is nil. 63 | @property (nonatomic, weak, nullable) id delegate; 64 | 65 | /// This can be used to add several accossories object. Note if you use `addAccessory` to add acceesory 66 | /// this array will be automatically created. Default is nil. 67 | @property (nonatomic, strong, nullable) NSMutableArray> *requestAccessories; 68 | 69 | /// Convenience method to add request accessory. See also `requestAccessories`. 70 | - (void)addAccessory:(id)accessory; 71 | 72 | /// Start the chain request, adding first request in the chain to request queue. 73 | - (void)start; 74 | 75 | /// Stop the chain request. Remaining request in chain will be cancelled. 76 | - (void)stop; 77 | 78 | /// Add request to request chain. 79 | /// 80 | /// @param request The request to be chained. 81 | /// @param callback The finish callback 82 | - (void)addRequest:(YTKBaseRequest *)request callback:(nullable YTKChainCallback)callback; 83 | 84 | @end 85 | 86 | NS_ASSUME_NONNULL_END 87 | -------------------------------------------------------------------------------- /WB_NeiApiManager/YTKNetwork/YTKNetworkConfig.h: -------------------------------------------------------------------------------- 1 | // 2 | // YTKNetworkConfig.h 3 | // 4 | // Copyright (c) 2012-2016 YTKNetwork https://github.com/yuantiku 5 | // 6 | // Permission is hereby granted, free of charge, to any person obtaining a copy 7 | // of this software and associated documentation files (the "Software"), to deal 8 | // in the Software without restriction, including without limitation the rights 9 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | // copies of the Software, and to permit persons to whom the Software is 11 | // furnished to do so, subject to the following conditions: 12 | // 13 | // The above copyright notice and this permission notice shall be included in 14 | // all copies or substantial portions of the Software. 15 | // 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | // THE SOFTWARE. 23 | 24 | #import 25 | 26 | NS_ASSUME_NONNULL_BEGIN 27 | 28 | @class YTKBaseRequest; 29 | @class AFSecurityPolicy; 30 | 31 | /// YTKUrlFilterProtocol can be used to append common parameters to requests before sending them. 32 | @protocol YTKUrlFilterProtocol 33 | /// Preprocess request URL before actually sending them. 34 | /// 35 | /// @param originUrl request's origin URL, which is returned by `requestUrl` 36 | /// @param request request itself 37 | /// 38 | /// @return A new url which will be used as a new `requestUrl` 39 | - (NSString *)filterUrl:(NSString *)originUrl withRequest:(YTKBaseRequest *)request; 40 | @end 41 | 42 | /// YTKCacheDirPathFilterProtocol can be used to append common path components when caching response results 43 | @protocol YTKCacheDirPathFilterProtocol 44 | /// Preprocess cache path before actually saving them. 45 | /// 46 | /// @param originPath original base cache path, which is generated in `YTKRequest` class. 47 | /// @param request request itself 48 | /// 49 | /// @return A new path which will be used as base path when caching. 50 | - (NSString *)filterCacheDirPath:(NSString *)originPath withRequest:(YTKBaseRequest *)request; 51 | @end 52 | 53 | /// YTKNetworkConfig stored global network-related configurations, which will be used in `YTKNetworkAgent` 54 | /// to form and filter requests, as well as caching response. 55 | @interface YTKNetworkConfig : NSObject 56 | 57 | - (instancetype)init NS_UNAVAILABLE; 58 | + (instancetype)new NS_UNAVAILABLE; 59 | 60 | /// Return a shared config object. 61 | + (YTKNetworkConfig *)sharedConfig; 62 | 63 | /// Request base URL, such as "http://www.yuantiku.com". Default is empty string. 64 | @property (nonatomic, strong) NSString *baseUrl; 65 | /// Request CDN URL. Default is empty string. 66 | @property (nonatomic, strong) NSString *cdnUrl; 67 | /// URL filters. See also `YTKUrlFilterProtocol`. 68 | @property (nonatomic, strong, readonly) NSArray> *urlFilters; 69 | /// Cache path filters. See also `YTKCacheDirPathFilterProtocol`. 70 | @property (nonatomic, strong, readonly) NSArray> *cacheDirPathFilters; 71 | /// Security policy will be used by AFNetworking. See also `AFSecurityPolicy`. 72 | @property (nonatomic, strong) AFSecurityPolicy *securityPolicy; 73 | /// Whether to log debug info. Default is NO; 74 | @property (nonatomic) BOOL debugLogEnabled; 75 | /// SessionConfiguration will be used to initialize AFHTTPSessionManager. Default is nil. 76 | @property (nonatomic, strong) NSURLSessionConfiguration* sessionConfiguration; 77 | 78 | /// Add a new URL filter. 79 | - (void)addUrlFilter:(id)filter; 80 | /// Remove all URL filters. 81 | - (void)clearUrlFilter; 82 | /// Add a new cache path filter 83 | - (void)addCacheDirPathFilter:(id)filter; 84 | /// Clear all cache path filters. 85 | - (void)clearCacheDirPathFilter; 86 | 87 | @end 88 | 89 | NS_ASSUME_NONNULL_END 90 | -------------------------------------------------------------------------------- /WB_NeiApiManager/YTKNetwork/YTKRequest.h: -------------------------------------------------------------------------------- 1 | // 2 | // YTKRequest.h 3 | // 4 | // Copyright (c) 2012-2016 YTKNetwork https://github.com/yuantiku 5 | // 6 | // Permission is hereby granted, free of charge, to any person obtaining a copy 7 | // of this software and associated documentation files (the "Software"), to deal 8 | // in the Software without restriction, including without limitation the rights 9 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | // copies of the Software, and to permit persons to whom the Software is 11 | // furnished to do so, subject to the following conditions: 12 | // 13 | // The above copyright notice and this permission notice shall be included in 14 | // all copies or substantial portions of the Software. 15 | // 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | // THE SOFTWARE. 23 | 24 | #import "YTKBaseRequest.h" 25 | 26 | NS_ASSUME_NONNULL_BEGIN 27 | 28 | FOUNDATION_EXPORT NSString *const YTKRequestCacheErrorDomain; 29 | 30 | NS_ENUM(NSInteger) { 31 | YTKRequestCacheErrorExpired = -1, 32 | YTKRequestCacheErrorVersionMismatch = -2, 33 | YTKRequestCacheErrorSensitiveDataMismatch = -3, 34 | YTKRequestCacheErrorAppVersionMismatch = -4, 35 | YTKRequestCacheErrorInvalidCacheTime = -5, 36 | YTKRequestCacheErrorInvalidMetadata = -6, 37 | YTKRequestCacheErrorInvalidCacheData = -7, 38 | }; 39 | 40 | /// YTKRequest is the base class you should inherit to create your own request class. 41 | /// Based on YTKBaseRequest, YTKRequest adds local caching feature. Note download 42 | /// request will not be cached whatsoever, because download request may involve complicated 43 | /// cache control policy controlled by `Cache-Control`, `Last-Modified`, etc. 44 | @interface YTKRequest : YTKBaseRequest 45 | 46 | /// Whether to use cache as response or not. 47 | /// Default is NO, which means caching will take effect with specific arguments. 48 | /// Note that `cacheTimeInSeconds` default is -1. As a result cache data is not actually 49 | /// used as response unless you return a positive value in `cacheTimeInSeconds`. 50 | /// 51 | /// Also note that this option does not affect storing the response, which means response will always be saved 52 | /// even `ignoreCache` is YES. 53 | @property (nonatomic) BOOL ignoreCache; 54 | 55 | /// Whether data is from local cache. 56 | - (BOOL)isDataFromCache; 57 | 58 | /// Manually load cache from storage. 59 | /// 60 | /// @param error If an error occurred causing cache loading failed, an error object will be passed, otherwise NULL. 61 | /// 62 | /// @return Whether cache is successfully loaded. 63 | - (BOOL)loadCacheWithError:(NSError * __autoreleasing *)error; 64 | 65 | /// Start request without reading local cache even if it exists. Use this to update local cache. 66 | - (void)startWithoutCache; 67 | 68 | /// Save response data (probably from another request) to this request's cache location 69 | - (void)saveResponseDataToCacheFile:(NSData *)data; 70 | 71 | #pragma mark - Subclass Override 72 | 73 | /// The max time duration that cache can stay in disk until it's considered expired. 74 | /// Default is -1, which means response is not actually saved as cache. 75 | - (NSInteger)cacheTimeInSeconds; 76 | 77 | /// Version can be used to identify and invalidate local cache. Default is 0. 78 | - (long long)cacheVersion; 79 | 80 | /// This can be used as additional identifier that tells the cache needs updating. 81 | /// 82 | /// @discussion The `description` string of this object will be used as an identifier to verify whether cache 83 | /// is invalid. Using `NSArray` or `NSDictionary` as return value type is recommended. However, 84 | /// If you intend to use your custom class type, make sure that `description` is correctly implemented. 85 | - (nullable id)cacheSensitiveData; 86 | 87 | /// Whether cache is asynchronously written to storage. Default is YES. 88 | - (BOOL)writeCacheAsynchronously; 89 | 90 | @end 91 | 92 | NS_ASSUME_NONNULL_END 93 | -------------------------------------------------------------------------------- /WB_NeiApiManager/YTKNetwork/YTKBatchRequest.h: -------------------------------------------------------------------------------- 1 | // 2 | // YTKBatchRequest.h 3 | // 4 | // Copyright (c) 2012-2016 YTKNetwork https://github.com/yuantiku 5 | // 6 | // Permission is hereby granted, free of charge, to any person obtaining a copy 7 | // of this software and associated documentation files (the "Software"), to deal 8 | // in the Software without restriction, including without limitation the rights 9 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | // copies of the Software, and to permit persons to whom the Software is 11 | // furnished to do so, subject to the following conditions: 12 | // 13 | // The above copyright notice and this permission notice shall be included in 14 | // all copies or substantial portions of the Software. 15 | // 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | // THE SOFTWARE. 23 | 24 | #import 25 | 26 | NS_ASSUME_NONNULL_BEGIN 27 | 28 | @class YTKRequest; 29 | @class YTKBatchRequest; 30 | @protocol YTKRequestAccessory; 31 | 32 | /// The YTKBatchRequestDelegate protocol defines several optional methods you can use 33 | /// to receive network-related messages. All the delegate methods will be called 34 | /// on the main queue. Note the delegate methods will be called when all the requests 35 | /// of batch request finishes. 36 | @protocol YTKBatchRequestDelegate 37 | 38 | @optional 39 | /// Tell the delegate that the batch request has finished successfully/ 40 | /// 41 | /// @param batchRequest The corresponding batch request. 42 | - (void)batchRequestFinished:(YTKBatchRequest *)batchRequest; 43 | 44 | /// Tell the delegate that the batch request has failed. 45 | /// 46 | /// @param batchRequest The corresponding batch request. 47 | - (void)batchRequestFailed:(YTKBatchRequest *)batchRequest; 48 | 49 | @end 50 | 51 | /// YTKBatchRequest can be used to batch several YTKRequest. Note that when used inside YTKBatchRequest, a single 52 | /// YTKRequest will have its own callback and delegate cleared, in favor of the batch request callback. 53 | @interface YTKBatchRequest : NSObject 54 | 55 | /// All the requests are stored in this array. 56 | @property (nonatomic, strong, readonly) NSArray *requestArray; 57 | 58 | /// The delegate object of the batch request. Default is nil. 59 | @property (nonatomic, weak, nullable) id delegate; 60 | 61 | /// The success callback. Note this will be called only if all the requests are finished. 62 | /// This block will be called on the main queue. 63 | @property (nonatomic, copy, nullable) void (^successCompletionBlock)(YTKBatchRequest *); 64 | 65 | /// The failure callback. Note this will be called if one of the requests fails. 66 | /// This block will be called on the main queue. 67 | @property (nonatomic, copy, nullable) void (^failureCompletionBlock)(YTKBatchRequest *); 68 | 69 | /// Tag can be used to identify batch request. Default value is 0. 70 | @property (nonatomic) NSInteger tag; 71 | 72 | /// This can be used to add several accossories object. Note if you use `addAccessory` to add acceesory 73 | /// this array will be automatically created. Default is nil. 74 | @property (nonatomic, strong, nullable) NSMutableArray> *requestAccessories; 75 | 76 | /// The first request that failed (and causing the batch request to fail). 77 | @property (nonatomic, strong, readonly, nullable) YTKRequest *failedRequest; 78 | 79 | /// Creates a `YTKBatchRequest` with a bunch of requests. 80 | /// 81 | /// @param requestArray requests useds to create batch request. 82 | /// 83 | - (instancetype)initWithRequestArray:(NSArray *)requestArray; 84 | 85 | /// Set completion callbacks 86 | - (void)setCompletionBlockWithSuccess:(nullable void (^)(YTKBatchRequest *batchRequest))success 87 | failure:(nullable void (^)(YTKBatchRequest *batchRequest))failure; 88 | 89 | /// Nil out both success and failure callback blocks. 90 | - (void)clearCompletionBlock; 91 | 92 | /// Convenience method to add request accessory. See also `requestAccessories`. 93 | - (void)addAccessory:(id)accessory; 94 | 95 | /// Append all the requests to queue. 96 | - (void)start; 97 | 98 | /// Stop all the requests of the batch request. 99 | - (void)stop; 100 | 101 | /// Convenience method to start the batch request with block callbacks. 102 | - (void)startWithCompletionBlockWithSuccess:(nullable void (^)(YTKBatchRequest *batchRequest))success 103 | failure:(nullable void (^)(YTKBatchRequest *batchRequest))failure; 104 | 105 | /// Whether all response data is from local cache. 106 | - (BOOL)isDataFromCache; 107 | 108 | 109 | 110 | @end 111 | 112 | NS_ASSUME_NONNULL_END 113 | -------------------------------------------------------------------------------- /WB_NeiApiManager/YTKNetwork/YTKChainRequest.m: -------------------------------------------------------------------------------- 1 | // 2 | // YTKChainRequest.m 3 | // 4 | // Copyright (c) 2012-2016 YTKNetwork https://github.com/yuantiku 5 | // 6 | // Permission is hereby granted, free of charge, to any person obtaining a copy 7 | // of this software and associated documentation files (the "Software"), to deal 8 | // in the Software without restriction, including without limitation the rights 9 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | // copies of the Software, and to permit persons to whom the Software is 11 | // furnished to do so, subject to the following conditions: 12 | // 13 | // The above copyright notice and this permission notice shall be included in 14 | // all copies or substantial portions of the Software. 15 | // 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | // THE SOFTWARE. 23 | 24 | #import "YTKChainRequest.h" 25 | #import "YTKChainRequestAgent.h" 26 | #import "YTKNetworkPrivate.h" 27 | #import "YTKBaseRequest.h" 28 | 29 | @interface YTKChainRequest() 30 | 31 | @property (strong, nonatomic) NSMutableArray *requestArray; 32 | @property (strong, nonatomic) NSMutableArray *requestCallbackArray; 33 | @property (assign, nonatomic) NSUInteger nextRequestIndex; 34 | @property (strong, nonatomic) YTKChainCallback emptyCallback; 35 | 36 | @end 37 | 38 | @implementation YTKChainRequest 39 | 40 | - (instancetype)init { 41 | self = [super init]; 42 | if (self) { 43 | _nextRequestIndex = 0; 44 | _requestArray = [NSMutableArray array]; 45 | _requestCallbackArray = [NSMutableArray array]; 46 | _emptyCallback = ^(YTKChainRequest *chainRequest, YTKBaseRequest *baseRequest) { 47 | // do nothing 48 | }; 49 | } 50 | return self; 51 | } 52 | 53 | - (void)start { 54 | if (_nextRequestIndex > 0) { 55 | YTKLog(@"Error! Chain request has already started."); 56 | return; 57 | } 58 | 59 | if ([_requestArray count] > 0) { 60 | [self toggleAccessoriesWillStartCallBack]; 61 | [self startNextRequest]; 62 | [[YTKChainRequestAgent sharedAgent] addChainRequest:self]; 63 | } else { 64 | YTKLog(@"Error! Chain request array is empty."); 65 | } 66 | } 67 | 68 | - (void)stop { 69 | [self toggleAccessoriesWillStopCallBack]; 70 | [self clearRequest]; 71 | [[YTKChainRequestAgent sharedAgent] removeChainRequest:self]; 72 | [self toggleAccessoriesDidStopCallBack]; 73 | } 74 | 75 | - (void)addRequest:(YTKBaseRequest *)request callback:(YTKChainCallback)callback { 76 | [_requestArray addObject:request]; 77 | if (callback != nil) { 78 | [_requestCallbackArray addObject:callback]; 79 | } else { 80 | [_requestCallbackArray addObject:_emptyCallback]; 81 | } 82 | } 83 | 84 | - (NSArray *)requestArray { 85 | return _requestArray; 86 | } 87 | 88 | - (BOOL)startNextRequest { 89 | if (_nextRequestIndex < [_requestArray count]) { 90 | YTKBaseRequest *request = _requestArray[_nextRequestIndex]; 91 | _nextRequestIndex++; 92 | request.delegate = self; 93 | [request clearCompletionBlock]; 94 | [request start]; 95 | return YES; 96 | } else { 97 | return NO; 98 | } 99 | } 100 | 101 | #pragma mark - Network Request Delegate 102 | 103 | - (void)requestFinished:(YTKBaseRequest *)request { 104 | NSUInteger currentRequestIndex = _nextRequestIndex - 1; 105 | YTKChainCallback callback = _requestCallbackArray[currentRequestIndex]; 106 | callback(self, request); 107 | if (![self startNextRequest]) { 108 | [self toggleAccessoriesWillStopCallBack]; 109 | if ([_delegate respondsToSelector:@selector(chainRequestFinished:)]) { 110 | [_delegate chainRequestFinished:self]; 111 | [[YTKChainRequestAgent sharedAgent] removeChainRequest:self]; 112 | } 113 | [self toggleAccessoriesDidStopCallBack]; 114 | } 115 | } 116 | 117 | - (void)requestFailed:(YTKBaseRequest *)request { 118 | [self toggleAccessoriesWillStopCallBack]; 119 | if ([_delegate respondsToSelector:@selector(chainRequestFailed:failedBaseRequest:)]) { 120 | [_delegate chainRequestFailed:self failedBaseRequest:request]; 121 | [[YTKChainRequestAgent sharedAgent] removeChainRequest:self]; 122 | } 123 | [self toggleAccessoriesDidStopCallBack]; 124 | } 125 | 126 | - (void)clearRequest { 127 | NSUInteger currentRequestIndex = _nextRequestIndex - 1; 128 | if (currentRequestIndex < [_requestArray count]) { 129 | YTKBaseRequest *request = _requestArray[currentRequestIndex]; 130 | [request stop]; 131 | } 132 | [_requestArray removeAllObjects]; 133 | [_requestCallbackArray removeAllObjects]; 134 | } 135 | 136 | #pragma mark - Request Accessoies 137 | 138 | - (void)addAccessory:(id)accessory { 139 | if (!self.requestAccessories) { 140 | self.requestAccessories = [NSMutableArray array]; 141 | } 142 | [self.requestAccessories addObject:accessory]; 143 | } 144 | 145 | @end 146 | -------------------------------------------------------------------------------- /WB_NetApiManager使用说明.md: -------------------------------------------------------------------------------- 1 | WB_NetApiManager 介绍 2 | ===================== 3 | 4 | 最近闲来无事,整理了前几个项目做得积累的经验...基于YTKNetwork进行再封装,实现TYKNetwork一些基本的使用 5 | 6 | 因为没有服务器..我就不做demo了 封装的网络请求较为简单想要测一下很简单...并且经历了好几个项目的测试的,,,这个其实就是把之前项目的代码整理起来的...用起来不会出什么问题 7 | 8 | 入门级封装 各位大大有什么好的意见和建议请联系我 9 | 10 | QQ 413151868 11 | 12 | 13 | ## WB_NetApiManager 基本组成 14 | 15 | 16 | #########注意事项########### 17 | 1.PCH要引用 #import "WB_NetApiMacro.h" 18 | 19 | 2.如果 是http请求 请在info.plist里进行修改 具体修改自行百度 20 | 21 | 3.AFNetworking可以使用cocopod 但是YTKNetwork不要使用...因为我对YTKNetwork部分代码进行修改例如适配text/html..打印获取的数据等 22 | 23 | #pragma mark -----代码 24 | ------------------------- 25 | platform :ios, ‘8.0’ 26 | 27 | target '项目名称' do 28 | 29 | pod 'AFNetworking', '~> 3.0' 30 | 31 | end 32 | 33 | ---------------------------------- 34 | 35 | 36 | WB_NetApiManager 包括以下几个基本的类: 37 | 38 | * WB_ArgumentFilterProtocol 类:用于配置全局参数,比如版本号 39 | * WB_BaseRequest 类:网络请求基类 所有的网络请求继承这个方法 40 | * WB_Request 类:继承WB_BaseRequest类 获取数据API的基类,所有获取数据的API 都需要继承于这个方法 41 | * WB_UploadImageRequest 类:上传图片API的基类,所有上传图片的API 都需要继承于这个方法 如果批量上传图片 请使用下面的类 42 | * WB_BatchUploadImgRequest 类:批量上传图片api 43 | * WB_NetApiConstant 类 : 定义全局常量 初始化网络请求api 44 | 45 | * WB_NetApiMacro : 配置公共参数 46 | 47 | 48 | 下面简单介绍下网络获取和批量上传图片的使用 49 | 50 | ### WB_NetApiMacro 51 | 52 | 配置公共参数 53 | 54 | 1 请求方式 GET POST 55 | 2 统一管理接口地址..方便正式服务器和测试服务器之间的切换 方便开发 56 | 3 打印输入的宏写在这里面 57 | 58 | ### WB_NetApiConstant 类 59 | 60 | 程序运行是要打开api 61 | 62 | ```objectivec 63 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 64 | // Override point for customization after application launch. 65 | 66 | self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen] bounds]]; 67 | 68 | //初始化网络请求 69 | [self initRequest]; 70 | 71 | [self initWindow]; 72 | 73 | self.window.backgroundColor = [UIColor whiteColor]; 74 | [self.window makeKeyAndVisible]; 75 | 76 | 77 | return YES; 78 | } 79 | 80 | #pragma mark ————— 初始化网络请求 ————— 81 | -(void)initRequest{ 82 | 83 | [WB_NetApiConstant sharedInstance]; 84 | 85 | } 86 | 87 | ``` 88 | ### WB_Request 类 获取接口数据继承此类 89 | 90 | 看代码 91 | 1 创建api继承与此类 初始化方法带参数 92 | ```objectivec 93 | 94 | #import "WB_Request.h" 95 | 96 | @interface HomeNetApi : WB_Request 97 | 98 | 99 | -(id)initWithPageNum:(NSInteger )pagenum; 100 | 101 | 102 | @end 103 | 104 | ``` 105 | 2 配置接口地址和传参 106 | ```objectivec 107 | #import "HomeNetApi.h" 108 | 109 | @implementation HomeNetApi 110 | { 111 | NSInteger _pagenum; 112 | } 113 | -(id)initWithPageNum:(NSInteger )pagenum 114 | { 115 | if (self = [super init]) 116 | { 117 | _pagenum = pagenum; 118 | } 119 | 120 | return self; 121 | } 122 | 123 | ###########接口地址######### 124 | -(NSString *)requestUrl 125 | { 126 | return @"home/index/start"; 127 | } 128 | #########传参############# 129 | -(id)requestArgument 130 | { 131 | return @{ 132 | @"pagenum" :@(_pagenum), 133 | }; 134 | } 135 | 136 | @end 137 | 138 | ``` 139 | 3 调用api 开始网络请求 140 | ```objectivec 141 | 142 | HomeNetApi *api = [[HomeNetApi alloc] initWithPageNum:0]; 143 | [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) { 144 | 145 | } failure:^(__kindof YTKBaseRequest * _Nonnull request) { 146 | 147 | }]; 148 | 149 | ``` 150 | 151 | ### WB_BatchUploadImgRequest 类 批量上传图片 152 | 153 | 154 | 批量上传图片只有一个方法..实现就好 如果有获取每一张上传图片的上传进度...有一个代理实现就可以实时获取上传进度 155 | 156 | 看代码 157 | 158 | 1 实现初始化方法 : -(instancetype)initWithImgArray:(NSMutableArray *)imgArray; 159 | 160 | ```objectivec 161 | NSMutableArray *arr = [NSMutableArray arrayWithObject:_img.image]; 162 | [arr addObject:_second.image]; 163 | WB_BatchUploadImgRequest *api = [[WB_BatchUploadImgRequest alloc] initWithImgArray:arr]; 164 | api.mDelegate = self; 165 | [api startWithCompletionBlockWithSuccess:^(YTKBatchRequest * _Nonnull batchRequest) { 166 | NSLog(@"succeed"); 167 | //图片上传成功 168 | NSArray *requests = batchRequest.requestArray; 169 | //获取每张图片返回的图片名 170 | WB_UploadImageRequest *api = (WB_UploadImageRequest *)requests[0]; 171 | [api getContent]; 172 | } failure:^(YTKBatchRequest * _Nonnull batchRequest) { 173 | NSLog(@"failed"); 174 | }]; 175 | 176 | ``` 177 | 178 | 2 代理获取上传进度 实现代理方法 -(void)upBatchRequestProgressWithApiTag:(NSInteger )apiTag andProgress:(NSProgress *)progress; 179 | ```objectivec 180 | 181 | -(void)upBatchRequestProgressWithApiTag:(NSInteger )apiTag andProgress:(NSProgress *)progress 182 | { 183 | NSLog(@"第%ld张图片加载了%.2f------------",apiTag,progress.fractionCompleted); 184 | } 185 | 186 | ``` 187 | 188 | 189 | 190 | ## 其他说明 191 | 请求头 在WB_Request类里第32行添加请求头 192 | 193 | 194 | 网络请求的处理和断网提醒在YTKNetworkAgent的第670-700行 195 | 196 | 关于数据返回要提一句 为了方便开发 网络请求成功会返回对应的jsonStr和相对应的字典转成的属性 197 | 198 | 创建model后吧需要的属性粘贴进去就好..大大节省了开发时间 199 | 200 | 201 | 下面是打印的效果 会打印出每一个字段对应的属性 用的是否直接粘贴就好 202 | 203 | 204 | ``` 控制台 205 | 2017-09-28 12:05:13.700320+0800 WB_iOS_FrameWork[3677:299879] 206 | @property (nonatomic ,copy) NSString *time; 207 | 208 | @property (nonatomic ,copy) NSString *appModel; 209 | 210 | @property (nonatomic ,copy) NSString *title; 211 | 212 | @property (nonatomic ,copy) NSString *name; 213 | 214 | @property (nonatomic ,copy) NSString *adPic; 215 | 216 | @property (nonatomic ,copy) NSString *seller_id; 217 | 2017-09-28 12:05:13.700637+0800 WB_iOS_FrameWork[3677:299879] 218 | @property (nonatomic ,copy) NSString *title; 219 | 220 | @property (nonatomic ,copy) NSString *icon; 221 | 222 | @property (nonatomic ,copy) NSString *type; 223 | ``` 224 | 225 | 226 | 227 | 228 | 229 | 以上几个示例代码在 Demo 工程中也可获得。 230 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WB_NeiApiManager 2 | 基于猿题库网络请求再次封装 3 | 4 | 5 | 6 | WB_NetApiManager 介绍 7 | ===================== 8 | 9 | 最近闲来无事,整理了前几个项目做得积累的经验...基于YTKNetwork进行再封装,实现TYKNetwork一些基本的使用 10 | 11 | 因为没有服务器..我就不做demo了 封装的网络请求较为简单想要测一下很简单...并且经历了好几个项目的测试的,,,这个其实就是把之前项目的代码整理起来的...用起来不会出什么问题 12 | 13 | 入门级封装 各位大大有什么好的意见和建议请联系我 14 | 15 | QQ 413151868 16 | 17 | 18 | ## WB_NetApiManager 基本组成 19 | 20 | 21 | #########注意事项########### 22 | 1.PCH要引用 #import "WB_NetApiMacro.h" 23 | 24 | 2.如果 是http请求 请在info.plist里进行修改 具体修改自行百度 25 | 26 | 3.AFNetworking可以使用cocopod 但是YTKNetwork不要使用...因为我对YTKNetwork部分代码进行修改例如适配text/html..打印获取的数据等 27 | 28 | #pragma mark -----代码 29 | ------------------------- 30 | platform :ios, ‘8.0’ 31 | 32 | target '项目名称' do 33 | 34 | pod 'AFNetworking', '~> 3.0' 35 | 36 | end 37 | 38 | ---------------------------------- 39 | 40 | 41 | WB_NetApiManager 包括以下几个基本的类: 42 | 43 | * WB_ArgumentFilterProtocol 类:用于配置全局参数,比如版本号 44 | * WB_BaseRequest 类:网络请求基类 所有的网络请求继承这个方法 45 | * WB_Request 类:继承WB_BaseRequest类 获取数据API的基类,所有获取数据的API 都需要继承于这个方法 46 | * WB_UploadImageRequest 类:上传图片API的基类,所有上传图片的API 都需要继承于这个方法 如果批量上传图片 请使用下面的类 47 | * WB_BatchUploadImgRequest 类:批量上传图片api 48 | * WB_NetApiConstant 类 : 定义全局常量 初始化网络请求api 49 | 50 | * WB_NetApiMacro : 配置公共参数 51 | 52 | 53 | 下面简单介绍下网络获取和批量上传图片的使用 54 | 55 | ### WB_NetApiMacro 56 | 57 | 配置公共参数 58 | 59 | 1 请求方式 GET POST 60 | 2 统一管理接口地址..方便正式服务器和测试服务器之间的切换 方便开发 61 | 3 打印输入的宏写在这里面 62 | 63 | ### WB_NetApiConstant 类 64 | 65 | 程序运行是要打开api 66 | 67 | ```objectivec 68 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 69 | // Override point for customization after application launch. 70 | 71 | self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen] bounds]]; 72 | 73 | //初始化网络请求 74 | [self initRequest]; 75 | 76 | [self initWindow]; 77 | 78 | self.window.backgroundColor = [UIColor whiteColor]; 79 | [self.window makeKeyAndVisible]; 80 | 81 | 82 | return YES; 83 | } 84 | 85 | #pragma mark ————— 初始化网络请求 ————— 86 | -(void)initRequest{ 87 | 88 | [WB_NetApiConstant sharedInstance]; 89 | 90 | } 91 | 92 | ``` 93 | ### WB_Request 类 获取接口数据继承此类 94 | 95 | 看代码 96 | 1 创建api继承与此类 初始化方法带参数 97 | ```objectivec 98 | 99 | #import "WB_Request.h" 100 | 101 | @interface HomeNetApi : WB_Request 102 | 103 | 104 | -(id)initWithPageNum:(NSInteger )pagenum; 105 | 106 | 107 | @end 108 | 109 | ``` 110 | 2 配置接口地址和传参 111 | ```objectivec 112 | #import "HomeNetApi.h" 113 | 114 | @implementation HomeNetApi 115 | { 116 | NSInteger _pagenum; 117 | } 118 | -(id)initWithPageNum:(NSInteger )pagenum 119 | { 120 | if (self = [super init]) 121 | { 122 | _pagenum = pagenum; 123 | } 124 | 125 | return self; 126 | } 127 | 128 | ###########接口地址######### 129 | -(NSString *)requestUrl 130 | { 131 | return @"home/index/start"; 132 | } 133 | #########传参############# 134 | -(id)requestArgument 135 | { 136 | return @{ 137 | @"pagenum" :@(_pagenum), 138 | }; 139 | } 140 | 141 | @end 142 | 143 | ``` 144 | 3 调用api 开始网络请求 145 | ```objectivec 146 | 147 | HomeNetApi *api = [[HomeNetApi alloc] initWithPageNum:0]; 148 | [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) { 149 | 150 | } failure:^(__kindof YTKBaseRequest * _Nonnull request) { 151 | 152 | }]; 153 | 154 | ``` 155 | 156 | ### WB_BatchUploadImgRequest 类 批量上传图片 157 | 158 | 159 | 批量上传图片只有一个方法..实现就好 如果有获取每一张上传图片的上传进度...有一个代理实现就可以实时获取上传进度 160 | 161 | 看代码 162 | 163 | 1 实现初始化方法 : -(instancetype)initWithImgArray:(NSMutableArray *)imgArray; 164 | 165 | ```objectivec 166 | NSMutableArray *arr = [NSMutableArray arrayWithObject:_img.image]; 167 | [arr addObject:_second.image]; 168 | WB_BatchUploadImgRequest *api = [[WB_BatchUploadImgRequest alloc] initWithImgArray:arr]; 169 | api.mDelegate = self; 170 | [api startWithCompletionBlockWithSuccess:^(YTKBatchRequest * _Nonnull batchRequest) { 171 | NSLog(@"succeed"); 172 | //图片上传成功 173 | NSArray *requests = batchRequest.requestArray; 174 | //获取每张图片返回的图片名 175 | WB_UploadImageRequest *api = (WB_UploadImageRequest *)requests[0]; 176 | [api getContent]; 177 | } failure:^(YTKBatchRequest * _Nonnull batchRequest) { 178 | NSLog(@"failed"); 179 | }]; 180 | 181 | ``` 182 | 183 | 2 代理获取上传进度 实现代理方法 -(void)upBatchRequestProgressWithApiTag:(NSInteger )apiTag andProgress:(NSProgress *)progress; 184 | ```objectivec 185 | 186 | -(void)upBatchRequestProgressWithApiTag:(NSInteger )apiTag andProgress:(NSProgress *)progress 187 | { 188 | NSLog(@"第%ld张图片加载了%.2f------------",apiTag,progress.fractionCompleted); 189 | } 190 | 191 | ``` 192 | 193 | 194 | 195 | ## 其他说明 196 | 请求头 在WB_Request类里第32行添加请求头 197 | 198 | 199 | 网络请求的处理和断网提醒在YTKNetworkAgent的第670-700行 200 | 201 | 关于数据返回要提一句 为了方便开发 网络请求成功会返回对应的jsonStr和相对应的字典转成的属性 202 | 203 | 创建model后吧需要的属性粘贴进去就好..大大节省了开发时间 204 | 205 | 206 | 下面是打印的效果 会打印出每一个字段对应的属性 用的是否直接粘贴就好 207 | 208 | 209 | ``` 控制台 210 | 2017-09-28 12:05:13.700320+0800 WB_iOS_FrameWork[3677:299879] 211 | @property (nonatomic ,copy) NSString *time; 212 | 213 | @property (nonatomic ,copy) NSString *appModel; 214 | 215 | @property (nonatomic ,copy) NSString *title; 216 | 217 | @property (nonatomic ,copy) NSString *name; 218 | 219 | @property (nonatomic ,copy) NSString *adPic; 220 | 221 | @property (nonatomic ,copy) NSString *seller_id; 222 | 2017-09-28 12:05:13.700637+0800 WB_iOS_FrameWork[3677:299879] 223 | @property (nonatomic ,copy) NSString *title; 224 | 225 | @property (nonatomic ,copy) NSString *icon; 226 | 227 | @property (nonatomic ,copy) NSString *type; 228 | ``` 229 | 230 | 231 | 232 | 233 | 234 | 以上几个示例代码在 Demo 工程中也可获得。 235 | -------------------------------------------------------------------------------- /WB_NeiApiManager/YTKNetwork/YTKBatchRequest.m: -------------------------------------------------------------------------------- 1 | // 2 | // YTKBatchRequest.m 3 | // 4 | // Copyright (c) 2012-2016 YTKNetwork https://github.com/yuantiku 5 | // 6 | // Permission is hereby granted, free of charge, to any person obtaining a copy 7 | // of this software and associated documentation files (the "Software"), to deal 8 | // in the Software without restriction, including without limitation the rights 9 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | // copies of the Software, and to permit persons to whom the Software is 11 | // furnished to do so, subject to the following conditions: 12 | // 13 | // The above copyright notice and this permission notice shall be included in 14 | // all copies or substantial portions of the Software. 15 | // 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | // THE SOFTWARE. 23 | 24 | #import "YTKBatchRequest.h" 25 | #import "YTKNetworkPrivate.h" 26 | #import "YTKBatchRequestAgent.h" 27 | #import "YTKRequest.h" 28 | 29 | @interface YTKBatchRequest() 30 | 31 | @property (nonatomic) NSInteger finishedCount; 32 | 33 | @end 34 | 35 | @implementation YTKBatchRequest 36 | 37 | - (instancetype)initWithRequestArray:(NSArray *)requestArray { 38 | self = [super init]; 39 | if (self) { 40 | _requestArray = [requestArray copy]; 41 | _finishedCount = 0; 42 | for (YTKRequest * req in _requestArray) { 43 | if (![req isKindOfClass:[YTKRequest class]]) { 44 | YTKLog(@"Error, request item must be YTKRequest instance."); 45 | return nil; 46 | } 47 | } 48 | } 49 | return self; 50 | } 51 | 52 | - (void)start { 53 | if (_finishedCount > 0) { 54 | YTKLog(@"Error! Batch request has already started."); 55 | return; 56 | } 57 | _failedRequest = nil; 58 | [[YTKBatchRequestAgent sharedAgent] addBatchRequest:self]; 59 | [self toggleAccessoriesWillStartCallBack]; 60 | for (YTKRequest * req in _requestArray) { 61 | req.delegate = self; 62 | [req clearCompletionBlock]; 63 | [req start]; 64 | } 65 | } 66 | 67 | - (void)stop { 68 | [self toggleAccessoriesWillStopCallBack]; 69 | _delegate = nil; 70 | [self clearRequest]; 71 | [self toggleAccessoriesDidStopCallBack]; 72 | [[YTKBatchRequestAgent sharedAgent] removeBatchRequest:self]; 73 | } 74 | 75 | - (void)startWithCompletionBlockWithSuccess:(void (^)(YTKBatchRequest *batchRequest))success 76 | failure:(void (^)(YTKBatchRequest *batchRequest))failure { 77 | [self setCompletionBlockWithSuccess:success failure:failure]; 78 | [self start]; 79 | } 80 | 81 | - (void)setCompletionBlockWithSuccess:(void (^)(YTKBatchRequest *batchRequest))success 82 | failure:(void (^)(YTKBatchRequest *batchRequest))failure { 83 | self.successCompletionBlock = success; 84 | self.failureCompletionBlock = failure; 85 | } 86 | 87 | - (void)clearCompletionBlock { 88 | // nil out to break the retain cycle. 89 | self.successCompletionBlock = nil; 90 | self.failureCompletionBlock = nil; 91 | } 92 | 93 | - (BOOL)isDataFromCache { 94 | BOOL result = YES; 95 | for (YTKRequest *request in _requestArray) { 96 | if (!request.isDataFromCache) { 97 | result = NO; 98 | } 99 | } 100 | return result; 101 | } 102 | 103 | 104 | - (void)dealloc { 105 | [self clearRequest]; 106 | } 107 | 108 | #pragma mark - Network Request Delegate 109 | 110 | - (void)requestFinished:(YTKRequest *)request { 111 | _finishedCount++; 112 | if (_finishedCount == _requestArray.count) { 113 | [self toggleAccessoriesWillStopCallBack]; 114 | if ([_delegate respondsToSelector:@selector(batchRequestFinished:)]) { 115 | [_delegate batchRequestFinished:self]; 116 | } 117 | if (_successCompletionBlock) { 118 | _successCompletionBlock(self); 119 | } 120 | [self clearCompletionBlock]; 121 | [self toggleAccessoriesDidStopCallBack]; 122 | [[YTKBatchRequestAgent sharedAgent] removeBatchRequest:self]; 123 | } 124 | } 125 | 126 | - (void)requestFailed:(YTKRequest *)request { 127 | _failedRequest = request; 128 | [self toggleAccessoriesWillStopCallBack]; 129 | // Stop 130 | for (YTKRequest *req in _requestArray) { 131 | [req stop]; 132 | } 133 | // Callback 134 | if ([_delegate respondsToSelector:@selector(batchRequestFailed:)]) { 135 | [_delegate batchRequestFailed:self]; 136 | } 137 | if (_failureCompletionBlock) { 138 | _failureCompletionBlock(self); 139 | } 140 | // Clear 141 | [self clearCompletionBlock]; 142 | 143 | [self toggleAccessoriesDidStopCallBack]; 144 | [[YTKBatchRequestAgent sharedAgent] removeBatchRequest:self]; 145 | } 146 | 147 | - (void)clearRequest { 148 | for (YTKRequest * req in _requestArray) { 149 | [req stop]; 150 | } 151 | [self clearCompletionBlock]; 152 | } 153 | 154 | 155 | 156 | 157 | #pragma mark - Request Accessoies 158 | 159 | - (void)addAccessory:(id)accessory { 160 | if (!self.requestAccessories) { 161 | self.requestAccessories = [NSMutableArray array]; 162 | } 163 | [self.requestAccessories addObject:accessory]; 164 | } 165 | 166 | @end 167 | -------------------------------------------------------------------------------- /WB_NeiApiManager/YTKNetwork/YTKBaseRequest.m: -------------------------------------------------------------------------------- 1 | // 2 | // YTKBaseRequest.m 3 | // 4 | // Copyright (c) 2012-2016 YTKNetwork https://github.com/yuantiku 5 | // 6 | // Permission is hereby granted, free of charge, to any person obtaining a copy 7 | // of this software and associated documentation files (the "Software"), to deal 8 | // in the Software without restriction, including without limitation the rights 9 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | // copies of the Software, and to permit persons to whom the Software is 11 | // furnished to do so, subject to the following conditions: 12 | // 13 | // The above copyright notice and this permission notice shall be included in 14 | // all copies or substantial portions of the Software. 15 | // 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | // THE SOFTWARE. 23 | 24 | #import "YTKBaseRequest.h" 25 | #import "YTKNetworkAgent.h" 26 | #import "YTKNetworkPrivate.h" 27 | 28 | #if __has_include() 29 | #import 30 | #else 31 | #import "AFNetworking.h" 32 | #endif 33 | 34 | NSString *const YTKRequestValidationErrorDomain = @"com.yuantiku.request.validation"; 35 | 36 | @interface YTKBaseRequest () 37 | 38 | @property (nonatomic, strong, readwrite) NSURLSessionTask *requestTask; 39 | @property (nonatomic, strong, readwrite) NSData *responseData; 40 | @property (nonatomic, strong, readwrite) id responseJSONObject; 41 | @property (nonatomic, strong, readwrite) id responseObject; 42 | @property (nonatomic, strong, readwrite) NSString *responseString; 43 | @property (nonatomic, strong, readwrite) NSError *error; 44 | 45 | @end 46 | 47 | @implementation YTKBaseRequest 48 | 49 | #pragma mark - Request and Response Information 50 | 51 | - (NSHTTPURLResponse *)response { 52 | return (NSHTTPURLResponse *)self.requestTask.response; 53 | } 54 | 55 | - (NSInteger)responseStatusCode { 56 | return self.response.statusCode; 57 | } 58 | 59 | - (NSDictionary *)responseHeaders { 60 | return self.response.allHeaderFields; 61 | } 62 | 63 | - (NSURLRequest *)currentRequest { 64 | return self.requestTask.currentRequest; 65 | } 66 | 67 | - (NSURLRequest *)originalRequest { 68 | return self.requestTask.originalRequest; 69 | } 70 | 71 | - (BOOL)isCancelled { 72 | if (!self.requestTask) { 73 | return NO; 74 | } 75 | return self.requestTask.state == NSURLSessionTaskStateCanceling; 76 | } 77 | 78 | - (BOOL)isExecuting { 79 | if (!self.requestTask) { 80 | return NO; 81 | } 82 | return self.requestTask.state == NSURLSessionTaskStateRunning; 83 | } 84 | 85 | #pragma mark - Request Configuration 86 | 87 | - (void)setCompletionBlockWithSuccess:(YTKRequestCompletionBlock)success 88 | failure:(YTKRequestCompletionBlock)failure { 89 | self.successCompletionBlock = success; 90 | self.failureCompletionBlock = failure; 91 | } 92 | 93 | - (void)clearCompletionBlock { 94 | // nil out to break the retain cycle. 95 | self.successCompletionBlock = nil; 96 | self.failureCompletionBlock = nil; 97 | } 98 | 99 | - (void)addAccessory:(id)accessory { 100 | if (!self.requestAccessories) { 101 | self.requestAccessories = [NSMutableArray array]; 102 | } 103 | [self.requestAccessories addObject:accessory]; 104 | } 105 | 106 | #pragma mark - Request Action 107 | 108 | - (void)start { 109 | [self toggleAccessoriesWillStartCallBack]; 110 | [[YTKNetworkAgent sharedAgent] addRequest:self]; 111 | } 112 | 113 | - (void)stop { 114 | [self toggleAccessoriesWillStopCallBack]; 115 | self.delegate = nil; 116 | [[YTKNetworkAgent sharedAgent] cancelRequest:self]; 117 | [self toggleAccessoriesDidStopCallBack]; 118 | } 119 | 120 | - (void)startWithCompletionBlockWithSuccess:(YTKRequestCompletionBlock)success 121 | failure:(YTKRequestCompletionBlock)failure { 122 | [self setCompletionBlockWithSuccess:success failure:failure]; 123 | [self start]; 124 | } 125 | 126 | #pragma mark - Subclass Override 127 | 128 | - (void)requestCompletePreprocessor { 129 | } 130 | 131 | - (void)requestCompleteFilter { 132 | } 133 | 134 | - (void)requestFailedPreprocessor { 135 | } 136 | 137 | - (void)requestFailedFilter { 138 | } 139 | 140 | - (NSString *)requestUrl { 141 | return @""; 142 | } 143 | 144 | - (NSString *)cdnUrl { 145 | return @""; 146 | } 147 | 148 | - (NSString *)baseUrl { 149 | return @""; 150 | } 151 | 152 | - (NSTimeInterval)requestTimeoutInterval { 153 | return 60; 154 | } 155 | 156 | - (id)requestArgument { 157 | return nil; 158 | } 159 | 160 | - (id)cacheFileNameFilterForRequestArgument:(id)argument { 161 | return argument; 162 | } 163 | 164 | - (YTKRequestMethod)requestMethod { 165 | return YTKRequestMethodGET; 166 | } 167 | 168 | - (YTKRequestSerializerType)requestSerializerType { 169 | return YTKRequestSerializerTypeHTTP; 170 | } 171 | 172 | - (YTKResponseSerializerType)responseSerializerType { 173 | return YTKResponseSerializerTypeJSON; 174 | } 175 | 176 | - (NSArray *)requestAuthorizationHeaderFieldArray { 177 | return nil; 178 | } 179 | 180 | - (NSDictionary *)requestHeaderFieldValueDictionary { 181 | return nil; 182 | } 183 | 184 | - (NSURLRequest *)buildCustomUrlRequest { 185 | return nil; 186 | } 187 | 188 | - (BOOL)useCDN { 189 | return NO; 190 | } 191 | 192 | - (BOOL)allowsCellularAccess { 193 | return YES; 194 | } 195 | 196 | - (id)jsonValidator { 197 | return nil; 198 | } 199 | 200 | - (BOOL)statusCodeValidator { 201 | NSInteger statusCode = [self responseStatusCode]; 202 | return (statusCode >= 200 && statusCode <= 299); 203 | } 204 | - (BOOL)isShowErrorMessage 205 | { 206 | return YES; 207 | } 208 | #pragma mark - NSObject 209 | 210 | - (NSString *)description { 211 | return [NSString stringWithFormat:@"<%@: %p>{ URL: %@ } { method: %@ } { arguments: %@ }", NSStringFromClass([self class]), self, self.currentRequest.URL, self.currentRequest.HTTPMethod, self.requestArgument]; 212 | } 213 | 214 | @end 215 | -------------------------------------------------------------------------------- /WB_NeiApiManager/AFNetworking/AFSecurityPolicy.h: -------------------------------------------------------------------------------- 1 | // AFSecurityPolicy.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | #import 24 | 25 | typedef NS_ENUM(NSUInteger, AFSSLPinningMode) { 26 | AFSSLPinningModeNone, 27 | AFSSLPinningModePublicKey, 28 | AFSSLPinningModeCertificate, 29 | }; 30 | 31 | /** 32 | `AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections. 33 | 34 | Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled. 35 | */ 36 | 37 | NS_ASSUME_NONNULL_BEGIN 38 | 39 | @interface AFSecurityPolicy : NSObject 40 | 41 | /** 42 | The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `AFSSLPinningModeNone`. 43 | */ 44 | @property (readonly, nonatomic, assign) AFSSLPinningMode SSLPinningMode; 45 | 46 | /** 47 | The certificates used to evaluate server trust according to the SSL pinning mode. 48 | 49 | By default, this property is set to any (`.cer`) certificates included in the target compiling AFNetworking. Note that if you are using AFNetworking as embedded framework, no certificates will be pinned by default. Use `certificatesInBundle` to load certificates from your target, and then create a new policy by calling `policyWithPinningMode:withPinnedCertificates`. 50 | 51 | Note that if pinning is enabled, `evaluateServerTrust:forDomain:` will return true if any pinned certificate matches. 52 | */ 53 | @property (nonatomic, strong, nullable) NSSet *pinnedCertificates; 54 | 55 | /** 56 | Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`. 57 | */ 58 | @property (nonatomic, assign) BOOL allowInvalidCertificates; 59 | 60 | /** 61 | Whether or not to validate the domain name in the certificate's CN field. Defaults to `YES`. 62 | */ 63 | @property (nonatomic, assign) BOOL validatesDomainName; 64 | 65 | ///----------------------------------------- 66 | /// @name Getting Certificates from the Bundle 67 | ///----------------------------------------- 68 | 69 | /** 70 | Returns any certificates included in the bundle. If you are using AFNetworking as an embedded framework, you must use this method to find the certificates you have included in your app bundle, and use them when creating your security policy by calling `policyWithPinningMode:withPinnedCertificates`. 71 | 72 | @return The certificates included in the given bundle. 73 | */ 74 | + (NSSet *)certificatesInBundle:(NSBundle *)bundle; 75 | 76 | ///----------------------------------------- 77 | /// @name Getting Specific Security Policies 78 | ///----------------------------------------- 79 | 80 | /** 81 | Returns the shared default security policy, which does not allow invalid certificates, validates domain name, and does not validate against pinned certificates or public keys. 82 | 83 | @return The default security policy. 84 | */ 85 | + (instancetype)defaultPolicy; 86 | 87 | ///--------------------- 88 | /// @name Initialization 89 | ///--------------------- 90 | 91 | /** 92 | Creates and returns a security policy with the specified pinning mode. 93 | 94 | @param pinningMode The SSL pinning mode. 95 | 96 | @return A new security policy. 97 | */ 98 | + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode; 99 | 100 | /** 101 | Creates and returns a security policy with the specified pinning mode. 102 | 103 | @param pinningMode The SSL pinning mode. 104 | @param pinnedCertificates The certificates to pin against. 105 | 106 | @return A new security policy. 107 | */ 108 | + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates; 109 | 110 | ///------------------------------ 111 | /// @name Evaluating Server Trust 112 | ///------------------------------ 113 | 114 | /** 115 | Whether or not the specified server trust should be accepted, based on the security policy. 116 | 117 | This method should be used when responding to an authentication challenge from a server. 118 | 119 | @param serverTrust The X.509 certificate trust of the server. 120 | @param domain The domain of serverTrust. If `nil`, the domain will not be validated. 121 | 122 | @return Whether or not to trust the server. 123 | */ 124 | - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust 125 | forDomain:(nullable NSString *)domain; 126 | 127 | @end 128 | 129 | NS_ASSUME_NONNULL_END 130 | 131 | ///---------------- 132 | /// @name Constants 133 | ///---------------- 134 | 135 | /** 136 | ## SSL Pinning Modes 137 | 138 | The following constants are provided by `AFSSLPinningMode` as possible SSL pinning modes. 139 | 140 | enum { 141 | AFSSLPinningModeNone, 142 | AFSSLPinningModePublicKey, 143 | AFSSLPinningModeCertificate, 144 | } 145 | 146 | `AFSSLPinningModeNone` 147 | Do not used pinned certificates to validate servers. 148 | 149 | `AFSSLPinningModePublicKey` 150 | Validate host certificates against public keys of pinned certificates. 151 | 152 | `AFSSLPinningModeCertificate` 153 | Validate host certificates against pinned certificates. 154 | */ 155 | -------------------------------------------------------------------------------- /WB_NeiApiManager/AFNetworking/AFNetworkReachabilityManager.h: -------------------------------------------------------------------------------- 1 | // AFNetworkReachabilityManager.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | 24 | #if !TARGET_OS_WATCH 25 | #import 26 | 27 | typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { 28 | AFNetworkReachabilityStatusUnknown = -1, 29 | AFNetworkReachabilityStatusNotReachable = 0, 30 | AFNetworkReachabilityStatusReachableViaWWAN = 1, 31 | AFNetworkReachabilityStatusReachableViaWiFi = 2, 32 | }; 33 | 34 | NS_ASSUME_NONNULL_BEGIN 35 | 36 | /** 37 | `AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces. 38 | 39 | Reachability can be used to determine background information about why a network operation failed, or to trigger a network operation retrying when a connection is established. It should not be used to prevent a user from initiating a network request, as it's possible that an initial request may be required to establish reachability. 40 | 41 | See Apple's Reachability Sample Code ( https://developer.apple.com/library/ios/samplecode/reachability/ ) 42 | 43 | @warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined. 44 | */ 45 | @interface AFNetworkReachabilityManager : NSObject 46 | 47 | /** 48 | The current network reachability status. 49 | */ 50 | @property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; 51 | 52 | /** 53 | Whether or not the network is currently reachable. 54 | */ 55 | @property (readonly, nonatomic, assign, getter = isReachable) BOOL reachable; 56 | 57 | /** 58 | Whether or not the network is currently reachable via WWAN. 59 | */ 60 | @property (readonly, nonatomic, assign, getter = isReachableViaWWAN) BOOL reachableViaWWAN; 61 | 62 | /** 63 | Whether or not the network is currently reachable via WiFi. 64 | */ 65 | @property (readonly, nonatomic, assign, getter = isReachableViaWiFi) BOOL reachableViaWiFi; 66 | 67 | ///--------------------- 68 | /// @name Initialization 69 | ///--------------------- 70 | 71 | /** 72 | Returns the shared network reachability manager. 73 | */ 74 | + (instancetype)sharedManager; 75 | 76 | /** 77 | Creates and returns a network reachability manager with the default socket address. 78 | 79 | @return An initialized network reachability manager, actively monitoring the default socket address. 80 | */ 81 | + (instancetype)manager; 82 | 83 | /** 84 | Creates and returns a network reachability manager for the specified domain. 85 | 86 | @param domain The domain used to evaluate network reachability. 87 | 88 | @return An initialized network reachability manager, actively monitoring the specified domain. 89 | */ 90 | + (instancetype)managerForDomain:(NSString *)domain; 91 | 92 | /** 93 | Creates and returns a network reachability manager for the socket address. 94 | 95 | @param address The socket address (`sockaddr_in6`) used to evaluate network reachability. 96 | 97 | @return An initialized network reachability manager, actively monitoring the specified socket address. 98 | */ 99 | + (instancetype)managerForAddress:(const void *)address; 100 | 101 | /** 102 | Initializes an instance of a network reachability manager from the specified reachability object. 103 | 104 | @param reachability The reachability object to monitor. 105 | 106 | @return An initialized network reachability manager, actively monitoring the specified reachability. 107 | */ 108 | - (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability NS_DESIGNATED_INITIALIZER; 109 | 110 | /** 111 | * Initializes an instance of a network reachability manager 112 | * 113 | * @return nil as this method is unavailable 114 | */ 115 | - (nullable instancetype)init NS_UNAVAILABLE; 116 | 117 | ///-------------------------------------------------- 118 | /// @name Starting & Stopping Reachability Monitoring 119 | ///-------------------------------------------------- 120 | 121 | /** 122 | Starts monitoring for changes in network reachability status. 123 | */ 124 | - (void)startMonitoring; 125 | 126 | /** 127 | Stops monitoring for changes in network reachability status. 128 | */ 129 | - (void)stopMonitoring; 130 | 131 | ///------------------------------------------------- 132 | /// @name Getting Localized Reachability Description 133 | ///------------------------------------------------- 134 | 135 | /** 136 | Returns a localized string representation of the current network reachability status. 137 | */ 138 | - (NSString *)localizedNetworkReachabilityStatusString; 139 | 140 | ///--------------------------------------------------- 141 | /// @name Setting Network Reachability Change Callback 142 | ///--------------------------------------------------- 143 | 144 | /** 145 | Sets a callback to be executed when the network availability of the `baseURL` host changes. 146 | 147 | @param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`. 148 | */ 149 | - (void)setReachabilityStatusChangeBlock:(nullable void (^)(AFNetworkReachabilityStatus status))block; 150 | 151 | @end 152 | 153 | ///---------------- 154 | /// @name Constants 155 | ///---------------- 156 | 157 | /** 158 | ## Network Reachability 159 | 160 | The following constants are provided by `AFNetworkReachabilityManager` as possible network reachability statuses. 161 | 162 | enum { 163 | AFNetworkReachabilityStatusUnknown, 164 | AFNetworkReachabilityStatusNotReachable, 165 | AFNetworkReachabilityStatusReachableViaWWAN, 166 | AFNetworkReachabilityStatusReachableViaWiFi, 167 | } 168 | 169 | `AFNetworkReachabilityStatusUnknown` 170 | The `baseURL` host reachability is not known. 171 | 172 | `AFNetworkReachabilityStatusNotReachable` 173 | The `baseURL` host cannot be reached. 174 | 175 | `AFNetworkReachabilityStatusReachableViaWWAN` 176 | The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS. 177 | 178 | `AFNetworkReachabilityStatusReachableViaWiFi` 179 | The `baseURL` host can be reached via a Wi-Fi connection. 180 | 181 | ### Keys for Notification UserInfo Dictionary 182 | 183 | Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification. 184 | 185 | `AFNetworkingReachabilityNotificationStatusItem` 186 | A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification. 187 | The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status. 188 | */ 189 | 190 | ///-------------------- 191 | /// @name Notifications 192 | ///-------------------- 193 | 194 | /** 195 | Posted when network reachability changes. 196 | This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability. 197 | 198 | @warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import ` to the header prefix of the project (`Prefix.pch`). 199 | */ 200 | FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityDidChangeNotification; 201 | FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityNotificationStatusItem; 202 | 203 | ///-------------------- 204 | /// @name Functions 205 | ///-------------------- 206 | 207 | /** 208 | Returns a localized string representation of an `AFNetworkReachabilityStatus` value. 209 | */ 210 | FOUNDATION_EXPORT NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status); 211 | 212 | NS_ASSUME_NONNULL_END 213 | #endif 214 | -------------------------------------------------------------------------------- /WB_NeiApiManager/YTKNetwork/YTKNetworkPrivate.m: -------------------------------------------------------------------------------- 1 | // 2 | // YTKNetworkPrivate.m 3 | // 4 | // Copyright (c) 2012-2016 YTKNetwork https://github.com/yuantiku 5 | // 6 | // Permission is hereby granted, free of charge, to any person obtaining a copy 7 | // of this software and associated documentation files (the "Software"), to deal 8 | // in the Software without restriction, including without limitation the rights 9 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | // copies of the Software, and to permit persons to whom the Software is 11 | // furnished to do so, subject to the following conditions: 12 | // 13 | // The above copyright notice and this permission notice shall be included in 14 | // all copies or substantial portions of the Software. 15 | // 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | // THE SOFTWARE. 23 | 24 | #import 25 | #import "YTKNetworkPrivate.h" 26 | 27 | #if __has_include() 28 | #import 29 | #else 30 | #import "AFURLRequestSerialization.h" 31 | #endif 32 | 33 | void YTKLog(NSString *format, ...) { 34 | #ifdef DEBUG 35 | if (![YTKNetworkConfig sharedConfig].debugLogEnabled) { 36 | return; 37 | } 38 | va_list argptr; 39 | va_start(argptr, format); 40 | NSLogv(format, argptr); 41 | va_end(argptr); 42 | #endif 43 | } 44 | 45 | @implementation YTKNetworkUtils 46 | 47 | + (BOOL)validateJSON:(id)json withValidator:(id)jsonValidator { 48 | if ([json isKindOfClass:[NSDictionary class]] && 49 | [jsonValidator isKindOfClass:[NSDictionary class]]) { 50 | NSDictionary * dict = json; 51 | NSDictionary * validator = jsonValidator; 52 | BOOL result = YES; 53 | NSEnumerator * enumerator = [validator keyEnumerator]; 54 | NSString * key; 55 | while ((key = [enumerator nextObject]) != nil) { 56 | id value = dict[key]; 57 | id format = validator[key]; 58 | if ([value isKindOfClass:[NSDictionary class]] 59 | || [value isKindOfClass:[NSArray class]]) { 60 | result = [self validateJSON:value withValidator:format]; 61 | if (!result) { 62 | break; 63 | } 64 | } else { 65 | if ([value isKindOfClass:format] == NO && 66 | [value isKindOfClass:[NSNull class]] == NO) { 67 | result = NO; 68 | break; 69 | } 70 | } 71 | } 72 | return result; 73 | } else if ([json isKindOfClass:[NSArray class]] && 74 | [jsonValidator isKindOfClass:[NSArray class]]) { 75 | NSArray * validatorArray = (NSArray *)jsonValidator; 76 | if (validatorArray.count > 0) { 77 | NSArray * array = json; 78 | NSDictionary * validator = jsonValidator[0]; 79 | for (id item in array) { 80 | BOOL result = [self validateJSON:item withValidator:validator]; 81 | if (!result) { 82 | return NO; 83 | } 84 | } 85 | } 86 | return YES; 87 | } else if ([json isKindOfClass:jsonValidator]) { 88 | return YES; 89 | } else { 90 | return NO; 91 | } 92 | } 93 | 94 | + (void)addDoNotBackupAttribute:(NSString *)path { 95 | NSURL *url = [NSURL fileURLWithPath:path]; 96 | NSError *error = nil; 97 | [url setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:&error]; 98 | if (error) { 99 | YTKLog(@"error to set do not backup attribute, error = %@", error); 100 | } 101 | } 102 | 103 | + (NSString *)md5StringFromString:(NSString *)string { 104 | NSParameterAssert(string != nil && [string length] > 0); 105 | 106 | const char *value = [string UTF8String]; 107 | 108 | unsigned char outputBuffer[CC_MD5_DIGEST_LENGTH]; 109 | CC_MD5(value, (CC_LONG)strlen(value), outputBuffer); 110 | 111 | NSMutableString *outputString = [[NSMutableString alloc] initWithCapacity:CC_MD5_DIGEST_LENGTH * 2]; 112 | for(NSInteger count = 0; count < CC_MD5_DIGEST_LENGTH; count++){ 113 | [outputString appendFormat:@"%02x", outputBuffer[count]]; 114 | } 115 | 116 | return outputString; 117 | } 118 | 119 | + (NSString *)appVersionString { 120 | return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]; 121 | } 122 | 123 | + (NSStringEncoding)stringEncodingWithRequest:(YTKBaseRequest *)request { 124 | // From AFNetworking 2.6.3 125 | NSStringEncoding stringEncoding = NSUTF8StringEncoding; 126 | if (request.response.textEncodingName) { 127 | CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)request.response.textEncodingName); 128 | if (encoding != kCFStringEncodingInvalidId) { 129 | stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding); 130 | } 131 | } 132 | return stringEncoding; 133 | } 134 | 135 | + (BOOL)validateResumeData:(NSData *)data { 136 | // From http://stackoverflow.com/a/22137510/3562486 137 | if (!data || [data length] < 1) return NO; 138 | 139 | NSError *error; 140 | NSDictionary *resumeDictionary = [NSPropertyListSerialization propertyListWithData:data options:NSPropertyListImmutable format:NULL error:&error]; 141 | if (!resumeDictionary || error) return NO; 142 | 143 | // Before iOS 9 & Mac OS X 10.11 144 | #if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED < 90000)\ 145 | || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED < 101100) 146 | NSString *localFilePath = [resumeDictionary objectForKey:@"NSURLSessionResumeInfoLocalPath"]; 147 | if ([localFilePath length] < 1) return NO; 148 | return [[NSFileManager defaultManager] fileExistsAtPath:localFilePath]; 149 | #endif 150 | // After iOS 9 we can not actually detects if the cache file exists. This plist file has a somehow 151 | // complicated structue. Besides, the plist structure is different between iOS 9 and iOS 10. 152 | // We can only assume that the plist being successfully parsed means the resume data is valid. 153 | return YES; 154 | } 155 | 156 | @end 157 | 158 | @implementation YTKBaseRequest (RequestAccessory) 159 | 160 | - (void)toggleAccessoriesWillStartCallBack { 161 | for (id accessory in self.requestAccessories) { 162 | if ([accessory respondsToSelector:@selector(requestWillStart:)]) { 163 | [accessory requestWillStart:self]; 164 | } 165 | } 166 | } 167 | 168 | - (void)toggleAccessoriesWillStopCallBack { 169 | for (id accessory in self.requestAccessories) { 170 | if ([accessory respondsToSelector:@selector(requestWillStop:)]) { 171 | [accessory requestWillStop:self]; 172 | } 173 | } 174 | } 175 | 176 | - (void)toggleAccessoriesDidStopCallBack { 177 | for (id accessory in self.requestAccessories) { 178 | if ([accessory respondsToSelector:@selector(requestDidStop:)]) { 179 | [accessory requestDidStop:self]; 180 | } 181 | } 182 | } 183 | 184 | @end 185 | 186 | @implementation YTKBatchRequest (RequestAccessory) 187 | 188 | - (void)toggleAccessoriesWillStartCallBack { 189 | for (id accessory in self.requestAccessories) { 190 | if ([accessory respondsToSelector:@selector(requestWillStart:)]) { 191 | [accessory requestWillStart:self]; 192 | } 193 | } 194 | } 195 | 196 | - (void)toggleAccessoriesWillStopCallBack { 197 | for (id accessory in self.requestAccessories) { 198 | if ([accessory respondsToSelector:@selector(requestWillStop:)]) { 199 | [accessory requestWillStop:self]; 200 | } 201 | } 202 | } 203 | 204 | - (void)toggleAccessoriesDidStopCallBack { 205 | for (id accessory in self.requestAccessories) { 206 | if ([accessory respondsToSelector:@selector(requestDidStop:)]) { 207 | [accessory requestDidStop:self]; 208 | } 209 | } 210 | } 211 | 212 | @end 213 | 214 | @implementation YTKChainRequest (RequestAccessory) 215 | 216 | - (void)toggleAccessoriesWillStartCallBack { 217 | for (id accessory in self.requestAccessories) { 218 | if ([accessory respondsToSelector:@selector(requestWillStart:)]) { 219 | [accessory requestWillStart:self]; 220 | } 221 | } 222 | } 223 | 224 | - (void)toggleAccessoriesWillStopCallBack { 225 | for (id accessory in self.requestAccessories) { 226 | if ([accessory respondsToSelector:@selector(requestWillStop:)]) { 227 | [accessory requestWillStop:self]; 228 | } 229 | } 230 | } 231 | 232 | - (void)toggleAccessoriesDidStopCallBack { 233 | for (id accessory in self.requestAccessories) { 234 | if ([accessory respondsToSelector:@selector(requestDidStop:)]) { 235 | [accessory requestDidStop:self]; 236 | } 237 | } 238 | } 239 | 240 | @end 241 | -------------------------------------------------------------------------------- /WB_NeiApiManager/AFNetworking/AFNetworkReachabilityManager.m: -------------------------------------------------------------------------------- 1 | // AFNetworkReachabilityManager.m 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import "AFNetworkReachabilityManager.h" 23 | #if !TARGET_OS_WATCH 24 | 25 | #import 26 | #import 27 | #import 28 | #import 29 | #import 30 | 31 | NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change"; 32 | NSString * const AFNetworkingReachabilityNotificationStatusItem = @"AFNetworkingReachabilityNotificationStatusItem"; 33 | 34 | typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status); 35 | 36 | NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status) { 37 | switch (status) { 38 | case AFNetworkReachabilityStatusNotReachable: 39 | return NSLocalizedStringFromTable(@"Not Reachable", @"AFNetworking", nil); 40 | case AFNetworkReachabilityStatusReachableViaWWAN: 41 | return NSLocalizedStringFromTable(@"Reachable via WWAN", @"AFNetworking", nil); 42 | case AFNetworkReachabilityStatusReachableViaWiFi: 43 | return NSLocalizedStringFromTable(@"Reachable via WiFi", @"AFNetworking", nil); 44 | case AFNetworkReachabilityStatusUnknown: 45 | default: 46 | return NSLocalizedStringFromTable(@"Unknown", @"AFNetworking", nil); 47 | } 48 | } 49 | 50 | static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) { 51 | BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0); 52 | BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0); 53 | BOOL canConnectionAutomatically = (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0)); 54 | BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0); 55 | BOOL isNetworkReachable = (isReachable && (!needsConnection || canConnectWithoutUserInteraction)); 56 | 57 | AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown; 58 | if (isNetworkReachable == NO) { 59 | status = AFNetworkReachabilityStatusNotReachable; 60 | } 61 | #if TARGET_OS_IPHONE 62 | else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) { 63 | status = AFNetworkReachabilityStatusReachableViaWWAN; 64 | } 65 | #endif 66 | else { 67 | status = AFNetworkReachabilityStatusReachableViaWiFi; 68 | } 69 | 70 | return status; 71 | } 72 | 73 | /** 74 | * Queue a status change notification for the main thread. 75 | * 76 | * This is done to ensure that the notifications are received in the same order 77 | * as they are sent. If notifications are sent directly, it is possible that 78 | * a queued notification (for an earlier status condition) is processed after 79 | * the later update, resulting in the listener being left in the wrong state. 80 | */ 81 | static void AFPostReachabilityStatusChange(SCNetworkReachabilityFlags flags, AFNetworkReachabilityStatusBlock block) { 82 | AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags); 83 | dispatch_async(dispatch_get_main_queue(), ^{ 84 | if (block) { 85 | block(status); 86 | } 87 | NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; 88 | NSDictionary *userInfo = @{ AFNetworkingReachabilityNotificationStatusItem: @(status) }; 89 | [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:userInfo]; 90 | }); 91 | } 92 | 93 | static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) { 94 | AFPostReachabilityStatusChange(flags, (__bridge AFNetworkReachabilityStatusBlock)info); 95 | } 96 | 97 | 98 | static const void * AFNetworkReachabilityRetainCallback(const void *info) { 99 | return Block_copy(info); 100 | } 101 | 102 | static void AFNetworkReachabilityReleaseCallback(const void *info) { 103 | if (info) { 104 | Block_release(info); 105 | } 106 | } 107 | 108 | @interface AFNetworkReachabilityManager () 109 | @property (readonly, nonatomic, assign) SCNetworkReachabilityRef networkReachability; 110 | @property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; 111 | @property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock; 112 | @end 113 | 114 | @implementation AFNetworkReachabilityManager 115 | 116 | + (instancetype)sharedManager { 117 | static AFNetworkReachabilityManager *_sharedManager = nil; 118 | static dispatch_once_t onceToken; 119 | dispatch_once(&onceToken, ^{ 120 | _sharedManager = [self manager]; 121 | }); 122 | 123 | return _sharedManager; 124 | } 125 | 126 | + (instancetype)managerForDomain:(NSString *)domain { 127 | SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]); 128 | 129 | AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; 130 | 131 | CFRelease(reachability); 132 | 133 | return manager; 134 | } 135 | 136 | + (instancetype)managerForAddress:(const void *)address { 137 | SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address); 138 | AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; 139 | 140 | CFRelease(reachability); 141 | 142 | return manager; 143 | } 144 | 145 | + (instancetype)manager 146 | { 147 | #if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 90000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) 148 | struct sockaddr_in6 address; 149 | bzero(&address, sizeof(address)); 150 | address.sin6_len = sizeof(address); 151 | address.sin6_family = AF_INET6; 152 | #else 153 | struct sockaddr_in address; 154 | bzero(&address, sizeof(address)); 155 | address.sin_len = sizeof(address); 156 | address.sin_family = AF_INET; 157 | #endif 158 | return [self managerForAddress:&address]; 159 | } 160 | 161 | - (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability { 162 | self = [super init]; 163 | if (!self) { 164 | return nil; 165 | } 166 | 167 | _networkReachability = CFRetain(reachability); 168 | self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown; 169 | 170 | return self; 171 | } 172 | 173 | - (instancetype)init NS_UNAVAILABLE 174 | { 175 | return nil; 176 | } 177 | 178 | - (void)dealloc { 179 | [self stopMonitoring]; 180 | 181 | if (_networkReachability != NULL) { 182 | CFRelease(_networkReachability); 183 | } 184 | } 185 | 186 | #pragma mark - 187 | 188 | - (BOOL)isReachable { 189 | return [self isReachableViaWWAN] || [self isReachableViaWiFi]; 190 | } 191 | 192 | - (BOOL)isReachableViaWWAN { 193 | return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN; 194 | } 195 | 196 | - (BOOL)isReachableViaWiFi { 197 | return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi; 198 | } 199 | 200 | #pragma mark - 201 | 202 | - (void)startMonitoring { 203 | [self stopMonitoring]; 204 | 205 | if (!self.networkReachability) { 206 | return; 207 | } 208 | 209 | __weak __typeof(self)weakSelf = self; 210 | AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) { 211 | __strong __typeof(weakSelf)strongSelf = weakSelf; 212 | 213 | strongSelf.networkReachabilityStatus = status; 214 | if (strongSelf.networkReachabilityStatusBlock) { 215 | strongSelf.networkReachabilityStatusBlock(status); 216 | } 217 | 218 | }; 219 | 220 | SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL}; 221 | SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context); 222 | SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); 223 | 224 | dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{ 225 | SCNetworkReachabilityFlags flags; 226 | if (SCNetworkReachabilityGetFlags(self.networkReachability, &flags)) { 227 | AFPostReachabilityStatusChange(flags, callback); 228 | } 229 | }); 230 | } 231 | 232 | - (void)stopMonitoring { 233 | if (!self.networkReachability) { 234 | return; 235 | } 236 | 237 | SCNetworkReachabilityUnscheduleFromRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); 238 | } 239 | 240 | #pragma mark - 241 | 242 | - (NSString *)localizedNetworkReachabilityStatusString { 243 | return AFStringFromNetworkReachabilityStatus(self.networkReachabilityStatus); 244 | } 245 | 246 | #pragma mark - 247 | 248 | - (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block { 249 | self.networkReachabilityStatusBlock = block; 250 | } 251 | 252 | #pragma mark - NSKeyValueObserving 253 | 254 | + (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key { 255 | if ([key isEqualToString:@"reachable"] || [key isEqualToString:@"reachableViaWWAN"] || [key isEqualToString:@"reachableViaWiFi"]) { 256 | return [NSSet setWithObject:@"networkReachabilityStatus"]; 257 | } 258 | 259 | return [super keyPathsForValuesAffectingValueForKey:key]; 260 | } 261 | 262 | @end 263 | #endif 264 | -------------------------------------------------------------------------------- /WB_NeiApiManager/AFNetworking/AFURLResponseSerialization.h: -------------------------------------------------------------------------------- 1 | // AFURLResponseSerialization.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | #import 24 | 25 | NS_ASSUME_NONNULL_BEGIN 26 | 27 | /** 28 | The `AFURLResponseSerialization` protocol is adopted by an object that decodes data into a more useful object representation, according to details in the server response. Response serializers may additionally perform validation on the incoming response and data. 29 | 30 | For example, a JSON response serializer may check for an acceptable status code (`2XX` range) and content type (`application/json`), decoding a valid JSON response into an object. 31 | */ 32 | @protocol AFURLResponseSerialization 33 | 34 | /** 35 | The response object decoded from the data associated with a specified response. 36 | 37 | @param response The response to be processed. 38 | @param data The response data to be decoded. 39 | @param error The error that occurred while attempting to decode the response data. 40 | 41 | @return The object decoded from the specified response data. 42 | */ 43 | - (nullable id)responseObjectForResponse:(nullable NSURLResponse *)response 44 | data:(nullable NSData *)data 45 | error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW; 46 | 47 | @end 48 | 49 | #pragma mark - 50 | 51 | /** 52 | `AFHTTPResponseSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation. 53 | 54 | Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPResponseSerializer` in order to ensure consistent default behavior. 55 | */ 56 | @interface AFHTTPResponseSerializer : NSObject 57 | 58 | - (instancetype)init; 59 | 60 | @property (nonatomic, assign) NSStringEncoding stringEncoding DEPRECATED_MSG_ATTRIBUTE("The string encoding is never used. AFHTTPResponseSerializer only validates status codes and content types but does not try to decode the received data in any way."); 61 | 62 | /** 63 | Creates and returns a serializer with default configuration. 64 | */ 65 | + (instancetype)serializer; 66 | 67 | ///----------------------------------------- 68 | /// @name Configuring Response Serialization 69 | ///----------------------------------------- 70 | 71 | /** 72 | The acceptable HTTP status codes for responses. When non-`nil`, responses with status codes not contained by the set will result in an error during validation. 73 | 74 | See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html 75 | */ 76 | @property (nonatomic, copy, nullable) NSIndexSet *acceptableStatusCodes; 77 | 78 | /** 79 | The acceptable MIME types for responses. When non-`nil`, responses with a `Content-Type` with MIME types that do not intersect with the set will result in an error during validation. 80 | */ 81 | @property (nonatomic, copy, nullable) NSSet *acceptableContentTypes; 82 | 83 | /** 84 | Validates the specified response and data. 85 | 86 | In its base implementation, this method checks for an acceptable status code and content type. Subclasses may wish to add other domain-specific checks. 87 | 88 | @param response The response to be validated. 89 | @param data The data associated with the response. 90 | @param error The error that occurred while attempting to validate the response. 91 | 92 | @return `YES` if the response is valid, otherwise `NO`. 93 | */ 94 | - (BOOL)validateResponse:(nullable NSHTTPURLResponse *)response 95 | data:(nullable NSData *)data 96 | error:(NSError * _Nullable __autoreleasing *)error; 97 | 98 | @end 99 | 100 | #pragma mark - 101 | 102 | 103 | /** 104 | `AFJSONResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes JSON responses. 105 | 106 | By default, `AFJSONResponseSerializer` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types: 107 | 108 | - `application/json` 109 | - `text/json` 110 | - `text/javascript` 111 | */ 112 | @interface AFJSONResponseSerializer : AFHTTPResponseSerializer 113 | 114 | - (instancetype)init; 115 | 116 | /** 117 | Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default. 118 | */ 119 | @property (nonatomic, assign) NSJSONReadingOptions readingOptions; 120 | 121 | /** 122 | Whether to remove keys with `NSNull` values from response JSON. Defaults to `NO`. 123 | */ 124 | @property (nonatomic, assign) BOOL removesKeysWithNullValues; 125 | 126 | /** 127 | Creates and returns a JSON serializer with specified reading and writing options. 128 | 129 | @param readingOptions The specified JSON reading options. 130 | */ 131 | + (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions; 132 | 133 | @end 134 | 135 | #pragma mark - 136 | 137 | /** 138 | `AFXMLParserResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLParser` objects. 139 | 140 | By default, `AFXMLParserResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: 141 | 142 | - `application/xml` 143 | - `text/xml` 144 | */ 145 | @interface AFXMLParserResponseSerializer : AFHTTPResponseSerializer 146 | 147 | @end 148 | 149 | #pragma mark - 150 | 151 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED 152 | 153 | /** 154 | `AFXMLDocumentResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. 155 | 156 | By default, `AFXMLDocumentResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: 157 | 158 | - `application/xml` 159 | - `text/xml` 160 | */ 161 | @interface AFXMLDocumentResponseSerializer : AFHTTPResponseSerializer 162 | 163 | - (instancetype)init; 164 | 165 | /** 166 | Input and output options specifically intended for `NSXMLDocument` objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default. 167 | */ 168 | @property (nonatomic, assign) NSUInteger options; 169 | 170 | /** 171 | Creates and returns an XML document serializer with the specified options. 172 | 173 | @param mask The XML document options. 174 | */ 175 | + (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask; 176 | 177 | @end 178 | 179 | #endif 180 | 181 | #pragma mark - 182 | 183 | /** 184 | `AFPropertyListResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. 185 | 186 | By default, `AFPropertyListResponseSerializer` accepts the following MIME types: 187 | 188 | - `application/x-plist` 189 | */ 190 | @interface AFPropertyListResponseSerializer : AFHTTPResponseSerializer 191 | 192 | - (instancetype)init; 193 | 194 | /** 195 | The property list format. Possible values are described in "NSPropertyListFormat". 196 | */ 197 | @property (nonatomic, assign) NSPropertyListFormat format; 198 | 199 | /** 200 | The property list reading options. Possible values are described in "NSPropertyListMutabilityOptions." 201 | */ 202 | @property (nonatomic, assign) NSPropertyListReadOptions readOptions; 203 | 204 | /** 205 | Creates and returns a property list serializer with a specified format, read options, and write options. 206 | 207 | @param format The property list format. 208 | @param readOptions The property list reading options. 209 | */ 210 | + (instancetype)serializerWithFormat:(NSPropertyListFormat)format 211 | readOptions:(NSPropertyListReadOptions)readOptions; 212 | 213 | @end 214 | 215 | #pragma mark - 216 | 217 | /** 218 | `AFImageResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes image responses. 219 | 220 | By default, `AFImageResponseSerializer` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage: 221 | 222 | - `image/tiff` 223 | - `image/jpeg` 224 | - `image/gif` 225 | - `image/png` 226 | - `image/ico` 227 | - `image/x-icon` 228 | - `image/bmp` 229 | - `image/x-bmp` 230 | - `image/x-xbitmap` 231 | - `image/x-win-bitmap` 232 | */ 233 | @interface AFImageResponseSerializer : AFHTTPResponseSerializer 234 | 235 | #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH 236 | /** 237 | The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance. 238 | */ 239 | @property (nonatomic, assign) CGFloat imageScale; 240 | 241 | /** 242 | Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance on iOS when used with `setCompletionBlockWithSuccess:failure:`, as it allows a bitmap representation to be constructed in the background rather than on the main thread. `YES` by default. 243 | */ 244 | @property (nonatomic, assign) BOOL automaticallyInflatesResponseImage; 245 | #endif 246 | 247 | @end 248 | 249 | #pragma mark - 250 | 251 | /** 252 | `AFCompoundSerializer` is a subclass of `AFHTTPResponseSerializer` that delegates the response serialization to the first `AFHTTPResponseSerializer` object that returns an object for `responseObjectForResponse:data:error:`, falling back on the default behavior of `AFHTTPResponseSerializer`. This is useful for supporting multiple potential types and structures of server responses with a single serializer. 253 | */ 254 | @interface AFCompoundResponseSerializer : AFHTTPResponseSerializer 255 | 256 | /** 257 | The component response serializers. 258 | */ 259 | @property (readonly, nonatomic, copy) NSArray > *responseSerializers; 260 | 261 | /** 262 | Creates and returns a compound serializer comprised of the specified response serializers. 263 | 264 | @warning Each response serializer specified must be a subclass of `AFHTTPResponseSerializer`, and response to `-validateResponse:data:error:`. 265 | */ 266 | + (instancetype)compoundSerializerWithResponseSerializers:(NSArray > *)responseSerializers; 267 | 268 | @end 269 | 270 | ///---------------- 271 | /// @name Constants 272 | ///---------------- 273 | 274 | /** 275 | ## Error Domains 276 | 277 | The following error domain is predefined. 278 | 279 | - `NSString * const AFURLResponseSerializationErrorDomain` 280 | 281 | ### Constants 282 | 283 | `AFURLResponseSerializationErrorDomain` 284 | AFURLResponseSerializer errors. Error codes for `AFURLResponseSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`. 285 | */ 286 | FOUNDATION_EXPORT NSString * const AFURLResponseSerializationErrorDomain; 287 | 288 | /** 289 | ## User info dictionary keys 290 | 291 | These keys may exist in the user info dictionary, in addition to those defined for NSError. 292 | 293 | - `NSString * const AFNetworkingOperationFailingURLResponseErrorKey` 294 | - `NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey` 295 | 296 | ### Constants 297 | 298 | `AFNetworkingOperationFailingURLResponseErrorKey` 299 | The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`. 300 | 301 | `AFNetworkingOperationFailingURLResponseDataErrorKey` 302 | The corresponding value is an `NSData` containing the original data of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`. 303 | */ 304 | FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseErrorKey; 305 | 306 | FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey; 307 | 308 | NS_ASSUME_NONNULL_END 309 | -------------------------------------------------------------------------------- /WB_NeiApiManager/AFNetworking/AFSecurityPolicy.m: -------------------------------------------------------------------------------- 1 | // AFSecurityPolicy.m 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import "AFSecurityPolicy.h" 23 | 24 | #import 25 | 26 | #if !TARGET_OS_IOS && !TARGET_OS_WATCH && !TARGET_OS_TV 27 | static NSData * AFSecKeyGetData(SecKeyRef key) { 28 | CFDataRef data = NULL; 29 | 30 | __Require_noErr_Quiet(SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data), _out); 31 | 32 | return (__bridge_transfer NSData *)data; 33 | 34 | _out: 35 | if (data) { 36 | CFRelease(data); 37 | } 38 | 39 | return nil; 40 | } 41 | #endif 42 | 43 | static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) { 44 | #if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV 45 | return [(__bridge id)key1 isEqual:(__bridge id)key2]; 46 | #else 47 | return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)]; 48 | #endif 49 | } 50 | 51 | static id AFPublicKeyForCertificate(NSData *certificate) { 52 | id allowedPublicKey = nil; 53 | SecCertificateRef allowedCertificate; 54 | SecPolicyRef policy = nil; 55 | SecTrustRef allowedTrust = nil; 56 | SecTrustResultType result; 57 | 58 | allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate); 59 | __Require_Quiet(allowedCertificate != NULL, _out); 60 | 61 | policy = SecPolicyCreateBasicX509(); 62 | __Require_noErr_Quiet(SecTrustCreateWithCertificates(allowedCertificate, policy, &allowedTrust), _out); 63 | __Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out); 64 | 65 | allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust); 66 | 67 | _out: 68 | if (allowedTrust) { 69 | CFRelease(allowedTrust); 70 | } 71 | 72 | if (policy) { 73 | CFRelease(policy); 74 | } 75 | 76 | if (allowedCertificate) { 77 | CFRelease(allowedCertificate); 78 | } 79 | 80 | return allowedPublicKey; 81 | } 82 | 83 | static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) { 84 | BOOL isValid = NO; 85 | SecTrustResultType result; 86 | __Require_noErr_Quiet(SecTrustEvaluate(serverTrust, &result), _out); 87 | 88 | isValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed); 89 | 90 | _out: 91 | return isValid; 92 | } 93 | 94 | static NSArray * AFCertificateTrustChainForServerTrust(SecTrustRef serverTrust) { 95 | CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust); 96 | NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount]; 97 | 98 | for (CFIndex i = 0; i < certificateCount; i++) { 99 | SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i); 100 | [trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]; 101 | } 102 | 103 | return [NSArray arrayWithArray:trustChain]; 104 | } 105 | 106 | static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) { 107 | SecPolicyRef policy = SecPolicyCreateBasicX509(); 108 | CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust); 109 | NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount]; 110 | for (CFIndex i = 0; i < certificateCount; i++) { 111 | SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i); 112 | 113 | SecCertificateRef someCertificates[] = {certificate}; 114 | CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL); 115 | 116 | SecTrustRef trust; 117 | __Require_noErr_Quiet(SecTrustCreateWithCertificates(certificates, policy, &trust), _out); 118 | 119 | SecTrustResultType result; 120 | __Require_noErr_Quiet(SecTrustEvaluate(trust, &result), _out); 121 | 122 | [trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)]; 123 | 124 | _out: 125 | if (trust) { 126 | CFRelease(trust); 127 | } 128 | 129 | if (certificates) { 130 | CFRelease(certificates); 131 | } 132 | 133 | continue; 134 | } 135 | CFRelease(policy); 136 | 137 | return [NSArray arrayWithArray:trustChain]; 138 | } 139 | 140 | #pragma mark - 141 | 142 | @interface AFSecurityPolicy() 143 | @property (readwrite, nonatomic, assign) AFSSLPinningMode SSLPinningMode; 144 | @property (readwrite, nonatomic, strong) NSSet *pinnedPublicKeys; 145 | @end 146 | 147 | @implementation AFSecurityPolicy 148 | 149 | + (NSSet *)certificatesInBundle:(NSBundle *)bundle { 150 | NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."]; 151 | 152 | NSMutableSet *certificates = [NSMutableSet setWithCapacity:[paths count]]; 153 | for (NSString *path in paths) { 154 | NSData *certificateData = [NSData dataWithContentsOfFile:path]; 155 | [certificates addObject:certificateData]; 156 | } 157 | 158 | return [NSSet setWithSet:certificates]; 159 | } 160 | 161 | + (NSSet *)defaultPinnedCertificates { 162 | static NSSet *_defaultPinnedCertificates = nil; 163 | static dispatch_once_t onceToken; 164 | dispatch_once(&onceToken, ^{ 165 | NSBundle *bundle = [NSBundle bundleForClass:[self class]]; 166 | _defaultPinnedCertificates = [self certificatesInBundle:bundle]; 167 | }); 168 | 169 | return _defaultPinnedCertificates; 170 | } 171 | 172 | + (instancetype)defaultPolicy { 173 | AFSecurityPolicy *securityPolicy = [[self alloc] init]; 174 | securityPolicy.SSLPinningMode = AFSSLPinningModeNone; 175 | 176 | return securityPolicy; 177 | } 178 | 179 | + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode { 180 | return [self policyWithPinningMode:pinningMode withPinnedCertificates:[self defaultPinnedCertificates]]; 181 | } 182 | 183 | + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates { 184 | AFSecurityPolicy *securityPolicy = [[self alloc] init]; 185 | securityPolicy.SSLPinningMode = pinningMode; 186 | 187 | [securityPolicy setPinnedCertificates:pinnedCertificates]; 188 | 189 | return securityPolicy; 190 | } 191 | 192 | - (instancetype)init { 193 | self = [super init]; 194 | if (!self) { 195 | return nil; 196 | } 197 | 198 | self.validatesDomainName = YES; 199 | 200 | return self; 201 | } 202 | 203 | - (void)setPinnedCertificates:(NSSet *)pinnedCertificates { 204 | _pinnedCertificates = pinnedCertificates; 205 | 206 | if (self.pinnedCertificates) { 207 | NSMutableSet *mutablePinnedPublicKeys = [NSMutableSet setWithCapacity:[self.pinnedCertificates count]]; 208 | for (NSData *certificate in self.pinnedCertificates) { 209 | id publicKey = AFPublicKeyForCertificate(certificate); 210 | if (!publicKey) { 211 | continue; 212 | } 213 | [mutablePinnedPublicKeys addObject:publicKey]; 214 | } 215 | self.pinnedPublicKeys = [NSSet setWithSet:mutablePinnedPublicKeys]; 216 | } else { 217 | self.pinnedPublicKeys = nil; 218 | } 219 | } 220 | 221 | #pragma mark - 222 | 223 | - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust 224 | forDomain:(NSString *)domain 225 | { 226 | if (domain && self.allowInvalidCertificates && self.validatesDomainName && (self.SSLPinningMode == AFSSLPinningModeNone || [self.pinnedCertificates count] == 0)) { 227 | // https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/OverridingSSLChainValidationCorrectly.html 228 | // According to the docs, you should only trust your provided certs for evaluation. 229 | // Pinned certificates are added to the trust. Without pinned certificates, 230 | // there is nothing to evaluate against. 231 | // 232 | // From Apple Docs: 233 | // "Do not implicitly trust self-signed certificates as anchors (kSecTrustOptionImplicitAnchors). 234 | // Instead, add your own (self-signed) CA certificate to the list of trusted anchors." 235 | NSLog(@"In order to validate a domain name for self signed certificates, you MUST use pinning."); 236 | return NO; 237 | } 238 | 239 | NSMutableArray *policies = [NSMutableArray array]; 240 | if (self.validatesDomainName) { 241 | [policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)]; 242 | } else { 243 | [policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()]; 244 | } 245 | 246 | SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies); 247 | 248 | if (self.SSLPinningMode == AFSSLPinningModeNone) { 249 | return self.allowInvalidCertificates || AFServerTrustIsValid(serverTrust); 250 | } else if (!AFServerTrustIsValid(serverTrust) && !self.allowInvalidCertificates) { 251 | return NO; 252 | } 253 | 254 | switch (self.SSLPinningMode) { 255 | case AFSSLPinningModeNone: 256 | default: 257 | return NO; 258 | case AFSSLPinningModeCertificate: { 259 | NSMutableArray *pinnedCertificates = [NSMutableArray array]; 260 | for (NSData *certificateData in self.pinnedCertificates) { 261 | [pinnedCertificates addObject:(__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData)]; 262 | } 263 | SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)pinnedCertificates); 264 | 265 | if (!AFServerTrustIsValid(serverTrust)) { 266 | return NO; 267 | } 268 | 269 | // obtain the chain after being validated, which *should* contain the pinned certificate in the last position (if it's the Root CA) 270 | NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust); 271 | 272 | for (NSData *trustChainCertificate in [serverCertificates reverseObjectEnumerator]) { 273 | if ([self.pinnedCertificates containsObject:trustChainCertificate]) { 274 | return YES; 275 | } 276 | } 277 | 278 | return NO; 279 | } 280 | case AFSSLPinningModePublicKey: { 281 | NSUInteger trustedPublicKeyCount = 0; 282 | NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust); 283 | 284 | for (id trustChainPublicKey in publicKeys) { 285 | for (id pinnedPublicKey in self.pinnedPublicKeys) { 286 | if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)trustChainPublicKey, (__bridge SecKeyRef)pinnedPublicKey)) { 287 | trustedPublicKeyCount += 1; 288 | } 289 | } 290 | } 291 | return trustedPublicKeyCount > 0; 292 | } 293 | } 294 | 295 | return NO; 296 | } 297 | 298 | #pragma mark - NSKeyValueObserving 299 | 300 | + (NSSet *)keyPathsForValuesAffectingPinnedPublicKeys { 301 | return [NSSet setWithObject:@"pinnedCertificates"]; 302 | } 303 | 304 | #pragma mark - NSSecureCoding 305 | 306 | + (BOOL)supportsSecureCoding { 307 | return YES; 308 | } 309 | 310 | - (instancetype)initWithCoder:(NSCoder *)decoder { 311 | 312 | self = [self init]; 313 | if (!self) { 314 | return nil; 315 | } 316 | 317 | self.SSLPinningMode = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(SSLPinningMode))] unsignedIntegerValue]; 318 | self.allowInvalidCertificates = [decoder decodeBoolForKey:NSStringFromSelector(@selector(allowInvalidCertificates))]; 319 | self.validatesDomainName = [decoder decodeBoolForKey:NSStringFromSelector(@selector(validatesDomainName))]; 320 | self.pinnedCertificates = [decoder decodeObjectOfClass:[NSArray class] forKey:NSStringFromSelector(@selector(pinnedCertificates))]; 321 | 322 | return self; 323 | } 324 | 325 | - (void)encodeWithCoder:(NSCoder *)coder { 326 | [coder encodeObject:[NSNumber numberWithUnsignedInteger:self.SSLPinningMode] forKey:NSStringFromSelector(@selector(SSLPinningMode))]; 327 | [coder encodeBool:self.allowInvalidCertificates forKey:NSStringFromSelector(@selector(allowInvalidCertificates))]; 328 | [coder encodeBool:self.validatesDomainName forKey:NSStringFromSelector(@selector(validatesDomainName))]; 329 | [coder encodeObject:self.pinnedCertificates forKey:NSStringFromSelector(@selector(pinnedCertificates))]; 330 | } 331 | 332 | #pragma mark - NSCopying 333 | 334 | - (instancetype)copyWithZone:(NSZone *)zone { 335 | AFSecurityPolicy *securityPolicy = [[[self class] allocWithZone:zone] init]; 336 | securityPolicy.SSLPinningMode = self.SSLPinningMode; 337 | securityPolicy.allowInvalidCertificates = self.allowInvalidCertificates; 338 | securityPolicy.validatesDomainName = self.validatesDomainName; 339 | securityPolicy.pinnedCertificates = [self.pinnedCertificates copyWithZone:zone]; 340 | 341 | return securityPolicy; 342 | } 343 | 344 | @end 345 | -------------------------------------------------------------------------------- /WB_NeiApiManager/YTKNetwork/YTKBaseRequest.h: -------------------------------------------------------------------------------- 1 | // 2 | // YTKBaseRequest.h 3 | // 4 | // Copyright (c) 2012-2016 YTKNetwork https://github.com/yuantiku 5 | // 6 | // Permission is hereby granted, free of charge, to any person obtaining a copy 7 | // of this software and associated documentation files (the "Software"), to deal 8 | // in the Software without restriction, including without limitation the rights 9 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | // copies of the Software, and to permit persons to whom the Software is 11 | // furnished to do so, subject to the following conditions: 12 | // 13 | // The above copyright notice and this permission notice shall be included in 14 | // all copies or substantial portions of the Software. 15 | // 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | // THE SOFTWARE. 23 | 24 | #import 25 | 26 | NS_ASSUME_NONNULL_BEGIN 27 | 28 | FOUNDATION_EXPORT NSString *const YTKRequestValidationErrorDomain; 29 | 30 | NS_ENUM(NSInteger) { 31 | YTKRequestValidationErrorInvalidStatusCode = -8, 32 | YTKRequestValidationErrorInvalidJSONFormat = -9, 33 | }; 34 | 35 | /// HTTP Request method. 36 | typedef NS_ENUM(NSInteger, YTKRequestMethod) { 37 | YTKRequestMethodGET = 0, 38 | YTKRequestMethodPOST, 39 | YTKRequestMethodHEAD, 40 | YTKRequestMethodPUT, 41 | YTKRequestMethodDELETE, 42 | YTKRequestMethodPATCH, 43 | }; 44 | 45 | /// Request serializer type. 46 | typedef NS_ENUM(NSInteger, YTKRequestSerializerType) { 47 | YTKRequestSerializerTypeHTTP = 0, 48 | YTKRequestSerializerTypeJSON, 49 | }; 50 | 51 | /// Response serializer type, which determines response serialization process and 52 | /// the type of `responseObject`. 53 | typedef NS_ENUM(NSInteger, YTKResponseSerializerType) { 54 | /// NSData type 55 | YTKResponseSerializerTypeHTTP, 56 | /// JSON object type 57 | YTKResponseSerializerTypeJSON, 58 | /// NSXMLParser type 59 | YTKResponseSerializerTypeXMLParser, 60 | }; 61 | 62 | /// Request priority 63 | typedef NS_ENUM(NSInteger, YTKRequestPriority) { 64 | YTKRequestPriorityLow = -4L, 65 | YTKRequestPriorityDefault = 0, 66 | YTKRequestPriorityHigh = 4, 67 | }; 68 | 69 | @protocol AFMultipartFormData; 70 | 71 | typedef void (^AFConstructingBlock)(id formData); 72 | typedef void (^AFURLSessionTaskProgressBlock)(NSProgress *); 73 | 74 | @class YTKBaseRequest; 75 | 76 | typedef void(^YTKRequestCompletionBlock)(__kindof YTKBaseRequest *request); 77 | 78 | /// The YTKRequestDelegate protocol defines several optional methods you can use 79 | /// to receive network-related messages. All the delegate methods will be called 80 | /// on the main queue. 81 | @protocol YTKRequestDelegate 82 | 83 | @optional 84 | /// Tell the delegate that the request has finished successfully. 85 | /// 86 | /// @param request The corresponding request. 87 | - (void)requestFinished:(__kindof YTKBaseRequest *)request; 88 | 89 | /// Tell the delegate that the request has failed. 90 | /// 91 | /// @param request The corresponding request. 92 | - (void)requestFailed:(__kindof YTKBaseRequest *)request; 93 | 94 | @end 95 | 96 | /// The YTKRequestAccessory protocol defines several optional methods that can be 97 | /// used to track the status of a request. Objects that conforms this protocol 98 | /// ("accessories") can perform additional configurations accordingly. All the 99 | /// accessory methods will be called on the main queue. 100 | @protocol YTKRequestAccessory 101 | 102 | @optional 103 | 104 | /// Inform the accessory that the request is about to start. 105 | /// 106 | /// @param request The corresponding request. 107 | - (void)requestWillStart:(id)request; 108 | 109 | /// Inform the accessory that the request is about to stop. This method is called 110 | /// before executing `requestFinished` and `successCompletionBlock`. 111 | /// 112 | /// @param request The corresponding request. 113 | - (void)requestWillStop:(id)request; 114 | 115 | /// Inform the accessory that the request has already stoped. This method is called 116 | /// after executing `requestFinished` and `successCompletionBlock`. 117 | /// 118 | /// @param request The corresponding request. 119 | - (void)requestDidStop:(id)request; 120 | 121 | @end 122 | 123 | /// YTKBaseRequest is the abstract class of network request. It provides many options 124 | /// for constructing request. It's the base class of `YTKRequest`. 125 | @interface YTKBaseRequest : NSObject 126 | 127 | #pragma mark - Request and Response Information 128 | ///============================================================================= 129 | /// @name Request and Response Information 130 | ///============================================================================= 131 | 132 | /// The underlying NSURLSessionTask. 133 | /// 134 | /// @warning This value is actually nil and should not be accessed before the request starts. 135 | @property (nonatomic, strong, readonly) NSURLSessionTask *requestTask; 136 | 137 | /// Shortcut for `requestTask.currentRequest`. 138 | @property (nonatomic, strong, readonly) NSURLRequest *currentRequest; 139 | 140 | /// Shortcut for `requestTask.originalRequest`. 141 | @property (nonatomic, strong, readonly) NSURLRequest *originalRequest; 142 | 143 | /// Shortcut for `requestTask.response`. 144 | @property (nonatomic, strong, readonly) NSHTTPURLResponse *response; 145 | 146 | /// The response status code. 147 | @property (nonatomic, readonly) NSInteger responseStatusCode; 148 | 149 | /// The response header fields. 150 | @property (nonatomic, strong, readonly, nullable) NSDictionary *responseHeaders; 151 | 152 | /// The raw data representation of response. Note this value can be nil if request failed. 153 | @property (nonatomic, strong, readonly, nullable) NSData *responseData; 154 | 155 | /// The string representation of response. Note this value can be nil if request failed. 156 | @property (nonatomic, strong, readonly, nullable) NSString *responseString; 157 | 158 | /// This serialized response object. The actual type of this object is determined by 159 | /// `YTKResponseSerializerType`. Note this value can be nil if request failed. 160 | /// 161 | /// @discussion If `resumableDownloadPath` and DownloadTask is using, this value will 162 | /// be the path to which file is successfully saved (NSURL), or nil if request failed. 163 | @property (nonatomic, strong, readonly, nullable) id responseObject; 164 | 165 | /// If you use `YTKResponseSerializerTypeJSON`, this is a convenience (and sematic) getter 166 | /// for the response object. Otherwise this value is nil. 167 | @property (nonatomic, strong, readonly, nullable) id responseJSONObject; 168 | 169 | /// This error can be either serialization error or network error. If nothing wrong happens 170 | /// this value will be nil. 171 | @property (nonatomic, strong, readonly, nullable) NSError *error; 172 | 173 | /// Return cancelled state of request task. 174 | @property (nonatomic, readonly, getter=isCancelled) BOOL cancelled; 175 | 176 | /// Executing state of request task. 177 | @property (nonatomic, readonly, getter=isExecuting) BOOL executing; 178 | 179 | 180 | #pragma mark - Request Configuration 181 | ///============================================================================= 182 | /// @name Request Configuration 183 | ///============================================================================= 184 | 185 | /// Tag can be used to identify request. Default value is 0. 186 | @property (nonatomic) NSInteger tag; 187 | 188 | /// The userInfo can be used to store additional info about the request. Default is nil. 189 | @property (nonatomic, strong, nullable) NSDictionary *userInfo; 190 | 191 | /// The delegate object of the request. If you choose block style callback you can ignore this. 192 | /// Default is nil. 193 | @property (nonatomic, weak, nullable) id delegate; 194 | 195 | /// The success callback. Note if this value is not nil and `requestFinished` delegate method is 196 | /// also implemented, both will be executed but delegate method is first called. This block 197 | /// will be called on the main queue. 198 | @property (nonatomic, copy, nullable) YTKRequestCompletionBlock successCompletionBlock; 199 | 200 | /// The failure callback. Note if this value is not nil and `requestFailed` delegate method is 201 | /// also implemented, both will be executed but delegate method is first called. This block 202 | /// will be called on the main queue. 203 | @property (nonatomic, copy, nullable) YTKRequestCompletionBlock failureCompletionBlock; 204 | 205 | /// This can be used to add several accossories object. Note if you use `addAccessory` to add acceesory 206 | /// this array will be automatically created. Default is nil. 207 | @property (nonatomic, strong, nullable) NSMutableArray> *requestAccessories; 208 | 209 | /// This can be use to construct HTTP body when needed in POST request. Default is nil. 210 | @property (nonatomic, copy, nullable) AFConstructingBlock constructingBodyBlock; 211 | 212 | /// This value is used to perform resumable download request. Default is nil. 213 | /// 214 | /// @discussion NSURLSessionDownloadTask is used when this value is not nil. 215 | /// The exist file at the path will be removed before the request starts. If request succeed, file will 216 | /// be saved to this path automatically, otherwise the response will be saved to `responseData` 217 | /// and `responseString`. For this to work, server must support `Range` and response with 218 | /// proper `Last-Modified` and/or `Etag`. See `NSURLSessionDownloadTask` for more detail. 219 | @property (nonatomic, strong, nullable) NSString *resumableDownloadPath; 220 | 221 | /// You can use this block to track the download progress. See also `resumableDownloadPath`. 222 | @property (nonatomic, copy, nullable) AFURLSessionTaskProgressBlock resumableDownloadProgressBlock; 223 | 224 | /// The priority of the request. Effective only on iOS 8+. Default is `YTKRequestPriorityDefault`. 225 | @property (nonatomic) YTKRequestPriority requestPriority; 226 | 227 | /// Set completion callbacks 228 | - (void)setCompletionBlockWithSuccess:(nullable YTKRequestCompletionBlock)success 229 | failure:(nullable YTKRequestCompletionBlock)failure; 230 | 231 | /// Nil out both success and failure callback blocks. 232 | - (void)clearCompletionBlock; 233 | 234 | /// Convenience method to add request accessory. See also `requestAccessories`. 235 | - (void)addAccessory:(id)accessory; 236 | 237 | 238 | #pragma mark - Request Action 239 | ///============================================================================= 240 | /// @name Request Action 241 | ///============================================================================= 242 | 243 | /// Append self to request queue and start the request. 244 | - (void)start; 245 | 246 | /// Remove self from request queue and cancel the request. 247 | - (void)stop; 248 | 249 | /// Convenience method to start the request with block callbacks. 250 | - (void)startWithCompletionBlockWithSuccess:(nullable YTKRequestCompletionBlock)success 251 | failure:(nullable YTKRequestCompletionBlock)failure; 252 | 253 | 254 | #pragma mark - Subclass Override 255 | ///============================================================================= 256 | /// @name Subclass Override 257 | ///============================================================================= 258 | 259 | /// Called on background thread after request succeded but before switching to main thread. Note if 260 | /// cache is loaded, this method WILL be called on the main thread, just like `requestCompleteFilter`. 261 | - (void)requestCompletePreprocessor; 262 | 263 | /// Called on the main thread after request succeeded. 264 | - (void)requestCompleteFilter; 265 | 266 | /// Called on background thread after request failed but before switching to main thread. See also 267 | /// `requestCompletePreprocessor`. 268 | - (void)requestFailedPreprocessor; 269 | 270 | /// Called on the main thread when request failed. 271 | - (void)requestFailedFilter; 272 | 273 | /// The baseURL of request. This should only contain the host part of URL, e.g., http://www.example.com. 274 | /// See also `requestUrl` 275 | - (NSString *)baseUrl; 276 | 277 | /// The URL path of request. This should only contain the path part of URL, e.g., /v1/user. See alse `baseUrl`. 278 | /// 279 | /// @discussion This will be concated with `baseUrl` using [NSURL URLWithString:relativeToURL]. 280 | /// Because of this, it is recommended that the usage should stick to rules stated above. 281 | /// Otherwise the result URL may not be correctly formed. See also `URLString:relativeToURL` 282 | /// for more information. 283 | /// 284 | /// Additionaly, if `requestUrl` itself is a valid URL, it will be used as the result URL and 285 | /// `baseUrl` will be ignored. 286 | - (NSString *)requestUrl; 287 | 288 | /// Optional CDN URL for request. 289 | - (NSString *)cdnUrl; 290 | 291 | /// Requset timeout interval. Default is 60s. 292 | /// 293 | /// @discussion When using `resumableDownloadPath`(NSURLSessionDownloadTask), the session seems to completely ignore 294 | /// `timeoutInterval` property of `NSURLRequest`. One effective way to set timeout would be using 295 | /// `timeoutIntervalForResource` of `NSURLSessionConfiguration`. 296 | - (NSTimeInterval)requestTimeoutInterval; 297 | 298 | /// Additional request argument. 299 | - (nullable id)requestArgument; 300 | 301 | /// Override this method to filter requests with certain arguments when caching. 302 | - (id)cacheFileNameFilterForRequestArgument:(id)argument; 303 | 304 | /// HTTP request method. 305 | - (YTKRequestMethod)requestMethod; 306 | 307 | /// Request serializer type. 308 | - (YTKRequestSerializerType)requestSerializerType; 309 | 310 | /// Response serializer type. See also `responseObject`. 311 | - (YTKResponseSerializerType)responseSerializerType; 312 | 313 | /// Username and password used for HTTP authorization. Should be formed as @[@"Username", @"Password"]. 314 | - (nullable NSArray *)requestAuthorizationHeaderFieldArray; 315 | 316 | /// Additional HTTP request header field. 317 | - (nullable NSDictionary *)requestHeaderFieldValueDictionary; 318 | 319 | /// Use this to build custom request. If this method return non-nil value, `requestUrl`, `requestTimeoutInterval`, 320 | /// `requestArgument`, `allowsCellularAccess`, `requestMethod` and `requestSerializerType` will all be ignored. 321 | - (nullable NSURLRequest *)buildCustomUrlRequest; 322 | 323 | /// Should use CDN when sending request. 324 | - (BOOL)useCDN; 325 | 326 | /// Whether the request is allowed to use the cellular radio (if present). Default is YES. 327 | - (BOOL)allowsCellularAccess; 328 | 329 | /// The validator will be used to test if `responseJSONObject` is correctly formed. 330 | - (nullable id)jsonValidator; 331 | 332 | /// This validator will be used to test if `responseStatusCode` is valid. 333 | - (BOOL)statusCodeValidator; 334 | 335 | /// 是否展示错误信息 336 | - (BOOL) isShowErrorMessage; 337 | @end 338 | 339 | NS_ASSUME_NONNULL_END 340 | -------------------------------------------------------------------------------- /WB_NeiApiManager/YTKNetwork/YTKRequest.m: -------------------------------------------------------------------------------- 1 | // 2 | // YTKRequest.m 3 | // 4 | // Copyright (c) 2012-2016 YTKNetwork https://github.com/yuantiku 5 | // 6 | // Permission is hereby granted, free of charge, to any person obtaining a copy 7 | // of this software and associated documentation files (the "Software"), to deal 8 | // in the Software without restriction, including without limitation the rights 9 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | // copies of the Software, and to permit persons to whom the Software is 11 | // furnished to do so, subject to the following conditions: 12 | // 13 | // The above copyright notice and this permission notice shall be included in 14 | // all copies or substantial portions of the Software. 15 | // 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | // THE SOFTWARE. 23 | 24 | #import "YTKNetworkConfig.h" 25 | #import "YTKRequest.h" 26 | #import "YTKNetworkPrivate.h" 27 | 28 | #ifndef NSFoundationVersionNumber_iOS_8_0 29 | #define NSFoundationVersionNumber_With_QoS_Available 1140.11 30 | #else 31 | #define NSFoundationVersionNumber_With_QoS_Available NSFoundationVersionNumber_iOS_8_0 32 | #endif 33 | 34 | NSString *const YTKRequestCacheErrorDomain = @"com.yuantiku.request.caching"; 35 | 36 | static dispatch_queue_t ytkrequest_cache_writing_queue() { 37 | static dispatch_queue_t queue; 38 | static dispatch_once_t onceToken; 39 | dispatch_once(&onceToken, ^{ 40 | dispatch_queue_attr_t attr = DISPATCH_QUEUE_SERIAL; 41 | if (NSFoundationVersionNumber >= NSFoundationVersionNumber_With_QoS_Available) { 42 | attr = dispatch_queue_attr_make_with_qos_class(attr, QOS_CLASS_BACKGROUND, 0); 43 | } 44 | queue = dispatch_queue_create("com.yuantiku.ytkrequest.caching", attr); 45 | }); 46 | 47 | return queue; 48 | } 49 | 50 | @interface YTKCacheMetadata : NSObject 51 | 52 | @property (nonatomic, assign) long long version; 53 | @property (nonatomic, strong) NSString *sensitiveDataString; 54 | @property (nonatomic, assign) NSStringEncoding stringEncoding; 55 | @property (nonatomic, strong) NSDate *creationDate; 56 | @property (nonatomic, strong) NSString *appVersionString; 57 | 58 | @end 59 | 60 | @implementation YTKCacheMetadata 61 | 62 | + (BOOL)supportsSecureCoding { 63 | return YES; 64 | } 65 | 66 | - (void)encodeWithCoder:(NSCoder *)aCoder { 67 | [aCoder encodeObject:@(self.version) forKey:NSStringFromSelector(@selector(version))]; 68 | [aCoder encodeObject:self.sensitiveDataString forKey:NSStringFromSelector(@selector(sensitiveDataString))]; 69 | [aCoder encodeObject:@(self.stringEncoding) forKey:NSStringFromSelector(@selector(stringEncoding))]; 70 | [aCoder encodeObject:self.creationDate forKey:NSStringFromSelector(@selector(creationDate))]; 71 | [aCoder encodeObject:self.appVersionString forKey:NSStringFromSelector(@selector(appVersionString))]; 72 | } 73 | 74 | - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder { 75 | self = [self init]; 76 | if (!self) { 77 | return nil; 78 | } 79 | 80 | self.version = [[aDecoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(version))] integerValue]; 81 | self.sensitiveDataString = [aDecoder decodeObjectOfClass:[NSString class] forKey:NSStringFromSelector(@selector(sensitiveDataString))]; 82 | self.stringEncoding = [[aDecoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(stringEncoding))] integerValue]; 83 | self.creationDate = [aDecoder decodeObjectOfClass:[NSDate class] forKey:NSStringFromSelector(@selector(creationDate))]; 84 | self.appVersionString = [aDecoder decodeObjectOfClass:[NSString class] forKey:NSStringFromSelector(@selector(appVersionString))]; 85 | 86 | return self; 87 | } 88 | 89 | @end 90 | 91 | @interface YTKRequest() 92 | 93 | @property (nonatomic, strong) NSData *cacheData; 94 | @property (nonatomic, strong) NSString *cacheString; 95 | @property (nonatomic, strong) id cacheJSON; 96 | @property (nonatomic, strong) NSXMLParser *cacheXML; 97 | 98 | @property (nonatomic, strong) YTKCacheMetadata *cacheMetadata; 99 | @property (nonatomic, assign) BOOL dataFromCache; 100 | 101 | @end 102 | 103 | @implementation YTKRequest 104 | 105 | - (void)start { 106 | if (self.ignoreCache) { 107 | [self startWithoutCache]; 108 | return; 109 | } 110 | 111 | // Do not cache download request. 112 | if (self.resumableDownloadPath) { 113 | [self startWithoutCache]; 114 | return; 115 | } 116 | 117 | if (![self loadCacheWithError:nil]) { 118 | [self startWithoutCache]; 119 | return; 120 | } 121 | 122 | _dataFromCache = YES; 123 | 124 | dispatch_async(dispatch_get_main_queue(), ^{ 125 | [self requestCompletePreprocessor]; 126 | [self requestCompleteFilter]; 127 | YTKRequest *strongSelf = self; 128 | [strongSelf.delegate requestFinished:strongSelf]; 129 | if (strongSelf.successCompletionBlock) { 130 | strongSelf.successCompletionBlock(strongSelf); 131 | } 132 | [strongSelf clearCompletionBlock]; 133 | }); 134 | } 135 | 136 | - (void)startWithoutCache { 137 | [self clearCacheVariables]; 138 | [super start]; 139 | } 140 | 141 | #pragma mark - Network Request Delegate 142 | 143 | - (void)requestCompletePreprocessor { 144 | [super requestCompletePreprocessor]; 145 | 146 | if (self.writeCacheAsynchronously) { 147 | dispatch_async(ytkrequest_cache_writing_queue(), ^{ 148 | [self saveResponseDataToCacheFile:[super responseData]]; 149 | }); 150 | } else { 151 | [self saveResponseDataToCacheFile:[super responseData]]; 152 | } 153 | } 154 | 155 | #pragma mark - Subclass Override 156 | 157 | - (NSInteger)cacheTimeInSeconds { 158 | return -1; 159 | } 160 | 161 | - (long long)cacheVersion { 162 | return 0; 163 | } 164 | 165 | - (id)cacheSensitiveData { 166 | return nil; 167 | } 168 | 169 | - (BOOL)writeCacheAsynchronously { 170 | return YES; 171 | } 172 | 173 | #pragma mark - 174 | 175 | - (BOOL)isDataFromCache { 176 | return _dataFromCache; 177 | } 178 | 179 | - (NSData *)responseData { 180 | if (_cacheData) { 181 | return _cacheData; 182 | } 183 | return [super responseData]; 184 | } 185 | 186 | - (NSString *)responseString { 187 | if (_cacheString) { 188 | return _cacheString; 189 | } 190 | return [super responseString]; 191 | } 192 | 193 | - (id)responseJSONObject { 194 | if (_cacheJSON) { 195 | return _cacheJSON; 196 | } 197 | return [super responseJSONObject]; 198 | } 199 | 200 | - (id)responseObject { 201 | if (_cacheJSON) { 202 | return _cacheJSON; 203 | } 204 | if (_cacheXML) { 205 | return _cacheXML; 206 | } 207 | if (_cacheData) { 208 | return _cacheData; 209 | } 210 | return [super responseObject]; 211 | } 212 | 213 | #pragma mark - 214 | 215 | - (BOOL)loadCacheWithError:(NSError * _Nullable __autoreleasing *)error { 216 | // Make sure cache time in valid. 217 | if ([self cacheTimeInSeconds] < 0) { 218 | if (error) { 219 | *error = [NSError errorWithDomain:YTKRequestCacheErrorDomain code:YTKRequestCacheErrorInvalidCacheTime userInfo:@{ NSLocalizedDescriptionKey:@"Invalid cache time"}]; 220 | } 221 | return NO; 222 | } 223 | 224 | // Try load metadata. 225 | if (![self loadCacheMetadata]) { 226 | if (error) { 227 | *error = [NSError errorWithDomain:YTKRequestCacheErrorDomain code:YTKRequestCacheErrorInvalidMetadata userInfo:@{ NSLocalizedDescriptionKey:@"Invalid metadata. Cache may not exist"}]; 228 | } 229 | return NO; 230 | } 231 | 232 | // Check if cache is still valid. 233 | if (![self validateCacheWithError:error]) { 234 | return NO; 235 | } 236 | 237 | // Try load cache. 238 | if (![self loadCacheData]) { 239 | if (error) { 240 | *error = [NSError errorWithDomain:YTKRequestCacheErrorDomain code:YTKRequestCacheErrorInvalidCacheData userInfo:@{ NSLocalizedDescriptionKey:@"Invalid cache data"}]; 241 | } 242 | return NO; 243 | } 244 | 245 | return YES; 246 | } 247 | 248 | - (BOOL)validateCacheWithError:(NSError * _Nullable __autoreleasing *)error { 249 | // Date 250 | NSDate *creationDate = self.cacheMetadata.creationDate; 251 | NSTimeInterval duration = -[creationDate timeIntervalSinceNow]; 252 | if (duration < 0 || duration > [self cacheTimeInSeconds]) { 253 | if (error) { 254 | *error = [NSError errorWithDomain:YTKRequestCacheErrorDomain code:YTKRequestCacheErrorExpired userInfo:@{ NSLocalizedDescriptionKey:@"Cache expired"}]; 255 | } 256 | return NO; 257 | } 258 | // Version 259 | long long cacheVersionFileContent = self.cacheMetadata.version; 260 | if (cacheVersionFileContent != [self cacheVersion]) { 261 | if (error) { 262 | *error = [NSError errorWithDomain:YTKRequestCacheErrorDomain code:YTKRequestCacheErrorVersionMismatch userInfo:@{ NSLocalizedDescriptionKey:@"Cache version mismatch"}]; 263 | } 264 | return NO; 265 | } 266 | // Sensitive data 267 | NSString *sensitiveDataString = self.cacheMetadata.sensitiveDataString; 268 | NSString *currentSensitiveDataString = ((NSObject *)[self cacheSensitiveData]).description; 269 | if (sensitiveDataString || currentSensitiveDataString) { 270 | // If one of the strings is nil, short-circuit evaluation will trigger 271 | if (sensitiveDataString.length != currentSensitiveDataString.length || ![sensitiveDataString isEqualToString:currentSensitiveDataString]) { 272 | if (error) { 273 | *error = [NSError errorWithDomain:YTKRequestCacheErrorDomain code:YTKRequestCacheErrorSensitiveDataMismatch userInfo:@{ NSLocalizedDescriptionKey:@"Cache sensitive data mismatch"}]; 274 | } 275 | return NO; 276 | } 277 | } 278 | // App version 279 | NSString *appVersionString = self.cacheMetadata.appVersionString; 280 | NSString *currentAppVersionString = [YTKNetworkUtils appVersionString]; 281 | if (appVersionString || currentAppVersionString) { 282 | if (appVersionString.length != currentAppVersionString.length || ![appVersionString isEqualToString:currentAppVersionString]) { 283 | if (error) { 284 | *error = [NSError errorWithDomain:YTKRequestCacheErrorDomain code:YTKRequestCacheErrorAppVersionMismatch userInfo:@{ NSLocalizedDescriptionKey:@"App version mismatch"}]; 285 | } 286 | return NO; 287 | } 288 | } 289 | return YES; 290 | } 291 | 292 | - (BOOL)loadCacheMetadata { 293 | NSString *path = [self cacheMetadataFilePath]; 294 | NSFileManager * fileManager = [NSFileManager defaultManager]; 295 | if ([fileManager fileExistsAtPath:path isDirectory:nil]) { 296 | @try { 297 | _cacheMetadata = [NSKeyedUnarchiver unarchiveObjectWithFile:path]; 298 | return YES; 299 | } @catch (NSException *exception) { 300 | YTKLog(@"Load cache metadata failed, reason = %@", exception.reason); 301 | return NO; 302 | } 303 | } 304 | return NO; 305 | } 306 | 307 | - (BOOL)loadCacheData { 308 | NSString *path = [self cacheFilePath]; 309 | NSFileManager *fileManager = [NSFileManager defaultManager]; 310 | NSError *error = nil; 311 | 312 | if ([fileManager fileExistsAtPath:path isDirectory:nil]) { 313 | NSData *data = [NSData dataWithContentsOfFile:path]; 314 | _cacheData = data; 315 | _cacheString = [[NSString alloc] initWithData:_cacheData encoding:self.cacheMetadata.stringEncoding]; 316 | switch (self.responseSerializerType) { 317 | case YTKResponseSerializerTypeHTTP: 318 | // Do nothing. 319 | return YES; 320 | case YTKResponseSerializerTypeJSON: 321 | _cacheJSON = [NSJSONSerialization JSONObjectWithData:_cacheData options:(NSJSONReadingOptions)0 error:&error]; 322 | return error == nil; 323 | case YTKResponseSerializerTypeXMLParser: 324 | _cacheXML = [[NSXMLParser alloc] initWithData:_cacheData]; 325 | return YES; 326 | } 327 | } 328 | return NO; 329 | } 330 | 331 | - (void)saveResponseDataToCacheFile:(NSData *)data { 332 | if ([self cacheTimeInSeconds] > 0 && ![self isDataFromCache]) { 333 | if (data != nil) { 334 | @try { 335 | // New data will always overwrite old data. 336 | [data writeToFile:[self cacheFilePath] atomically:YES]; 337 | 338 | YTKCacheMetadata *metadata = [[YTKCacheMetadata alloc] init]; 339 | metadata.version = [self cacheVersion]; 340 | metadata.sensitiveDataString = ((NSObject *)[self cacheSensitiveData]).description; 341 | metadata.stringEncoding = [YTKNetworkUtils stringEncodingWithRequest:self]; 342 | metadata.creationDate = [NSDate date]; 343 | metadata.appVersionString = [YTKNetworkUtils appVersionString]; 344 | [NSKeyedArchiver archiveRootObject:metadata toFile:[self cacheMetadataFilePath]]; 345 | } @catch (NSException *exception) { 346 | YTKLog(@"Save cache failed, reason = %@", exception.reason); 347 | } 348 | } 349 | } 350 | } 351 | 352 | - (void)clearCacheVariables { 353 | _cacheData = nil; 354 | _cacheXML = nil; 355 | _cacheJSON = nil; 356 | _cacheString = nil; 357 | _cacheMetadata = nil; 358 | _dataFromCache = NO; 359 | } 360 | 361 | #pragma mark - 362 | 363 | - (void)createDirectoryIfNeeded:(NSString *)path { 364 | NSFileManager *fileManager = [NSFileManager defaultManager]; 365 | BOOL isDir; 366 | if (![fileManager fileExistsAtPath:path isDirectory:&isDir]) { 367 | [self createBaseDirectoryAtPath:path]; 368 | } else { 369 | if (!isDir) { 370 | NSError *error = nil; 371 | [fileManager removeItemAtPath:path error:&error]; 372 | [self createBaseDirectoryAtPath:path]; 373 | } 374 | } 375 | } 376 | 377 | - (void)createBaseDirectoryAtPath:(NSString *)path { 378 | NSError *error = nil; 379 | [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES 380 | attributes:nil error:&error]; 381 | if (error) { 382 | YTKLog(@"create cache directory failed, error = %@", error); 383 | } else { 384 | [YTKNetworkUtils addDoNotBackupAttribute:path]; 385 | } 386 | } 387 | 388 | - (NSString *)cacheBasePath { 389 | NSString *pathOfLibrary = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 390 | NSString *path = [pathOfLibrary stringByAppendingPathComponent:@"LazyRequestCache"]; 391 | 392 | // Filter cache base path 393 | NSArray> *filters = [[YTKNetworkConfig sharedConfig] cacheDirPathFilters]; 394 | if (filters.count > 0) { 395 | for (id f in filters) { 396 | path = [f filterCacheDirPath:path withRequest:self]; 397 | } 398 | } 399 | 400 | [self createDirectoryIfNeeded:path]; 401 | return path; 402 | } 403 | 404 | - (NSString *)cacheFileName { 405 | NSString *requestUrl = [self requestUrl]; 406 | NSString *baseUrl = [YTKNetworkConfig sharedConfig].baseUrl; 407 | id argument = [self cacheFileNameFilterForRequestArgument:[self requestArgument]]; 408 | NSString *requestInfo = [NSString stringWithFormat:@"Method:%ld Host:%@ Url:%@ Argument:%@", 409 | (long)[self requestMethod], baseUrl, requestUrl, argument]; 410 | NSString *cacheFileName = [YTKNetworkUtils md5StringFromString:requestInfo]; 411 | return cacheFileName; 412 | } 413 | 414 | - (NSString *)cacheFilePath { 415 | NSString *cacheFileName = [self cacheFileName]; 416 | NSString *path = [self cacheBasePath]; 417 | path = [path stringByAppendingPathComponent:cacheFileName]; 418 | return path; 419 | } 420 | 421 | - (NSString *)cacheMetadataFilePath { 422 | NSString *cacheMetadataFileName = [NSString stringWithFormat:@"%@.metadata", [self cacheFileName]]; 423 | NSString *path = [self cacheBasePath]; 424 | path = [path stringByAppendingPathComponent:cacheMetadataFileName]; 425 | return path; 426 | } 427 | 428 | @end 429 | -------------------------------------------------------------------------------- /WB_NeiApiManager/AFNetworking/AFHTTPSessionManager.m: -------------------------------------------------------------------------------- 1 | // AFHTTPSessionManager.m 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import "AFHTTPSessionManager.h" 23 | 24 | #import "AFURLRequestSerialization.h" 25 | #import "AFURLResponseSerialization.h" 26 | 27 | #import 28 | #import 29 | #import 30 | 31 | #import 32 | #import 33 | #import 34 | #import 35 | #import 36 | 37 | #if TARGET_OS_IOS || TARGET_OS_TV 38 | #import 39 | #elif TARGET_OS_WATCH 40 | #import 41 | #endif 42 | 43 | @interface AFHTTPSessionManager () 44 | @property (readwrite, nonatomic, strong) NSURL *baseURL; 45 | @end 46 | 47 | @implementation AFHTTPSessionManager 48 | @dynamic responseSerializer; 49 | 50 | + (instancetype)manager { 51 | return [[[self class] alloc] initWithBaseURL:nil]; 52 | } 53 | 54 | - (instancetype)init { 55 | return [self initWithBaseURL:nil]; 56 | } 57 | 58 | - (instancetype)initWithBaseURL:(NSURL *)url { 59 | return [self initWithBaseURL:url sessionConfiguration:nil]; 60 | } 61 | 62 | - (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration { 63 | return [self initWithBaseURL:nil sessionConfiguration:configuration]; 64 | } 65 | 66 | - (instancetype)initWithBaseURL:(NSURL *)url 67 | sessionConfiguration:(NSURLSessionConfiguration *)configuration 68 | { 69 | self = [super initWithSessionConfiguration:configuration]; 70 | if (!self) { 71 | return nil; 72 | } 73 | 74 | // Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected 75 | if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) { 76 | url = [url URLByAppendingPathComponent:@""]; 77 | } 78 | 79 | self.baseURL = url; 80 | 81 | self.requestSerializer = [AFHTTPRequestSerializer serializer]; 82 | self.responseSerializer = [AFJSONResponseSerializer serializer]; 83 | 84 | return self; 85 | } 86 | 87 | #pragma mark - 88 | 89 | - (void)setRequestSerializer:(AFHTTPRequestSerializer *)requestSerializer { 90 | NSParameterAssert(requestSerializer); 91 | 92 | _requestSerializer = requestSerializer; 93 | } 94 | 95 | - (void)setResponseSerializer:(AFHTTPResponseSerializer *)responseSerializer { 96 | NSParameterAssert(responseSerializer); 97 | 98 | [super setResponseSerializer:responseSerializer]; 99 | } 100 | 101 | @dynamic securityPolicy; 102 | 103 | - (void)setSecurityPolicy:(AFSecurityPolicy *)securityPolicy { 104 | if (securityPolicy.SSLPinningMode != AFSSLPinningModeNone && ![self.baseURL.scheme isEqualToString:@"https"]) { 105 | NSString *pinningMode = @"Unknown Pinning Mode"; 106 | switch (securityPolicy.SSLPinningMode) { 107 | case AFSSLPinningModeNone: pinningMode = @"AFSSLPinningModeNone"; break; 108 | case AFSSLPinningModeCertificate: pinningMode = @"AFSSLPinningModeCertificate"; break; 109 | case AFSSLPinningModePublicKey: pinningMode = @"AFSSLPinningModePublicKey"; break; 110 | } 111 | NSString *reason = [NSString stringWithFormat:@"A security policy configured with `%@` can only be applied on a manager with a secure base URL (i.e. https)", pinningMode]; 112 | @throw [NSException exceptionWithName:@"Invalid Security Policy" reason:reason userInfo:nil]; 113 | } 114 | 115 | [super setSecurityPolicy:securityPolicy]; 116 | } 117 | 118 | #pragma mark - 119 | 120 | - (NSURLSessionDataTask *)GET:(NSString *)URLString 121 | parameters:(id)parameters 122 | success:(void (^)(NSURLSessionDataTask *task, id responseObject))success 123 | failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure 124 | { 125 | 126 | return [self GET:URLString parameters:parameters progress:nil success:success failure:failure]; 127 | } 128 | 129 | - (NSURLSessionDataTask *)GET:(NSString *)URLString 130 | parameters:(id)parameters 131 | progress:(void (^)(NSProgress * _Nonnull))downloadProgress 132 | success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success 133 | failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure 134 | { 135 | 136 | NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET" 137 | URLString:URLString 138 | parameters:parameters 139 | uploadProgress:nil 140 | downloadProgress:downloadProgress 141 | success:success 142 | failure:failure]; 143 | 144 | [dataTask resume]; 145 | 146 | return dataTask; 147 | } 148 | 149 | - (NSURLSessionDataTask *)HEAD:(NSString *)URLString 150 | parameters:(id)parameters 151 | success:(void (^)(NSURLSessionDataTask *task))success 152 | failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure 153 | { 154 | NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:^(NSURLSessionDataTask *task, __unused id responseObject) { 155 | if (success) { 156 | success(task); 157 | } 158 | } failure:failure]; 159 | 160 | [dataTask resume]; 161 | 162 | return dataTask; 163 | } 164 | 165 | - (NSURLSessionDataTask *)POST:(NSString *)URLString 166 | parameters:(id)parameters 167 | success:(void (^)(NSURLSessionDataTask *task, id responseObject))success 168 | failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure 169 | { 170 | return [self POST:URLString parameters:parameters progress:nil success:success failure:failure]; 171 | } 172 | 173 | - (NSURLSessionDataTask *)POST:(NSString *)URLString 174 | parameters:(id)parameters 175 | progress:(void (^)(NSProgress * _Nonnull))uploadProgress 176 | success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success 177 | failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure 178 | { 179 | NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters uploadProgress:uploadProgress downloadProgress:nil success:success failure:failure]; 180 | 181 | [dataTask resume]; 182 | 183 | return dataTask; 184 | } 185 | 186 | - (NSURLSessionDataTask *)POST:(NSString *)URLString 187 | parameters:(nullable id)parameters 188 | constructingBodyWithBlock:(nullable void (^)(id _Nonnull))block 189 | success:(nullable void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success 190 | failure:(nullable void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure 191 | { 192 | return [self POST:URLString parameters:parameters constructingBodyWithBlock:block progress:nil success:success failure:failure]; 193 | } 194 | 195 | - (NSURLSessionDataTask *)POST:(NSString *)URLString 196 | parameters:(id)parameters 197 | constructingBodyWithBlock:(void (^)(id formData))block 198 | progress:(nullable void (^)(NSProgress * _Nonnull))uploadProgress 199 | success:(void (^)(NSURLSessionDataTask *task, id responseObject))success 200 | failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure 201 | { 202 | NSError *serializationError = nil; 203 | NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError]; 204 | if (serializationError) { 205 | if (failure) { 206 | dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ 207 | failure(nil, serializationError); 208 | }); 209 | } 210 | 211 | return nil; 212 | } 213 | 214 | __block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:uploadProgress completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) { 215 | if (error) { 216 | if (failure) { 217 | failure(task, error); 218 | } 219 | } else { 220 | if (success) { 221 | success(task, responseObject); 222 | } 223 | } 224 | }]; 225 | 226 | [task resume]; 227 | 228 | return task; 229 | } 230 | 231 | - (NSURLSessionDataTask *)PUT:(NSString *)URLString 232 | parameters:(id)parameters 233 | success:(void (^)(NSURLSessionDataTask *task, id responseObject))success 234 | failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure 235 | { 236 | NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure]; 237 | 238 | [dataTask resume]; 239 | 240 | return dataTask; 241 | } 242 | 243 | - (NSURLSessionDataTask *)PATCH:(NSString *)URLString 244 | parameters:(id)parameters 245 | success:(void (^)(NSURLSessionDataTask *task, id responseObject))success 246 | failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure 247 | { 248 | NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure]; 249 | 250 | [dataTask resume]; 251 | 252 | return dataTask; 253 | } 254 | 255 | - (NSURLSessionDataTask *)DELETE:(NSString *)URLString 256 | parameters:(id)parameters 257 | success:(void (^)(NSURLSessionDataTask *task, id responseObject))success 258 | failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure 259 | { 260 | NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure]; 261 | 262 | [dataTask resume]; 263 | 264 | return dataTask; 265 | } 266 | 267 | - (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method 268 | URLString:(NSString *)URLString 269 | parameters:(id)parameters 270 | uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress 271 | downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress 272 | success:(void (^)(NSURLSessionDataTask *, id))success 273 | failure:(void (^)(NSURLSessionDataTask *, NSError *))failure 274 | { 275 | NSError *serializationError = nil; 276 | NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError]; 277 | if (serializationError) { 278 | if (failure) { 279 | dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ 280 | failure(nil, serializationError); 281 | }); 282 | } 283 | 284 | return nil; 285 | } 286 | 287 | __block NSURLSessionDataTask *dataTask = nil; 288 | dataTask = [self dataTaskWithRequest:request 289 | uploadProgress:uploadProgress 290 | downloadProgress:downloadProgress 291 | completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) { 292 | if (error) { 293 | if (failure) { 294 | failure(dataTask, error); 295 | } 296 | } else { 297 | if (success) { 298 | success(dataTask, responseObject); 299 | } 300 | } 301 | }]; 302 | 303 | return dataTask; 304 | } 305 | 306 | #pragma mark - NSObject 307 | 308 | - (NSString *)description { 309 | return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.session, self.operationQueue]; 310 | } 311 | 312 | #pragma mark - NSSecureCoding 313 | 314 | + (BOOL)supportsSecureCoding { 315 | return YES; 316 | } 317 | 318 | - (instancetype)initWithCoder:(NSCoder *)decoder { 319 | NSURL *baseURL = [decoder decodeObjectOfClass:[NSURL class] forKey:NSStringFromSelector(@selector(baseURL))]; 320 | NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"]; 321 | if (!configuration) { 322 | NSString *configurationIdentifier = [decoder decodeObjectOfClass:[NSString class] forKey:@"identifier"]; 323 | if (configurationIdentifier) { 324 | #if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1100) 325 | configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configurationIdentifier]; 326 | #else 327 | configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:configurationIdentifier]; 328 | #endif 329 | } 330 | } 331 | 332 | self = [self initWithBaseURL:baseURL sessionConfiguration:configuration]; 333 | if (!self) { 334 | return nil; 335 | } 336 | 337 | self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))]; 338 | self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))]; 339 | AFSecurityPolicy *decodedPolicy = [decoder decodeObjectOfClass:[AFSecurityPolicy class] forKey:NSStringFromSelector(@selector(securityPolicy))]; 340 | if (decodedPolicy) { 341 | self.securityPolicy = decodedPolicy; 342 | } 343 | 344 | return self; 345 | } 346 | 347 | - (void)encodeWithCoder:(NSCoder *)coder { 348 | [super encodeWithCoder:coder]; 349 | 350 | [coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))]; 351 | if ([self.session.configuration conformsToProtocol:@protocol(NSCoding)]) { 352 | [coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"]; 353 | } else { 354 | [coder encodeObject:self.session.configuration.identifier forKey:@"identifier"]; 355 | } 356 | [coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))]; 357 | [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))]; 358 | [coder encodeObject:self.securityPolicy forKey:NSStringFromSelector(@selector(securityPolicy))]; 359 | } 360 | 361 | #pragma mark - NSCopying 362 | 363 | - (instancetype)copyWithZone:(NSZone *)zone { 364 | AFHTTPSessionManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL sessionConfiguration:self.session.configuration]; 365 | 366 | HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone]; 367 | HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone]; 368 | HTTPClient.securityPolicy = [self.securityPolicy copyWithZone:zone]; 369 | return HTTPClient; 370 | } 371 | 372 | @end 373 | -------------------------------------------------------------------------------- /WB_NeiApiManager/AFNetworking/AFHTTPSessionManager.h: -------------------------------------------------------------------------------- 1 | // AFHTTPSessionManager.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | #if !TARGET_OS_WATCH 24 | #import 25 | #endif 26 | #import 27 | 28 | #if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV 29 | #import 30 | #else 31 | #import 32 | #endif 33 | 34 | #import "AFURLSessionManager.h" 35 | 36 | /** 37 | `AFHTTPSessionManager` is a subclass of `AFURLSessionManager` with convenience methods for making HTTP requests. When a `baseURL` is provided, requests made with the `GET` / `POST` / et al. convenience methods can be made with relative paths. 38 | 39 | ## Subclassing Notes 40 | 41 | Developers targeting iOS 7 or Mac OS X 10.9 or later that deal extensively with a web service are encouraged to subclass `AFHTTPSessionManager`, providing a class method that returns a shared singleton object on which authentication and other configuration can be shared across the application. 42 | 43 | For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `AFHTTPRequestOperationManager` may be used to similar effect. 44 | 45 | ## Methods to Override 46 | 47 | To change the behavior of all data task operation construction, which is also used in the `GET` / `POST` / et al. convenience methods, override `dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:`. 48 | 49 | ## Serialization 50 | 51 | Requests created by an HTTP client will contain default headers and encode parameters according to the `requestSerializer` property, which is an object conforming to ``. 52 | 53 | Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `` 54 | 55 | ## URL Construction Using Relative Paths 56 | 57 | For HTTP convenience methods, the request serializer constructs URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`, when provided. If `baseURL` is `nil`, `path` needs to resolve to a valid `NSURL` object using `NSURL +URLWithString:`. 58 | 59 | Below are a few examples of how `baseURL` and relative paths interact: 60 | 61 | NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"]; 62 | [NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo 63 | [NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz 64 | [NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo 65 | [NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo 66 | [NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/ 67 | [NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/ 68 | 69 | Also important to note is that a trailing slash will be added to any `baseURL` without one. This would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash. 70 | 71 | @warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance. 72 | */ 73 | 74 | NS_ASSUME_NONNULL_BEGIN 75 | 76 | @interface AFHTTPSessionManager : AFURLSessionManager 77 | 78 | /** 79 | The URL used to construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods. 80 | */ 81 | @property (readonly, nonatomic, strong, nullable) NSURL *baseURL; 82 | 83 | /** 84 | Requests created with `requestWithMethod:URLString:parameters:` & `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:` are constructed with a set of default headers using a parameter serialization specified by this property. By default, this is set to an instance of `AFHTTPRequestSerializer`, which serializes query string parameters for `GET`, `HEAD`, and `DELETE` requests, or otherwise URL-form-encodes HTTP message bodies. 85 | 86 | @warning `requestSerializer` must not be `nil`. 87 | */ 88 | @property (nonatomic, strong) AFHTTPRequestSerializer * requestSerializer; 89 | 90 | /** 91 | Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `AFJSONResponseSerializer`. 92 | 93 | @warning `responseSerializer` must not be `nil`. 94 | */ 95 | @property (nonatomic, strong) AFHTTPResponseSerializer * responseSerializer; 96 | 97 | ///------------------------------- 98 | /// @name Managing Security Policy 99 | ///------------------------------- 100 | 101 | /** 102 | The security policy used by created session to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified. A security policy configured with `AFSSLPinningModePublicKey` or `AFSSLPinningModeCertificate` can only be applied on a session manager initialized with a secure base URL (i.e. https). Applying a security policy with pinning enabled on an insecure session manager throws an `Invalid Security Policy` exception. 103 | */ 104 | @property (nonatomic, strong) AFSecurityPolicy *securityPolicy; 105 | 106 | ///--------------------- 107 | /// @name Initialization 108 | ///--------------------- 109 | 110 | /** 111 | Creates and returns an `AFHTTPSessionManager` object. 112 | */ 113 | + (instancetype)manager; 114 | 115 | /** 116 | Initializes an `AFHTTPSessionManager` object with the specified base URL. 117 | 118 | @param url The base URL for the HTTP client. 119 | 120 | @return The newly-initialized HTTP client 121 | */ 122 | - (instancetype)initWithBaseURL:(nullable NSURL *)url; 123 | 124 | /** 125 | Initializes an `AFHTTPSessionManager` object with the specified base URL. 126 | 127 | This is the designated initializer. 128 | 129 | @param url The base URL for the HTTP client. 130 | @param configuration The configuration used to create the managed session. 131 | 132 | @return The newly-initialized HTTP client 133 | */ 134 | - (instancetype)initWithBaseURL:(nullable NSURL *)url 135 | sessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER; 136 | 137 | ///--------------------------- 138 | /// @name Making HTTP Requests 139 | ///--------------------------- 140 | 141 | /** 142 | Creates and runs an `NSURLSessionDataTask` with a `GET` request. 143 | 144 | @param URLString The URL string used to create the request URL. 145 | @param parameters The parameters to be encoded according to the client request serializer. 146 | @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. 147 | @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. 148 | 149 | @see -dataTaskWithRequest:completionHandler: 150 | */ 151 | - (nullable NSURLSessionDataTask *)GET:(NSString *)URLString 152 | parameters:(nullable id)parameters 153 | success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success 154 | failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE; 155 | 156 | 157 | /** 158 | Creates and runs an `NSURLSessionDataTask` with a `GET` request. 159 | 160 | @param URLString The URL string used to create the request URL. 161 | @param parameters The parameters to be encoded according to the client request serializer. 162 | @param downloadProgress A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. 163 | @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. 164 | @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. 165 | 166 | @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: 167 | */ 168 | - (nullable NSURLSessionDataTask *)GET:(NSString *)URLString 169 | parameters:(nullable id)parameters 170 | progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgress 171 | success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success 172 | failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; 173 | 174 | /** 175 | Creates and runs an `NSURLSessionDataTask` with a `HEAD` request. 176 | 177 | @param URLString The URL string used to create the request URL. 178 | @param parameters The parameters to be encoded according to the client request serializer. 179 | @param success A block object to be executed when the task finishes successfully. This block has no return value and takes a single arguments: the data task. 180 | @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. 181 | 182 | @see -dataTaskWithRequest:completionHandler: 183 | */ 184 | - (nullable NSURLSessionDataTask *)HEAD:(NSString *)URLString 185 | parameters:(nullable id)parameters 186 | success:(nullable void (^)(NSURLSessionDataTask *task))success 187 | failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; 188 | 189 | /** 190 | Creates and runs an `NSURLSessionDataTask` with a `POST` request. 191 | 192 | @param URLString The URL string used to create the request URL. 193 | @param parameters The parameters to be encoded according to the client request serializer. 194 | @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. 195 | @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. 196 | 197 | @see -dataTaskWithRequest:completionHandler: 198 | */ 199 | - (nullable NSURLSessionDataTask *)POST:(NSString *)URLString 200 | parameters:(nullable id)parameters 201 | success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success 202 | failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE; 203 | 204 | /** 205 | Creates and runs an `NSURLSessionDataTask` with a `POST` request. 206 | 207 | @param URLString The URL string used to create the request URL. 208 | @param parameters The parameters to be encoded according to the client request serializer. 209 | @param uploadProgress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. 210 | @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. 211 | @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. 212 | 213 | @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: 214 | */ 215 | - (nullable NSURLSessionDataTask *)POST:(NSString *)URLString 216 | parameters:(nullable id)parameters 217 | progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress 218 | success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success 219 | failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; 220 | 221 | /** 222 | Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request. 223 | 224 | @param URLString The URL string used to create the request URL. 225 | @param parameters The parameters to be encoded according to the client request serializer. 226 | @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. 227 | @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. 228 | @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. 229 | 230 | @see -dataTaskWithRequest:completionHandler: 231 | */ 232 | - (nullable NSURLSessionDataTask *)POST:(NSString *)URLString 233 | parameters:(nullable id)parameters 234 | constructingBodyWithBlock:(nullable void (^)(id formData))block 235 | success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success 236 | failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE; 237 | 238 | /** 239 | Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request. 240 | 241 | @param URLString The URL string used to create the request URL. 242 | @param parameters The parameters to be encoded according to the client request serializer. 243 | @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. 244 | @param uploadProgress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. 245 | @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. 246 | @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. 247 | 248 | @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: 249 | */ 250 | - (nullable NSURLSessionDataTask *)POST:(NSString *)URLString 251 | parameters:(nullable id)parameters 252 | constructingBodyWithBlock:(nullable void (^)(id formData))block 253 | progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress 254 | success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success 255 | failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; 256 | 257 | /** 258 | Creates and runs an `NSURLSessionDataTask` with a `PUT` request. 259 | 260 | @param URLString The URL string used to create the request URL. 261 | @param parameters The parameters to be encoded according to the client request serializer. 262 | @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. 263 | @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. 264 | 265 | @see -dataTaskWithRequest:completionHandler: 266 | */ 267 | - (nullable NSURLSessionDataTask *)PUT:(NSString *)URLString 268 | parameters:(nullable id)parameters 269 | success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success 270 | failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; 271 | 272 | /** 273 | Creates and runs an `NSURLSessionDataTask` with a `PATCH` request. 274 | 275 | @param URLString The URL string used to create the request URL. 276 | @param parameters The parameters to be encoded according to the client request serializer. 277 | @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. 278 | @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. 279 | 280 | @see -dataTaskWithRequest:completionHandler: 281 | */ 282 | - (nullable NSURLSessionDataTask *)PATCH:(NSString *)URLString 283 | parameters:(nullable id)parameters 284 | success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success 285 | failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; 286 | 287 | /** 288 | Creates and runs an `NSURLSessionDataTask` with a `DELETE` request. 289 | 290 | @param URLString The URL string used to create the request URL. 291 | @param parameters The parameters to be encoded according to the client request serializer. 292 | @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. 293 | @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. 294 | 295 | @see -dataTaskWithRequest:completionHandler: 296 | */ 297 | - (nullable NSURLSessionDataTask *)DELETE:(NSString *)URLString 298 | parameters:(nullable id)parameters 299 | success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success 300 | failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; 301 | 302 | @end 303 | 304 | NS_ASSUME_NONNULL_END 305 | --------------------------------------------------------------------------------