diff --git a/PPNetworkHelper.xcodeproj/project.pbxproj b/PPNetworkHelper.xcodeproj/project.pbxproj index ba55f07..679ab14 100755 --- a/PPNetworkHelper.xcodeproj/project.pbxproj +++ b/PPNetworkHelper.xcodeproj/project.pbxproj @@ -7,7 +7,6 @@ objects = { /* Begin PBXBuildFile section */ - 1D5FA55A1F0DE16900CD5B57 /* PPInterfacedConst.m in Sources */ = {isa = PBXBuildFile; fileRef = 1D5FA5591F0DE16900CD5B57 /* PPInterfacedConst.m */; }; 22142E2B1D5E096E00EE2C40 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 22142E2A1D5E096E00EE2C40 /* main.m */; }; 22142E2E1D5E096E00EE2C40 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 22142E2D1D5E096E00EE2C40 /* AppDelegate.m */; }; 22142E311D5E096E00EE2C40 /* ViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 22142E301D5E096E00EE2C40 /* ViewController.m */; }; @@ -53,7 +52,6 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ - 1D5FA5591F0DE16900CD5B57 /* PPInterfacedConst.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = PPInterfacedConst.m; sourceTree = ""; }; 22142E261D5E096E00EE2C40 /* PPNetworkHelper.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = PPNetworkHelper.app; sourceTree = BUILT_PRODUCTS_DIR; }; 22142E2A1D5E096E00EE2C40 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; 22142E2C1D5E096E00EE2C40 /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; @@ -115,7 +113,6 @@ 22BEDC481D64B67100A72128 /* PPNetworkCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = PPNetworkCache.m; sourceTree = ""; }; 22BEDC491D64B67100A72128 /* PPNetworkHelper.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PPNetworkHelper.h; sourceTree = ""; }; 22BEDC4A1D64B67100A72128 /* PPNetworkHelper.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = PPNetworkHelper.m; sourceTree = ""; }; - 35639C3A1E9B616200FEA954 /* PPInterfacedConst.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PPInterfacedConst.h; sourceTree = ""; }; 35639C3D1E9B630C00FEA954 /* PPHTTPRequest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PPHTTPRequest.h; sourceTree = ""; }; 35639C3E1E9B630C00FEA954 /* PPHTTPRequest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = PPHTTPRequest.m; sourceTree = ""; }; /* End PBXFileReference section */ @@ -290,8 +287,6 @@ 35639C401E9B634900FEA954 /* PPHTTPRequestLayer */ = { isa = PBXGroup; children = ( - 35639C3A1E9B616200FEA954 /* PPInterfacedConst.h */, - 1D5FA5591F0DE16900CD5B57 /* PPInterfacedConst.m */, 35639C3D1E9B630C00FEA954 /* PPHTTPRequest.h */, 35639C3E1E9B630C00FEA954 /* PPHTTPRequest.m */, ); @@ -347,7 +342,7 @@ TargetAttributes = { 22142E251D5E096E00EE2C40 = { CreatedOnToolsVersion = 7.3.1; - DevelopmentTeam = YY4NTQ7LN8; + DevelopmentTeam = 77LD5G9JF9; }; 22142E3E1D5E096E00EE2C40 = { CreatedOnToolsVersion = 7.3.1; @@ -411,7 +406,6 @@ 22BEDC4C1D64B67100A72128 /* PPNetworkHelper.m in Sources */, 22BEDC4B1D64B67100A72128 /* PPNetworkCache.m in Sources */, 224086591D7074EA007E4E15 /* AFURLSessionManager.m in Sources */, - 1D5FA55A1F0DE16900CD5B57 /* PPInterfacedConst.m in Sources */, 224086581D7074EA007E4E15 /* AFURLResponseSerialization.m in Sources */, 224086611D7074EA007E4E15 /* UIImageView+AFNetworking.m in Sources */, 224086711D7074F5007E4E15 /* YYMemoryCache.m in Sources */, @@ -562,7 +556,7 @@ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CODE_SIGN_IDENTITY = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - DEVELOPMENT_TEAM = YY4NTQ7LN8; + DEVELOPMENT_TEAM = 77LD5G9JF9; INFOPLIST_FILE = PPNetworkHelper/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; @@ -578,7 +572,7 @@ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CODE_SIGN_IDENTITY = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - DEVELOPMENT_TEAM = YY4NTQ7LN8; + DEVELOPMENT_TEAM = 77LD5G9JF9; INFOPLIST_FILE = PPNetworkHelper/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; diff --git a/PPNetworkHelper.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/PPNetworkHelper.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/PPNetworkHelper.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/PPNetworkHelper.xcodeproj/project.xcworkspace/xcuserdata/GSTB.xcuserdatad/UserInterfaceState.xcuserstate b/PPNetworkHelper.xcodeproj/project.xcworkspace/xcuserdata/GSTB.xcuserdatad/UserInterfaceState.xcuserstate new file mode 100644 index 0000000..5abf656 Binary files /dev/null and b/PPNetworkHelper.xcodeproj/project.xcworkspace/xcuserdata/GSTB.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/PPNetworkHelper.xcodeproj/xcuserdata/GSTB.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist b/PPNetworkHelper.xcodeproj/xcuserdata/GSTB.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist new file mode 100644 index 0000000..e83f929 --- /dev/null +++ b/PPNetworkHelper.xcodeproj/xcuserdata/GSTB.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist @@ -0,0 +1,33 @@ + + + + + + + + + + + + + diff --git a/PPNetworkHelper.xcodeproj/xcuserdata/GSTB.xcuserdatad/xcschemes/xcschememanagement.plist b/PPNetworkHelper.xcodeproj/xcuserdata/GSTB.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 0000000..60f46d5 --- /dev/null +++ b/PPNetworkHelper.xcodeproj/xcuserdata/GSTB.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,19 @@ + + + + + SchemeUserState + + PPNetworkHelper.xcscheme + + orderHint + 0 + + PPNetworkHelper.xcscheme_^#shared#^_ + + orderHint + 0 + + + + diff --git a/PPNetworkHelper/PPHTTPRequest.m b/PPNetworkHelper/PPHTTPRequest.m index 9de2821..3fe54ff 100644 --- a/PPNetworkHelper/PPHTTPRequest.m +++ b/PPNetworkHelper/PPHTTPRequest.m @@ -7,7 +7,6 @@ // #import "PPHTTPRequest.h" -#import "PPInterfacedConst.h" #import "PPNetworkHelper.h" @implementation PPHTTPRequest @@ -15,13 +14,13 @@ @implementation PPHTTPRequest + (NSURLSessionTask *)getLoginWithParameters:(id)parameters success:(PPRequestSuccess)success failure:(PPRequestFailure)failure { // 将请求前缀与请求路径拼接成一个完整的URL - NSString *url = [NSString stringWithFormat:@"%@%@",kApiPrefix,kLogin]; + NSString *url = [NSString stringWithFormat:@"%@%@",@"https://www.baidu.com",@"/login"]; return [self requestWithURL:url parameters:parameters success:success failure:failure]; } /** 退出*/ + (NSURLSessionTask *)getExitWithParameters:(id)parameters success:(PPRequestSuccess)success failure:(PPRequestFailure)failure { - NSString *url = [NSString stringWithFormat:@"%@%@",kApiPrefix,kExit]; + NSString *url = [NSString stringWithFormat:@"%@%@",@"https://www.baidu.com",@"/exit"]; return [self requestWithURL:url parameters:parameters success:success failure:failure]; } @@ -37,12 +36,12 @@ + (NSURLSessionTask *)getExitWithParameters:(id)parameters success:(PPRequestSuc + (NSURLSessionTask *)requestWithURL:(NSString *)URL parameters:(NSDictionary *)parameter success:(PPRequestSuccess)success failure:(PPRequestFailure)failure { // 在请求之前你可以统一配置你请求的相关参数 ,设置请求头, 请求参数的格式, 返回数据的格式....这样你就不需要每次请求都要设置一遍相关参数 - // 设置请求头 - [PPNetworkHelper setValue:@"9" forHTTPHeaderField:@"fromType"]; + [PPNetworkHelper setResponseSerializer:PPResponseSerializerHTTP]; + // 设置请求头 + [PPNetworkHelper setValue:@"v1.0.0" forHTTPHeaderField:@"api-version"]; // 发起请求 - return [PPNetworkHelper POST:URL parameters:parameter success:^(id responseObject) { - + return [PPNetworkHelper request:POST URLString:URL parameters:parameter success:^(id responseObject) { // 在这里你可以根据项目自定义其他一些重复操作,比如加载页面时候的等待效果, 提醒弹窗.... success(responseObject); @@ -50,6 +49,7 @@ + (NSURLSessionTask *)requestWithURL:(NSString *)URL parameters:(NSDictionary *) // 同上 failure(error); }]; + } @end diff --git a/PPNetworkHelper/PPInterfacedConst.h b/PPNetworkHelper/PPInterfacedConst.h deleted file mode 100644 index 742910b..0000000 --- a/PPNetworkHelper/PPInterfacedConst.h +++ /dev/null @@ -1,32 +0,0 @@ -// -// PPInterfacedConst.h -// PPNetworkHelper -// -// Created by AndyPang on 2017/4/10. -// Copyright © 2017年 AndyPang. All rights reserved. -// - -#import -/* - - 将项目中所有的接口写在这里,方便统一管理,降低耦合 - - 这里通过宏定义来切换你当前的服务器类型, - 将你要切换的服务器类型宏后面置为真(即>0即可),其余为假(置为0) - 如下:现在的状态为测试服务器 - 这样做切换方便,不用来回每个网络请求修改请求域名,降低出错事件 - */ - -#define DevelopSever 0 -#define TestSever 1 -#define ProductSever 0 - -/** 接口前缀-开发服务器*/ -UIKIT_EXTERN NSString *const kApiPrefix; - -#pragma mark - 详细接口地址 -/** 登录*/ -UIKIT_EXTERN NSString *const kLogin; -/** 平台会员退出*/ -UIKIT_EXTERN NSString *const kExit; - diff --git a/PPNetworkHelper/PPInterfacedConst.m b/PPNetworkHelper/PPInterfacedConst.m deleted file mode 100644 index bf14af4..0000000 --- a/PPNetworkHelper/PPInterfacedConst.m +++ /dev/null @@ -1,25 +0,0 @@ -// -// PPInterfacedConst.m -// PPNetworkHelper -// -// Created by YiAi on 2017/7/6. -// Copyright © 2017年 AndyPang. All rights reserved. -// - -#import "PPInterfacedConst.h" - -#if DevelopSever -/** 接口前缀-开发服务器*/ -NSString *const kApiPrefix = @"接口服务器的请求前缀 例: http://192.168.10.10:8080"; -#elif TestSever -/** 接口前缀-测试服务器*/ -NSString *const kApiPrefix = @"https://www.baidu.com"; -#elif ProductSever -/** 接口前缀-生产服务器*/ -NSString *const kApiPrefix = @"https://www.baidu.com"; -#endif - -/** 登录*/ -NSString *const kLogin = @"/login"; -/** 平台会员退出*/ -NSString *const kExit = @"/exit"; diff --git a/PPNetworkHelper/PPNetworkHelper/PPNetworkHelper.h b/PPNetworkHelper/PPNetworkHelper/PPNetworkHelper.h index cd0cdfb..0fd0d2d 100755 --- a/PPNetworkHelper/PPNetworkHelper/PPNetworkHelper.h +++ b/PPNetworkHelper/PPNetworkHelper/PPNetworkHelper.h @@ -29,7 +29,7 @@ #import #import #import "PPNetworkCache.h" - +#import "AFNetworking.h" #ifndef kIsNetwork #define kIsNetwork [PPNetworkHelper isNetwork] // 一次性判断是否有网的宏 #endif @@ -41,6 +41,15 @@ #ifndef kIsWiFiNetwork #define kIsWiFiNetwork [PPNetworkHelper isWiFiNetwork] // 一次性判断是否为WiFi网络的宏 #endif +//请求方式 +typedef enum: NSInteger{ + GET,//GET请求 + POST, + DELETE, + HEAD, + PATCH, + PUT, +}PPRequestMethod; typedef NS_ENUM(NSUInteger, PPNetworkStatusType) { /// 未知网络 @@ -82,10 +91,11 @@ typedef void (^PPHttpProgress)(NSProgress *progress); /// 网络状态的Block typedef void(^PPNetworkStatus)(PPNetworkStatusType status); -@class AFHTTPSessionManager; -@interface PPNetworkHelper : NSObject +@interface PPNetworkHelper : AFHTTPSessionManager -/// 有网YES, 无网:NO +/** + 有网YES, 无网:NO + */ + (BOOL)isNetwork; /// 手机网络:YES, 反之:NO @@ -94,15 +104,9 @@ typedef void(^PPNetworkStatus)(PPNetworkStatusType status); /// WiFi网络:YES, 反之:NO + (BOOL)isWiFiNetwork; -/// 取消所有HTTP请求 -+ (void)cancelAllRequest; - /// 实时获取网络状态,通过Block回调实时获取(此方法可多次调用) + (void)networkStatusWithBlock:(PPNetworkStatus)networkStatus; -/// 取消指定URL的HTTP请求 -+ (void)cancelRequestWithURL:(NSString *)URL; - /// 开启日志打印 (Debug级别) + (void)openLog; @@ -111,68 +115,46 @@ typedef void(^PPNetworkStatus)(PPNetworkStatusType status); /** - * GET请求,无缓存 - * - * @param URL 请求地址 - * @param parameters 请求参数 - * @param success 请求成功的回调 - * @param failure 请求失败的回调 - * - * @return 返回的对象可取消请求,调用cancel方法 + 取消所有HTTP请求 */ -+ (__kindof NSURLSessionTask *)GET:(NSString *)URL - parameters:(id)parameters - success:(PPHttpRequestSuccess)success - failure:(PPHttpRequestFailed)failure; ++ (void)cancelAllRequest; /** - * GET请求,自动缓存 - * - * @param URL 请求地址 - * @param parameters 请求参数 - * @param responseCache 缓存数据的回调 - * @param success 请求成功的回调 - * @param failure 请求失败的回调 - * - * @return 返回的对象可取消请求,调用cancel方法 + 取消指定URL的HTTP请求 */ -+ (__kindof NSURLSessionTask *)GET:(NSString *)URL - parameters:(id)parameters - responseCache:(PPHttpRequestCache)responseCache - success:(PPHttpRequestSuccess)success - failure:(PPHttpRequestFailed)failure; ++ (void)cancelRequestWithURL:(NSString *)URL; + /** - * POST请求,无缓存 - * - * @param URL 请求地址 - * @param parameters 请求参数 - * @param success 请求成功的回调 - * @param failure 请求失败的回调 - * - * @return 返回的对象可取消请求,调用cancel方法 + 网络请求,有缓存 + + @param method 请求方式 GET/POST(可根据枚举自行选择多种请求方式) + @param URLString 请求地址 + @param parameters 请求参数 + @param responseCache 缓存数据的回调 + @param success 请求成功的回调 + @param failure 请求失败的回调 + @return 返回的对象可取消请求,调用cancel方法 */ -+ (__kindof NSURLSessionTask *)POST:(NSString *)URL - parameters:(id)parameters - success:(PPHttpRequestSuccess)success - failure:(PPHttpRequestFailed)failure; ++(NSURLSessionTask *)request:(PPRequestMethod)method URLString:(NSString *)URLString parameters:(id)parameters + responseCache:(PPHttpRequestCache)responseCache + success:(PPHttpRequestSuccess)success + failure:(PPHttpRequestFailed)failure; + /** - * POST请求,自动缓存 - * - * @param URL 请求地址 - * @param parameters 请求参数 - * @param responseCache 缓存数据的回调 - * @param success 请求成功的回调 - * @param failure 请求失败的回调 - * - * @return 返回的对象可取消请求,调用cancel方法 + 网络请求,无缓存 + + @param method 请求方式 GET/POST(可根据枚举自行选择多种请求方式) + @param URLString 请求地址 + @param parameters 请求参数 + @param success 请求成功的回调 + @param failure 请求失败的回调 + @return 返回的对象可取消请求,调用cancel方法 */ -+ (__kindof NSURLSessionTask *)POST:(NSString *)URL - parameters:(id)parameters - responseCache:(PPHttpRequestCache)responseCache - success:(PPHttpRequestSuccess)success - failure:(PPHttpRequestFailed)failure; ++(NSURLSessionTask *)request:(PPRequestMethod)method URLString:(NSString *)URLString parameters:(id)parameters + success:(PPHttpRequestSuccess)success + failure:(PPHttpRequestFailed)failure; /** * 上传文件 diff --git a/PPNetworkHelper/PPNetworkHelper/PPNetworkHelper.m b/PPNetworkHelper/PPNetworkHelper/PPNetworkHelper.m index 3f2d57e..07692ce 100755 --- a/PPNetworkHelper/PPNetworkHelper/PPNetworkHelper.m +++ b/PPNetworkHelper/PPNetworkHelper/PPNetworkHelper.m @@ -18,13 +18,28 @@ #endif #define NSStringFormat(format,...) [NSString stringWithFormat:format,##__VA_ARGS__] +//网络工具协议 +@protocol NetworkToolsProxy +@optional ++ (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(id)parameters + uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress + downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress + success:(void (^)(NSURLSessionDataTask *, id))success + failure:(void (^)(NSURLSessionDataTask *, NSError *))failure; +@end + +@interface PPNetworkHelper() + +@end @implementation PPNetworkHelper static BOOL _isOpenLog; // 是否已开启日志打印 -static NSMutableArray *_allSessionTask; -static AFHTTPSessionManager *_sessionManager; +static AFHTTPSessionManager *_sessionManager; +static NSMutableArray *_allSessionTask; #pragma mark - 开始监听网络 + (void)networkStatusWithBlock:(PPNetworkStatus)networkStatus { @@ -71,9 +86,11 @@ + (void)closeLog { _isOpenLog = NO; } -+ (void)cancelAllRequest { ++ (void)cancelAllRequest +{ // 锁操作 - @synchronized(self) { + @synchronized(self) + { [[self allSessionTask] enumerateObjectsUsingBlock:^(NSURLSessionTask *_Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) { [task cancel]; }]; @@ -81,10 +98,13 @@ + (void)cancelAllRequest { } } -+ (void)cancelRequestWithURL:(NSString *)URL { ++ (void)cancelRequestWithURL:(NSString *)URL +{ if (!URL) { return; } - @synchronized (self) { + @synchronized (self) + { [[self allSessionTask] enumerateObjectsUsingBlock:^(NSURLSessionTask *_Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) { + if ([task.currentRequest.URL.absoluteString hasPrefix:URL]) { [task cancel]; [[self allSessionTask] removeObject:task]; @@ -94,86 +114,145 @@ + (void)cancelRequestWithURL:(NSString *)URL { } } -#pragma mark - GET请求无缓存 -+ (NSURLSessionTask *)GET:(NSString *)URL - parameters:(id)parameters - success:(PPHttpRequestSuccess)success - failure:(PPHttpRequestFailed)failure { - return [self GET:URL parameters:parameters responseCache:nil success:success failure:failure]; -} -#pragma mark - POST请求无缓存 -+ (NSURLSessionTask *)POST:(NSString *)URL - parameters:(id)parameters - success:(PPHttpRequestSuccess)success - failure:(PPHttpRequestFailed)failure { - return [self POST:URL parameters:parameters responseCache:nil success:success failure:failure]; ++(NSURLSessionTask *)request:(PPRequestMethod)method URLString:(NSString *)URLString parameters:(id)parameters + success:(PPHttpRequestSuccess)success + failure:(PPHttpRequestFailed)failure{ + return [self request:method URLString:URLString parameters:(id)parameters responseCache:nil success:success failure:failure]; } -#pragma mark - GET请求自动缓存 -+ (NSURLSessionTask *)GET:(NSString *)URL - parameters:(id)parameters - responseCache:(PPHttpRequestCache)responseCache - success:(PPHttpRequestSuccess)success - failure:(PPHttpRequestFailed)failure { - //读取缓存 - responseCache!=nil ? responseCache([PPNetworkCache httpCacheForURL:URL parameters:parameters]) : nil; - - NSURLSessionTask *sessionTask = [_sessionManager GET:URL parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) { - - } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { - - if (_isOpenLog) {PPLog(@"responseObject = %@",responseObject);} - [[self allSessionTask] removeObject:task]; - success ? success(responseObject) : nil; - //对数据进行异步缓存 - responseCache!=nil ? [PPNetworkCache setHttpCache:responseObject URL:URL parameters:parameters] : nil; - - } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { - - if (_isOpenLog) {PPLog(@"error = %@",error);} - [[self allSessionTask] removeObject:task]; - failure ? failure(error) : nil; - - }]; - // 添加sessionTask到数组 - sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil ; ++ (NSURLSessionTask *)request:(PPRequestMethod)method URLString:(NSString *)URLString parameters:(id)parameters + responseCache:(PPHttpRequestCache)responseCache + success:(PPHttpRequestSuccess)success + failure:(PPHttpRequestFailed)failure{ - return sessionTask; -} - -#pragma mark - POST请求自动缓存 -+ (NSURLSessionTask *)POST:(NSString *)URL - parameters:(id)parameters - responseCache:(PPHttpRequestCache)responseCache - success:(PPHttpRequestSuccess)success - failure:(PPHttpRequestFailed)failure { //读取缓存 - responseCache!=nil ? responseCache([PPNetworkCache httpCacheForURL:URL parameters:parameters]) : nil; - - NSURLSessionTask *sessionTask = [_sessionManager POST:URL parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) { - - } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { - - if (_isOpenLog) {PPLog(@"responseObject = %@",responseObject);} - [[self allSessionTask] removeObject:task]; - success ? success(responseObject) : nil; - //对数据进行异步缓存 - responseCache!=nil ? [PPNetworkCache setHttpCache:responseObject URL:URL parameters:parameters] : nil; - - } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { - - if (_isOpenLog) {PPLog(@"error = %@",error);} - [[self allSessionTask] removeObject:task]; - failure ? failure(error) : nil; - - }]; + responseCache ? responseCache([PPNetworkCache httpCacheForURL:URLString parameters:parameters]) : nil; + NSURLSessionTask *sessionTask = nil; + switch (method) { + case GET: + { + sessionTask = [_sessionManager GET:URLString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) { + + } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + + [[self allSessionTask] removeObject:task]; + success ? success(responseObject) : nil; + //对数据进行异步缓存 + responseCache ? [PPNetworkCache setHttpCache:responseObject URL:URLString parameters:parameters] : nil; + PPLog(@"responseObject = %@",[self jsonToString:responseObject]); + + } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { + + [[self allSessionTask] removeObject:task]; + failure ? failure(error) : nil; + PPLog(@"error = %@",error); + + }]; + } + break; + case POST:{ + sessionTask = [_sessionManager POST:URLString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) { + + } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + + [[self allSessionTask] removeObject:task]; + success ? success(responseObject) : nil; + //对数据进行异步缓存 + responseCache ? [PPNetworkCache setHttpCache:responseObject URL:URLString parameters:parameters] : nil; + PPLog(@"responseObject = %@",[self jsonToString:responseObject]); + + } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { + + [[self allSessionTask] removeObject:task]; + failure ? failure(error) : nil; + PPLog(@"error = %@",error); + + }]; + } + break; + case DELETE:{ + sessionTask = [_sessionManager DELETE:URLString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + + [[self allSessionTask] removeObject:task]; + success ? success(responseObject) : nil; + //对数据进行异步缓存 + responseCache ? [PPNetworkCache setHttpCache:responseObject URL:URLString parameters:parameters] : nil; + PPLog(@"responseObject = %@",[self jsonToString:responseObject]); + + } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { + + [[self allSessionTask] removeObject:task]; + failure ? failure(error) : nil; + PPLog(@"error = %@",error); + + }]; + } + + break; + case HEAD: + { + [_sessionManager HEAD:URLString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task) { + [[self allSessionTask] removeObject:task]; + success ? success(task) : nil; + + + } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { + [[self allSessionTask] removeObject:task]; + failure ? failure(error) : nil; + PPLog(@"error = %@",error); + }]; + } + break; + case PUT:{ + sessionTask = [_sessionManager PUT:URLString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + + [[self allSessionTask] removeObject:task]; + success ? success(responseObject) : nil; + //对数据进行异步缓存 + responseCache ? [PPNetworkCache setHttpCache:responseObject URL:URLString parameters:parameters] : nil; + PPLog(@"responseObject = %@",[self jsonToString:responseObject]); + + } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { + + [[self allSessionTask] removeObject:task]; + failure ? failure(error) : nil; + PPLog(@"error = %@",error); + + }]; + } + + break; + case PATCH: + { + sessionTask = [_sessionManager PATCH:URLString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + + [[self allSessionTask] removeObject:task]; + success ? success(responseObject) : nil; + //对数据进行异步缓存 + responseCache ? [PPNetworkCache setHttpCache:responseObject URL:URLString parameters:parameters] : nil; + PPLog(@"responseObject = %@",[self jsonToString:responseObject]); + + } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { + + [[self allSessionTask] removeObject:task]; + failure ? failure(error) : nil; + PPLog(@"error = %@",error); + + }]; + } + break; + default: + break; + } // 添加最新的sessionTask到数组 sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil ; return sessionTask; } + + #pragma mark - 上传文件 + (NSURLSessionTask *)uploadFileWithURL:(NSString *)URL parameters:(id)parameters @@ -185,7 +264,7 @@ + (NSURLSessionTask *)uploadFileWithURL:(NSString *)URL NSURLSessionTask *sessionTask = [_sessionManager POST:URL parameters:parameters constructingBodyWithBlock:^(id _Nonnull formData) { NSError *error = nil; - [formData appendPartWithFileURL:[NSURL URLWithString:filePath] name:name error:&error]; + [formData appendPartWithFileURL:[NSURL fileURLWithPath:filePath] name:name error:&error]; (failure && error) ? failure(error) : nil; } progress:^(NSProgress * _Nonnull uploadProgress) { //上传进度 @@ -212,6 +291,7 @@ + (NSURLSessionTask *)uploadFileWithURL:(NSString *)URL } #pragma mark - 上传多张图片 + + (NSURLSessionTask *)uploadImagesWithURL:(NSString *)URL parameters:(id)parameters name:(NSString *)name @@ -303,6 +383,19 @@ + (NSURLSessionTask *)downloadWithURL:(NSString *)URL return downloadTask; } +/** + * json转字符串 + */ ++ (NSString *)jsonToString:(id)data { + if(data == nil) { return nil; } + if ([data isKindOfClass:[NSData class]]) { + return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; + } + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:NSJSONWritingPrettyPrinted error:nil]; + return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + +} + /** 存储着所有的请求task数组 */ @@ -320,18 +413,23 @@ + (NSMutableArray *)allSessionTask { + (void)load { [[AFNetworkReachabilityManager sharedManager] startMonitoring]; } -/** - * 所有的HTTP请求共享一个AFHTTPSessionManager - * 原理参考地址:http://www.jianshu.com/p/5969bbb4af9f - */ + + + (void)initialize { _sessionManager = [AFHTTPSessionManager manager]; + // 设置请求参数的类型:JSON (AFJSONRequestSerializer,AFHTTPRequestSerializer) + _sessionManager.requestSerializer = [AFJSONRequestSerializer serializer]; + // 设置请求的超时时间 _sessionManager.requestSerializer.timeoutInterval = 30.f; + // 设置服务器返回结果的类型:JSON (AFJSONResponseSerializer,AFHTTPResponseSerializer) + _sessionManager.responseSerializer = [AFJSONResponseSerializer serializer]; + _sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/plain", @"text/javascript", @"text/xml", @"image/*", nil]; // 打开状态栏的等待菊花 [AFNetworkActivityIndicatorManager sharedManager].enabled = YES; } + #pragma mark - 重置AFHTTPSessionManager相关属性 + (void)setAFHTTPSessionManagerProperty:(void (^)(AFHTTPSessionManager *))sessionManager { diff --git a/PPNetworkHelper/ViewController.m b/PPNetworkHelper/ViewController.m index 2827385..3747d8b 100755 --- a/PPNetworkHelper/ViewController.m +++ b/PPNetworkHelper/ViewController.m @@ -106,7 +106,11 @@ - (void)viewDidLoad { [self getCurrentNetworkStatus]; }); - [self PPHTTPRequestLayerDemo]; +// [self PPHTTPRequestLayerDemo]; + + + BOOL isOn = [[[NSUserDefaults standardUserDefaults] objectForKey:@"isOn"] boolValue]; + [self getData:isOn url:dataUrl]; } /** @@ -118,18 +122,19 @@ - (void)viewDidLoad { - (void)PPHTTPRequestLayerDemo { // 登陆 - [PPHTTPRequest getLoginWithParameters:@"参数" success:^(id response) { + [PPHTTPRequest getLoginWithParameters:@{} success:^(id response) { } failure:^(NSError *error) { }]; - // 退出 - [PPHTTPRequest getExitWithParameters:@"参数" success:^(id response) { - - } failure:^(NSError *error) { - - }]; +// // 退出 +// [PPHTTPRequest getExitWithParameters:@"参数" success:^(id response) { +// +// } failure:^(NSError *error) { +// +// }]; + } @@ -137,19 +142,23 @@ - (void)PPHTTPRequestLayerDemo #pragma mark - 这里的请求只是一个演示, 在真实的项目中建议不要这样做, 具体做法可以参照PPHTTPRequestLayer文件夹的例子 - (void)getData:(BOOL)isOn url:(NSString *)url { - + self.networkData.editable = NO; + self.cacheData.editable = NO; + NSDictionary *para = @{ @"a":@"list", @"c":@"data",@"client":@"iphone",@"page":@"0",@"per":@"10", @"type":@"29"}; // 自动缓存 if(isOn) { self.cacheStatus.text = @"缓存打开"; self.cacheSwitch.on = YES; - [PPNetworkHelper GET:url parameters:para responseCache:^(id responseCache) { + + [PPNetworkHelper request:GET URLString:url parameters:para responseCache:^(id responseCache) { // 1.先加载缓存数据 - self.cacheData.text = [self jsonToString:responseCache]; + self.cacheData.text = [NSString stringWithFormat:@"%@",responseCache]; } success:^(id responseObject) { // 2.再请求网络数据 - self.networkData.text = [self jsonToString:responseObject]; + self.networkData.text = [NSString stringWithFormat:@"%@",responseObject]; + self.cacheData.text = self.networkData.text; } failure:^(NSError *error) { }]; @@ -158,16 +167,20 @@ - (void)getData:(BOOL)isOn url:(NSString *)url // 无缓存 else { + self.cacheStatus.text = @"缓存关闭"; self.cacheSwitch.on = NO; self.cacheData.text = @""; - [PPNetworkHelper GET:url parameters:para success:^(id responseObject) { - self.networkData.text = [self jsonToString:responseObject]; + [PPNetworkHelper request:GET URLString:url parameters:para success:^(id responseObject) { + // 2.再请求网络数据 + self.networkData.text = [NSString stringWithFormat:@"%@",responseObject]; } failure:^(NSError *error) { + }]; + } } @@ -272,9 +285,6 @@ - (IBAction)download:(UIButton *)sender { self.progress.progress = 0; [self.downloadBtn setTitle:@"开始下载" forState:UIControlStateNormal]; } - - - } #pragma mark - 缓存开关 @@ -287,7 +297,7 @@ - (IBAction)isCache:(UISwitch *)sender { /** * json转字符串 */ -- (NSString *)jsonToString:(NSDictionary *)dic +- (NSString *)jsonToString:(NSData *)dic { if(!dic){ return nil; diff --git a/PPNetworkHelper/YYCache/YYDiskCache.m b/PPNetworkHelper/YYCache/YYDiskCache.m index 735cc5d..917e238 100755 --- a/PPNetworkHelper/YYCache/YYDiskCache.m +++ b/PPNetworkHelper/YYCache/YYDiskCache.m @@ -1,3 +1,7 @@ +// The converted code is limited to 2 KB. +// Upgrade your plan to remove this limitation. +// +// Converted to Swift 4 by Swiftify v4.2.20547 - https://objectivec2swift.com/ // // YYDiskCache.m // YYCache @@ -8,451 +12,49 @@ // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // - -#import "YYDiskCache.h" -#import "YYKVStorage.h" -#import -#import -#import -#import - -#define Lock() dispatch_semaphore_wait(self->_lock, DISPATCH_TIME_FOREVER) -#define Unlock() dispatch_semaphore_signal(self->_lock) - -static const int extended_data_key; - -/// Free disk space in bytes. -static int64_t _YYDiskSpaceFree() { - NSError *error = nil; - NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error]; - if (error) return -1; - int64_t space = [[attrs objectForKey:NSFileSystemFreeSize] longLongValue]; - if (space < 0) space = -1; - return space; +import CommonCrypto +import ObjectiveC +import UIKit +func Lock() { + dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER) } - -/// String's md5 hash. -static NSString *_YYNSStringMD5(NSString *string) { - if (!string) return nil; - NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding]; - unsigned char result[CC_MD5_DIGEST_LENGTH]; - CC_MD5(data.bytes, (CC_LONG)data.length, result); - return [NSString stringWithFormat: - @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", - result[0], result[1], result[2], result[3], - result[4], result[5], result[6], result[7], - result[8], result[9], result[10], result[11], - result[12], result[13], result[14], result[15] - ]; +func Unlock() -> Int { + return lock.signal() } - +private let extended_data_key: Int = 0 /// weak reference for all instances -static NSMapTable *_globalInstances; -static dispatch_semaphore_t _globalInstancesLock; - -static void _YYDiskCacheInitGlobal() { - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - _globalInstancesLock = dispatch_semaphore_create(1); - _globalInstances = [[NSMapTable alloc] initWithKeyOptions:NSPointerFunctionsStrongMemory valueOptions:NSPointerFunctionsWeakMemory capacity:0]; - }); -} - -static YYDiskCache *_YYDiskCacheGetGlobal(NSString *path) { - if (path.length == 0) return nil; - _YYDiskCacheInitGlobal(); - dispatch_semaphore_wait(_globalInstancesLock, DISPATCH_TIME_FOREVER); - id cache = [_globalInstances objectForKey:path]; - dispatch_semaphore_signal(_globalInstancesLock); - return cache; -} - -static void _YYDiskCacheSetGlobal(YYDiskCache *cache) { - if (cache.path.length == 0) return; - _YYDiskCacheInitGlobal(); - dispatch_semaphore_wait(_globalInstancesLock, DISPATCH_TIME_FOREVER); - [_globalInstances setObject:cache forKey:cache.path]; - dispatch_semaphore_signal(_globalInstancesLock); -} - - - -@implementation YYDiskCache { - YYKVStorage *_kv; - dispatch_semaphore_t _lock; - dispatch_queue_t _queue; -} - -- (void)_trimRecursively { - __weak typeof(self) _self = self; - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_autoTrimInterval * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{ - __strong typeof(_self) self = _self; - if (!self) return; - [self _trimInBackground]; - [self _trimRecursively]; - }); -} - -- (void)_trimInBackground { - __weak typeof(self) _self = self; - dispatch_async(_queue, ^{ - __strong typeof(_self) self = _self; - if (!self) return; - Lock(); - [self _trimToCost:self.costLimit]; - [self _trimToCount:self.countLimit]; - [self _trimToAge:self.ageLimit]; - [self _trimToFreeDiskSpace:self.freeDiskSpaceLimit]; - Unlock(); - }); -} - -- (void)_trimToCost:(NSUInteger)costLimit { - if (costLimit >= INT_MAX) return; - [_kv removeItemsToFitSize:(int)costLimit]; - -} - -- (void)_trimToCount:(NSUInteger)countLimit { - if (countLimit >= INT_MAX) return; - [_kv removeItemsToFitCount:(int)countLimit]; -} - -- (void)_trimToAge:(NSTimeInterval)ageLimit { - if (ageLimit <= 0) { - [_kv removeAllItems]; - return; - } - long timestamp = time(NULL); - if (timestamp <= ageLimit) return; - long age = timestamp - ageLimit; - if (age >= INT_MAX) return; - [_kv removeItemsEarlierThanTime:(int)age]; -} - -- (void)_trimToFreeDiskSpace:(NSUInteger)targetFreeDiskSpace { - if (targetFreeDiskSpace == 0) return; - int64_t totalBytes = [_kv getItemsSize]; - if (totalBytes <= 0) return; - int64_t diskFreeBytes = _YYDiskSpaceFree(); - if (diskFreeBytes < 0) return; - int64_t needTrimBytes = targetFreeDiskSpace - diskFreeBytes; - if (needTrimBytes <= 0) return; - int64_t costLimit = totalBytes - needTrimBytes; - if (costLimit < 0) costLimit = 0; - [self _trimToCost:(int)costLimit]; -} - -- (NSString *)_filenameForKey:(NSString *)key { - NSString *filename = nil; - if (_customFileNameBlock) filename = _customFileNameBlock(key); - if (!filename) filename = _YYNSStringMD5(key); - return filename; -} - -- (void)_appWillBeTerminated { - Lock(); - _kv = nil; - Unlock(); -} - -#pragma mark - public - -- (void)dealloc { - [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillTerminateNotification object:nil]; -} - -- (instancetype)init { - @throw [NSException exceptionWithName:@"YYDiskCache init error" reason:@"YYDiskCache must be initialized with a path. Use 'initWithPath:' or 'initWithPath:inlineThreshold:' instead." userInfo:nil]; - return [self initWithPath:@"" inlineThreshold:0]; -} - -- (instancetype)initWithPath:(NSString *)path { - return [self initWithPath:path inlineThreshold:1024 * 20]; // 20KB -} - -- (instancetype)initWithPath:(NSString *)path - inlineThreshold:(NSUInteger)threshold { - self = [super init]; - if (!self) return nil; - - YYDiskCache *globalCache = _YYDiskCacheGetGlobal(path); - if (globalCache) return globalCache; - - YYKVStorageType type; - if (threshold == 0) { - type = YYKVStorageTypeFile; - } else if (threshold == NSUIntegerMax) { - type = YYKVStorageTypeSQLite; - } else { - type = YYKVStorageTypeMixed; - } - - YYKVStorage *kv = [[YYKVStorage alloc] initWithPath:path type:type]; - if (!kv) return nil; - - _kv = kv; - _path = path; - _lock = dispatch_semaphore_create(1); - _queue = dispatch_queue_create("com.ibireme.cache.disk", DISPATCH_QUEUE_CONCURRENT); - _inlineThreshold = threshold; - _countLimit = NSUIntegerMax; - _costLimit = NSUIntegerMax; - _ageLimit = DBL_MAX; - _freeDiskSpaceLimit = 0; - _autoTrimInterval = 60; - - [self _trimRecursively]; - _YYDiskCacheSetGlobal(self); - - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_appWillBeTerminated) name:UIApplicationWillTerminateNotification object:nil]; - return self; -} - -- (BOOL)containsObjectForKey:(NSString *)key { - if (!key) return NO; - Lock(); - BOOL contains = [_kv itemExistsForKey:key]; - Unlock(); - return contains; -} - -- (void)containsObjectForKey:(NSString *)key withBlock:(void(^)(NSString *key, BOOL contains))block { - if (!block) return; - __weak typeof(self) _self = self; - dispatch_async(_queue, ^{ - __strong typeof(_self) self = _self; - BOOL contains = [self containsObjectForKey:key]; - block(key, contains); - }); -} - -- (id)objectForKey:(NSString *)key { - if (!key) return nil; - Lock(); - YYKVStorageItem *item = [_kv getItemForKey:key]; - Unlock(); - if (!item.value) return nil; - - id object = nil; - if (_customUnarchiveBlock) { - object = _customUnarchiveBlock(item.value); - } else { - @try { - object = [NSKeyedUnarchiver unarchiveObjectWithData:item.value]; - } - @catch (NSException *exception) { - // nothing to do... - } +private var _globalInstances: NSMapTable? +private var _globalInstancesLock: DispatchSemaphore? +/// Free disk space in bytes. +private func YYDiskSpaceFree() -> Int64 { + var error: Error? = nil + let attrs = try? FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory()) + if error != nil { + return -1 } - if (object && item.extendedData) { - [YYDiskCache setExtendedData:item.extendedData toObject:object]; + var space = Int64(attrs?[.systemFreeSize] ?? 0) + if Int(space) < 0 { + space = -1 } - return object; -} - -- (void)objectForKey:(NSString *)key withBlock:(void(^)(NSString *key, id object))block { - if (!block) return; - __weak typeof(self) _self = self; - dispatch_async(_queue, ^{ - __strong typeof(_self) self = _self; - id object = [self objectForKey:key]; - block(key, object); - }); + return space } - -- (void)setObject:(id)object forKey:(NSString *)key { - if (!key) return; - if (!object) { - [self removeObjectForKey:key]; - return; - } - - NSData *extendedData = [YYDiskCache getExtendedDataFromObject:object]; - NSData *value = nil; - if (_customArchiveBlock) { - value = _customArchiveBlock(object); - } else { - @try { - value = [NSKeyedArchiver archivedDataWithRootObject:object]; - } - @catch (NSException *exception) { - // nothing to do... - } - } - if (!value) return; - NSString *filename = nil; - if (_kv.type != YYKVStorageTypeSQLite) { - if (value.length > _inlineThreshold) { - filename = [self _filenameForKey:key]; - } +/// String's md5 hash. +private func YYNSStringMD5(string: String?) -> String? { + if string == nil { + return nil } - - Lock(); - [_kv saveItemWithKey:key value:value filename:filename extendedData:extendedData]; - Unlock(); -} - -- (void)setObject:(id)object forKey:(NSString *)key withBlock:(void(^)(void))block { - __weak typeof(self) _self = self; - dispatch_async(_queue, ^{ - __strong typeof(_self) self = _self; - [self setObject:object forKey:key]; - if (block) block(); - }); -} - -- (void)removeObjectForKey:(NSString *)key { - if (!key) return; - Lock(); - [_kv removeItemForKey:key]; - Unlock(); -} - -- (void)removeObjectForKey:(NSString *)key withBlock:(void(^)(NSString *key))block { - __weak typeof(self) _self = self; - dispatch_async(_queue, ^{ - __strong typeof(_self) self = _self; - [self removeObjectForKey:key]; - if (block) block(key); - }); -} - -- (void)removeAllObjects { - Lock(); - [_kv removeAllItems]; - Unlock(); -} - -- (void)removeAllObjectsWithBlock:(void(^)(void))block { - __weak typeof(self) _self = self; - dispatch_async(_queue, ^{ - __strong typeof(_self) self = _self; - [self removeAllObjects]; - if (block) block(); - }); -} - -- (void)removeAllObjectsWithProgressBlock:(void(^)(int removedCount, int totalCount))progress - endBlock:(void(^)(BOOL error))end { - __weak typeof(self) _self = self; - dispatch_async(_queue, ^{ - __strong typeof(_self) self = _self; - if (!self) { - if (end) end(YES); - return; - } - Lock(); - [_kv removeAllItemsWithProgressBlock:progress endBlock:end]; - Unlock(); - }); -} - -- (NSInteger)totalCount { - Lock(); - int count = [_kv getItemsCount]; - Unlock(); - return count; -} - -- (void)totalCountWithBlock:(void(^)(NSInteger totalCount))block { - if (!block) return; - __weak typeof(self) _self = self; - dispatch_async(_queue, ^{ - __strong typeof(_self) self = _self; - NSInteger totalCount = [self totalCount]; - block(totalCount); - }); -} - -- (NSInteger)totalCost { - Lock(); - int count = [_kv getItemsSize]; - Unlock(); - return count; -} - -- (void)totalCostWithBlock:(void(^)(NSInteger totalCost))block { - if (!block) return; - __weak typeof(self) _self = self; - dispatch_async(_queue, ^{ - __strong typeof(_self) self = _self; - NSInteger totalCost = [self totalCost]; - block(totalCost); - }); -} - -- (void)trimToCount:(NSUInteger)count { - Lock(); - [self _trimToCount:count]; - Unlock(); -} - -- (void)trimToCount:(NSUInteger)count withBlock:(void(^)(void))block { - __weak typeof(self) _self = self; - dispatch_async(_queue, ^{ - __strong typeof(_self) self = _self; - [self trimToCount:count]; - if (block) block(); - }); -} - -- (void)trimToCost:(NSUInteger)cost { - Lock(); - [self _trimToCost:cost]; - Unlock(); -} - -- (void)trimToCost:(NSUInteger)cost withBlock:(void(^)(void))block { - __weak typeof(self) _self = self; - dispatch_async(_queue, ^{ - __strong typeof(_self) self = _self; - [self trimToCost:cost]; - if (block) block(); - }); -} - -- (void)trimToAge:(NSTimeInterval)age { - Lock(); - [self _trimToAge:age]; - Unlock(); -} - -- (void)trimToAge:(NSTimeInterval)age withBlock:(void(^)(void))block { - __weak typeof(self) _self = self; - dispatch_async(_queue, ^{ - __strong typeof(_self) self = _self; - [self trimToAge:age]; - if (block) block(); - }); -} - -+ (NSData *)getExtendedDataFromObject:(id)object { - if (!object) return nil; - return (NSData *)objc_getAssociatedObject(object, &extended_data_key); -} - -+ (void)setExtendedData:(NSData *)extendedData toObject:(id)object { - if (!object) return; - objc_setAssociatedObject(object, &extended_data_key, extendedData, OBJC_ASSOCIATION_RETAIN_NONATOMIC); -} - -- (NSString *)description { - if (_name) return [NSString stringWithFormat:@"<%@: %p> (%@:%@)", self.class, self, _name, _path]; - else return [NSString stringWithFormat:@"<%@: %p> (%@)", self.class, self, _path]; -} - -- (BOOL)errorLogsEnabled { - Lock(); - BOOL enabled = _kv.errorLogsEnabled; - Unlock(); - return enabled; -} - -- (void)setErrorLogsEnabled:(BOOL)errorLogsEnabled { - Lock(); - _kv.errorLogsEnabled = errorLogsEnabled; - Unlock(); -} - -@end + let data: Data? = string?.data(using: .utf8) + let result = [UInt8](repeating: 0, count: CC_MD5_DIGEST_LENGTH) + CC_MD5(data?.bytes, (data?.count ?? 0) as? CC_LONG, result) + return String(format: "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7], result[8], result[9], result[10], result[11], result[12], result[13], result[14], result[15]) +} +private func YYDiskCacheInitGlobal() { + // TODO: [Swiftify] ensure that the code below is executed only once (`dispatch_once()` is deprecated) + { + globalInstancesLock = DispatchSemaphore(value: 1) + globalInstances = NSMapTable(keyOptions: .strongMemory, valueOptions: .weakMemory, capacity: 0) +// +// The converted code is limited to 2 KB. +// Upgrade your plan to remove this limitation. +// +// %< ----------------------------------------------------------------------------------------- %< diff --git a/README.md b/README.md index 64be28f..d973d70 100755 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ then ### 1. 无自动缓存(GET与POST请求用法相同) #### 1.1 无缓存 ```objc -[PPNetworkHelper GET:url parameters:nil success:^(id responseObject) { +[PPNetworkHelper request:GET URLString:url parameters:nil success:^(id responseObject) { //请求成功 } failure:^(NSError *error) { //请求失败 @@ -39,7 +39,7 @@ then #### 1.2 无缓存,手动缓存 ```objc -[PPNetworkHelper GET:url parameters:nil success:^(id responseObject) { +[PPNetworkHelper request:GET URLString:url parameters:nil success:^(id responseObject) { //请求成功 //手动缓存 [PPNetworkCache setHttpCache:responseObject URL:url parameters:parameters]; @@ -50,7 +50,7 @@ then ### 2. 自动缓存(GET与POST请求用法相同) ```objc -[PPNetworkHelper GET:url parameters:nil responseCache:^(id responseCache) { +[PPNetworkHelper request:GET URLString:url parameters:nil responseCache:^(id responseCache) { //加载缓存数据 } success:^(id responseObject) { //请求成功