├── CooperAFNetworkSingleton.xcodeproj ├── project.xcworkspace │ └── contents.xcworkspacedata └── xcuserdata │ └── cjlcooper.xcuserdatad │ └── xcschemes │ ├── xcschememanagement.plist │ └── CooperAFNetworkSingleton.xcscheme ├── README.md ├── CooperAFNetworkSingleton ├── ViewController.h ├── AppDelegate.h ├── main.m ├── ViewController.m ├── Assets.xcassets │ └── AppIcon.appiconset │ │ └── Contents.json ├── Info.plist ├── Library │ ├── AFNetworking │ │ ├── AFNetworking.h │ │ ├── AFHTTPRequestOperation.h │ │ ├── AFSecurityPolicy.h │ │ ├── AFHTTPRequestOperation.m │ │ ├── AFNetworkReachabilityManager.h │ │ ├── AFNetworkReachabilityManager.m │ │ ├── AFHTTPRequestOperationManager.m │ │ ├── AFURLResponseSerialization.h │ │ ├── AFSecurityPolicy.m │ │ ├── AFHTTPSessionManager.m │ │ ├── AFURLConnectionOperation.h │ │ ├── AFHTTPRequestOperationManager.h │ │ └── AFHTTPSessionManager.h │ └── Network │ │ ├── NetworkSingleton.h │ │ ├── Reachability.h │ │ ├── NetworkSingleton.m │ │ └── Reachability.m ├── Base.lproj │ ├── Main.storyboard │ └── LaunchScreen.storyboard └── AppDelegate.m ├── CooperAFNetworkSingletonTests ├── Info.plist └── CooperAFNetworkSingletonTests.m └── CooperAFNetworkSingletonUITests ├── Info.plist └── CooperAFNetworkSingletonUITests.m /CooperAFNetworkSingleton.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CooperAFNetworkSingleton: 2 | 3 | CooperAFNetworkSingleton是基于AFNetworking再封装的框架; 4 | 支持cookie 5 | 6 | # Usage: 7 | 8 | [[NetworkSingleton sharedManager] postDataToServer:nil url:@"" successBlock:^(id responseBody) { 9 | 10 | } failureBlock:^(NSString *error) { 11 | 12 | }]; 13 | } 14 | -------------------------------------------------------------------------------- /CooperAFNetworkSingleton/ViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.h 3 | // CooperAFNetworkSingleton 4 | // 5 | // Created by cjlcooper@163.com on 17/3/15. 6 | // Copyright © 2017年 Cooper. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface ViewController : UIViewController 12 | 13 | 14 | @end 15 | 16 | -------------------------------------------------------------------------------- /CooperAFNetworkSingleton/AppDelegate.h: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.h 3 | // CooperAFNetworkSingleton 4 | // 5 | // Created by cjlcooper@163.com on 17/3/15. 6 | // Copyright © 2017年 Cooper. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface AppDelegate : UIResponder 12 | 13 | @property (strong, nonatomic) UIWindow *window; 14 | 15 | 16 | @end 17 | 18 | -------------------------------------------------------------------------------- /CooperAFNetworkSingleton/main.m: -------------------------------------------------------------------------------- 1 | // 2 | // main.m 3 | // CooperAFNetworkSingleton 4 | // 5 | // Created by cjlcooper@163.com on 17/3/15. 6 | // Copyright © 2017年 Cooper. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "AppDelegate.h" 11 | 12 | int main(int argc, char * argv[]) { 13 | @autoreleasepool { 14 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /CooperAFNetworkSingletonTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleVersion 20 | 1 21 | 22 | 23 | -------------------------------------------------------------------------------- /CooperAFNetworkSingletonUITests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleVersion 20 | 1 21 | 22 | 23 | -------------------------------------------------------------------------------- /CooperAFNetworkSingleton.xcodeproj/xcuserdata/cjlcooper.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | CooperAFNetworkSingleton.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | SuppressBuildableAutocreation 14 | 15 | 00D898431E78C83D002BC48F 16 | 17 | primary 18 | 19 | 20 | 00D8985C1E78C83D002BC48F 21 | 22 | primary 23 | 24 | 25 | 00D898671E78C83D002BC48F 26 | 27 | primary 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /CooperAFNetworkSingleton/ViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.m 3 | // CooperAFNetworkSingleton 4 | // 5 | // Created by cjlcooper@163.com on 17/3/15. 6 | // Copyright © 2017年 Cooper. All rights reserved. 7 | // 8 | 9 | #import "ViewController.h" 10 | #import "NetworkSingleton.h" 11 | 12 | @interface ViewController () 13 | 14 | @end 15 | 16 | @implementation ViewController 17 | 18 | - (void)viewDidLoad { 19 | [super viewDidLoad]; 20 | // Do any additional setup after loading the view, typically from a nib. 21 | [self postNetworkAction]; 22 | } 23 | 24 | //post 25 | - (void)postNetworkAction{ 26 | [[NetworkSingleton sharedManager] postDataToServer:nil url:@"" successBlock:^(id responseBody) { 27 | 28 | } failureBlock:^(NSString *error) { 29 | 30 | }]; 31 | } 32 | 33 | //get 34 | - (void)getNetworkAction{ 35 | [[NetworkSingleton sharedManager] getDateFormServer:nil url:@"" successBlock:^(id responseBody) { 36 | 37 | } failureBlock:^(NSString *error) { 38 | 39 | }]; 40 | } 41 | 42 | 43 | - (void)didReceiveMemoryWarning { 44 | [super didReceiveMemoryWarning]; 45 | // Dispose of any resources that can be recreated. 46 | } 47 | 48 | 49 | @end 50 | -------------------------------------------------------------------------------- /CooperAFNetworkSingletonTests/CooperAFNetworkSingletonTests.m: -------------------------------------------------------------------------------- 1 | // 2 | // CooperAFNetworkSingletonTests.m 3 | // CooperAFNetworkSingletonTests 4 | // 5 | // Created by cjlcooper@163.com on 17/3/15. 6 | // Copyright © 2017年 Cooper. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface CooperAFNetworkSingletonTests : XCTestCase 12 | 13 | @end 14 | 15 | @implementation CooperAFNetworkSingletonTests 16 | 17 | - (void)setUp { 18 | [super setUp]; 19 | // Put setup code here. This method is called before the invocation of each test method in the class. 20 | } 21 | 22 | - (void)tearDown { 23 | // Put teardown code here. This method is called after the invocation of each test method in the class. 24 | [super tearDown]; 25 | } 26 | 27 | - (void)testExample { 28 | // This is an example of a functional test case. 29 | // Use XCTAssert and related functions to verify your tests produce the correct results. 30 | } 31 | 32 | - (void)testPerformanceExample { 33 | // This is an example of a performance test case. 34 | [self measureBlock:^{ 35 | // Put the code you want to measure the time of here. 36 | }]; 37 | } 38 | 39 | @end 40 | -------------------------------------------------------------------------------- /CooperAFNetworkSingleton/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "size" : "29x29", 6 | "scale" : "2x" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "size" : "29x29", 11 | "scale" : "3x" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "size" : "40x40", 16 | "scale" : "2x" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "size" : "40x40", 21 | "scale" : "3x" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "size" : "60x60", 26 | "scale" : "2x" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "size" : "60x60", 31 | "scale" : "3x" 32 | }, 33 | { 34 | "idiom" : "ipad", 35 | "size" : "29x29", 36 | "scale" : "1x" 37 | }, 38 | { 39 | "idiom" : "ipad", 40 | "size" : "29x29", 41 | "scale" : "2x" 42 | }, 43 | { 44 | "idiom" : "ipad", 45 | "size" : "40x40", 46 | "scale" : "1x" 47 | }, 48 | { 49 | "idiom" : "ipad", 50 | "size" : "40x40", 51 | "scale" : "2x" 52 | }, 53 | { 54 | "idiom" : "ipad", 55 | "size" : "76x76", 56 | "scale" : "1x" 57 | }, 58 | { 59 | "idiom" : "ipad", 60 | "size" : "76x76", 61 | "scale" : "2x" 62 | } 63 | ], 64 | "info" : { 65 | "version" : 1, 66 | "author" : "xcode" 67 | } 68 | } -------------------------------------------------------------------------------- /CooperAFNetworkSingletonUITests/CooperAFNetworkSingletonUITests.m: -------------------------------------------------------------------------------- 1 | // 2 | // CooperAFNetworkSingletonUITests.m 3 | // CooperAFNetworkSingletonUITests 4 | // 5 | // Created by cjlcooper@163.com on 17/3/15. 6 | // Copyright © 2017年 Cooper. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface CooperAFNetworkSingletonUITests : XCTestCase 12 | 13 | @end 14 | 15 | @implementation CooperAFNetworkSingletonUITests 16 | 17 | - (void)setUp { 18 | [super setUp]; 19 | 20 | // Put setup code here. This method is called before the invocation of each test method in the class. 21 | 22 | // In UI tests it is usually best to stop immediately when a failure occurs. 23 | self.continueAfterFailure = NO; 24 | // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. 25 | [[[XCUIApplication alloc] init] launch]; 26 | 27 | // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. 28 | } 29 | 30 | - (void)tearDown { 31 | // Put teardown code here. This method is called after the invocation of each test method in the class. 32 | [super tearDown]; 33 | } 34 | 35 | - (void)testExample { 36 | // Use recording to get started writing UI tests. 37 | // Use XCTAssert and related functions to verify your tests produce the correct results. 38 | } 39 | 40 | @end 41 | -------------------------------------------------------------------------------- /CooperAFNetworkSingleton/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | APPL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleVersion 20 | 1 21 | LSRequiresIPhoneOS 22 | 23 | UILaunchStoryboardName 24 | LaunchScreen 25 | UIMainStoryboardFile 26 | Main 27 | UIRequiredDeviceCapabilities 28 | 29 | armv7 30 | 31 | UISupportedInterfaceOrientations 32 | 33 | UIInterfaceOrientationPortrait 34 | UIInterfaceOrientationLandscapeLeft 35 | UIInterfaceOrientationLandscapeRight 36 | 37 | UISupportedInterfaceOrientations~ipad 38 | 39 | UIInterfaceOrientationPortrait 40 | UIInterfaceOrientationPortraitUpsideDown 41 | UIInterfaceOrientationLandscapeLeft 42 | UIInterfaceOrientationLandscapeRight 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /CooperAFNetworkSingleton/Library/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 | -------------------------------------------------------------------------------- /CooperAFNetworkSingleton/Base.lproj/Main.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /CooperAFNetworkSingleton/Base.lproj/LaunchScreen.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /CooperAFNetworkSingleton/Library/Network/NetworkSingleton.h: -------------------------------------------------------------------------------- 1 | // 2 | // NetworkSingleton.m 3 | // cjl 4 | // 5 | // Created by 陈家黎 on 15/9/24. 6 | // Copyright (c) 2015年 cjl. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "AFNetworking.h" 11 | #import "AFHTTPRequestOperationManager.h" 12 | 13 | //请求超时 14 | #define TIMEOUT 5 15 | 16 | typedef void(^SuccessBlock)(id responseBody); 17 | typedef void(^FailureBlock)(NSString *error); 18 | 19 | 20 | @interface NetworkSingleton : NSObject 21 | 22 | +(NetworkSingleton *)sharedManager; 23 | -(AFHTTPRequestOperationManager *)baseHtppRequest; 24 | 25 | #pragma mark - LOGIN 26 | -(void)loginToServer:(NSDictionary *)parameters url:(NSString *)url successBlock:(SuccessBlock)successBlock failureBlock:(FailureBlock)failureBlock; 27 | 28 | #pragma mark - POST 29 | -(void)postDataToServer:(NSMutableDictionary *)parameters url:(NSString *)url successBlock:(SuccessBlock)successBlock failureBlock:(FailureBlock)failureBlock; 30 | 31 | #pragma mark - GET 32 | -(void)getDateFormServer:(NSDictionary *)parameters url:(NSString *)url successBlock:(SuccessBlock)successBlock failureBlock:(FailureBlock)failureBlock; 33 | 34 | #pragma mark - updateImageFace 35 | -(void)updateImageFace:(NSDictionary *)parameters url:(NSString *)url filePath:(NSString*) filePath 36 | fileName:(NSString*) fileName successBlock:(SuccessBlock)successBlock failureBlock:(FailureBlock)failureBlock; 37 | 38 | -(void)updateManyImages:(NSDictionary *)parameters url:(NSString *)url fileDataDic:(NSMutableDictionary*)dataDic filePathArray:(NSMutableArray*) filePathArray 39 | fileName:(NSString*) fileName successBlock:(SuccessBlock)successBlock failureBlock:(FailureBlock)failureBlock; 40 | 41 | -(void) uploadFileToServer:(UIImage *)image successBlock:(SuccessBlock)successBlock failureBlock:(FailureBlock)failureBlock; 42 | 43 | -(void) saveCookies; 44 | - (void)loadCookies; 45 | 46 | #pragma mark - setSecretkey 47 | -(void)setSecretKeyToServer:(NSMutableDictionary *)parameters url:(NSString *)url successBlock:(SuccessBlock)successBlock failureBlock:(FailureBlock)failureBlock; 48 | 49 | 50 | @end 51 | -------------------------------------------------------------------------------- /CooperAFNetworkSingleton/AppDelegate.m: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.m 3 | // CooperAFNetworkSingleton 4 | // 5 | // Created by cjlcooper@163.com on 17/3/15. 6 | // Copyright © 2017年 Cooper. All rights reserved. 7 | // 8 | 9 | #import "AppDelegate.h" 10 | 11 | @interface AppDelegate () 12 | 13 | @end 14 | 15 | @implementation AppDelegate 16 | 17 | 18 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 19 | // Override point for customization after application launch. 20 | return YES; 21 | } 22 | 23 | 24 | - (void)applicationWillResignActive:(UIApplication *)application { 25 | // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 26 | // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. 27 | } 28 | 29 | 30 | - (void)applicationDidEnterBackground:(UIApplication *)application { 31 | // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 32 | // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 33 | } 34 | 35 | 36 | - (void)applicationWillEnterForeground:(UIApplication *)application { 37 | // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. 38 | } 39 | 40 | 41 | - (void)applicationDidBecomeActive:(UIApplication *)application { 42 | // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 43 | } 44 | 45 | 46 | - (void)applicationWillTerminate:(UIApplication *)application { 47 | // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 48 | } 49 | 50 | 51 | @end 52 | -------------------------------------------------------------------------------- /CooperAFNetworkSingleton/Library/Network/Reachability.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2011, Tony Million. 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are met: 7 | 8 | 1. Redistributions of source code must retain the above copyright notice, this 9 | list of conditions and the following disclaimer. 10 | 11 | 2. Redistributions in binary form must reproduce the above copyright notice, 12 | this list of conditions and the following disclaimer in the documentation 13 | and/or other materials provided with the distribution. 14 | 15 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 16 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 18 | ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 19 | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 20 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 21 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 22 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 23 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 24 | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 25 | POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #import 29 | #import 30 | 31 | //! Project version number for MacOSReachability. 32 | FOUNDATION_EXPORT double ReachabilityVersionNumber; 33 | 34 | //! Project version string for MacOSReachability. 35 | FOUNDATION_EXPORT const unsigned char ReachabilityVersionString[]; 36 | 37 | /** 38 | * Create NS_ENUM macro if it does not exist on the targeted version of iOS or OS X. 39 | * 40 | * @see http://nshipster.com/ns_enum-ns_options/ 41 | **/ 42 | #ifndef NS_ENUM 43 | #define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type 44 | #endif 45 | 46 | extern NSString *const GkReachabilityChangedNotification; 47 | 48 | typedef NS_ENUM(NSInteger, NetworkStatus) { 49 | // Apple NetworkStatus Compatible Names. 50 | NotReachable = 0, 51 | ReachableViaWiFi = 2, 52 | ReachableViaWWAN = 1 53 | }; 54 | 55 | @class Reachability; 56 | 57 | typedef void (^NetworkReachable)(Reachability * reachability); 58 | typedef void (^NetworkUnreachable)(Reachability * reachability); 59 | typedef void (^NetworkReachability)(Reachability * reachability, SCNetworkConnectionFlags flags); 60 | 61 | 62 | @interface Reachability : NSObject 63 | 64 | @property (nonatomic, copy) NetworkReachable reachableBlock; 65 | @property (nonatomic, copy) NetworkUnreachable unreachableBlock; 66 | @property (nonatomic, copy) NetworkReachability reachabilityBlock; 67 | 68 | @property (nonatomic, assign) BOOL reachableOnWWAN; 69 | 70 | 71 | +(instancetype)reachabilityWithHostname:(NSString*)hostname; 72 | // This is identical to the function above, but is here to maintain 73 | //compatibility with Apples original code. (see .m) 74 | +(instancetype)reachabilityWithHostName:(NSString*)hostname; 75 | +(instancetype)reachabilityForInternetConnection; 76 | +(instancetype)reachabilityWithAddress:(void *)hostAddress; 77 | +(instancetype)reachabilityForLocalWiFi; 78 | 79 | -(instancetype)initWithReachabilityRef:(SCNetworkReachabilityRef)ref; 80 | 81 | -(BOOL)startNotifier; 82 | -(void)stopNotifier; 83 | 84 | -(BOOL)isReachable; 85 | -(BOOL)isReachableViaWWAN; 86 | -(BOOL)isReachableViaWiFi; 87 | 88 | // WWAN may be available, but not active until a connection has been established. 89 | // WiFi may require a connection for VPN on Demand. 90 | -(BOOL)isConnectionRequired; // Identical DDG variant. 91 | -(BOOL)connectionRequired; // Apple's routine. 92 | // Dynamic, on demand connection? 93 | -(BOOL)isConnectionOnDemand; 94 | // Is user intervention required? 95 | -(BOOL)isInterventionRequired; 96 | 97 | -(NetworkStatus)currentReachabilityStatus; 98 | -(SCNetworkReachabilityFlags)reachabilityFlags; 99 | -(NSString*)currentReachabilityString; 100 | -(NSString*)currentReachabilityFlags; 101 | 102 | @end -------------------------------------------------------------------------------- /CooperAFNetworkSingleton/Library/AFNetworking/AFHTTPRequestOperation.h: -------------------------------------------------------------------------------- 1 | // AFHTTPRequestOperation.h 2 | // Copyright (c) 2011–2015 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 "AFURLConnectionOperation.h" 24 | 25 | NS_ASSUME_NONNULL_BEGIN 26 | 27 | /** 28 | `AFHTTPRequestOperation` is a subclass of `AFURLConnectionOperation` for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request. 29 | */ 30 | @interface AFHTTPRequestOperation : AFURLConnectionOperation 31 | 32 | ///------------------------------------------------ 33 | /// @name Getting HTTP URL Connection Information 34 | ///------------------------------------------------ 35 | 36 | /** 37 | The last HTTP response received by the operation's connection. 38 | */ 39 | @property (readonly, nonatomic, strong, nullable) NSHTTPURLResponse *response; 40 | 41 | /** 42 | 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 AFHTTPResponse serializer, which uses the raw data as its response object. The serializer validates the status code to be in the `2XX` range, denoting success. If the response serializer generates an error in `-responseObjectForResponse:data:error:`, the `failure` callback of the session task or request operation will be executed; otherwise, the `success` callback will be executed. 43 | 44 | @warning `responseSerializer` must not be `nil`. Setting a response serializer will clear out any cached value 45 | */ 46 | @property (nonatomic, strong) AFHTTPResponseSerializer * responseSerializer; 47 | 48 | /** 49 | An object constructed by the `responseSerializer` from the response and response data. Returns `nil` unless the operation `isFinished`, has a `response`, and has `responseData` with non-zero content length. If an error occurs during serialization, `nil` will be returned, and the `error` property will be populated with the serialization error. 50 | */ 51 | @property (readonly, nonatomic, strong, nullable) id responseObject; 52 | 53 | ///----------------------------------------------------------- 54 | /// @name Setting Completion Block Success / Failure Callbacks 55 | ///----------------------------------------------------------- 56 | 57 | /** 58 | Sets the `completionBlock` property with a block that executes either the specified success or failure block, depending on the state of the request on completion. If `error` returns a value, which can be caused by an unacceptable status code or content type, then `failure` is executed. Otherwise, `success` is executed. 59 | 60 | This method should be overridden in subclasses in order to specify the response object passed into the success block. 61 | 62 | @param success The block to be executed on the completion of a successful request. This block has no return value and takes two arguments: the receiver operation and the object constructed from the response data of the request. 63 | @param failure The block to be executed on the completion of an unsuccessful request. This block has no return value and takes two arguments: the receiver operation and the error that occurred during the request. 64 | */ 65 | - (void)setCompletionBlockWithSuccess:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success 66 | failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; 67 | 68 | @end 69 | 70 | NS_ASSUME_NONNULL_END 71 | -------------------------------------------------------------------------------- /CooperAFNetworkSingleton.xcodeproj/xcuserdata/cjlcooper.xcuserdatad/xcschemes/CooperAFNetworkSingleton.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 33 | 39 | 40 | 41 | 43 | 49 | 50 | 51 | 52 | 53 | 59 | 60 | 61 | 62 | 63 | 64 | 74 | 76 | 82 | 83 | 84 | 85 | 86 | 87 | 93 | 95 | 101 | 102 | 103 | 104 | 106 | 107 | 110 | 111 | 112 | -------------------------------------------------------------------------------- /CooperAFNetworkSingleton/Library/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 | -------------------------------------------------------------------------------- /CooperAFNetworkSingleton/Library/AFNetworking/AFHTTPRequestOperation.m: -------------------------------------------------------------------------------- 1 | // AFHTTPRequestOperation.m 2 | // Copyright (c) 2011–2015 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 "AFHTTPRequestOperation.h" 23 | 24 | static dispatch_queue_t http_request_operation_processing_queue() { 25 | static dispatch_queue_t af_http_request_operation_processing_queue; 26 | static dispatch_once_t onceToken; 27 | dispatch_once(&onceToken, ^{ 28 | af_http_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.http-request.processing", DISPATCH_QUEUE_CONCURRENT); 29 | }); 30 | 31 | return af_http_request_operation_processing_queue; 32 | } 33 | 34 | static dispatch_group_t http_request_operation_completion_group() { 35 | static dispatch_group_t af_http_request_operation_completion_group; 36 | static dispatch_once_t onceToken; 37 | dispatch_once(&onceToken, ^{ 38 | af_http_request_operation_completion_group = dispatch_group_create(); 39 | }); 40 | 41 | return af_http_request_operation_completion_group; 42 | } 43 | 44 | #pragma mark - 45 | 46 | @interface AFURLConnectionOperation () 47 | @property (readwrite, nonatomic, strong) NSURLRequest *request; 48 | @property (readwrite, nonatomic, strong) NSURLResponse *response; 49 | @end 50 | 51 | @interface AFHTTPRequestOperation () 52 | @property (readwrite, nonatomic, strong) NSHTTPURLResponse *response; 53 | @property (readwrite, nonatomic, strong) id responseObject; 54 | @property (readwrite, nonatomic, strong) NSError *responseSerializationError; 55 | @property (readwrite, nonatomic, strong) NSRecursiveLock *lock; 56 | @end 57 | 58 | @implementation AFHTTPRequestOperation 59 | @dynamic response; 60 | @dynamic lock; 61 | 62 | - (instancetype)initWithRequest:(NSURLRequest *)urlRequest { 63 | self = [super initWithRequest:urlRequest]; 64 | if (!self) { 65 | return nil; 66 | } 67 | 68 | self.responseSerializer = [AFHTTPResponseSerializer serializer]; 69 | 70 | return self; 71 | } 72 | 73 | - (void)setResponseSerializer:(AFHTTPResponseSerializer *)responseSerializer { 74 | NSParameterAssert(responseSerializer); 75 | 76 | [self.lock lock]; 77 | _responseSerializer = responseSerializer; 78 | self.responseObject = nil; 79 | self.responseSerializationError = nil; 80 | [self.lock unlock]; 81 | } 82 | 83 | - (id)responseObject { 84 | [self.lock lock]; 85 | if (!_responseObject && [self isFinished] && !self.error) { 86 | NSError *error = nil; 87 | self.responseObject = [self.responseSerializer responseObjectForResponse:self.response data:self.responseData error:&error]; 88 | if (error) { 89 | self.responseSerializationError = error; 90 | } 91 | } 92 | [self.lock unlock]; 93 | 94 | return _responseObject; 95 | } 96 | 97 | - (NSError *)error { 98 | if (_responseSerializationError) { 99 | return _responseSerializationError; 100 | } else { 101 | return [super error]; 102 | } 103 | } 104 | 105 | #pragma mark - AFHTTPRequestOperation 106 | 107 | - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 108 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure 109 | { 110 | // completionBlock is manually nilled out in AFURLConnectionOperation to break the retain cycle. 111 | #pragma clang diagnostic push 112 | #pragma clang diagnostic ignored "-Warc-retain-cycles" 113 | #pragma clang diagnostic ignored "-Wgnu" 114 | self.completionBlock = ^{ 115 | if (self.completionGroup) { 116 | dispatch_group_enter(self.completionGroup); 117 | } 118 | 119 | dispatch_async(http_request_operation_processing_queue(), ^{ 120 | if (self.error) { 121 | if (failure) { 122 | dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{ 123 | failure(self, self.error); 124 | }); 125 | } 126 | } else { 127 | id responseObject = self.responseObject; 128 | if (self.error) { 129 | if (failure) { 130 | dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{ 131 | failure(self, self.error); 132 | }); 133 | } 134 | } else { 135 | if (success) { 136 | dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{ 137 | success(self, responseObject); 138 | }); 139 | } 140 | } 141 | } 142 | 143 | if (self.completionGroup) { 144 | dispatch_group_leave(self.completionGroup); 145 | } 146 | }); 147 | }; 148 | #pragma clang diagnostic pop 149 | } 150 | 151 | #pragma mark - AFURLRequestOperation 152 | 153 | - (void)pause { 154 | [super pause]; 155 | 156 | u_int64_t offset = 0; 157 | if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) { 158 | offset = [(NSNumber *)[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] unsignedLongLongValue]; 159 | } else { 160 | offset = [(NSData *)[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length]; 161 | } 162 | 163 | NSMutableURLRequest *mutableURLRequest = [self.request mutableCopy]; 164 | if ([self.response respondsToSelector:@selector(allHeaderFields)] && [[self.response allHeaderFields] valueForKey:@"ETag"]) { 165 | [mutableURLRequest setValue:[[self.response allHeaderFields] valueForKey:@"ETag"] forHTTPHeaderField:@"If-Range"]; 166 | } 167 | [mutableURLRequest setValue:[NSString stringWithFormat:@"bytes=%llu-", offset] forHTTPHeaderField:@"Range"]; 168 | self.request = mutableURLRequest; 169 | } 170 | 171 | #pragma mark - NSSecureCoding 172 | 173 | + (BOOL)supportsSecureCoding { 174 | return YES; 175 | } 176 | 177 | - (id)initWithCoder:(NSCoder *)decoder { 178 | self = [super initWithCoder:decoder]; 179 | if (!self) { 180 | return nil; 181 | } 182 | 183 | self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))]; 184 | 185 | return self; 186 | } 187 | 188 | - (void)encodeWithCoder:(NSCoder *)coder { 189 | [super encodeWithCoder:coder]; 190 | 191 | [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))]; 192 | } 193 | 194 | #pragma mark - NSCopying 195 | 196 | - (id)copyWithZone:(NSZone *)zone { 197 | AFHTTPRequestOperation *operation = [super copyWithZone:zone]; 198 | 199 | operation.responseSerializer = [self.responseSerializer copyWithZone:zone]; 200 | operation.completionQueue = self.completionQueue; 201 | operation.completionGroup = self.completionGroup; 202 | 203 | return operation; 204 | } 205 | 206 | @end 207 | -------------------------------------------------------------------------------- /CooperAFNetworkSingleton/Library/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 | -------------------------------------------------------------------------------- /CooperAFNetworkSingleton/Library/Network/NetworkSingleton.m: -------------------------------------------------------------------------------- 1 | // 2 | // NetworkSingleton.m 3 | // cjl 4 | // 5 | // Created by 陈家黎 on 15/9/24. 6 | // Copyright (c) 2015年 cjl. All rights reserved. 7 | // 8 | 9 | 10 | 11 | #import "NetworkSingleton.h" 12 | #import "AFHTTPRequestOperationManager.h" 13 | #import "AppDelegate.h" 14 | 15 | @implementation NetworkSingleton{ 16 | NSUserDefaults *ud; 17 | AppDelegate *appdelegate; 18 | } 19 | 20 | +(NetworkSingleton *)sharedManager{ 21 | static NetworkSingleton *sharedNetworkSingleton = nil; 22 | static dispatch_once_t predicate; 23 | dispatch_once(&predicate,^{ 24 | sharedNetworkSingleton = [[self alloc] init]; 25 | }); 26 | return sharedNetworkSingleton; 27 | } 28 | 29 | 30 | -(BOOL) isConnectionAvailable{ 31 | BOOL isExistenceNetwork = YES; 32 | 33 | if (!isExistenceNetwork) { 34 | return NO; 35 | } 36 | 37 | return isExistenceNetwork; 38 | } 39 | 40 | -(AFHTTPRequestOperationManager *)baseHtppRequest{ 41 | AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 42 | 43 | manager.requestSerializer.HTTPShouldHandleCookies = YES; 44 | [manager.requestSerializer setTimeoutInterval:TIMEOUT]; 45 | manager.requestSerializer = [AFJSONRequestSerializer serializer]; 46 | manager.responseSerializer = [AFJSONResponseSerializer serializer]; 47 | manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"text/html", @"application/json", nil]; 48 | [self isConnectionAvailable]; 49 | //[NSException raise:@"网络错误" format:@"当前网络不可以用,请检查网络连"]; 50 | return manager; 51 | } 52 | 53 | 54 | -(void) uploadFileToServer:(UIImage *)image successBlock:(SuccessBlock)successBlock failureBlock:(FailureBlock)failureBlock{ 55 | // AFHTTPRequestOperationManager *manager = [self baseHtppRequest]; 56 | // 57 | // NSData *imageData = UIImageJPEGRepresentation(image, 1); 58 | 59 | // [manager POST:urlUploadFile parameters:nil constructingBodyWithBlock:^(id formData) { 60 | // [formData appendPartWithFileData :imageData name:@"myimage" fileName:@"1.png" mimeType:@"image/jpeg"]; 61 | // } success:^(AFHTTPRequestOperation *operation,id responseObject) { 62 | // successBlock(responseObject); 63 | // //NSLog(@"Success: %@", responseObject); 64 | // } failure:^(AFHTTPRequestOperation *operation,NSError *error) { 65 | // NSLog(@"Error: %@", error); 66 | // }]; 67 | }; 68 | 69 | -(void)loginToServer:(NSDictionary *)parameters url:(NSString *)url successBlock:(SuccessBlock)successBlock failureBlock:(FailureBlock)failureBlock{ 70 | AFHTTPRequestOperationManager *manager = [self baseHtppRequest]; 71 | manager.responseSerializer = [AFHTTPResponseSerializer serializer]; 72 | manager.requestSerializer.HTTPShouldHandleCookies = YES; 73 | NSString *urlStr = [url stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 74 | urlStr= (NSString*) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef)urlStr, NULL,(CFStringRef)@"!*'();@$,%#[]", kCFStringEncodingUTF8 )); 75 | 76 | [manager POST:[self URLEncodedStringValue:urlStr] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject){ 77 | successBlock(responseObject); 78 | } failure:^(AFHTTPRequestOperation *operation, NSError *error){ 79 | NSLog(@"Error: %@", error); 80 | }]; 81 | } 82 | 83 | -(void)postDataToServer:(NSMutableDictionary *)parameters url:(NSString *)url successBlock:(SuccessBlock)successBlock failureBlock:(FailureBlock)failureBlock{ 84 | //开始网络请求发送通知 85 | AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 86 | manager.requestSerializer = [AFHTTPRequestSerializer serializer]; 87 | manager.responseSerializer = [AFHTTPResponseSerializer serializer]; 88 | manager.requestSerializer.timeoutInterval = 15.0;//超时时间 89 | // 将dict中的数组转成json 90 | parameters = [self dealDictArray:parameters]; 91 | //申明返回的结果是json类型 92 | NSString *urlStr = [url stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 93 | [manager POST:urlStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject){ 94 | successBlock(responseObject); 95 | 96 | } failure:^(AFHTTPRequestOperation *operation, NSError *error){ 97 | 98 | }]; 99 | } 100 | 101 | // 将dict中的数组转成json 102 | - (NSMutableDictionary *)dealDictArray:(NSMutableDictionary *)dict{ 103 | for (NSString *keyStr in [dict allKeys]) { 104 | id tempValue = [dict objectForKey:keyStr]; 105 | if ([tempValue isKindOfClass:[NSArray class]] || [tempValue isKindOfClass:[NSMutableArray class]]) { 106 | 107 | } 108 | } 109 | 110 | return dict; 111 | } 112 | 113 | -(void)getDateFormServer:(NSDictionary *)parameters url:(NSString *)url successBlock:(SuccessBlock)successBlock failureBlock:(FailureBlock)failureBlock{ 114 | AFHTTPRequestOperationManager *manager = [self baseHtppRequest]; 115 | NSString *urlStr = [url stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 116 | [manager GET:urlStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject){ 117 | successBlock(responseObject); 118 | } failure:^(AFHTTPRequestOperation *operation, NSError *error){ 119 | NSLog(@"Error: %@", error); 120 | }]; 121 | } 122 | 123 | -(void)updateImageFace:(NSDictionary *)parameters url:(NSString *)url filePath:(NSString*) filePath 124 | fileName:(NSString*) fileName successBlock:(SuccessBlock)successBlock failureBlock:(FailureBlock)failureBlock{ 125 | 126 | AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 127 | //申明返回的结果是json类型 128 | manager.responseSerializer = [AFJSONResponseSerializer serializer]; 129 | NSData *imageData = UIImageJPEGRepresentation([UIImage imageWithContentsOfFile:filePath], 0.1); 130 | // 131 | if (imageData != nil) { 132 | [manager POST:url parameters:parameters constructingBodyWithBlock:^(id formData) { 133 | [formData appendPartWithFileData:imageData name:fileName fileName:fileName mimeType:@"image/jpeg"]; 134 | } success:^(AFHTTPRequestOperation *operation, id responseObject){ 135 | successBlock(responseObject); 136 | } failure:^(AFHTTPRequestOperation *operation, NSError *error){ 137 | NSLog(@"%@",error); 138 | }]; 139 | 140 | }else{ 141 | NSLog(@"数据为空"); 142 | } 143 | } 144 | 145 | -(void)updateManyImages:(NSDictionary *)parameters url:(NSString *)url fileDataDic:(NSMutableDictionary*)dataDic filePathArray:(NSMutableArray*) filePathArray 146 | fileName:(NSString*) fileName successBlock:(SuccessBlock)successBlock failureBlock:(FailureBlock)failureBlock{ 147 | 148 | AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 149 | AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer]; 150 | //申明返回的结果是json类型 151 | manager.responseSerializer = [AFJSONResponseSerializer serializer]; 152 | 153 | AFHTTPRequestOperation *operation = [manager POST:url parameters:parameters constructingBodyWithBlock:^(id formData){ 154 | for (int i=0; i 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 | -------------------------------------------------------------------------------- /CooperAFNetworkSingleton/Library/AFNetworking/AFHTTPRequestOperationManager.m: -------------------------------------------------------------------------------- 1 | // AFHTTPRequestOperationManager.m 2 | // Copyright (c) 2011–2015 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 | #import "AFHTTPRequestOperationManager.h" 25 | #import "AFHTTPRequestOperation.h" 26 | 27 | #import 28 | #import 29 | 30 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 31 | #import 32 | #endif 33 | 34 | @interface AFHTTPRequestOperationManager () 35 | @property (readwrite, nonatomic, strong) NSURL *baseURL; 36 | @end 37 | 38 | @implementation AFHTTPRequestOperationManager 39 | 40 | + (instancetype)manager { 41 | return [[self alloc] initWithBaseURL:nil]; 42 | } 43 | 44 | - (instancetype)init { 45 | return [self initWithBaseURL:nil]; 46 | } 47 | 48 | - (instancetype)initWithBaseURL:(NSURL *)url { 49 | self = [super init]; 50 | if (!self) { 51 | return nil; 52 | } 53 | 54 | // Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected 55 | if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) { 56 | url = [url URLByAppendingPathComponent:@""]; 57 | } 58 | 59 | self.baseURL = url; 60 | 61 | self.requestSerializer = [AFHTTPRequestSerializer serializer]; 62 | self.responseSerializer = [AFJSONResponseSerializer serializer]; 63 | 64 | self.securityPolicy = [AFSecurityPolicy defaultPolicy]; 65 | 66 | self.reachabilityManager = [AFNetworkReachabilityManager sharedManager]; 67 | 68 | self.operationQueue = [[NSOperationQueue alloc] init]; 69 | 70 | self.shouldUseCredentialStorage = YES; 71 | 72 | return self; 73 | } 74 | 75 | #pragma mark - 76 | 77 | #ifdef _SYSTEMCONFIGURATION_H 78 | #endif 79 | 80 | - (void)setRequestSerializer:(AFHTTPRequestSerializer *)requestSerializer { 81 | NSParameterAssert(requestSerializer); 82 | 83 | _requestSerializer = requestSerializer; 84 | } 85 | 86 | - (void)setResponseSerializer:(AFHTTPResponseSerializer *)responseSerializer { 87 | NSParameterAssert(responseSerializer); 88 | 89 | _responseSerializer = responseSerializer; 90 | } 91 | 92 | #pragma mark - 93 | 94 | - (AFHTTPRequestOperation *)HTTPRequestOperationWithHTTPMethod:(NSString *)method 95 | URLString:(NSString *)URLString 96 | parameters:(id)parameters 97 | success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 98 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure 99 | { 100 | NSError *serializationError = nil; 101 | NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError]; 102 | if (serializationError) { 103 | if (failure) { 104 | dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ 105 | failure(nil, serializationError); 106 | }); 107 | } 108 | 109 | return nil; 110 | } 111 | 112 | return [self HTTPRequestOperationWithRequest:request success:success failure:failure]; 113 | } 114 | 115 | - (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request 116 | success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 117 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure 118 | { 119 | AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 120 | operation.responseSerializer = self.responseSerializer; 121 | operation.shouldUseCredentialStorage = self.shouldUseCredentialStorage; 122 | operation.credential = self.credential; 123 | operation.securityPolicy = self.securityPolicy; 124 | 125 | [operation setCompletionBlockWithSuccess:success failure:failure]; 126 | operation.completionQueue = self.completionQueue; 127 | operation.completionGroup = self.completionGroup; 128 | 129 | return operation; 130 | } 131 | 132 | #pragma mark - 133 | 134 | - (AFHTTPRequestOperation *)GET:(NSString *)URLString 135 | parameters:(id)parameters 136 | success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 137 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure 138 | { 139 | AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"GET" URLString:URLString parameters:parameters success:success failure:failure]; 140 | 141 | [self.operationQueue addOperation:operation]; 142 | 143 | return operation; 144 | } 145 | 146 | - (AFHTTPRequestOperation *)HEAD:(NSString *)URLString 147 | parameters:(id)parameters 148 | success:(void (^)(AFHTTPRequestOperation *operation))success 149 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure 150 | { 151 | AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters success:^(AFHTTPRequestOperation *requestOperation, __unused id responseObject) { 152 | if (success) { 153 | success(requestOperation); 154 | } 155 | } failure:failure]; 156 | 157 | [self.operationQueue addOperation:operation]; 158 | 159 | return operation; 160 | } 161 | 162 | - (AFHTTPRequestOperation *)POST:(NSString *)URLString 163 | parameters:(id)parameters 164 | success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 165 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure{ 166 | 167 | AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"POST" URLString:URLString parameters:parameters success:success failure:failure]; 168 | [self.operationQueue addOperation:operation]; 169 | 170 | return operation; 171 | } 172 | 173 | - (AFHTTPRequestOperation *)POST:(NSString *)URLString 174 | parameters:(id)parameters 175 | constructingBodyWithBlock:(void (^)(id formData))block 176 | success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 177 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure 178 | { 179 | NSError *serializationError = nil; 180 | NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError]; 181 | 182 | if (serializationError) { 183 | if (failure) { 184 | #pragma clang diagnostic push 185 | #pragma clang diagnostic ignored "-Wgnu" 186 | dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ 187 | failure(nil, serializationError); 188 | }); 189 | #pragma clang diagnostic pop 190 | } 191 | 192 | return nil; 193 | } 194 | 195 | AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; 196 | 197 | [self.operationQueue addOperation:operation]; 198 | 199 | return operation; 200 | } 201 | 202 | - (AFHTTPRequestOperation *)PUT:(NSString *)URLString 203 | parameters:(id)parameters 204 | success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 205 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure 206 | { 207 | AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters success:success failure:failure]; 208 | 209 | [self.operationQueue addOperation:operation]; 210 | 211 | return operation; 212 | } 213 | 214 | - (AFHTTPRequestOperation *)PATCH:(NSString *)URLString 215 | parameters:(id)parameters 216 | success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 217 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure 218 | { 219 | AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters success:success failure:failure]; 220 | 221 | [self.operationQueue addOperation:operation]; 222 | 223 | return operation; 224 | } 225 | 226 | - (AFHTTPRequestOperation *)DELETE:(NSString *)URLString 227 | parameters:(id)parameters 228 | success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 229 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure 230 | { 231 | AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters success:success failure:failure]; 232 | 233 | [self.operationQueue addOperation:operation]; 234 | 235 | return operation; 236 | } 237 | 238 | #pragma mark - NSObject 239 | 240 | - (NSString *)description { 241 | return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.operationQueue]; 242 | } 243 | 244 | #pragma mark - NSSecureCoding 245 | 246 | + (BOOL)supportsSecureCoding { 247 | return YES; 248 | } 249 | 250 | - (id)initWithCoder:(NSCoder *)decoder { 251 | NSURL *baseURL = [decoder decodeObjectForKey:NSStringFromSelector(@selector(baseURL))]; 252 | 253 | self = [self initWithBaseURL:baseURL]; 254 | if (!self) { 255 | return nil; 256 | } 257 | 258 | self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))]; 259 | self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))]; 260 | 261 | return self; 262 | } 263 | 264 | - (void)encodeWithCoder:(NSCoder *)coder { 265 | [coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))]; 266 | [coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))]; 267 | [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))]; 268 | } 269 | 270 | #pragma mark - NSCopying 271 | 272 | - (id)copyWithZone:(NSZone *)zone { 273 | AFHTTPRequestOperationManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL]; 274 | 275 | HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone]; 276 | HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone]; 277 | 278 | return HTTPClient; 279 | } 280 | 281 | @end 282 | -------------------------------------------------------------------------------- /CooperAFNetworkSingleton/Library/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 | -------------------------------------------------------------------------------- /CooperAFNetworkSingleton/Library/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 | -------------------------------------------------------------------------------- /CooperAFNetworkSingleton/Library/Network/Reachability.m: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2011, Tony Million. 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are met: 7 | 8 | 1. Redistributions of source code must retain the above copyright notice, this 9 | list of conditions and the following disclaimer. 10 | 11 | 2. Redistributions in binary form must reproduce the above copyright notice, 12 | this list of conditions and the following disclaimer in the documentation 13 | and/or other materials provided with the distribution. 14 | 15 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 16 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 18 | ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 19 | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 20 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 21 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 22 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 23 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 24 | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 25 | POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #import "Reachability.h" 29 | 30 | #import 31 | #import 32 | #import 33 | #import 34 | #import 35 | #import 36 | 37 | 38 | NSString *const GkReachabilityChangedNotification = @"GkReachabilityChangedNotification"; 39 | 40 | 41 | @interface Reachability () 42 | 43 | @property (nonatomic, assign) SCNetworkReachabilityRef reachabilityRef; 44 | @property (nonatomic, strong) dispatch_queue_t reachabilitySerialQueue; 45 | @property (nonatomic, strong) id reachabilityObject; 46 | 47 | -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags; 48 | -(BOOL)isReachableWithFlags:(SCNetworkReachabilityFlags)flags; 49 | 50 | @end 51 | 52 | 53 | static NSString *reachabilityFlags(SCNetworkReachabilityFlags flags) 54 | { 55 | return [NSString stringWithFormat:@"%c%c %c%c%c%c%c%c%c", 56 | #if TARGET_OS_IPHONE 57 | (flags & kSCNetworkReachabilityFlagsIsWWAN) ? 'W' : '-', 58 | #else 59 | 'X', 60 | #endif 61 | (flags & kSCNetworkReachabilityFlagsReachable) ? 'R' : '-', 62 | (flags & kSCNetworkReachabilityFlagsConnectionRequired) ? 'c' : '-', 63 | (flags & kSCNetworkReachabilityFlagsTransientConnection) ? 't' : '-', 64 | (flags & kSCNetworkReachabilityFlagsInterventionRequired) ? 'i' : '-', 65 | (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) ? 'C' : '-', 66 | (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) ? 'D' : '-', 67 | (flags & kSCNetworkReachabilityFlagsIsLocalAddress) ? 'l' : '-', 68 | (flags & kSCNetworkReachabilityFlagsIsDirect) ? 'd' : '-']; 69 | } 70 | 71 | // Start listening for reachability notifications on the current run loop 72 | static void TMReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void* info) 73 | { 74 | #pragma unused (target) 75 | 76 | Reachability *reachability = ((__bridge Reachability*)info); 77 | 78 | // We probably don't need an autoreleasepool here, as GCD docs state each queue has its own autorelease pool, 79 | // but what the heck eh? 80 | @autoreleasepool 81 | { 82 | [reachability reachabilityChanged:flags]; 83 | } 84 | } 85 | 86 | 87 | @implementation Reachability 88 | 89 | #pragma mark - Class Constructor Methods 90 | 91 | +(instancetype)reachabilityWithHostName:(NSString*)hostname 92 | { 93 | return [Reachability reachabilityWithHostname:hostname]; 94 | } 95 | 96 | +(instancetype)reachabilityWithHostname:(NSString*)hostname 97 | { 98 | SCNetworkReachabilityRef ref = SCNetworkReachabilityCreateWithName(NULL, [hostname UTF8String]); 99 | if (ref) 100 | { 101 | id reachability = [[self alloc] initWithReachabilityRef:ref]; 102 | return reachability; 103 | } 104 | 105 | return nil; 106 | } 107 | 108 | +(instancetype)reachabilityWithAddress:(void *)hostAddress 109 | { 110 | SCNetworkReachabilityRef ref = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)hostAddress); 111 | if (ref) 112 | { 113 | id reachability = [[self alloc] initWithReachabilityRef:ref]; 114 | 115 | return reachability; 116 | } 117 | 118 | return nil; 119 | } 120 | 121 | +(instancetype)reachabilityForInternetConnection 122 | { 123 | struct sockaddr_in6 zeroAddress; 124 | bzero(&zeroAddress, sizeof(zeroAddress)); 125 | zeroAddress.sin6_len = sizeof(zeroAddress); 126 | zeroAddress.sin6_family = AF_INET6; 127 | 128 | return [self reachabilityWithAddress:&zeroAddress]; 129 | } 130 | 131 | +(instancetype)reachabilityForLocalWiFi 132 | { 133 | struct sockaddr_in6 localWifiAddress; 134 | bzero(&localWifiAddress, sizeof(localWifiAddress)); 135 | localWifiAddress.sin6_len = sizeof(localWifiAddress); 136 | localWifiAddress.sin6_family = AF_INET6; 137 | // IN_LINKLOCALNETNUM is defined in as 169.254.0.0 138 | // localWifiAddress.sin6_addr.__u6_addr = htonl(IN_LINKLOCALNETNUM); 139 | 140 | return [self reachabilityWithAddress:&localWifiAddress]; 141 | } 142 | 143 | 144 | // Initialization methods 145 | 146 | -(instancetype)initWithReachabilityRef:(SCNetworkReachabilityRef)ref 147 | { 148 | self = [super init]; 149 | if (self != nil) 150 | { 151 | self.reachableOnWWAN = YES; 152 | self.reachabilityRef = ref; 153 | 154 | // We need to create a serial queue. 155 | // We allocate this once for the lifetime of the notifier. 156 | 157 | self.reachabilitySerialQueue = dispatch_queue_create("com.tonymillion.reachability", NULL); 158 | } 159 | 160 | return self; 161 | } 162 | 163 | -(void)dealloc 164 | { 165 | [self stopNotifier]; 166 | 167 | if(self.reachabilityRef) 168 | { 169 | CFRelease(self.reachabilityRef); 170 | self.reachabilityRef = nil; 171 | } 172 | 173 | self.reachableBlock = nil; 174 | self.unreachableBlock = nil; 175 | self.reachabilityBlock = nil; 176 | self.reachabilitySerialQueue = nil; 177 | } 178 | 179 | #pragma mark - Notifier Methods 180 | 181 | // Notifier 182 | // NOTE: This uses GCD to trigger the blocks - they *WILL NOT* be called on THE MAIN THREAD 183 | // - In other words DO NOT DO ANY UI UPDATES IN THE BLOCKS. 184 | // INSTEAD USE dispatch_async(dispatch_get_main_queue(), ^{UISTUFF}) (or dispatch_sync if you want) 185 | 186 | -(BOOL)startNotifier 187 | { 188 | // allow start notifier to be called multiple times 189 | if(self.reachabilityObject && (self.reachabilityObject == self)) 190 | { 191 | return YES; 192 | } 193 | 194 | 195 | SCNetworkReachabilityContext context = { 0, NULL, NULL, NULL, NULL }; 196 | context.info = (__bridge void *)self; 197 | 198 | if(SCNetworkReachabilitySetCallback(self.reachabilityRef, TMReachabilityCallback, &context)) 199 | { 200 | // Set it as our reachability queue, which will retain the queue 201 | if(SCNetworkReachabilitySetDispatchQueue(self.reachabilityRef, self.reachabilitySerialQueue)) 202 | { 203 | // this should do a retain on ourself, so as long as we're in notifier mode we shouldn't disappear out from under ourselves 204 | // woah 205 | self.reachabilityObject = self; 206 | return YES; 207 | } 208 | else 209 | { 210 | #ifdef DEBUG 211 | NSLog(@"SCNetworkReachabilitySetDispatchQueue() failed: %s", SCErrorString(SCError())); 212 | #endif 213 | 214 | // UH OH - FAILURE - stop any callbacks! 215 | SCNetworkReachabilitySetCallback(self.reachabilityRef, NULL, NULL); 216 | } 217 | } 218 | else 219 | { 220 | #ifdef DEBUG 221 | NSLog(@"SCNetworkReachabilitySetCallback() failed: %s", SCErrorString(SCError())); 222 | #endif 223 | } 224 | 225 | // if we get here we fail at the internet 226 | self.reachabilityObject = nil; 227 | return NO; 228 | } 229 | 230 | -(void)stopNotifier 231 | { 232 | // First stop, any callbacks! 233 | SCNetworkReachabilitySetCallback(self.reachabilityRef, NULL, NULL); 234 | 235 | // Unregister target from the GCD serial dispatch queue. 236 | SCNetworkReachabilitySetDispatchQueue(self.reachabilityRef, NULL); 237 | 238 | self.reachabilityObject = nil; 239 | } 240 | 241 | #pragma mark - reachability tests 242 | 243 | // This is for the case where you flick the airplane mode; 244 | // you end up getting something like this: 245 | //Reachability: WR ct----- 246 | //Reachability: -- ------- 247 | //Reachability: WR ct----- 248 | //Reachability: -- ------- 249 | // We treat this as 4 UNREACHABLE triggers - really apple should do better than this 250 | 251 | #define testcase (kSCNetworkReachabilityFlagsConnectionRequired | kSCNetworkReachabilityFlagsTransientConnection) 252 | 253 | -(BOOL)isReachableWithFlags:(SCNetworkReachabilityFlags)flags 254 | { 255 | BOOL connectionUP = YES; 256 | 257 | if(!(flags & kSCNetworkReachabilityFlagsReachable)) 258 | connectionUP = NO; 259 | 260 | if( (flags & testcase) == testcase ) 261 | connectionUP = NO; 262 | 263 | #if TARGET_OS_IPHONE 264 | if(flags & kSCNetworkReachabilityFlagsIsWWAN) 265 | { 266 | // We're on 3G. 267 | if(!self.reachableOnWWAN) 268 | { 269 | // We don't want to connect when on 3G. 270 | connectionUP = NO; 271 | } 272 | } 273 | #endif 274 | 275 | return connectionUP; 276 | } 277 | 278 | -(BOOL)isReachable 279 | { 280 | SCNetworkReachabilityFlags flags; 281 | 282 | if(!SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags)) 283 | return NO; 284 | 285 | return [self isReachableWithFlags:flags]; 286 | } 287 | 288 | -(BOOL)isReachableViaWWAN 289 | { 290 | #if TARGET_OS_IPHONE 291 | 292 | SCNetworkReachabilityFlags flags = 0; 293 | 294 | if(SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags)) 295 | { 296 | // Check we're REACHABLE 297 | if(flags & kSCNetworkReachabilityFlagsReachable) 298 | { 299 | // Now, check we're on WWAN 300 | if(flags & kSCNetworkReachabilityFlagsIsWWAN) 301 | { 302 | return YES; 303 | } 304 | } 305 | } 306 | #endif 307 | 308 | return NO; 309 | } 310 | 311 | -(BOOL)isReachableViaWiFi 312 | { 313 | SCNetworkReachabilityFlags flags = 0; 314 | 315 | if(SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags)) 316 | { 317 | // Check we're reachable 318 | if((flags & kSCNetworkReachabilityFlagsReachable)) 319 | { 320 | #if TARGET_OS_IPHONE 321 | // Check we're NOT on WWAN 322 | if((flags & kSCNetworkReachabilityFlagsIsWWAN)) 323 | { 324 | return NO; 325 | } 326 | #endif 327 | return YES; 328 | } 329 | } 330 | 331 | return NO; 332 | } 333 | 334 | 335 | // WWAN may be available, but not active until a connection has been established. 336 | // WiFi may require a connection for VPN on Demand. 337 | -(BOOL)isConnectionRequired 338 | { 339 | return [self connectionRequired]; 340 | } 341 | 342 | -(BOOL)connectionRequired 343 | { 344 | SCNetworkReachabilityFlags flags; 345 | 346 | if(SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags)) 347 | { 348 | return (flags & kSCNetworkReachabilityFlagsConnectionRequired); 349 | } 350 | 351 | return NO; 352 | } 353 | 354 | // Dynamic, on demand connection? 355 | -(BOOL)isConnectionOnDemand 356 | { 357 | SCNetworkReachabilityFlags flags; 358 | 359 | if (SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags)) 360 | { 361 | return ((flags & kSCNetworkReachabilityFlagsConnectionRequired) && 362 | (flags & (kSCNetworkReachabilityFlagsConnectionOnTraffic | kSCNetworkReachabilityFlagsConnectionOnDemand))); 363 | } 364 | 365 | return NO; 366 | } 367 | 368 | // Is user intervention required? 369 | -(BOOL)isInterventionRequired 370 | { 371 | SCNetworkReachabilityFlags flags; 372 | 373 | if (SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags)) 374 | { 375 | return ((flags & kSCNetworkReachabilityFlagsConnectionRequired) && 376 | (flags & kSCNetworkReachabilityFlagsInterventionRequired)); 377 | } 378 | 379 | return NO; 380 | } 381 | 382 | 383 | #pragma mark - reachability status stuff 384 | 385 | -(NetworkStatus)currentReachabilityStatus 386 | { 387 | if([self isReachable]) 388 | { 389 | if([self isReachableViaWiFi]) 390 | return ReachableViaWiFi; 391 | 392 | #if TARGET_OS_IPHONE 393 | return ReachableViaWWAN; 394 | #endif 395 | } 396 | 397 | return NotReachable; 398 | } 399 | 400 | -(SCNetworkReachabilityFlags)reachabilityFlags 401 | { 402 | SCNetworkReachabilityFlags flags = 0; 403 | 404 | if(SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags)) 405 | { 406 | return flags; 407 | } 408 | 409 | return 0; 410 | } 411 | 412 | -(NSString*)currentReachabilityString 413 | { 414 | NetworkStatus temp = [self currentReachabilityStatus]; 415 | 416 | if(temp == ReachableViaWWAN) 417 | { 418 | // Updated for the fact that we have CDMA phones now! 419 | return NSLocalizedString(@"Cellular", @""); 420 | } 421 | if (temp == ReachableViaWiFi) 422 | { 423 | return NSLocalizedString(@"WiFi", @""); 424 | } 425 | 426 | return NSLocalizedString(@"No Connection", @""); 427 | } 428 | 429 | -(NSString*)currentReachabilityFlags 430 | { 431 | return reachabilityFlags([self reachabilityFlags]); 432 | } 433 | 434 | #pragma mark - Callback function calls this method 435 | 436 | -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags 437 | { 438 | if([self isReachableWithFlags:flags]) 439 | { 440 | if(self.reachableBlock) 441 | { 442 | self.reachableBlock(self); 443 | } 444 | } 445 | else 446 | { 447 | if(self.unreachableBlock) 448 | { 449 | self.unreachableBlock(self); 450 | } 451 | } 452 | 453 | if(self.reachabilityBlock) 454 | { 455 | self.reachabilityBlock(self, flags); 456 | } 457 | 458 | // this makes sure the change notification happens on the MAIN THREAD 459 | dispatch_async(dispatch_get_main_queue(), ^{ 460 | [[NSNotificationCenter defaultCenter] postNotificationName:GkReachabilityChangedNotification 461 | object:self]; 462 | }); 463 | } 464 | 465 | #pragma mark - Debug Description 466 | 467 | - (NSString *) description 468 | { 469 | NSString *description = [NSString stringWithFormat:@"<%@: %#x (%@)>", 470 | NSStringFromClass([self class]), (unsigned int) self, [self currentReachabilityFlags]]; 471 | return description; 472 | } 473 | 474 | @end 475 | -------------------------------------------------------------------------------- /CooperAFNetworkSingleton/Library/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 | -------------------------------------------------------------------------------- /CooperAFNetworkSingleton/Library/AFNetworking/AFURLConnectionOperation.h: -------------------------------------------------------------------------------- 1 | // AFURLConnectionOperation.h 2 | // Copyright (c) 2011–2015 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 | #import 25 | #import "AFURLRequestSerialization.h" 26 | #import "AFURLResponseSerialization.h" 27 | #import "AFSecurityPolicy.h" 28 | 29 | #ifndef NS_DESIGNATED_INITIALIZER 30 | #if __has_attribute(objc_designated_initializer) 31 | #define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer)) 32 | #else 33 | #define NS_DESIGNATED_INITIALIZER 34 | #endif 35 | #endif 36 | 37 | /** 38 | `AFURLConnectionOperation` is a subclass of `NSOperation` that implements `NSURLConnection` delegate methods. 39 | 40 | ## Subclassing Notes 41 | 42 | This is the base class of all network request operations. You may wish to create your own subclass in order to implement additional `NSURLConnection` delegate methods (see "`NSURLConnection` Delegate Methods" below), or to provide additional properties and/or class constructors. 43 | 44 | If you are creating a subclass that communicates over the HTTP or HTTPS protocols, you may want to consider subclassing `AFHTTPRequestOperation` instead, as it supports specifying acceptable content types or status codes. 45 | 46 | ## NSURLConnection Delegate Methods 47 | 48 | `AFURLConnectionOperation` implements the following `NSURLConnection` delegate methods: 49 | 50 | - `connection:didReceiveResponse:` 51 | - `connection:didReceiveData:` 52 | - `connectionDidFinishLoading:` 53 | - `connection:didFailWithError:` 54 | - `connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:` 55 | - `connection:willCacheResponse:` 56 | - `connectionShouldUseCredentialStorage:` 57 | - `connection:needNewBodyStream:` 58 | - `connection:willSendRequestForAuthenticationChallenge:` 59 | 60 | If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first. 61 | 62 | ## Callbacks and Completion Blocks 63 | 64 | The built-in `completionBlock` provided by `NSOperation` allows for custom behavior to be executed after the request finishes. It is a common pattern for class constructors in subclasses to take callback block parameters, and execute them conditionally in the body of its `completionBlock`. Make sure to handle cancelled operations appropriately when setting a `completionBlock` (i.e. returning early before parsing response data). See the implementation of any of the `AFHTTPRequestOperation` subclasses for an example of this. 65 | 66 | Subclasses are strongly discouraged from overriding `setCompletionBlock:`, as `AFURLConnectionOperation`'s implementation includes a workaround to mitigate retain cycles, and what Apple rather ominously refers to as ["The Deallocation Problem"](http://developer.apple.com/library/ios/#technotes/tn2109/). 67 | 68 | ## SSL Pinning 69 | 70 | Relying on the CA trust model to validate SSL certificates exposes your app to security vulnerabilities, such as man-in-the-middle attacks. For applications that connect to known servers, SSL certificate pinning provides an increased level of security, by checking server certificate validity against those specified in the app bundle. 71 | 72 | SSL with certificate pinning is strongly recommended for any application that transmits sensitive information to an external webservice. 73 | 74 | Connections will be validated on all matching certificates with a `.cer` extension in the bundle root. 75 | 76 | ## NSCoding & NSCopying Conformance 77 | 78 | `AFURLConnectionOperation` conforms to the `NSCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. However, because of the intrinsic limitations of capturing the exact state of an operation at a particular moment, there are some important caveats to keep in mind: 79 | 80 | ### NSCoding Caveats 81 | 82 | - Encoded operations do not include any block or stream properties. Be sure to set `completionBlock`, `outputStream`, and any callback blocks as necessary when using `-initWithCoder:` or `NSKeyedUnarchiver`. 83 | - Operations are paused on `encodeWithCoder:`. If the operation was encoded while paused or still executing, its archived state will return `YES` for `isReady`. Otherwise, the state of an operation when encoding will remain unchanged. 84 | 85 | ### NSCopying Caveats 86 | 87 | - `-copy` and `-copyWithZone:` return a new operation with the `NSURLRequest` of the original. So rather than an exact copy of the operation at that particular instant, the copying mechanism returns a completely new instance, which can be useful for retrying operations. 88 | - A copy of an operation will not include the `outputStream` of the original. 89 | - Operation copies do not include `completionBlock`, as it often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ operation when copied. 90 | */ 91 | 92 | NS_ASSUME_NONNULL_BEGIN 93 | 94 | @interface AFURLConnectionOperation : NSOperation 95 | 96 | ///------------------------------- 97 | /// @name Accessing Run Loop Modes 98 | ///------------------------------- 99 | 100 | /** 101 | The run loop modes in which the operation will run on the network thread. By default, this is a single-member set containing `NSRunLoopCommonModes`. 102 | */ 103 | @property (nonatomic, strong) NSSet *runLoopModes; 104 | 105 | ///----------------------------------------- 106 | /// @name Getting URL Connection Information 107 | ///----------------------------------------- 108 | 109 | /** 110 | The request used by the operation's connection. 111 | */ 112 | @property (readonly, nonatomic, strong) NSURLRequest *request; 113 | 114 | /** 115 | The last response received by the operation's connection. 116 | */ 117 | @property (readonly, nonatomic, strong, nullable) NSURLResponse *response; 118 | 119 | /** 120 | The error, if any, that occurred in the lifecycle of the request. 121 | */ 122 | @property (readonly, nonatomic, strong, nullable) NSError *error; 123 | 124 | ///---------------------------- 125 | /// @name Getting Response Data 126 | ///---------------------------- 127 | 128 | /** 129 | The data received during the request. 130 | */ 131 | @property (readonly, nonatomic, strong, nullable) NSData *responseData; 132 | 133 | /** 134 | The string representation of the response data. 135 | */ 136 | @property (readonly, nonatomic, copy, nullable) NSString *responseString; 137 | 138 | /** 139 | The string encoding of the response. 140 | 141 | If the response does not specify a valid string encoding, `responseStringEncoding` will return `NSUTF8StringEncoding`. 142 | */ 143 | @property (readonly, nonatomic, assign) NSStringEncoding responseStringEncoding; 144 | 145 | ///------------------------------- 146 | /// @name Managing URL Credentials 147 | ///------------------------------- 148 | 149 | /** 150 | Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default. 151 | 152 | This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`. 153 | */ 154 | @property (nonatomic, assign) BOOL shouldUseCredentialStorage; 155 | 156 | /** 157 | The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`. 158 | 159 | This will be overridden by any shared credentials that exist for the username or password of the request URL, if present. 160 | */ 161 | @property (nonatomic, strong, nullable) NSURLCredential *credential; 162 | 163 | ///------------------------------- 164 | /// @name Managing Security Policy 165 | ///------------------------------- 166 | 167 | /** 168 | The security policy used to evaluate server trust for secure connections. 169 | */ 170 | @property (nonatomic, strong) AFSecurityPolicy *securityPolicy; 171 | 172 | ///------------------------ 173 | /// @name Accessing Streams 174 | ///------------------------ 175 | 176 | /** 177 | The input stream used to read data to be sent during the request. 178 | 179 | This property acts as a proxy to the `HTTPBodyStream` property of `request`. 180 | */ 181 | @property (nonatomic, strong) NSInputStream *inputStream; 182 | 183 | /** 184 | The output stream that is used to write data received until the request is finished. 185 | 186 | By default, data is accumulated into a buffer that is stored into `responseData` upon completion of the request, with the intermediary `outputStream` property set to `nil`. When `outputStream` is set, the data will not be accumulated into an internal buffer, and as a result, the `responseData` property of the completed request will be `nil`. The output stream will be scheduled in the network thread runloop upon being set. 187 | */ 188 | @property (nonatomic, strong, nullable) NSOutputStream *outputStream; 189 | 190 | ///--------------------------------- 191 | /// @name Managing Callback Queues 192 | ///--------------------------------- 193 | 194 | /** 195 | The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used. 196 | */ 197 | #if OS_OBJECT_USE_OBJC 198 | @property (nonatomic, strong, nullable) dispatch_queue_t completionQueue; 199 | #else 200 | @property (nonatomic, assign, nullable) dispatch_queue_t completionQueue; 201 | #endif 202 | 203 | /** 204 | The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used. 205 | */ 206 | #if OS_OBJECT_USE_OBJC 207 | @property (nonatomic, strong, nullable) dispatch_group_t completionGroup; 208 | #else 209 | @property (nonatomic, assign, nullable) dispatch_group_t completionGroup; 210 | #endif 211 | 212 | ///--------------------------------------------- 213 | /// @name Managing Request Operation Information 214 | ///--------------------------------------------- 215 | 216 | /** 217 | The user info dictionary for the receiver. 218 | */ 219 | @property (nonatomic, strong) NSDictionary *userInfo; 220 | // FIXME: It doesn't seem that this userInfo is used anywhere in the implementation. 221 | 222 | ///------------------------------------------------------ 223 | /// @name Initializing an AFURLConnectionOperation Object 224 | ///------------------------------------------------------ 225 | 226 | /** 227 | Initializes and returns a newly allocated operation object with a url connection configured with the specified url request. 228 | 229 | This is the designated initializer. 230 | 231 | @param urlRequest The request object to be used by the operation connection. 232 | */ 233 | - (instancetype)initWithRequest:(NSURLRequest *)urlRequest NS_DESIGNATED_INITIALIZER; 234 | 235 | ///---------------------------------- 236 | /// @name Pausing / Resuming Requests 237 | ///---------------------------------- 238 | 239 | /** 240 | Pauses the execution of the request operation. 241 | 242 | A paused operation returns `NO` for `-isReady`, `-isExecuting`, and `-isFinished`. As such, it will remain in an `NSOperationQueue` until it is either cancelled or resumed. Pausing a finished, cancelled, or paused operation has no effect. 243 | */ 244 | - (void)pause; 245 | 246 | /** 247 | Whether the request operation is currently paused. 248 | 249 | @return `YES` if the operation is currently paused, otherwise `NO`. 250 | */ 251 | - (BOOL)isPaused; 252 | 253 | /** 254 | Resumes the execution of the paused request operation. 255 | 256 | Pause/Resume behavior varies depending on the underlying implementation for the operation class. In its base implementation, resuming a paused requests restarts the original request. However, since HTTP defines a specification for how to request a specific content range, `AFHTTPRequestOperation` will resume downloading the request from where it left off, instead of restarting the original request. 257 | */ 258 | - (void)resume; 259 | 260 | ///---------------------------------------------- 261 | /// @name Configuring Backgrounding Task Behavior 262 | ///---------------------------------------------- 263 | 264 | /** 265 | Specifies that the operation should continue execution after the app has entered the background, and the expiration handler for that background task. 266 | 267 | @param handler A handler to be called shortly before the application’s remaining background time reaches 0. The handler is wrapped in a block that cancels the operation, and cleans up and marks the end of execution, unlike the `handler` parameter in `UIApplication -beginBackgroundTaskWithExpirationHandler:`, which expects this to be done in the handler itself. The handler is called synchronously on the main thread, thus blocking the application’s suspension momentarily while the application is notified. 268 | */ 269 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 270 | - (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(nullable void (^)(void))handler NS_EXTENSION_UNAVAILABLE_IOS("Not available in app extensions."); 271 | #endif 272 | 273 | ///--------------------------------- 274 | /// @name Setting Progress Callbacks 275 | ///--------------------------------- 276 | 277 | /** 278 | Sets a callback to be called when an undetermined number of bytes have been uploaded to the server. 279 | 280 | @param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes three arguments: the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times, and will execute on the main thread. 281 | */ 282 | - (void)setUploadProgressBlock:(nullable void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block; 283 | 284 | /** 285 | Sets a callback to be called when an undetermined number of bytes have been downloaded from the server. 286 | 287 | @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the main thread. 288 | */ 289 | - (void)setDownloadProgressBlock:(nullable void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block; 290 | 291 | ///------------------------------------------------- 292 | /// @name Setting NSURLConnection Delegate Callbacks 293 | ///------------------------------------------------- 294 | 295 | /** 296 | Sets a block to be executed when the connection will authenticate a challenge in order to download its request, as handled by the `NSURLConnectionDelegate` method `connection:willSendRequestForAuthenticationChallenge:`. 297 | 298 | @param block A block object to be executed when the connection will authenticate a challenge in order to download its request. The block has no return type and takes two arguments: the URL connection object, and the challenge that must be authenticated. This block must invoke one of the challenge-responder methods (NSURLAuthenticationChallengeSender protocol). 299 | 300 | If `allowsInvalidSSLCertificate` is set to YES, `connection:willSendRequestForAuthenticationChallenge:` will attempt to have the challenge sender use credentials with invalid SSL certificates. 301 | */ 302 | - (void)setWillSendRequestForAuthenticationChallengeBlock:(nullable void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block; 303 | 304 | /** 305 | Sets a block to be executed when the server redirects the request from one URL to another URL, or when the request URL changed by the `NSURLProtocol` subclass handling the request in order to standardize its format, as handled by the `NSURLConnectionDataDelegate` method `connection:willSendRequest:redirectResponse:`. 306 | 307 | @param block A block object to be executed when the request URL was changed. The block returns an `NSURLRequest` object, the URL request to redirect, and takes three arguments: the URL connection object, the the proposed redirected request, and the URL response that caused the redirect. 308 | */ 309 | - (void)setRedirectResponseBlock:(nullable NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block; 310 | 311 | 312 | /** 313 | Sets a block to be executed to modify the response a connection will cache, if any, as handled by the `NSURLConnectionDelegate` method `connection:willCacheResponse:`. 314 | 315 | @param block A block object to be executed to determine what response a connection will cache, if any. The block returns an `NSCachedURLResponse` object, the cached response to store in memory or `nil` to prevent the response from being cached, and takes two arguments: the URL connection object, and the cached response provided for the request. 316 | */ 317 | - (void)setCacheResponseBlock:(nullable NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block; 318 | 319 | /// 320 | 321 | /** 322 | 323 | */ 324 | + (NSArray *)batchOfRequestOperations:(nullable NSArray *)operations 325 | progressBlock:(nullable void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock 326 | completionBlock:(nullable void (^)(NSArray *operations))completionBlock; 327 | 328 | @end 329 | 330 | ///-------------------- 331 | /// @name Notifications 332 | ///-------------------- 333 | 334 | /** 335 | Posted when an operation begins executing. 336 | */ 337 | extern NSString * const AFNetworkingOperationDidStartNotification; 338 | 339 | /** 340 | Posted when an operation finishes. 341 | */ 342 | extern NSString * const AFNetworkingOperationDidFinishNotification; 343 | 344 | NS_ASSUME_NONNULL_END 345 | -------------------------------------------------------------------------------- /CooperAFNetworkSingleton/Library/AFNetworking/AFHTTPRequestOperationManager.h: -------------------------------------------------------------------------------- 1 | // AFHTTPRequestOperationManager.h 2 | // Copyright (c) 2011–2015 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 | #import 25 | 26 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 27 | #import 28 | #else 29 | #import 30 | #endif 31 | 32 | #import "AFHTTPRequestOperation.h" 33 | #import "AFURLResponseSerialization.h" 34 | #import "AFURLRequestSerialization.h" 35 | #import "AFSecurityPolicy.h" 36 | #import "AFNetworkReachabilityManager.h" 37 | 38 | #ifndef NS_DESIGNATED_INITIALIZER 39 | #if __has_attribute(objc_designated_initializer) 40 | #define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer)) 41 | #else 42 | #define NS_DESIGNATED_INITIALIZER 43 | #endif 44 | #endif 45 | 46 | NS_ASSUME_NONNULL_BEGIN 47 | 48 | /** 49 | `AFHTTPRequestOperationManager` encapsulates the common patterns of communicating with a web application over HTTP, including request creation, response serialization, network reachability monitoring, and security, as well as request operation management. 50 | 51 | ## Subclassing Notes 52 | 53 | 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. 54 | 55 | For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `AFHTTPRequestOperationManager` may be used to similar effect. 56 | 57 | ## Methods to Override 58 | 59 | To change the behavior of all request operation construction for an `AFHTTPRequestOperationManager` subclass, override `HTTPRequestOperationWithRequest:success:failure`. 60 | 61 | ## Serialization 62 | 63 | Requests created by an HTTP client will contain default headers and encode parameters according to the `requestSerializer` property, which is an object conforming to ``. 64 | 65 | Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `` 66 | 67 | ## URL Construction Using Relative Paths 68 | 69 | 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:`. 70 | 71 | Below are a few examples of how `baseURL` and relative paths interact: 72 | 73 | NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"]; 74 | [NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo 75 | [NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz 76 | [NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo 77 | [NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo 78 | [NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/ 79 | [NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/ 80 | 81 | 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. 82 | 83 | ## Network Reachability Monitoring 84 | 85 | Network reachability status and change monitoring is available through the `reachabilityManager` property. Applications may choose to monitor network reachability conditions in order to prevent or suspend any outbound requests. See `AFNetworkReachabilityManager` for more details. 86 | 87 | ## NSSecureCoding & NSCopying Caveats 88 | 89 | `AFHTTPRequestOperationManager` conforms to the `NSSecureCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. There are a few minor caveats to keep in mind, however: 90 | 91 | - Archives and copies of HTTP clients will be initialized with an empty operation queue. 92 | - NSSecureCoding cannot serialize / deserialize block properties, so an archive of an HTTP client will not include any reachability callback block that may be set. 93 | */ 94 | @interface AFHTTPRequestOperationManager : NSObject 95 | 96 | /** 97 | The URL used to monitor reachability, and construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods. 98 | */ 99 | @property (readonly, nonatomic, strong, nullable) NSURL *baseURL; 100 | 101 | /** 102 | 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. 103 | 104 | @warning `requestSerializer` must not be `nil`. 105 | */ 106 | @property (nonatomic, strong) AFHTTPRequestSerializer * requestSerializer; 107 | 108 | /** 109 | 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 a JSON serializer, which serializes data from responses with a `application/json` MIME type, and falls back to the raw data object. The serializer validates the status code to be in the `2XX` range, denoting success. If the response serializer generates an error in `-responseObjectForResponse:data:error:`, the `failure` callback of the session task or request operation will be executed; otherwise, the `success` callback will be executed. 110 | 111 | @warning `responseSerializer` must not be `nil`. 112 | */ 113 | @property (nonatomic, strong) AFHTTPResponseSerializer * responseSerializer; 114 | 115 | /** 116 | The operation queue on which request operations are scheduled and run. 117 | */ 118 | @property (nonatomic, strong) NSOperationQueue *operationQueue; 119 | 120 | ///------------------------------- 121 | /// @name Managing URL Credentials 122 | ///------------------------------- 123 | 124 | /** 125 | Whether request operations should consult the credential storage for authenticating the connection. `YES` by default. 126 | 127 | @see AFURLConnectionOperation -shouldUseCredentialStorage 128 | */ 129 | @property (nonatomic, assign) BOOL shouldUseCredentialStorage; 130 | 131 | /** 132 | The credential used by request operations for authentication challenges. 133 | 134 | @see AFURLConnectionOperation -credential 135 | */ 136 | @property (nonatomic, strong, nullable) NSURLCredential *credential; 137 | 138 | ///------------------------------- 139 | /// @name Managing Security Policy 140 | ///------------------------------- 141 | 142 | /** 143 | The security policy used by created request operations to evaluate server trust for secure connections. `AFHTTPRequestOperationManager` uses the `defaultPolicy` unless otherwise specified. 144 | */ 145 | @property (nonatomic, strong) AFSecurityPolicy *securityPolicy; 146 | 147 | ///------------------------------------ 148 | /// @name Managing Network Reachability 149 | ///------------------------------------ 150 | 151 | /** 152 | The network reachability manager. `AFHTTPRequestOperationManager` uses the `sharedManager` by default. 153 | */ 154 | @property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager; 155 | 156 | ///------------------------------- 157 | /// @name Managing Callback Queues 158 | ///------------------------------- 159 | 160 | /** 161 | The dispatch queue for the `completionBlock` of request operations. If `NULL` (default), the main queue is used. 162 | */ 163 | #if OS_OBJECT_HAVE_OBJC_SUPPORT 164 | @property (nonatomic, strong, nullable) dispatch_queue_t completionQueue; 165 | #else 166 | @property (nonatomic, assign, nullable) dispatch_queue_t completionQueue; 167 | #endif 168 | 169 | /** 170 | The dispatch group for the `completionBlock` of request operations. If `NULL` (default), a private dispatch group is used. 171 | */ 172 | #if OS_OBJECT_HAVE_OBJC_SUPPORT 173 | @property (nonatomic, strong, nullable) dispatch_group_t completionGroup; 174 | #else 175 | @property (nonatomic, assign, nullable) dispatch_group_t completionGroup; 176 | #endif 177 | 178 | ///--------------------------------------------- 179 | /// @name Creating and Initializing HTTP Clients 180 | ///--------------------------------------------- 181 | 182 | /** 183 | Creates and returns an `AFHTTPRequestOperationManager` object. 184 | */ 185 | + (instancetype)manager; 186 | 187 | /** 188 | Initializes an `AFHTTPRequestOperationManager` object with the specified base URL. 189 | 190 | This is the designated initializer. 191 | 192 | @param url The base URL for the HTTP client. 193 | 194 | @return The newly-initialized HTTP client 195 | */ 196 | - (instancetype)initWithBaseURL:(nullable NSURL *)url NS_DESIGNATED_INITIALIZER; 197 | 198 | ///--------------------------------------- 199 | /// @name Managing HTTP Request Operations 200 | ///--------------------------------------- 201 | 202 | /** 203 | Creates an `AFHTTPRequestOperation`, and sets the response serializers to that of the HTTP client. 204 | 205 | @param request The request object to be loaded asynchronously during execution of the operation. 206 | @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request. 207 | @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred. 208 | */ 209 | - (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request 210 | success:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success 211 | failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; 212 | 213 | ///--------------------------- 214 | /// @name Making HTTP Requests 215 | ///--------------------------- 216 | 217 | /** 218 | Creates and runs an `AFHTTPRequestOperation` with a `GET` request. 219 | 220 | @param URLString The URL string used to create the request URL. 221 | @param parameters The parameters to be encoded according to the client request serializer. 222 | @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. 223 | @param failure A block object to be executed when the request operation 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 request operation and the error describing the network or parsing error that occurred. 224 | 225 | @see -HTTPRequestOperationWithRequest:success:failure: 226 | */ 227 | - (nullable AFHTTPRequestOperation *)GET:(NSString *)URLString 228 | parameters:(nullable id)parameters 229 | success:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success 230 | failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; 231 | 232 | /** 233 | Creates and runs an `AFHTTPRequestOperation` with a `HEAD` request. 234 | 235 | @param URLString The URL string used to create the request URL. 236 | @param parameters The parameters to be encoded according to the client request serializer. 237 | @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes a single arguments: the request operation. 238 | @param failure A block object to be executed when the request operation 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 request operation and the error describing the network or parsing error that occurred. 239 | 240 | @see -HTTPRequestOperationWithRequest:success:failure: 241 | */ 242 | - (nullable AFHTTPRequestOperation *)HEAD:(NSString *)URLString 243 | parameters:(nullable id)parameters 244 | success:(nullable void (^)(AFHTTPRequestOperation *operation))success 245 | failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; 246 | 247 | /** 248 | Creates and runs an `AFHTTPRequestOperation` with a `POST` request. 249 | 250 | @param URLString The URL string used to create the request URL. 251 | @param parameters The parameters to be encoded according to the client request serializer. 252 | @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. 253 | @param failure A block object to be executed when the request operation 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 request operation and the error describing the network or parsing error that occurred. 254 | 255 | @see -HTTPRequestOperationWithRequest:success:failure: 256 | */ 257 | - (nullable AFHTTPRequestOperation *)POST:(NSString *)URLString 258 | parameters:(nullable id)parameters 259 | success:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success 260 | failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; 261 | 262 | /** 263 | Creates and runs an `AFHTTPRequestOperation` with a multipart `POST` request. 264 | 265 | @param URLString The URL string used to create the request URL. 266 | @param parameters The parameters to be encoded according to the client request serializer. 267 | @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. 268 | @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. 269 | @param failure A block object to be executed when the request operation 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 request operation and the error describing the network or parsing error that occurred. 270 | 271 | @see -HTTPRequestOperationWithRequest:success:failure: 272 | */ 273 | - (nullable AFHTTPRequestOperation *)POST:(NSString *)URLString 274 | parameters:(nullable id)parameters 275 | constructingBodyWithBlock:(nullable void (^)(id formData))block 276 | success:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success 277 | failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; 278 | 279 | /** 280 | Creates and runs an `AFHTTPRequestOperation` with a `PUT` request. 281 | 282 | @param URLString The URL string used to create the request URL. 283 | @param parameters The parameters to be encoded according to the client request serializer. 284 | @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. 285 | @param failure A block object to be executed when the request operation 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 request operation and the error describing the network or parsing error that occurred. 286 | 287 | @see -HTTPRequestOperationWithRequest:success:failure: 288 | */ 289 | - (nullable AFHTTPRequestOperation *)PUT:(NSString *)URLString 290 | parameters:(nullable id)parameters 291 | success:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success 292 | failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; 293 | 294 | /** 295 | Creates and runs an `AFHTTPRequestOperation` with a `PATCH` request. 296 | 297 | @param URLString The URL string used to create the request URL. 298 | @param parameters The parameters to be encoded according to the client request serializer. 299 | @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. 300 | @param failure A block object to be executed when the request operation 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 request operation and the error describing the network or parsing error that occurred. 301 | 302 | @see -HTTPRequestOperationWithRequest:success:failure: 303 | */ 304 | - (nullable AFHTTPRequestOperation *)PATCH:(NSString *)URLString 305 | parameters:(nullable id)parameters 306 | success:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success 307 | failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; 308 | 309 | /** 310 | Creates and runs an `AFHTTPRequestOperation` with a `DELETE` request. 311 | 312 | @param URLString The URL string used to create the request URL. 313 | @param parameters The parameters to be encoded according to the client request serializer. 314 | @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. 315 | @param failure A block object to be executed when the request operation 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 request operation and the error describing the network or parsing error that occurred. 316 | 317 | @see -HTTPRequestOperationWithRequest:success:failure: 318 | */ 319 | - (nullable AFHTTPRequestOperation *)DELETE:(NSString *)URLString 320 | parameters:(nullable id)parameters 321 | success:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success 322 | failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; 323 | 324 | @end 325 | 326 | NS_ASSUME_NONNULL_END 327 | -------------------------------------------------------------------------------- /CooperAFNetworkSingleton/Library/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 | --------------------------------------------------------------------------------