├── .gitignore ├── 23F70E8F-E292-459E-B0A7-CBB774BBCB39.png ├── LICENSE ├── PGNetworkHelper.podspec ├── PGNetworkHelper ├── PGNetAPIClient.h ├── PGNetAPIClient.m ├── PGNetworkCache.h ├── PGNetworkCache.m ├── PGNetworkHelper+Synchronously.h ├── PGNetworkHelper+Synchronously.m ├── PGNetworkHelper.h └── PGNetworkHelper.m └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 4 | 5 | ## Build generated 6 | build/ 7 | DerivedData/ 8 | 9 | ## Various settings 10 | *.pbxuser 11 | !default.pbxuser 12 | *.mode1v3 13 | !default.mode1v3 14 | *.mode2v3 15 | !default.mode2v3 16 | *.perspectivev3 17 | !default.perspectivev3 18 | xcuserdata/ 19 | 20 | ## Other 21 | *.moved-aside 22 | *.xcuserstate 23 | 24 | ## Obj-C/Swift specific 25 | *.hmap 26 | *.ipa 27 | *.dSYM.zip 28 | *.dSYM 29 | 30 | # CocoaPods 31 | # 32 | # We recommend against adding the Pods directory to your .gitignore. However 33 | # you should judge for yourself, the pros and cons are mentioned at: 34 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 35 | # 36 | # Pods/ 37 | 38 | # Carthage 39 | # 40 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 41 | # Carthage/Checkouts 42 | 43 | Carthage/Build 44 | 45 | # fastlane 46 | # 47 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the 48 | # screenshots whenever they are needed. 49 | # For more information about the recommended setup visit: 50 | # https://github.com/fastlane/fastlane/blob/master/fastlane/docs/Gitignore.md 51 | 52 | fastlane/report.xml 53 | fastlane/screenshots 54 | 55 | #Code Injection 56 | # 57 | # After new code Injection tools there's a generated folder /iOSInjectionProject 58 | # https://github.com/johnno1962/injectionforxcode 59 | 60 | iOSInjectionProject/ 61 | -------------------------------------------------------------------------------- /23F70E8F-E292-459E-B0A7-CBB774BBCB39.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiaozhuxiong121/PGNetworkHelper/d944835be333feb6ed154ae968a7ce85f01110ba/23F70E8F-E292-459E-B0A7-CBB774BBCB39.png -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 piggybear 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 all 13 | 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 THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /PGNetworkHelper.podspec: -------------------------------------------------------------------------------- 1 | Pod::Spec.new do |s| 2 | s.name = "PGNetworkHelper" 3 | s.version = "2.0.1" 4 | s.summary = "PINCache做为AFNetworking缓存层,将AFNetworking请求的数据缓存起来,支持取消当前网络请求,以及取消所有的网络请求,除了常用的Get,Post方法,也将上传图片以及下载文件进行了封装,并且支持同步请求,使用方法及其简单。" 5 | s.homepage = "https://github.com/xiaozhuxiong121/PGNetworkHelper" 6 | s.license = "MIT" 7 | s.author = { "piggybear" => "piggybear_net@163.com" } 8 | s.platform = :ios, "8.0" 9 | s.source = { :git => "https://github.com/xiaozhuxiong121/PGNetworkHelper.git", :tag => s.version } 10 | s.source_files = "PGNetworkHelper", "PGNetworkHelper/*.{h,m}" 11 | s.frameworks = "UIKit" 12 | s.requires_arc = true 13 | 14 | s.dependency 'AFNetworking' 15 | s.dependency 'PINCache' 16 | end 17 | 18 | 19 | -------------------------------------------------------------------------------- /PGNetworkHelper/PGNetAPIClient.h: -------------------------------------------------------------------------------- 1 | // 2 | // PGNetAPIClient.h 3 | // 4 | // Created by piggybear on 16/8/22. 5 | // Copyright © 2016年 piggybear. All rights reserved. 6 | // 7 | 8 | #import 9 | 10 | @interface PGNetAPIClient : AFHTTPSessionManager 11 | 12 | + (void)baseUrl:(NSString *)baseUrl; 13 | + (void)policyWithPinningMode:(AFSSLPinningMode)pinningMode; 14 | 15 | + (instancetype)sharedClient; 16 | 17 | @end 18 | -------------------------------------------------------------------------------- /PGNetworkHelper/PGNetAPIClient.m: -------------------------------------------------------------------------------- 1 | // 2 | // PGNetAPIClient.m 3 | // 4 | // Created by piggybear on 16/8/22. 5 | // Copyright © 2016年 piggybear. All rights reserved. 6 | // 7 | 8 | #import "PGNetAPIClient.h" 9 | 10 | @implementation PGNetAPIClient 11 | 12 | static NSString *_baseUrl = @""; 13 | static AFSSLPinningMode _pinningMode = AFSSLPinningModeNone; 14 | 15 | + (instancetype)sharedClient { 16 | static PGNetAPIClient *_sharedClient = nil; 17 | static dispatch_once_t onceToken; 18 | dispatch_once(&onceToken, ^{ 19 | NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration ephemeralSessionConfiguration]; 20 | _sharedClient = [[PGNetAPIClient alloc] initWithBaseURL:[NSURL URLWithString:_baseUrl] sessionConfiguration:sessionConfiguration]; 21 | _sharedClient.securityPolicy = [AFSecurityPolicy policyWithPinningMode:_pinningMode]; 22 | }); 23 | return _sharedClient; 24 | } 25 | 26 | + (void)baseUrl:(NSString *)baseUrl { 27 | _baseUrl = baseUrl; 28 | } 29 | 30 | + (void)policyWithPinningMode:(AFSSLPinningMode)pinningMode { 31 | _pinningMode = pinningMode; 32 | } 33 | 34 | @end 35 | -------------------------------------------------------------------------------- /PGNetworkHelper/PGNetworkCache.h: -------------------------------------------------------------------------------- 1 | // 2 | // PGNetworkCache.h 3 | // 4 | // Created by piggybear on 16/8/22. 5 | // Copyright © 2016年 piggybear. All rights reserved. 6 | // 7 | 8 | #import 9 | #import 10 | 11 | #pragma mark - 网络数据缓存类 12 | 13 | @interface PGNetworkCache : NSObject 14 | 15 | /** 16 | * 设置缓存路径 17 | * 18 | * @param name 路径文件夹的名称 19 | */ 20 | + (void)pathName:(NSString *)name; 21 | 22 | /** 23 | * 缓存网络数据 24 | * 25 | * @param responseCache 服务器返回的数据 26 | * @param key 缓存数据对应的key值,推荐填入请求的URL 27 | */ 28 | + (void)saveResponseCache:(id )responseCache forKey:(NSString *)key; 29 | 30 | /** 31 | * 取出缓存的数据 32 | * 33 | * @param key 根据存入时候填入的key值来取出对应的数据 34 | * 35 | * @return 缓存的数据 36 | */ 37 | + (id)getResponseCacheForKey:(NSString *)key; 38 | 39 | /** 40 | * 41 | * 删除缓存 42 | * @param key 要删除缓存的key值 43 | */ 44 | + (void)removeResponseCacheForKey:(NSString *)key; 45 | 46 | /** 47 | * 删除所有的缓存 48 | */ 49 | + (void)removeAllResponseCache; 50 | 51 | @end 52 | -------------------------------------------------------------------------------- /PGNetworkHelper/PGNetworkCache.m: -------------------------------------------------------------------------------- 1 | // 2 | // PGNetworkCache.m 3 | // 4 | // Created by piggybear on 16/8/22. 5 | // Copyright © 2016年 piggybear. All rights reserved. 6 | // 7 | 8 | #import "PGNetworkCache.h" 9 | #import 10 | 11 | @implementation PGNetworkCache 12 | static PINCache *pinCache = nil; 13 | 14 | + (void)pathName:(NSString *)name { 15 | NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject; 16 | cachePath = [cachePath stringByAppendingPathComponent:@"com.pinterest.PINDiskCache.PINCacheShared"]; 17 | cachePath = [cachePath stringByAppendingPathComponent:name]; 18 | pinCache = [[PINCache sharedCache] initWithName:@"name" rootPath:cachePath]; 19 | } 20 | 21 | + (void)saveResponseCache:(id )responseCache forKey:(NSString *)key { 22 | if (pinCache == nil) { 23 | pinCache = [PINCache sharedCache]; 24 | } 25 | [pinCache setObject:responseCache forKey:[self cachedFileNameForKey: key]]; 26 | } 27 | 28 | + (id)getResponseCacheForKey:(NSString *)key { 29 | if (pinCache == nil) { 30 | pinCache = [PINCache sharedCache]; 31 | } 32 | return [pinCache objectForKey:[self cachedFileNameForKey: key]]; 33 | } 34 | 35 | + (void)removeResponseCacheForKey:(NSString *)key { 36 | if (pinCache == nil) { 37 | pinCache = [PINCache sharedCache]; 38 | } 39 | [pinCache removeObjectForKey:[self cachedFileNameForKey: key]]; 40 | } 41 | 42 | + (void)removeAllResponseCache { 43 | if (pinCache == nil) { 44 | pinCache = [PINCache sharedCache]; 45 | } 46 | [pinCache removeAllObjects]; 47 | } 48 | 49 | + (NSString *)cachedFileNameForKey:(NSString *)key { 50 | const char *str = key.UTF8String; 51 | if (str == NULL) { 52 | str = ""; 53 | } 54 | unsigned char r[CC_MD5_DIGEST_LENGTH]; 55 | CC_MD5(str, (CC_LONG)strlen(str), r); 56 | NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%@", 57 | r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], 58 | r[11], r[12], r[13], r[14], r[15], [key.pathExtension isEqualToString:@""] ? @"" : [NSString stringWithFormat:@".%@", key.pathExtension]]; 59 | return filename; 60 | } 61 | 62 | @end 63 | 64 | -------------------------------------------------------------------------------- /PGNetworkHelper/PGNetworkHelper+Synchronously.h: -------------------------------------------------------------------------------- 1 | // 2 | // PGNetworkHelper+Synchronously.h 3 | // AFNetworking 4 | // 5 | // Created by piggybear on 2017/7/25. 6 | // 7 | 8 | #import "PGNetworkHelper.h" 9 | 10 | @interface PGNetworkHelper (Synchronously) 11 | /** 12 | * GET请求 13 | * 14 | * @param URL 请求地址 15 | * @param parameters 请求参数 16 | * @param cache 是否缓存数据 17 | * @param responseCache 缓存数据的回调 18 | * @param success 请求成功的回调 19 | * @param failure 请求失败的回调 20 | * 21 | * @return 返回的对象可取消请求,调用cancle方法 22 | */ 23 | + (NSURLSessionTask *)synchronouslyGET:(NSString *)URL 24 | parameters:(id)parameters 25 | cache:(BOOL)cache 26 | responseCache:(HttpRequestCache)responseCache 27 | success:(HttpRequestSuccess)success 28 | failure:(HttpRequestFailed)failure; 29 | 30 | /** 31 | * POST请求 32 | * 33 | * @param URL 请求地址 34 | * @param parameters 请求参数 35 | * @param cache 是否缓存数据 36 | * @param responseCache 缓存数据的回调 37 | * @param success 请求成功的回调 38 | * @param failure 请求失败的回调 39 | * 40 | * @return 返回的对象可取消请求,调用cancle方法 41 | */ 42 | + (NSURLSessionTask *)synchronouslyPOST:(NSString *)URL 43 | parameters:(id)parameters 44 | cache:(BOOL)cache 45 | responseCache:(HttpRequestCache)responseCache 46 | success:(HttpRequestSuccess)success 47 | failure:(HttpRequestFailed)failure; 48 | 49 | /** 50 | * 上传图片文件 51 | * 52 | * @param URL 请求地址 53 | * @param parameters 请求参数 54 | * @param images 图片数组 55 | * @param name 文件对应服务器上的字段 56 | * @param mimeType 图片文件的类型,例:png、jpeg(默认类型).... 57 | * @param progress 上传进度信息 58 | * @param success 请求成功的回调 59 | * @param failure 请求失败的回调 60 | * 61 | * @return 返回的对象可取消请求,调用cancle方法 62 | */ 63 | + (NSURLSessionTask *)synchronouslyUploadWithURL:(NSString *)URL 64 | parameters:(NSDictionary *)parameters 65 | images:(NSArray *)images 66 | name:(NSString *)name 67 | mimeType:(NSString *)mimeType 68 | progress:(HttpProgress)progress 69 | success:(HttpRequestSuccess)success 70 | failure:(HttpRequestFailed)failure; 71 | 72 | /** 73 | * 下载文件 74 | * 75 | * @param URL 请求地址 76 | * @param fileDir 文件存储目录(默认存储目录为Download) 77 | * @param progress 文件下载的进度信息 78 | * @param success 下载成功的回调(回调参数filePath:文件的路径) 79 | * @param failure 下载失败的回调 80 | * 81 | * @return 返回NSURLSessionDownloadTask实例,可用于暂停继续,暂停调用suspend方法,开始下载调用resume方法 82 | */ 83 | + (__kindof NSURLSessionTask *)synchronouslyDownloadWithURL:(NSString *)URL 84 | fileDir:(NSString *)fileDir 85 | progress:(HttpProgress)progress 86 | success:(void(^)(NSString *filePath))success 87 | failure:(HttpRequestFailed)failure; 88 | @end 89 | -------------------------------------------------------------------------------- /PGNetworkHelper/PGNetworkHelper+Synchronously.m: -------------------------------------------------------------------------------- 1 | // 2 | // PGNetworkHelper+Synchronously.m 3 | // AFNetworking 4 | // 5 | // Created by piggybear on 2017/7/25. 6 | // 7 | 8 | #import "PGNetworkHelper+Synchronously.h" 9 | 10 | @implementation PGNetworkHelper (Synchronously) 11 | + (NSURLSessionTask *)synchronouslyGET:(NSString *)URL parameters:(id)parameters cache:(BOOL)cache responseCache:(HttpRequestCache)responseCache success:(HttpRequestSuccess)success failure:(HttpRequestFailed)failure { 12 | [self exceptionLogic]; 13 | dispatch_semaphore_t semappore = dispatch_semaphore_create(0); 14 | NSURLSessionTask *task = [self GET:URL parameters:parameters cache:cache responseCache:responseCache success:^(id responseObject) { 15 | if (success) { 16 | success(responseObject); 17 | } 18 | dispatch_semaphore_signal(semappore); 19 | } failure:^(NSError *error) { 20 | if (failure) { 21 | failure(error); 22 | } 23 | dispatch_semaphore_signal(semappore); 24 | }]; 25 | dispatch_semaphore_wait(semappore, DISPATCH_TIME_FOREVER); 26 | return task; 27 | } 28 | 29 | + (NSURLSessionTask *)synchronouslyPOST:(NSString *)URL parameters:(id)parameters cache:(BOOL)cache responseCache:(HttpRequestCache)responseCache success:(HttpRequestSuccess)success failure:(HttpRequestFailed)failure { 30 | [self exceptionLogic]; 31 | dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); 32 | NSURLSessionTask *task = [self POST:URL parameters:parameters cache:cache responseCache:responseCache success:^(id responseObject) { 33 | if (success) { 34 | success(responseObject); 35 | } 36 | dispatch_semaphore_signal(semaphore); 37 | } failure:^(NSError *error) { 38 | if (failure) { 39 | failure(error); 40 | } 41 | dispatch_semaphore_signal(semaphore); 42 | }]; 43 | dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); 44 | return task; 45 | } 46 | 47 | + (NSURLSessionTask *)synchronouslyUploadWithURL:(NSString *)URL parameters:(NSDictionary *)parameters images:(NSArray *)images name:(NSString *)name mimeType:(NSString *)mimeType progress:(HttpProgress)progress success:(HttpRequestSuccess)success failure:(HttpRequestFailed)failure { 48 | [self exceptionLogic]; 49 | dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); 50 | NSURLSessionTask *task = [self uploadWithURL:URL parameters:parameters images:images name:name mimeType:mimeType progress:progress success:^(id responseObject) { 51 | if (success) { 52 | success(responseObject); 53 | } 54 | dispatch_semaphore_signal(semaphore); 55 | } failure:^(NSError *error) { 56 | if (failure) { 57 | failure(error); 58 | } 59 | dispatch_semaphore_signal(semaphore); 60 | }]; 61 | dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); 62 | return task; 63 | } 64 | 65 | + (NSURLSessionTask *)synchronouslyDownloadWithURL:(NSString *)URL fileDir:(NSString *)fileDir progress:(HttpProgress)progress success:(void (^)(NSString *))success failure:(HttpRequestFailed)failure { 66 | [self exceptionLogic]; 67 | dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); 68 | NSURLSessionTask *task = [self downloadWithURL:URL fileDir:fileDir progress:progress success:^(NSString *filePath) { 69 | if (success) { 70 | success(filePath); 71 | } 72 | dispatch_semaphore_signal(semaphore); 73 | } failure:^(NSError *error) { 74 | if (failure) { 75 | failure(error); 76 | } 77 | dispatch_semaphore_signal(semaphore); 78 | }]; 79 | dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); 80 | return task; 81 | } 82 | 83 | + (void)exceptionLogic { 84 | if ([NSThread isMainThread]) { 85 | if ([self manager].completionQueue == nil || [self manager].completionQueue == dispatch_get_main_queue()) { 86 | @throw 87 | [NSException exceptionWithName:NSInvalidArgumentException 88 | reason:@"Can't make a synchronous request on the same queue as the completion handler" 89 | userInfo:nil]; 90 | } 91 | } 92 | } 93 | 94 | @end 95 | -------------------------------------------------------------------------------- /PGNetworkHelper/PGNetworkHelper.h: -------------------------------------------------------------------------------- 1 | // 2 | // PGNetworkHelper.h 3 | // 4 | // Created by piggybear on 16/8/22. 5 | // Copyright © 2016年 piggybear. All rights reserved. 6 | // 7 | 8 | #import 9 | #import 10 | 11 | #import "PGNetworkCache.h" 12 | #import "PGNetAPIClient.h" 13 | 14 | typedef void(^HttpRequestSuccess)(id responseObject); 15 | typedef void(^HttpRequestFailed)(NSError *error); 16 | typedef void(^HttpRequestCache)(id responseCache); 17 | typedef void (^HttpProgress)(NSProgress *progress); 18 | 19 | @interface PGNetworkHelper : NSObject 20 | 21 | /** 22 | * 请求超时时间 23 | */ 24 | +(void)timeoutInterval:(NSTimeInterval)timeInterval; 25 | 26 | + (PGNetAPIClient *)manager; 27 | 28 | /** 29 | * GET请求 30 | * 31 | * @param URL 请求地址 32 | * @param parameters 请求参数 33 | * @param cache 是否缓存数据 34 | * @param responseCache 缓存数据的回调 35 | * @param success 请求成功的回调 36 | * @param failure 请求失败的回调 37 | * 38 | * @return 返回的对象可取消请求,调用cancle方法 39 | */ 40 | + (NSURLSessionTask *)GET:(NSString *)URL 41 | parameters:(id)parameters 42 | cache:(BOOL)cache 43 | responseCache:(HttpRequestCache)responseCache 44 | success:(HttpRequestSuccess)success 45 | failure:(HttpRequestFailed)failure; 46 | 47 | /** 48 | * POST请求 49 | * 50 | * @param URL 请求地址 51 | * @param parameters 请求参数 52 | * @param cache 是否缓存数据 53 | * @param responseCache 缓存数据的回调 54 | * @param success 请求成功的回调 55 | * @param failure 请求失败的回调 56 | * 57 | * @return 返回的对象可取消请求,调用cancle方法 58 | */ 59 | + (NSURLSessionTask *)POST:(NSString *)URL 60 | parameters:(id)parameters 61 | cache:(BOOL)cache 62 | responseCache:(HttpRequestCache)responseCache 63 | success:(HttpRequestSuccess)success 64 | failure:(HttpRequestFailed)failure; 65 | 66 | /** 67 | * 上传图片文件 68 | * 69 | * @param URL 请求地址 70 | * @param parameters 请求参数 71 | * @param images 图片数组 72 | * @param name 文件对应服务器上的字段 73 | * @param mimeType 图片文件的类型,例:png、jpeg(默认类型).... 74 | * @param progress 上传进度信息 75 | * @param success 请求成功的回调 76 | * @param failure 请求失败的回调 77 | * @return 返回的对象可取消请求,调用cancle方法 78 | */ 79 | + (NSURLSessionTask *)uploadWithURL:(NSString *)URL 80 | parameters:(NSDictionary *)parameters 81 | images:(NSArray *)images 82 | name:(NSString *)name 83 | mimeType:(NSString *)mimeType 84 | progress:(HttpProgress)progress 85 | success:(HttpRequestSuccess)success 86 | failure:(HttpRequestFailed)failure; 87 | 88 | /** 89 | * 下载文件 90 | * 91 | * @param URL 请求地址 92 | * @param fileDir 文件存储目录(默认存储目录为Download) 93 | * @param progress 文件下载的进度信息 94 | * @param success 下载成功的回调(回调参数filePath:文件的路径) 95 | * @param failure 下载失败的回调 96 | * @return 返回的对象可取消请求,调用cancle方法 97 | */ 98 | + (__kindof NSURLSessionTask *)downloadWithURL:(NSString *)URL 99 | fileDir:(NSString *)fileDir 100 | progress:(HttpProgress)progress 101 | success:(void(^)(NSString *filePath))success 102 | failure:(HttpRequestFailed)failure; 103 | 104 | /** 105 | * 取消所有的网络请求 106 | */ 107 | + (void)cancelAllOperations; 108 | 109 | /** 110 | 将数组或字典转成json字符串 111 | 112 | @param parameter 数组或字典 113 | @return json字符串 114 | */ 115 | + (NSString *)convertJsonStringFromDictionaryOrArray:(id)parameter; 116 | 117 | @end 118 | 119 | -------------------------------------------------------------------------------- /PGNetworkHelper/PGNetworkHelper.m: -------------------------------------------------------------------------------- 1 | // 2 | // PGNetworkHelper.m 3 | // 4 | // Created by piggybear on 16/8/22. 5 | // Copyright © 2016年 piggybear. All rights reserved. 6 | // 7 | 8 | #import "PGNetworkHelper.h" 9 | #import 10 | 11 | @implementation PGNetworkHelper 12 | + (NSURLSessionTask *)GET:(NSString *)URL 13 | parameters:(id)parameters 14 | cache:(BOOL)cache 15 | responseCache:(HttpRequestCache)responseCache 16 | success:(HttpRequestSuccess)success 17 | failure:(HttpRequestFailed)failure { 18 | NSString *cacheKey = URL; 19 | if (parameters) { 20 | cacheKey = [URL stringByAppendingString:[self convertJsonStringFromDictionaryOrArray:parameters]]; 21 | } 22 | if (responseCache) { 23 | responseCache([PGNetworkCache getResponseCacheForKey:cacheKey]); 24 | } 25 | AFHTTPSessionManager *manager = [self manager]; 26 | return [manager GET:URL parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) { 27 | } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { 28 | if (cache) { 29 | [PGNetworkCache saveResponseCache:responseObject forKey:cacheKey]; 30 | } 31 | if (success) { 32 | success(responseObject); 33 | } 34 | } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { 35 | failure ? failure(error) : nil; 36 | }]; 37 | } 38 | 39 | + (NSURLSessionTask *)POST:(NSString *)URL 40 | parameters:(id)parameters 41 | cache:(BOOL)cache 42 | responseCache:(HttpRequestCache)responseCache 43 | success:(HttpRequestSuccess)success 44 | failure:(HttpRequestFailed)failure { 45 | NSString *cacheKey = URL; 46 | if (parameters) { 47 | cacheKey = [URL stringByAppendingString:[self convertJsonStringFromDictionaryOrArray:parameters]]; 48 | } 49 | if (responseCache) { 50 | responseCache([PGNetworkCache getResponseCacheForKey:cacheKey]); 51 | } 52 | AFHTTPSessionManager *manager = [self manager]; 53 | return [manager POST:URL parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) { 54 | 55 | } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { 56 | if (cache) { 57 | [PGNetworkCache saveResponseCache:responseObject forKey:cacheKey]; 58 | } 59 | if (success) { 60 | success(responseObject); 61 | } 62 | } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { 63 | if (failure) { 64 | failure(error); 65 | } 66 | }]; 67 | } 68 | 69 | + (NSURLSessionTask *)uploadWithURL:(NSString *)URL 70 | parameters:(NSDictionary *)parameters 71 | images:(NSArray *)images 72 | name:(NSString *)name 73 | mimeType:(NSString *)mimeType 74 | progress:(HttpProgress)progress 75 | success:(HttpRequestSuccess)success 76 | failure:(HttpRequestFailed)failure { 77 | AFHTTPSessionManager *manager = [self manager]; 78 | return [manager POST:URL parameters:parameters constructingBodyWithBlock:^(id _Nonnull formData) { 79 | [images enumerateObjectsUsingBlock:^(UIImage * _Nonnull image, NSUInteger idx, BOOL * _Nonnull stop) { 80 | NSData *imageData = UIImageJPEGRepresentation(image, 0.5); 81 | long index = idx; 82 | NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]; 83 | long long totalMilliseconds = interval * 1000 ; 84 | NSString *fileName = [NSString stringWithFormat:@"%lld.png", totalMilliseconds]; 85 | NSString *name1 = [NSString stringWithFormat:@"%@%ld", name, index]; 86 | [formData appendPartWithFileData:imageData name:name1 fileName:fileName mimeType:[NSString stringWithFormat:@"image/%@",mimeType?mimeType:@"jpeg"]]; 87 | }]; 88 | } progress:^(NSProgress * _Nonnull uploadProgress) { 89 | progress ? progress(uploadProgress) : nil; 90 | } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { 91 | success(responseObject); 92 | } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { 93 | failure ? failure(error) : nil; 94 | }]; 95 | } 96 | 97 | + (NSURLSessionTask *)downloadWithURL:(NSString *)URL 98 | fileDir:(NSString *)fileDir 99 | progress:(HttpProgress)progress 100 | success:(void(^)(NSString *))success 101 | failure:(HttpRequestFailed)failure { 102 | AFHTTPSessionManager *manager = [self manager]; 103 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URL]]; 104 | NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) { 105 | progress ? progress(downloadProgress) : nil; 106 | } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) { 107 | NSString *downloadDir = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:fileDir ? fileDir : @"PGNetworkHelper"]; 108 | NSFileManager *fileManager = [NSFileManager defaultManager]; 109 | [fileManager createDirectoryAtPath:downloadDir withIntermediateDirectories:YES attributes:nil error:nil]; 110 | NSString *filePath = [downloadDir stringByAppendingPathComponent:response.suggestedFilename]; 111 | return [NSURL fileURLWithPath:filePath]; 112 | } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) { 113 | success ? success(filePath.absoluteString /** NSURL->NSString*/) : nil; 114 | failure && error ? failure(error) : nil; 115 | }]; 116 | [downloadTask resume]; 117 | return downloadTask; 118 | } 119 | 120 | + (PGNetAPIClient *)manager { 121 | static PGNetAPIClient *manager = NULL; 122 | static dispatch_once_t onceToken; 123 | dispatch_once(&onceToken, ^{ 124 | manager = [PGNetAPIClient sharedClient]; 125 | manager.completionQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); 126 | manager.requestSerializer = [AFJSONRequestSerializer serializer]; 127 | manager.requestSerializer.timeoutInterval = 20.0f; 128 | manager.requestSerializer.cachePolicy = NSURLCacheStorageNotAllowed; 129 | manager.responseSerializer = [AFJSONResponseSerializer serializer]; 130 | manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil]; 131 | }); 132 | return manager; 133 | } 134 | 135 | + (void)timeoutInterval:(NSTimeInterval)timeInterval { 136 | AFHTTPSessionManager *manager = [self manager]; 137 | manager.requestSerializer.timeoutInterval = timeInterval; 138 | } 139 | 140 | + (void)cancelAllOperations { 141 | [[self manager].operationQueue cancelAllOperations]; 142 | } 143 | 144 | + (NSString *)convertJsonStringFromDictionaryOrArray:(id)parameter { 145 | NSData *data = [NSJSONSerialization dataWithJSONObject:parameter options:NSJSONWritingPrettyPrinted error:nil]; 146 | NSString *jsonStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; 147 | return jsonStr; 148 | } 149 | 150 | @end 151 | 152 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![PGNetworkHelper](http://upload-images.jianshu.io/upload_images/1340308-6532130a70265dab.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)](https://github.com/xiaozhuxiong121/PGNetworkHelper) 2 | 3 | [![CocoaPods compatible](https://img.shields.io/cocoapods/v/PGNetworkHelper.svg)](https://cocoapods.org/pods/PGNetworkHelper) 4 | ![](https://img.shields.io/badge/platform-iOS-red.svg) ![](https://img.shields.io/badge/language-Objective--C-orange.svg) 5 | ![](https://img.shields.io/badge/license-MIT%20License-brightgreen.svg) 6 | [![](https://img.shields.io/badge/jianshu-piggybear-red.svg)](http://www.jianshu.com/u/3740632b2002) 7 | 8 | PINCache做为AFNetworking3.x缓存层,将AFNetworking3.x请求的数据缓存起来,支持取消当前网络请求,以及取消所有的网络请求,除了常用的Get,Post方法,也将上传图片以及下载文件进行了封装,使用方法极其简单。 9 | > PGNetworkHelper屏蔽了AFNetworking自带的缓存,并将PINCache缓存的key也用**MD5加密**,确保数据的安全。 10 | > 11 | > PGNetworkHelper也支持同步请求 12 | 13 | **AFNetworking本身就带有缓存策略,为什么要使用PINCache作为缓存呢?** 14 | > 第一,经过测试PINCache缓存比AFNetworking自带的缓存要快。 15 | > 第二,PINCache是将缓存数据进行了加密,更加安全。 16 | 17 | # CocoaPods安装 18 | ``` 19 | pod 'PGNetworkHelper', '>= 2.0' 20 | ``` 21 | # 使用 22 | ``` oc 23 | #import 24 | 25 | //设置baseUrl 26 | [PGNetAPIClient baseUrl:@"baseUrl"]; 27 | //设置SSL 28 | [PGNetAPIClient policyWithPinningMode:AFSSLPinningModeNone]; 29 | //设置缓存路径 30 | //多用户一般用userId来保存每个用户的缓存数据 31 | [PGNetworkCache pathName:@"userId"]; 32 | 33 | //GET请求 只需要将cache设置为true就可以自动缓存 34 | [PGNetworkHelper GET:@"yourUrlString" parameters:nil cache:false responseCache:nil success:^(id responseObject) { 35 | NSLog(@"responseObject = %@", responseObject); 36 | } failure:^(NSError *error) { 37 | NSLog(@"error = %@", error); 38 | }]; 39 | 40 | 41 | //POST请求 只需要将cache设置为true就可以自动缓存 42 | [PGNetworkHelper POST:@"yourUrlString" parameters:@{@"username":@"test",@"password":@"test"} cache:false responseCache:nil success:^(id responseObject) { 43 | NSLog(@"responseObject = %@", responseObject); 44 | } failure:^(NSError *error) { 45 | NSLog(@"error = %@", error); 46 | }]; 47 | 48 | ``` 49 | # 自动缓存 50 | ``` 51 | //只需要将cache设置为true就可以自动缓存,如果不想缓存就设置cache为false 52 | [PGNetworkHelper GET:@"yourUrlString" parameters:nil cache:true responseCache:^(id responseCache) { 53 | NSLog(@"responseCache = %@", responseCache); 54 | } success:^(id responseObject) { 55 | NSLog(@"responseObject = %@", responseObject); 56 | } failure:^(NSError *error) { 57 | NSLog(@"error = %@", error); 58 | }]; 59 | ``` 60 | # 使用手动缓存 61 | > 如果需要将数据先进行处理,然后在缓存也是可以的。 62 | 63 | ``` 64 | //cache设置为true 65 | [PGNetworkHelper GET:@"yourUrlString" parameters:nil cache:true responseCache:^(id responseCache) { 66 | NSLog(@"responseCache = %@", responseCache); 67 | } success:^(id responseObject) { 68 | //这里进行要缓存的数据,cacheKey就是url,如果有参数的话,就把参数拼接到cacheKey后面,下次就可以直接在responseCache block里面获取了 69 | [PGNetworkCache saveResponseCache:responseObject forKey:@""]; 70 | } failure:^(NSError *error) { 71 | NSLog(@"error = %@", error); 72 | }]; 73 | ``` 74 | # 删除缓存 75 | ``` 76 | [PGNetworkCache removeResponseCacheForKey:@"cacheKey"]; 77 | ``` 78 | 79 | # 删除所有的缓存 80 | ``` 81 | [PGNetworkCache removeAllResponseCache]; 82 | ``` 83 | 84 | # 同步请求 85 | ``` 86 | #import 87 | [PGNetworkHelper synchronouslyGET:@"yourUrlString" parameters:nil cache:true responseCache:^(id responseCache) { 88 | NSLog(@"responseCache = %@", responseCache); 89 | } success:^(id responseObject) { 90 | NSLog(@"responseObject = %@", responseObject); 91 | } failure:^(NSError *error) { 92 | NSLog(@"error = %@", error); 93 | }]; 94 | ``` 95 | # 取消当前的网络请求 96 | ``` 97 | NSURLSessionTask *task = [PGNetworkHelper GET:@"api/user/login.json" parameters:nil cache:false responseCache:nil success:^(id responseObject) { 98 | NSLog(@"responseObject = %@", responseObject); 99 | } failure:^(NSError *error) { 100 | NSLog(@"error = %@", error); 101 | }]; 102 | [task cancel]; //取消当前网络请求 103 | ``` 104 | 105 | # 取消所有的网络请求 106 | ``` 107 | [PGNetworkHelper cancelAllOperations]; 108 | ``` 109 | 110 | # 上传图片 111 | ``` 112 | /** 113 | * 上传图片文件 114 | * 115 | * @param URL 请求地址 116 | * @param parameters 请求参数 117 | * @param images 图片数组 118 | * @param name 文件对应服务器上的字段 119 | * @param fileName 文件名 120 | * @param mimeType 图片文件的类型,例:png、jpeg(默认类型).... 121 | * @param progress 上传进度信息 122 | * @param success 请求成功的回调 123 | * @param failure 请求失败的回调 124 | * 125 | * @return 返回的对象可取消请求,调用cancle方法 126 | */ 127 | + (__kindof NSURLSessionTask *)uploadWithURL:(NSString *)URL 128 | parameters:(NSDictionary *)parameters 129 | images:(NSArray *)images 130 | name:(NSString *)name 131 | fileName:(NSString *)fileName 132 | mimeType:(NSString *)mimeType 133 | progress:(HttpProgress)progress 134 | success:(HttpRequestSuccess)success 135 | failure:(HttpRequestFailed)failure; 136 | ``` 137 | 138 | # 下载文件 139 | 140 | ``` 141 | /** 142 | * 下载文件 143 | * 144 | * @param URL 请求地址 145 | * @param fileDir 文件存储目录(默认存储目录为Download) 146 | * @param progress 文件下载的进度信息 147 | * @param success 下载成功的回调(回调参数filePath:文件的路径) 148 | * @param failure 下载失败的回调 149 | * 150 | * @return 返回的对象可取消请求,调用cancle方法 151 | */ 152 | + (__kindof NSURLSessionTask *)downloadWithURL:(NSString *)URL 153 | fileDir:(NSString *)fileDir 154 | progress:(HttpProgress)progress 155 | success:(void(^)(NSString *filePath))success 156 | failure:(HttpRequestFailed)failure; 157 | ``` 158 | 159 | # 缓存数据 160 | ``` 161 | [PGNetworkCache saveResponseCache:@"CacheObject" forKey:@"cacheKey"]; 162 | ``` 163 | # 获取缓存数据 164 | ``` 165 | [PGNetworkCache getResponseCacheForKey:@"cacheKey"]; 166 | ``` 167 | 168 | # 许可证 169 | PGNetworkHelper 使用 MIT 许可证,详情见 LICENSE 文件。 170 | --------------------------------------------------------------------------------