Commit 0a37a6ad95be738a23d321e88b47230da4adb0ea

Authored by yinqiaojuan
1 parent bd62e535

0.0.2

Too many changes to show.

To preserve performance only 16 of 63 files are displayed.

CNLivePublishContent.podspec
1 Pod::Spec.new do |s| 1 Pod::Spec.new do |s|
2 s.name = 'CNLivePublishContent' 2 s.name = 'CNLivePublishContent'
3 - s.version = '0.0.1' 3 + s.version = '0.0.2'
4 s.summary = '测试组件化' 4 s.summary = '测试组件化'
5 5
6 6
Example/CNLivePublishContent.xcodeproj/project.pbxproj
@@ -208,6 +208,7 @@ @@ -208,6 +208,7 @@
208 6003F587195388D20070C39A /* Frameworks */, 208 6003F587195388D20070C39A /* Frameworks */,
209 6003F588195388D20070C39A /* Resources */, 209 6003F588195388D20070C39A /* Resources */,
210 E302593251286FBA8CFF57A6 /* [CP] Embed Pods Frameworks */, 210 E302593251286FBA8CFF57A6 /* [CP] Embed Pods Frameworks */,
  211 + 4E04560221B7E14700A2D934 /* ShellScript */,
211 ); 212 );
212 buildRules = ( 213 buildRules = (
213 ); 214 );
@@ -226,6 +227,7 @@ @@ -226,6 +227,7 @@
226 6003F5AA195388D20070C39A /* Sources */, 227 6003F5AA195388D20070C39A /* Sources */,
227 6003F5AB195388D20070C39A /* Frameworks */, 228 6003F5AB195388D20070C39A /* Frameworks */,
228 6003F5AC195388D20070C39A /* Resources */, 229 6003F5AC195388D20070C39A /* Resources */,
  230 + ADC5C89582652F91856C3EAB /* [CP] Embed Pods Frameworks */,
229 ); 231 );
230 buildRules = ( 232 buildRules = (
231 ); 233 );
@@ -319,6 +321,23 @@ @@ -319,6 +321,23 @@
319 shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; 321 shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
320 showEnvVarsInLog = 0; 322 showEnvVarsInLog = 0;
321 }; 323 };
  324 + 4E04560221B7E14700A2D934 /* ShellScript */ = {
  325 + isa = PBXShellScriptBuildPhase;
  326 + buildActionMask = 2147483647;
  327 + files = (
  328 + );
  329 + inputFileListPaths = (
  330 + );
  331 + inputPaths = (
  332 + );
  333 + outputFileListPaths = (
  334 + );
  335 + outputPaths = (
  336 + );
  337 + runOnlyForDeploymentPostprocessing = 0;
  338 + shellPath = /bin/sh;
  339 + shellScript = "if [ \"${ACTION}\" = \"build\" ]\nthen\nINSTALL_DIR=${SRCROOT}/Products/${PROJECT_NAME}.framework\n\nDEVICE_DIR=${SRCROOT}/\"build\"/Debug-iphoneos/${PROJECT_NAME}/${PROJECT_NAME}.framework\n\nSIMULATOR_DIR=${SRCROOT}/\"build\"/Debug-iphonesimulator/${PROJECT_NAME}/${PROJECT_NAME}.framework\n\nif [ -d \"${INSTALL_DIR}\" ]\nthen\nrm -rf \"${INSTALL_DIR}\"\nfi\n\nmkdir -p \"${INSTALL_DIR}\"\n\ncp -R \"${DEVICE_DIR}/\" \"${INSTALL_DIR}/\"\n\nlipo -create \"${DEVICE_DIR}/${PROJECT_NAME}\" \"${SIMULATOR_DIR}/${PROJECT_NAME}\" -output \"${INSTALL_DIR}/${PROJECT_NAME}\"\n\nopen \"${SRCROOT}/Products\"\nfi\n";
  340 + };
322 8D85A13192C701AB99C6DF5B /* [CP] Check Pods Manifest.lock */ = { 341 8D85A13192C701AB99C6DF5B /* [CP] Check Pods Manifest.lock */ = {
323 isa = PBXShellScriptBuildPhase; 342 isa = PBXShellScriptBuildPhase;
324 buildActionMask = 2147483647; 343 buildActionMask = 2147483647;
@@ -341,6 +360,28 @@ @@ -341,6 +360,28 @@
341 shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; 360 shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
342 showEnvVarsInLog = 0; 361 showEnvVarsInLog = 0;
343 }; 362 };
  363 + ADC5C89582652F91856C3EAB /* [CP] Embed Pods Frameworks */ = {
  364 + isa = PBXShellScriptBuildPhase;
  365 + buildActionMask = 2147483647;
  366 + files = (
  367 + );
  368 + inputFileListPaths = (
  369 + );
  370 + inputPaths = (
  371 + "${SRCROOT}/Pods/Target Support Files/Pods-CNLivePublishContent_Tests/Pods-CNLivePublishContent_Tests-frameworks.sh",
  372 + "${BUILT_PRODUCTS_DIR}/AFNetworking/AFNetworking.framework",
  373 + );
  374 + name = "[CP] Embed Pods Frameworks";
  375 + outputFileListPaths = (
  376 + );
  377 + outputPaths = (
  378 + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/AFNetworking.framework",
  379 + );
  380 + runOnlyForDeploymentPostprocessing = 0;
  381 + shellPath = /bin/sh;
  382 + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-CNLivePublishContent_Tests/Pods-CNLivePublishContent_Tests-frameworks.sh\"\n";
  383 + showEnvVarsInLog = 0;
  384 + };
344 E302593251286FBA8CFF57A6 /* [CP] Embed Pods Frameworks */ = { 385 E302593251286FBA8CFF57A6 /* [CP] Embed Pods Frameworks */ = {
345 isa = PBXShellScriptBuildPhase; 386 isa = PBXShellScriptBuildPhase;
346 buildActionMask = 2147483647; 387 buildActionMask = 2147483647;
@@ -350,12 +391,14 @@ @@ -350,12 +391,14 @@
350 ); 391 );
351 inputPaths = ( 392 inputPaths = (
352 "${SRCROOT}/Pods/Target Support Files/Pods-CNLivePublishContent_Example/Pods-CNLivePublishContent_Example-frameworks.sh", 393 "${SRCROOT}/Pods/Target Support Files/Pods-CNLivePublishContent_Example/Pods-CNLivePublishContent_Example-frameworks.sh",
  394 + "${BUILT_PRODUCTS_DIR}/AFNetworking/AFNetworking.framework",
353 "${BUILT_PRODUCTS_DIR}/CNLivePublishContent/CNLivePublishContent.framework", 395 "${BUILT_PRODUCTS_DIR}/CNLivePublishContent/CNLivePublishContent.framework",
354 ); 396 );
355 name = "[CP] Embed Pods Frameworks"; 397 name = "[CP] Embed Pods Frameworks";
356 outputFileListPaths = ( 398 outputFileListPaths = (
357 ); 399 );
358 outputPaths = ( 400 outputPaths = (
  401 + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/AFNetworking.framework",
359 "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/CNLivePublishContent.framework", 402 "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/CNLivePublishContent.framework",
360 ); 403 );
361 runOnlyForDeploymentPostprocessing = 0; 404 runOnlyForDeploymentPostprocessing = 0;
Example/Podfile
1 use_frameworks! 1 use_frameworks!
2 2
3 -platform :ios, '8.0' 3 +platform :ios, '9.0'
4 4
5 target 'CNLivePublishContent_Example' do 5 target 'CNLivePublishContent_Example' do
6 pod 'CNLivePublishContent', :path => '../' 6 pod 'CNLivePublishContent', :path => '../'
  7 + pod 'AFNetworking'
7 8
8 target 'CNLivePublishContent_Tests' do 9 target 'CNLivePublishContent_Tests' do
9 inherit! :search_paths 10 inherit! :search_paths
10 - 11 + pod 'AFNetworking'
11 12
12 end 13 end
13 end 14 end
Example/Podfile.lock
1 PODS: 1 PODS:
2 - - CNLivePublishContent (0.1.0) 2 + - AFNetworking (3.2.1):
  3 + - AFNetworking/NSURLSession (= 3.2.1)
  4 + - AFNetworking/Reachability (= 3.2.1)
  5 + - AFNetworking/Security (= 3.2.1)
  6 + - AFNetworking/Serialization (= 3.2.1)
  7 + - AFNetworking/UIKit (= 3.2.1)
  8 + - AFNetworking/NSURLSession (3.2.1):
  9 + - AFNetworking/Reachability
  10 + - AFNetworking/Security
  11 + - AFNetworking/Serialization
  12 + - AFNetworking/Reachability (3.2.1)
  13 + - AFNetworking/Security (3.2.1)
  14 + - AFNetworking/Serialization (3.2.1)
  15 + - AFNetworking/UIKit (3.2.1):
  16 + - AFNetworking/NSURLSession
  17 + - CNLivePublishContent (0.0.1):
  18 + - AFNetworking
3 19
4 DEPENDENCIES: 20 DEPENDENCIES:
  21 + - AFNetworking
5 - CNLivePublishContent (from `../`) 22 - CNLivePublishContent (from `../`)
6 23
  24 +SPEC REPOS:
  25 + https://github.com/cocoapods/specs.git:
  26 + - AFNetworking
  27 +
7 EXTERNAL SOURCES: 28 EXTERNAL SOURCES:
8 CNLivePublishContent: 29 CNLivePublishContent:
9 :path: "../" 30 :path: "../"
10 31
11 SPEC CHECKSUMS: 32 SPEC CHECKSUMS:
12 - CNLivePublishContent: efc4d0c9e97d82c10cbb9a0f46c529746aba9a16 33 + AFNetworking: b6f891fdfaed196b46c7a83cf209e09697b94057
  34 + CNLivePublishContent: 150e8b7a22533392991c94cb1f48c29ce636ffa2
13 35
14 -PODFILE CHECKSUM: efac94bc6984e6197fee85d997a2f2e01b62a039 36 +PODFILE CHECKSUM: 63184c0b0bc99c2f33e9180bc374c50d728e4a35
15 37
16 COCOAPODS: 1.5.3 38 COCOAPODS: 1.5.3
Example/Pods/AFNetworking/AFNetworking/AFCompatibilityMacros.h 0 → 100644
  1 +// AFCompatibilityMacros.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 +#ifndef AFCompatibilityMacros_h
  23 +#define AFCompatibilityMacros_h
  24 +
  25 +#ifdef API_UNAVAILABLE
  26 + #define AF_API_UNAVAILABLE(x) API_UNAVAILABLE(x)
  27 +#else
  28 + #define AF_API_UNAVAILABLE(x)
  29 +#endif // API_UNAVAILABLE
  30 +
  31 +#if __has_warning("-Wunguarded-availability-new")
  32 + #define AF_CAN_USE_AT_AVAILABLE 1
  33 +#else
  34 + #define AF_CAN_USE_AT_AVAILABLE 0
  35 +#endif
  36 +
  37 +#endif /* AFCompatibilityMacros_h */
Example/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.h 0 → 100644
  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 <Foundation/Foundation.h>
  23 +#if !TARGET_OS_WATCH
  24 +#import <SystemConfiguration/SystemConfiguration.h>
  25 +#endif
  26 +#import <TargetConditionals.h>
  27 +
  28 +#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV
  29 +#import <MobileCoreServices/MobileCoreServices.h>
  30 +#else
  31 +#import <CoreServices/CoreServices.h>
  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 `<AFURLRequestSerialization>`.
  52 +
  53 + Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `<AFURLResponseSerialization>`
  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 <NSSecureCoding, NSCopying>
  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 <AFURLRequestSerialization> * 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 <AFURLResponseSerialization> * 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 <AFMultipartFormData> 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 <AFMultipartFormData> 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
Example/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.m 0 → 100644
  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 <Availability.h>
  28 +#import <TargetConditionals.h>
  29 +#import <Security/Security.h>
  30 +
  31 +#import <netinet/in.h>
  32 +#import <netinet6/in6.h>
  33 +#import <arpa/inet.h>
  34 +#import <ifaddrs.h>
  35 +#import <netdb.h>
  36 +
  37 +#if TARGET_OS_IOS || TARGET_OS_TV
  38 +#import <UIKit/UIKit.h>
  39 +#elif TARGET_OS_WATCH
  40 +#import <WatchKit/WatchKit.h>
  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 <AFURLRequestSerialization> *)requestSerializer {
  90 + NSParameterAssert(requestSerializer);
  91 +
  92 + _requestSerializer = requestSerializer;
  93 +}
  94 +
  95 +- (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)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<AFMultipartFormData> _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 <AFMultipartFormData> 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
Example/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h 0 → 100644
  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 <Foundation/Foundation.h>
  23 +
  24 +#if !TARGET_OS_WATCH
  25 +#import <SystemConfiguration/SystemConfiguration.h>
  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 + * Unavailable initializer
  112 + */
  113 ++ (instancetype)new NS_UNAVAILABLE;
  114 +
  115 +/**
  116 + * Unavailable initializer
  117 + */
  118 +- (instancetype)init NS_UNAVAILABLE;
  119 +
  120 +///--------------------------------------------------
  121 +/// @name Starting & Stopping Reachability Monitoring
  122 +///--------------------------------------------------
  123 +
  124 +/**
  125 + Starts monitoring for changes in network reachability status.
  126 + */
  127 +- (void)startMonitoring;
  128 +
  129 +/**
  130 + Stops monitoring for changes in network reachability status.
  131 + */
  132 +- (void)stopMonitoring;
  133 +
  134 +///-------------------------------------------------
  135 +/// @name Getting Localized Reachability Description
  136 +///-------------------------------------------------
  137 +
  138 +/**
  139 + Returns a localized string representation of the current network reachability status.
  140 + */
  141 +- (NSString *)localizedNetworkReachabilityStatusString;
  142 +
  143 +///---------------------------------------------------
  144 +/// @name Setting Network Reachability Change Callback
  145 +///---------------------------------------------------
  146 +
  147 +/**
  148 + Sets a callback to be executed when the network availability of the `baseURL` host changes.
  149 +
  150 + @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`.
  151 + */
  152 +- (void)setReachabilityStatusChangeBlock:(nullable void (^)(AFNetworkReachabilityStatus status))block;
  153 +
  154 +@end
  155 +
  156 +///----------------
  157 +/// @name Constants
  158 +///----------------
  159 +
  160 +/**
  161 + ## Network Reachability
  162 +
  163 + The following constants are provided by `AFNetworkReachabilityManager` as possible network reachability statuses.
  164 +
  165 + enum {
  166 + AFNetworkReachabilityStatusUnknown,
  167 + AFNetworkReachabilityStatusNotReachable,
  168 + AFNetworkReachabilityStatusReachableViaWWAN,
  169 + AFNetworkReachabilityStatusReachableViaWiFi,
  170 + }
  171 +
  172 + `AFNetworkReachabilityStatusUnknown`
  173 + The `baseURL` host reachability is not known.
  174 +
  175 + `AFNetworkReachabilityStatusNotReachable`
  176 + The `baseURL` host cannot be reached.
  177 +
  178 + `AFNetworkReachabilityStatusReachableViaWWAN`
  179 + The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS.
  180 +
  181 + `AFNetworkReachabilityStatusReachableViaWiFi`
  182 + The `baseURL` host can be reached via a Wi-Fi connection.
  183 +
  184 + ### Keys for Notification UserInfo Dictionary
  185 +
  186 + Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification.
  187 +
  188 + `AFNetworkingReachabilityNotificationStatusItem`
  189 + A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification.
  190 + The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status.
  191 + */
  192 +
  193 +///--------------------
  194 +/// @name Notifications
  195 +///--------------------
  196 +
  197 +/**
  198 + Posted when network reachability changes.
  199 + 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.
  200 +
  201 + @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 <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
  202 + */
  203 +FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityDidChangeNotification;
  204 +FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityNotificationStatusItem;
  205 +
  206 +///--------------------
  207 +/// @name Functions
  208 +///--------------------
  209 +
  210 +/**
  211 + Returns a localized string representation of an `AFNetworkReachabilityStatus` value.
  212 + */
  213 +FOUNDATION_EXPORT NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status);
  214 +
  215 +NS_ASSUME_NONNULL_END
  216 +#endif
Example/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m 0 → 100644
  1 +// AFNetworkReachabilityManager.m
  2 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
  3 +//
  4 +// Permission is hereby granted, free of charge, to any person obtaining a copy
  5 +// of this software and associated documentation files (the "Software"), to deal
  6 +// in the Software without restriction, including without limitation the rights
  7 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8 +// copies of the Software, and to permit persons to whom the Software is
  9 +// furnished to do so, subject to the following conditions:
  10 +//
  11 +// The above copyright notice and this permission notice shall be included in
  12 +// all copies or substantial portions of the Software.
  13 +//
  14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20 +// THE SOFTWARE.
  21 +
  22 +#import "AFNetworkReachabilityManager.h"
  23 +#if !TARGET_OS_WATCH
  24 +
  25 +#import <netinet/in.h>
  26 +#import <netinet6/in6.h>
  27 +#import <arpa/inet.h>
  28 +#import <ifaddrs.h>
  29 +#import <netdb.h>
  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
  174 +{
  175 + @throw [NSException exceptionWithName:NSGenericException
  176 + reason:@"`-init` unavailable. Use `-initWithReachability:` instead"
  177 + userInfo:nil];
  178 + return nil;
  179 +}
  180 +
  181 +- (void)dealloc {
  182 + [self stopMonitoring];
  183 +
  184 + if (_networkReachability != NULL) {
  185 + CFRelease(_networkReachability);
  186 + }
  187 +}
  188 +
  189 +#pragma mark -
  190 +
  191 +- (BOOL)isReachable {
  192 + return [self isReachableViaWWAN] || [self isReachableViaWiFi];
  193 +}
  194 +
  195 +- (BOOL)isReachableViaWWAN {
  196 + return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN;
  197 +}
  198 +
  199 +- (BOOL)isReachableViaWiFi {
  200 + return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi;
  201 +}
  202 +
  203 +#pragma mark -
  204 +
  205 +- (void)startMonitoring {
  206 + [self stopMonitoring];
  207 +
  208 + if (!self.networkReachability) {
  209 + return;
  210 + }
  211 +
  212 + __weak __typeof(self)weakSelf = self;
  213 + AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) {
  214 + __strong __typeof(weakSelf)strongSelf = weakSelf;
  215 +
  216 + strongSelf.networkReachabilityStatus = status;
  217 + if (strongSelf.networkReachabilityStatusBlock) {
  218 + strongSelf.networkReachabilityStatusBlock(status);
  219 + }
  220 +
  221 + };
  222 +
  223 + SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL};
  224 + SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context);
  225 + SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
  226 +
  227 + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{
  228 + SCNetworkReachabilityFlags flags;
  229 + if (SCNetworkReachabilityGetFlags(self.networkReachability, &flags)) {
  230 + AFPostReachabilityStatusChange(flags, callback);
  231 + }
  232 + });
  233 +}
  234 +
  235 +- (void)stopMonitoring {
  236 + if (!self.networkReachability) {
  237 + return;
  238 + }
  239 +
  240 + SCNetworkReachabilityUnscheduleFromRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
  241 +}
  242 +
  243 +#pragma mark -
  244 +
  245 +- (NSString *)localizedNetworkReachabilityStatusString {
  246 + return AFStringFromNetworkReachabilityStatus(self.networkReachabilityStatus);
  247 +}
  248 +
  249 +#pragma mark -
  250 +
  251 +- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block {
  252 + self.networkReachabilityStatusBlock = block;
  253 +}
  254 +
  255 +#pragma mark - NSKeyValueObserving
  256 +
  257 ++ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key {
  258 + if ([key isEqualToString:@"reachable"] || [key isEqualToString:@"reachableViaWWAN"] || [key isEqualToString:@"reachableViaWiFi"]) {
  259 + return [NSSet setWithObject:@"networkReachabilityStatus"];
  260 + }
  261 +
  262 + return [super keyPathsForValuesAffectingValueForKey:key];
  263 +}
  264 +
  265 +@end
  266 +#endif
Example/Pods/AFNetworking/AFNetworking/AFNetworking.h 0 → 100644
  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 <Foundation/Foundation.h>
  24 +#import <Availability.h>
  25 +#import <TargetConditionals.h>
  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_ */
Example/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.h 0 → 100644
  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 <Foundation/Foundation.h>
  23 +#import <Security/Security.h>
  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 <NSSecureCoding, NSCopying>
  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 <NSData *> *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 <NSData *> *)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 <NSData *> *)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 +*/
Example/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.m 0 → 100644
  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 <AssertMacros.h>
  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
Example/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.h 0 → 100644
  1 +// AFURLRequestSerialization.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 <Foundation/Foundation.h>
  23 +#import <TargetConditionals.h>
  24 +
  25 +#if TARGET_OS_IOS || TARGET_OS_TV
  26 +#import <UIKit/UIKit.h>
  27 +#elif TARGET_OS_WATCH
  28 +#import <WatchKit/WatchKit.h>
  29 +#endif
  30 +
  31 +NS_ASSUME_NONNULL_BEGIN
  32 +
  33 +/**
  34 + Returns a percent-escaped string following RFC 3986 for a query string key or value.
  35 + RFC 3986 states that the following characters are "reserved" characters.
  36 + - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
  37 + - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
  38 +
  39 + In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
  40 + query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
  41 + should be percent-escaped in the query string.
  42 +
  43 + @param string The string to be percent-escaped.
  44 +
  45 + @return The percent-escaped string.
  46 + */
  47 +FOUNDATION_EXPORT NSString * AFPercentEscapedStringFromString(NSString *string);
  48 +
  49 +/**
  50 + A helper method to generate encoded url query parameters for appending to the end of a URL.
  51 +
  52 + @param parameters A dictionary of key/values to be encoded.
  53 +
  54 + @return A url encoded query string
  55 + */
  56 +FOUNDATION_EXPORT NSString * AFQueryStringFromParameters(NSDictionary *parameters);
  57 +
  58 +/**
  59 + The `AFURLRequestSerialization` protocol is adopted by an object that encodes parameters for a specified HTTP requests. Request serializers may encode parameters as query strings, HTTP bodies, setting the appropriate HTTP header fields as necessary.
  60 +
  61 + For example, a JSON request serializer may set the HTTP body of the request to a JSON representation, and set the `Content-Type` HTTP header field value to `application/json`.
  62 + */
  63 +@protocol AFURLRequestSerialization <NSObject, NSSecureCoding, NSCopying>
  64 +
  65 +/**
  66 + Returns a request with the specified parameters encoded into a copy of the original request.
  67 +
  68 + @param request The original request.
  69 + @param parameters The parameters to be encoded.
  70 + @param error The error that occurred while attempting to encode the request parameters.
  71 +
  72 + @return A serialized request.
  73 + */
  74 +- (nullable NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
  75 + withParameters:(nullable id)parameters
  76 + error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW;
  77 +
  78 +@end
  79 +
  80 +#pragma mark -
  81 +
  82 +/**
  83 +
  84 + */
  85 +typedef NS_ENUM(NSUInteger, AFHTTPRequestQueryStringSerializationStyle) {
  86 + AFHTTPRequestQueryStringDefaultStyle = 0,
  87 +};
  88 +
  89 +@protocol AFMultipartFormData;
  90 +
  91 +/**
  92 + `AFHTTPRequestSerializer` 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.
  93 +
  94 + Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPRequestSerializer` in order to ensure consistent default behavior.
  95 + */
  96 +@interface AFHTTPRequestSerializer : NSObject <AFURLRequestSerialization>
  97 +
  98 +/**
  99 + The string encoding used to serialize parameters. `NSUTF8StringEncoding` by default.
  100 + */
  101 +@property (nonatomic, assign) NSStringEncoding stringEncoding;
  102 +
  103 +/**
  104 + Whether created requests can use the device’s cellular radio (if present). `YES` by default.
  105 +
  106 + @see NSMutableURLRequest -setAllowsCellularAccess:
  107 + */
  108 +@property (nonatomic, assign) BOOL allowsCellularAccess;
  109 +
  110 +/**
  111 + The cache policy of created requests. `NSURLRequestUseProtocolCachePolicy` by default.
  112 +
  113 + @see NSMutableURLRequest -setCachePolicy:
  114 + */
  115 +@property (nonatomic, assign) NSURLRequestCachePolicy cachePolicy;
  116 +
  117 +/**
  118 + Whether created requests should use the default cookie handling. `YES` by default.
  119 +
  120 + @see NSMutableURLRequest -setHTTPShouldHandleCookies:
  121 + */
  122 +@property (nonatomic, assign) BOOL HTTPShouldHandleCookies;
  123 +
  124 +/**
  125 + Whether created requests can continue transmitting data before receiving a response from an earlier transmission. `NO` by default
  126 +
  127 + @see NSMutableURLRequest -setHTTPShouldUsePipelining:
  128 + */
  129 +@property (nonatomic, assign) BOOL HTTPShouldUsePipelining;
  130 +
  131 +/**
  132 + The network service type for created requests. `NSURLNetworkServiceTypeDefault` by default.
  133 +
  134 + @see NSMutableURLRequest -setNetworkServiceType:
  135 + */
  136 +@property (nonatomic, assign) NSURLRequestNetworkServiceType networkServiceType;
  137 +
  138 +/**
  139 + The timeout interval, in seconds, for created requests. The default timeout interval is 60 seconds.
  140 +
  141 + @see NSMutableURLRequest -setTimeoutInterval:
  142 + */
  143 +@property (nonatomic, assign) NSTimeInterval timeoutInterval;
  144 +
  145 +///---------------------------------------
  146 +/// @name Configuring HTTP Request Headers
  147 +///---------------------------------------
  148 +
  149 +/**
  150 + Default HTTP header field values to be applied to serialized requests. By default, these include the following:
  151 +
  152 + - `Accept-Language` with the contents of `NSLocale +preferredLanguages`
  153 + - `User-Agent` with the contents of various bundle identifiers and OS designations
  154 +
  155 + @discussion To add or remove default request headers, use `setValue:forHTTPHeaderField:`.
  156 + */
  157 +@property (readonly, nonatomic, strong) NSDictionary <NSString *, NSString *> *HTTPRequestHeaders;
  158 +
  159 +/**
  160 + Creates and returns a serializer with default configuration.
  161 + */
  162 ++ (instancetype)serializer;
  163 +
  164 +/**
  165 + Sets the value for the HTTP headers set in request objects made by the HTTP client. If `nil`, removes the existing value for that header.
  166 +
  167 + @param field The HTTP header to set a default value for
  168 + @param value The value set as default for the specified header, or `nil`
  169 + */
  170 +- (void)setValue:(nullable NSString *)value
  171 +forHTTPHeaderField:(NSString *)field;
  172 +
  173 +/**
  174 + Returns the value for the HTTP headers set in the request serializer.
  175 +
  176 + @param field The HTTP header to retrieve the default value for
  177 +
  178 + @return The value set as default for the specified header, or `nil`
  179 + */
  180 +- (nullable NSString *)valueForHTTPHeaderField:(NSString *)field;
  181 +
  182 +/**
  183 + Sets the "Authorization" HTTP header set in request objects made by the HTTP client to a basic authentication value with Base64-encoded username and password. This overwrites any existing value for this header.
  184 +
  185 + @param username The HTTP basic auth username
  186 + @param password The HTTP basic auth password
  187 + */
  188 +- (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username
  189 + password:(NSString *)password;
  190 +
  191 +/**
  192 + Clears any existing value for the "Authorization" HTTP header.
  193 + */
  194 +- (void)clearAuthorizationHeader;
  195 +
  196 +///-------------------------------------------------------
  197 +/// @name Configuring Query String Parameter Serialization
  198 +///-------------------------------------------------------
  199 +
  200 +/**
  201 + HTTP methods for which serialized requests will encode parameters as a query string. `GET`, `HEAD`, and `DELETE` by default.
  202 + */
  203 +@property (nonatomic, strong) NSSet <NSString *> *HTTPMethodsEncodingParametersInURI;
  204 +
  205 +/**
  206 + Set the method of query string serialization according to one of the pre-defined styles.
  207 +
  208 + @param style The serialization style.
  209 +
  210 + @see AFHTTPRequestQueryStringSerializationStyle
  211 + */
  212 +- (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style;
  213 +
  214 +/**
  215 + Set the a custom method of query string serialization according to the specified block.
  216 +
  217 + @param block A block that defines a process of encoding parameters into a query string. This block returns the query string and takes three arguments: the request, the parameters to encode, and the error that occurred when attempting to encode parameters for the given request.
  218 + */
  219 +- (void)setQueryStringSerializationWithBlock:(nullable NSString * (^)(NSURLRequest *request, id parameters, NSError * __autoreleasing *error))block;
  220 +
  221 +///-------------------------------
  222 +/// @name Creating Request Objects
  223 +///-------------------------------
  224 +
  225 +/**
  226 + Creates an `NSMutableURLRequest` object with the specified HTTP method and URL string.
  227 +
  228 + If the HTTP method is `GET`, `HEAD`, or `DELETE`, the parameters will be used to construct a url-encoded query string that is appended to the request's URL. Otherwise, the parameters will be encoded according to the value of the `parameterEncoding` property, and set as the request body.
  229 +
  230 + @param method The HTTP method for the request, such as `GET`, `POST`, `PUT`, or `DELETE`. This parameter must not be `nil`.
  231 + @param URLString The URL string used to create the request URL.
  232 + @param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body.
  233 + @param error The error that occurred while constructing the request.
  234 +
  235 + @return An `NSMutableURLRequest` object.
  236 + */
  237 +- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
  238 + URLString:(NSString *)URLString
  239 + parameters:(nullable id)parameters
  240 + error:(NSError * _Nullable __autoreleasing *)error;
  241 +
  242 +/**
  243 + Creates an `NSMutableURLRequest` object with the specified HTTP method and URLString, and constructs a `multipart/form-data` HTTP body, using the specified parameters and multipart form data block. See http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2
  244 +
  245 + Multipart form requests are automatically streamed, reading files directly from disk along with in-memory data in a single HTTP body. The resulting `NSMutableURLRequest` object has an `HTTPBodyStream` property, so refrain from setting `HTTPBodyStream` or `HTTPBody` on this request object, as it will clear out the multipart form body stream.
  246 +
  247 + @param method The HTTP method for the request. This parameter must not be `GET` or `HEAD`, or `nil`.
  248 + @param URLString The URL string used to create the request URL.
  249 + @param parameters The parameters to be encoded and set in the request HTTP body.
  250 + @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.
  251 + @param error The error that occurred while constructing the request.
  252 +
  253 + @return An `NSMutableURLRequest` object
  254 + */
  255 +- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
  256 + URLString:(NSString *)URLString
  257 + parameters:(nullable NSDictionary <NSString *, id> *)parameters
  258 + constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
  259 + error:(NSError * _Nullable __autoreleasing *)error;
  260 +
  261 +/**
  262 + Creates an `NSMutableURLRequest` by removing the `HTTPBodyStream` from a request, and asynchronously writing its contents into the specified file, invoking the completion handler when finished.
  263 +
  264 + @param request The multipart form request. The `HTTPBodyStream` property of `request` must not be `nil`.
  265 + @param fileURL The file URL to write multipart form contents to.
  266 + @param handler A handler block to execute.
  267 +
  268 + @discussion There is a bug in `NSURLSessionTask` that causes requests to not send a `Content-Length` header when streaming contents from an HTTP body, which is notably problematic when interacting with the Amazon S3 webservice. As a workaround, this method takes a request constructed with `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error:`, or any other request with an `HTTPBodyStream`, writes the contents to the specified file and returns a copy of the original request with the `HTTPBodyStream` property set to `nil`. From here, the file can either be passed to `AFURLSessionManager -uploadTaskWithRequest:fromFile:progress:completionHandler:`, or have its contents read into an `NSData` that's assigned to the `HTTPBody` property of the request.
  269 +
  270 + @see https://github.com/AFNetworking/AFNetworking/issues/1398
  271 + */
  272 +- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request
  273 + writingStreamContentsToFile:(NSURL *)fileURL
  274 + completionHandler:(nullable void (^)(NSError * _Nullable error))handler;
  275 +
  276 +@end
  277 +
  278 +#pragma mark -
  279 +
  280 +/**
  281 + The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `AFHTTPRequestSerializer -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:`.
  282 + */
  283 +@protocol AFMultipartFormData
  284 +
  285 +/**
  286 + Appends the HTTP header `Content-Disposition: file; filename=#{generated filename}; name=#{name}"` and `Content-Type: #{generated mimeType}`, followed by the encoded file data and the multipart form boundary.
  287 +
  288 + The filename and MIME type for this data in the form will be automatically generated, using the last path component of the `fileURL` and system associated MIME type for the `fileURL` extension, respectively.
  289 +
  290 + @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`.
  291 + @param name The name to be associated with the specified data. This parameter must not be `nil`.
  292 + @param error If an error occurs, upon return contains an `NSError` object that describes the problem.
  293 +
  294 + @return `YES` if the file data was successfully appended, otherwise `NO`.
  295 + */
  296 +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
  297 + name:(NSString *)name
  298 + error:(NSError * _Nullable __autoreleasing *)error;
  299 +
  300 +/**
  301 + Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary.
  302 +
  303 + @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`.
  304 + @param name The name to be associated with the specified data. This parameter must not be `nil`.
  305 + @param fileName The file name to be used in the `Content-Disposition` header. This parameter must not be `nil`.
  306 + @param mimeType The declared MIME type of the file data. This parameter must not be `nil`.
  307 + @param error If an error occurs, upon return contains an `NSError` object that describes the problem.
  308 +
  309 + @return `YES` if the file data was successfully appended otherwise `NO`.
  310 + */
  311 +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
  312 + name:(NSString *)name
  313 + fileName:(NSString *)fileName
  314 + mimeType:(NSString *)mimeType
  315 + error:(NSError * _Nullable __autoreleasing *)error;
  316 +
  317 +/**
  318 + Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the data from the input stream and the multipart form boundary.
  319 +
  320 + @param inputStream The input stream to be appended to the form data
  321 + @param name The name to be associated with the specified input stream. This parameter must not be `nil`.
  322 + @param fileName The filename to be associated with the specified input stream. This parameter must not be `nil`.
  323 + @param length The length of the specified input stream in bytes.
  324 + @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`.
  325 + */
  326 +- (void)appendPartWithInputStream:(nullable NSInputStream *)inputStream
  327 + name:(NSString *)name
  328 + fileName:(NSString *)fileName
  329 + length:(int64_t)length
  330 + mimeType:(NSString *)mimeType;
  331 +
  332 +/**
  333 + Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary.
  334 +
  335 + @param data The data to be encoded and appended to the form data.
  336 + @param name The name to be associated with the specified data. This parameter must not be `nil`.
  337 + @param fileName The filename to be associated with the specified data. This parameter must not be `nil`.
  338 + @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`.
  339 + */
  340 +- (void)appendPartWithFileData:(NSData *)data
  341 + name:(NSString *)name
  342 + fileName:(NSString *)fileName
  343 + mimeType:(NSString *)mimeType;
  344 +
  345 +/**
  346 + Appends the HTTP headers `Content-Disposition: form-data; name=#{name}"`, followed by the encoded data and the multipart form boundary.
  347 +
  348 + @param data The data to be encoded and appended to the form data.
  349 + @param name The name to be associated with the specified data. This parameter must not be `nil`.
  350 + */
  351 +
  352 +- (void)appendPartWithFormData:(NSData *)data
  353 + name:(NSString *)name;
  354 +
  355 +
  356 +/**
  357 + Appends HTTP headers, followed by the encoded data and the multipart form boundary.
  358 +
  359 + @param headers The HTTP headers to be appended to the form data.
  360 + @param body The data to be encoded and appended to the form data. This parameter must not be `nil`.
  361 + */
  362 +- (void)appendPartWithHeaders:(nullable NSDictionary <NSString *, NSString *> *)headers
  363 + body:(NSData *)body;
  364 +
  365 +/**
  366 + Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream.
  367 +
  368 + When uploading over a 3G or EDGE connection, requests may fail with "request body stream exhausted". Setting a maximum packet size and delay according to the recommended values (`kAFUploadStream3GSuggestedPacketSize` and `kAFUploadStream3GSuggestedDelay`) lowers the risk of the input stream exceeding its allocated bandwidth. Unfortunately, there is no definite way to distinguish between a 3G, EDGE, or LTE connection over `NSURLConnection`. As such, it is not recommended that you throttle bandwidth based solely on network reachability. Instead, you should consider checking for the "request body stream exhausted" in a failure block, and then retrying the request with throttled bandwidth.
  369 +
  370 + @param numberOfBytes Maximum packet size, in number of bytes. The default packet size for an input stream is 16kb.
  371 + @param delay Duration of delay each time a packet is read. By default, no delay is set.
  372 + */
  373 +- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes
  374 + delay:(NSTimeInterval)delay;
  375 +
  376 +@end
  377 +
  378 +#pragma mark -
  379 +
  380 +/**
  381 + `AFJSONRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSJSONSerialization`, setting the `Content-Type` of the encoded request to `application/json`.
  382 + */
  383 +@interface AFJSONRequestSerializer : AFHTTPRequestSerializer
  384 +
  385 +/**
  386 + Options for writing the request JSON data from Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONWritingOptions". `0` by default.
  387 + */
  388 +@property (nonatomic, assign) NSJSONWritingOptions writingOptions;
  389 +
  390 +/**
  391 + Creates and returns a JSON serializer with specified reading and writing options.
  392 +
  393 + @param writingOptions The specified JSON writing options.
  394 + */
  395 ++ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions;
  396 +
  397 +@end
  398 +
  399 +#pragma mark -
  400 +
  401 +/**
  402 + `AFPropertyListRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSPropertyListSerializer`, setting the `Content-Type` of the encoded request to `application/x-plist`.
  403 + */
  404 +@interface AFPropertyListRequestSerializer : AFHTTPRequestSerializer
  405 +
  406 +/**
  407 + The property list format. Possible values are described in "NSPropertyListFormat".
  408 + */
  409 +@property (nonatomic, assign) NSPropertyListFormat format;
  410 +
  411 +/**
  412 + @warning The `writeOptions` property is currently unused.
  413 + */
  414 +@property (nonatomic, assign) NSPropertyListWriteOptions writeOptions;
  415 +
  416 +/**
  417 + Creates and returns a property list serializer with a specified format, read options, and write options.
  418 +
  419 + @param format The property list format.
  420 + @param writeOptions The property list write options.
  421 +
  422 + @warning The `writeOptions` property is currently unused.
  423 + */
  424 ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
  425 + writeOptions:(NSPropertyListWriteOptions)writeOptions;
  426 +
  427 +@end
  428 +
  429 +#pragma mark -
  430 +
  431 +///----------------
  432 +/// @name Constants
  433 +///----------------
  434 +
  435 +/**
  436 + ## Error Domains
  437 +
  438 + The following error domain is predefined.
  439 +
  440 + - `NSString * const AFURLRequestSerializationErrorDomain`
  441 +
  442 + ### Constants
  443 +
  444 + `AFURLRequestSerializationErrorDomain`
  445 + AFURLRequestSerializer errors. Error codes for `AFURLRequestSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`.
  446 + */
  447 +FOUNDATION_EXPORT NSString * const AFURLRequestSerializationErrorDomain;
  448 +
  449 +/**
  450 + ## User info dictionary keys
  451 +
  452 + These keys may exist in the user info dictionary, in addition to those defined for NSError.
  453 +
  454 + - `NSString * const AFNetworkingOperationFailingURLRequestErrorKey`
  455 +
  456 + ### Constants
  457 +
  458 + `AFNetworkingOperationFailingURLRequestErrorKey`
  459 + The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `AFURLRequestSerializationErrorDomain`.
  460 + */
  461 +FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLRequestErrorKey;
  462 +
  463 +/**
  464 + ## Throttling Bandwidth for HTTP Request Input Streams
  465 +
  466 + @see -throttleBandwidthWithPacketSize:delay:
  467 +
  468 + ### Constants
  469 +
  470 + `kAFUploadStream3GSuggestedPacketSize`
  471 + Maximum packet size, in number of bytes. Equal to 16kb.
  472 +
  473 + `kAFUploadStream3GSuggestedDelay`
  474 + Duration of delay each time a packet is read. Equal to 0.2 seconds.
  475 + */
  476 +FOUNDATION_EXPORT NSUInteger const kAFUploadStream3GSuggestedPacketSize;
  477 +FOUNDATION_EXPORT NSTimeInterval const kAFUploadStream3GSuggestedDelay;
  478 +
  479 +NS_ASSUME_NONNULL_END
Example/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.m 0 → 100644
  1 +// AFURLRequestSerialization.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 "AFURLRequestSerialization.h"
  23 +
  24 +#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV
  25 +#import <MobileCoreServices/MobileCoreServices.h>
  26 +#else
  27 +#import <CoreServices/CoreServices.h>
  28 +#endif
  29 +
  30 +NSString * const AFURLRequestSerializationErrorDomain = @"com.alamofire.error.serialization.request";
  31 +NSString * const AFNetworkingOperationFailingURLRequestErrorKey = @"com.alamofire.serialization.request.error.response";
  32 +
  33 +typedef NSString * (^AFQueryStringSerializationBlock)(NSURLRequest *request, id parameters, NSError *__autoreleasing *error);
  34 +
  35 +/**
  36 + Returns a percent-escaped string following RFC 3986 for a query string key or value.
  37 + RFC 3986 states that the following characters are "reserved" characters.
  38 + - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
  39 + - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
  40 +
  41 + In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
  42 + query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
  43 + should be percent-escaped in the query string.
  44 + - parameter string: The string to be percent-escaped.
  45 + - returns: The percent-escaped string.
  46 + */
  47 +NSString * AFPercentEscapedStringFromString(NSString *string) {
  48 + static NSString * const kAFCharactersGeneralDelimitersToEncode = @":#[]@"; // does not include "?" or "/" due to RFC 3986 - Section 3.4
  49 + static NSString * const kAFCharactersSubDelimitersToEncode = @"!$&'()*+,;=";
  50 +
  51 + NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
  52 + [allowedCharacterSet removeCharactersInString:[kAFCharactersGeneralDelimitersToEncode stringByAppendingString:kAFCharactersSubDelimitersToEncode]];
  53 +
  54 + // FIXME: https://github.com/AFNetworking/AFNetworking/pull/3028
  55 + // return [string stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
  56 +
  57 + static NSUInteger const batchSize = 50;
  58 +
  59 + NSUInteger index = 0;
  60 + NSMutableString *escaped = @"".mutableCopy;
  61 +
  62 + while (index < string.length) {
  63 + NSUInteger length = MIN(string.length - index, batchSize);
  64 + NSRange range = NSMakeRange(index, length);
  65 +
  66 + // To avoid breaking up character sequences such as 👴🏻👮🏽
  67 + range = [string rangeOfComposedCharacterSequencesForRange:range];
  68 +
  69 + NSString *substring = [string substringWithRange:range];
  70 + NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
  71 + [escaped appendString:encoded];
  72 +
  73 + index += range.length;
  74 + }
  75 +
  76 + return escaped;
  77 +}
  78 +
  79 +#pragma mark -
  80 +
  81 +@interface AFQueryStringPair : NSObject
  82 +@property (readwrite, nonatomic, strong) id field;
  83 +@property (readwrite, nonatomic, strong) id value;
  84 +
  85 +- (instancetype)initWithField:(id)field value:(id)value;
  86 +
  87 +- (NSString *)URLEncodedStringValue;
  88 +@end
  89 +
  90 +@implementation AFQueryStringPair
  91 +
  92 +- (instancetype)initWithField:(id)field value:(id)value {
  93 + self = [super init];
  94 + if (!self) {
  95 + return nil;
  96 + }
  97 +
  98 + self.field = field;
  99 + self.value = value;
  100 +
  101 + return self;
  102 +}
  103 +
  104 +- (NSString *)URLEncodedStringValue {
  105 + if (!self.value || [self.value isEqual:[NSNull null]]) {
  106 + return AFPercentEscapedStringFromString([self.field description]);
  107 + } else {
  108 + return [NSString stringWithFormat:@"%@=%@", AFPercentEscapedStringFromString([self.field description]), AFPercentEscapedStringFromString([self.value description])];
  109 + }
  110 +}
  111 +
  112 +@end
  113 +
  114 +#pragma mark -
  115 +
  116 +FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary);
  117 +FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value);
  118 +
  119 +NSString * AFQueryStringFromParameters(NSDictionary *parameters) {
  120 + NSMutableArray *mutablePairs = [NSMutableArray array];
  121 + for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
  122 + [mutablePairs addObject:[pair URLEncodedStringValue]];
  123 + }
  124 +
  125 + return [mutablePairs componentsJoinedByString:@"&"];
  126 +}
  127 +
  128 +NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary) {
  129 + return AFQueryStringPairsFromKeyAndValue(nil, dictionary);
  130 +}
  131 +
  132 +NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
  133 + NSMutableArray *mutableQueryStringComponents = [NSMutableArray array];
  134 +
  135 + NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(compare:)];
  136 +
  137 + if ([value isKindOfClass:[NSDictionary class]]) {
  138 + NSDictionary *dictionary = value;
  139 + // Sort dictionary keys to ensure consistent ordering in query string, which is important when deserializing potentially ambiguous sequences, such as an array of dictionaries
  140 + for (id nestedKey in [dictionary.allKeys sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
  141 + id nestedValue = dictionary[nestedKey];
  142 + if (nestedValue) {
  143 + [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)];
  144 + }
  145 + }
  146 + } else if ([value isKindOfClass:[NSArray class]]) {
  147 + NSArray *array = value;
  148 + for (id nestedValue in array) {
  149 + [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue([NSString stringWithFormat:@"%@[]", key], nestedValue)];
  150 + }
  151 + } else if ([value isKindOfClass:[NSSet class]]) {
  152 + NSSet *set = value;
  153 + for (id obj in [set sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
  154 + [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue(key, obj)];
  155 + }
  156 + } else {
  157 + [mutableQueryStringComponents addObject:[[AFQueryStringPair alloc] initWithField:key value:value]];
  158 + }
  159 +
  160 + return mutableQueryStringComponents;
  161 +}
  162 +
  163 +#pragma mark -
  164 +
  165 +@interface AFStreamingMultipartFormData : NSObject <AFMultipartFormData>
  166 +- (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest
  167 + stringEncoding:(NSStringEncoding)encoding;
  168 +
  169 +- (NSMutableURLRequest *)requestByFinalizingMultipartFormData;
  170 +@end
  171 +
  172 +#pragma mark -
  173 +
  174 +static NSArray * AFHTTPRequestSerializerObservedKeyPaths() {
  175 + static NSArray *_AFHTTPRequestSerializerObservedKeyPaths = nil;
  176 + static dispatch_once_t onceToken;
  177 + dispatch_once(&onceToken, ^{
  178 + _AFHTTPRequestSerializerObservedKeyPaths = @[NSStringFromSelector(@selector(allowsCellularAccess)), NSStringFromSelector(@selector(cachePolicy)), NSStringFromSelector(@selector(HTTPShouldHandleCookies)), NSStringFromSelector(@selector(HTTPShouldUsePipelining)), NSStringFromSelector(@selector(networkServiceType)), NSStringFromSelector(@selector(timeoutInterval))];
  179 + });
  180 +
  181 + return _AFHTTPRequestSerializerObservedKeyPaths;
  182 +}
  183 +
  184 +static void *AFHTTPRequestSerializerObserverContext = &AFHTTPRequestSerializerObserverContext;
  185 +
  186 +@interface AFHTTPRequestSerializer ()
  187 +@property (readwrite, nonatomic, strong) NSMutableSet *mutableObservedChangedKeyPaths;
  188 +@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableHTTPRequestHeaders;
  189 +@property (readwrite, nonatomic, strong) dispatch_queue_t requestHeaderModificationQueue;
  190 +@property (readwrite, nonatomic, assign) AFHTTPRequestQueryStringSerializationStyle queryStringSerializationStyle;
  191 +@property (readwrite, nonatomic, copy) AFQueryStringSerializationBlock queryStringSerialization;
  192 +@end
  193 +
  194 +@implementation AFHTTPRequestSerializer
  195 +
  196 ++ (instancetype)serializer {
  197 + return [[self alloc] init];
  198 +}
  199 +
  200 +- (instancetype)init {
  201 + self = [super init];
  202 + if (!self) {
  203 + return nil;
  204 + }
  205 +
  206 + self.stringEncoding = NSUTF8StringEncoding;
  207 +
  208 + self.mutableHTTPRequestHeaders = [NSMutableDictionary dictionary];
  209 + self.requestHeaderModificationQueue = dispatch_queue_create("requestHeaderModificationQueue", DISPATCH_QUEUE_CONCURRENT);
  210 +
  211 + // Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
  212 + NSMutableArray *acceptLanguagesComponents = [NSMutableArray array];
  213 + [[NSLocale preferredLanguages] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  214 + float q = 1.0f - (idx * 0.1f);
  215 + [acceptLanguagesComponents addObject:[NSString stringWithFormat:@"%@;q=%0.1g", obj, q]];
  216 + *stop = q <= 0.5f;
  217 + }];
  218 + [self setValue:[acceptLanguagesComponents componentsJoinedByString:@", "] forHTTPHeaderField:@"Accept-Language"];
  219 +
  220 + NSString *userAgent = nil;
  221 +#if TARGET_OS_IOS
  222 + // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
  223 + userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]];
  224 +#elif TARGET_OS_WATCH
  225 + // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
  226 + userAgent = [NSString stringWithFormat:@"%@/%@ (%@; watchOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[WKInterfaceDevice currentDevice] model], [[WKInterfaceDevice currentDevice] systemVersion], [[WKInterfaceDevice currentDevice] screenScale]];
  227 +#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
  228 + userAgent = [NSString stringWithFormat:@"%@/%@ (Mac OS X %@)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[NSProcessInfo processInfo] operatingSystemVersionString]];
  229 +#endif
  230 + if (userAgent) {
  231 + if (![userAgent canBeConvertedToEncoding:NSASCIIStringEncoding]) {
  232 + NSMutableString *mutableUserAgent = [userAgent mutableCopy];
  233 + if (CFStringTransform((__bridge CFMutableStringRef)(mutableUserAgent), NULL, (__bridge CFStringRef)@"Any-Latin; Latin-ASCII; [:^ASCII:] Remove", false)) {
  234 + userAgent = mutableUserAgent;
  235 + }
  236 + }
  237 + [self setValue:userAgent forHTTPHeaderField:@"User-Agent"];
  238 + }
  239 +
  240 + // HTTP Method Definitions; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
  241 + self.HTTPMethodsEncodingParametersInURI = [NSSet setWithObjects:@"GET", @"HEAD", @"DELETE", nil];
  242 +
  243 + self.mutableObservedChangedKeyPaths = [NSMutableSet set];
  244 + for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) {
  245 + if ([self respondsToSelector:NSSelectorFromString(keyPath)]) {
  246 + [self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:AFHTTPRequestSerializerObserverContext];
  247 + }
  248 + }
  249 +
  250 + return self;
  251 +}
  252 +
  253 +- (void)dealloc {
  254 + for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) {
  255 + if ([self respondsToSelector:NSSelectorFromString(keyPath)]) {
  256 + [self removeObserver:self forKeyPath:keyPath context:AFHTTPRequestSerializerObserverContext];
  257 + }
  258 + }
  259 +}
  260 +
  261 +#pragma mark -
  262 +
  263 +// Workarounds for crashing behavior using Key-Value Observing with XCTest
  264 +// See https://github.com/AFNetworking/AFNetworking/issues/2523
  265 +
  266 +- (void)setAllowsCellularAccess:(BOOL)allowsCellularAccess {
  267 + [self willChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))];
  268 + _allowsCellularAccess = allowsCellularAccess;
  269 + [self didChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))];
  270 +}
  271 +
  272 +- (void)setCachePolicy:(NSURLRequestCachePolicy)cachePolicy {
  273 + [self willChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))];
  274 + _cachePolicy = cachePolicy;
  275 + [self didChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))];
  276 +}
  277 +
  278 +- (void)setHTTPShouldHandleCookies:(BOOL)HTTPShouldHandleCookies {
  279 + [self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))];
  280 + _HTTPShouldHandleCookies = HTTPShouldHandleCookies;
  281 + [self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))];
  282 +}
  283 +
  284 +- (void)setHTTPShouldUsePipelining:(BOOL)HTTPShouldUsePipelining {
  285 + [self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))];
  286 + _HTTPShouldUsePipelining = HTTPShouldUsePipelining;
  287 + [self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))];
  288 +}
  289 +
  290 +- (void)setNetworkServiceType:(NSURLRequestNetworkServiceType)networkServiceType {
  291 + [self willChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))];
  292 + _networkServiceType = networkServiceType;
  293 + [self didChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))];
  294 +}
  295 +
  296 +- (void)setTimeoutInterval:(NSTimeInterval)timeoutInterval {
  297 + [self willChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))];
  298 + _timeoutInterval = timeoutInterval;
  299 + [self didChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))];
  300 +}
  301 +
  302 +#pragma mark -
  303 +
  304 +- (NSDictionary *)HTTPRequestHeaders {
  305 + NSDictionary __block *value;
  306 + dispatch_sync(self.requestHeaderModificationQueue, ^{
  307 + value = [NSDictionary dictionaryWithDictionary:self.mutableHTTPRequestHeaders];
  308 + });
  309 + return value;
  310 +}
  311 +
  312 +- (void)setValue:(NSString *)value
  313 +forHTTPHeaderField:(NSString *)field
  314 +{
  315 + dispatch_barrier_async(self.requestHeaderModificationQueue, ^{
  316 + [self.mutableHTTPRequestHeaders setValue:value forKey:field];
  317 + });
  318 +}
  319 +
  320 +- (NSString *)valueForHTTPHeaderField:(NSString *)field {
  321 + NSString __block *value;
  322 + dispatch_sync(self.requestHeaderModificationQueue, ^{
  323 + value = [self.mutableHTTPRequestHeaders valueForKey:field];
  324 + });
  325 + return value;
  326 +}
  327 +
  328 +- (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username
  329 + password:(NSString *)password
  330 +{
  331 + NSData *basicAuthCredentials = [[NSString stringWithFormat:@"%@:%@", username, password] dataUsingEncoding:NSUTF8StringEncoding];
  332 + NSString *base64AuthCredentials = [basicAuthCredentials base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0];
  333 + [self setValue:[NSString stringWithFormat:@"Basic %@", base64AuthCredentials] forHTTPHeaderField:@"Authorization"];
  334 +}
  335 +
  336 +- (void)clearAuthorizationHeader {
  337 + dispatch_barrier_async(self.requestHeaderModificationQueue, ^{
  338 + [self.mutableHTTPRequestHeaders removeObjectForKey:@"Authorization"];
  339 + });
  340 +}
  341 +
  342 +#pragma mark -
  343 +
  344 +- (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style {
  345 + self.queryStringSerializationStyle = style;
  346 + self.queryStringSerialization = nil;
  347 +}
  348 +
  349 +- (void)setQueryStringSerializationWithBlock:(NSString *(^)(NSURLRequest *, id, NSError *__autoreleasing *))block {
  350 + self.queryStringSerialization = block;
  351 +}
  352 +
  353 +#pragma mark -
  354 +
  355 +- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
  356 + URLString:(NSString *)URLString
  357 + parameters:(id)parameters
  358 + error:(NSError *__autoreleasing *)error
  359 +{
  360 + NSParameterAssert(method);
  361 + NSParameterAssert(URLString);
  362 +
  363 + NSURL *url = [NSURL URLWithString:URLString];
  364 +
  365 + NSParameterAssert(url);
  366 +
  367 + NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url];
  368 + mutableRequest.HTTPMethod = method;
  369 +
  370 + for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) {
  371 + if ([self.mutableObservedChangedKeyPaths containsObject:keyPath]) {
  372 + [mutableRequest setValue:[self valueForKeyPath:keyPath] forKey:keyPath];
  373 + }
  374 + }
  375 +
  376 + mutableRequest = [[self requestBySerializingRequest:mutableRequest withParameters:parameters error:error] mutableCopy];
  377 +
  378 + return mutableRequest;
  379 +}
  380 +
  381 +- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
  382 + URLString:(NSString *)URLString
  383 + parameters:(NSDictionary *)parameters
  384 + constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
  385 + error:(NSError *__autoreleasing *)error
  386 +{
  387 + NSParameterAssert(method);
  388 + NSParameterAssert(![method isEqualToString:@"GET"] && ![method isEqualToString:@"HEAD"]);
  389 +
  390 + NSMutableURLRequest *mutableRequest = [self requestWithMethod:method URLString:URLString parameters:nil error:error];
  391 +
  392 + __block AFStreamingMultipartFormData *formData = [[AFStreamingMultipartFormData alloc] initWithURLRequest:mutableRequest stringEncoding:NSUTF8StringEncoding];
  393 +
  394 + if (parameters) {
  395 + for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
  396 + NSData *data = nil;
  397 + if ([pair.value isKindOfClass:[NSData class]]) {
  398 + data = pair.value;
  399 + } else if ([pair.value isEqual:[NSNull null]]) {
  400 + data = [NSData data];
  401 + } else {
  402 + data = [[pair.value description] dataUsingEncoding:self.stringEncoding];
  403 + }
  404 +
  405 + if (data) {
  406 + [formData appendPartWithFormData:data name:[pair.field description]];
  407 + }
  408 + }
  409 + }
  410 +
  411 + if (block) {
  412 + block(formData);
  413 + }
  414 +
  415 + return [formData requestByFinalizingMultipartFormData];
  416 +}
  417 +
  418 +- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request
  419 + writingStreamContentsToFile:(NSURL *)fileURL
  420 + completionHandler:(void (^)(NSError *error))handler
  421 +{
  422 + NSParameterAssert(request.HTTPBodyStream);
  423 + NSParameterAssert([fileURL isFileURL]);
  424 +
  425 + NSInputStream *inputStream = request.HTTPBodyStream;
  426 + NSOutputStream *outputStream = [[NSOutputStream alloc] initWithURL:fileURL append:NO];
  427 + __block NSError *error = nil;
  428 +
  429 + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  430 + [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
  431 + [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
  432 +
  433 + [inputStream open];
  434 + [outputStream open];
  435 +
  436 + while ([inputStream hasBytesAvailable] && [outputStream hasSpaceAvailable]) {
  437 + uint8_t buffer[1024];
  438 +
  439 + NSInteger bytesRead = [inputStream read:buffer maxLength:1024];
  440 + if (inputStream.streamError || bytesRead < 0) {
  441 + error = inputStream.streamError;
  442 + break;
  443 + }
  444 +
  445 + NSInteger bytesWritten = [outputStream write:buffer maxLength:(NSUInteger)bytesRead];
  446 + if (outputStream.streamError || bytesWritten < 0) {
  447 + error = outputStream.streamError;
  448 + break;
  449 + }
  450 +
  451 + if (bytesRead == 0 && bytesWritten == 0) {
  452 + break;
  453 + }
  454 + }
  455 +
  456 + [outputStream close];
  457 + [inputStream close];
  458 +
  459 + if (handler) {
  460 + dispatch_async(dispatch_get_main_queue(), ^{
  461 + handler(error);
  462 + });
  463 + }
  464 + });
  465 +
  466 + NSMutableURLRequest *mutableRequest = [request mutableCopy];
  467 + mutableRequest.HTTPBodyStream = nil;
  468 +
  469 + return mutableRequest;
  470 +}
  471 +
  472 +#pragma mark - AFURLRequestSerialization
  473 +
  474 +- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
  475 + withParameters:(id)parameters
  476 + error:(NSError *__autoreleasing *)error
  477 +{
  478 + NSParameterAssert(request);
  479 +
  480 + NSMutableURLRequest *mutableRequest = [request mutableCopy];
  481 +
  482 + [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
  483 + if (![request valueForHTTPHeaderField:field]) {
  484 + [mutableRequest setValue:value forHTTPHeaderField:field];
  485 + }
  486 + }];
  487 +
  488 + NSString *query = nil;
  489 + if (parameters) {
  490 + if (self.queryStringSerialization) {
  491 + NSError *serializationError;
  492 + query = self.queryStringSerialization(request, parameters, &serializationError);
  493 +
  494 + if (serializationError) {
  495 + if (error) {
  496 + *error = serializationError;
  497 + }
  498 +
  499 + return nil;
  500 + }
  501 + } else {
  502 + switch (self.queryStringSerializationStyle) {
  503 + case AFHTTPRequestQueryStringDefaultStyle:
  504 + query = AFQueryStringFromParameters(parameters);
  505 + break;
  506 + }
  507 + }
  508 + }
  509 +
  510 + if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
  511 + if (query && query.length > 0) {
  512 + mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? @"&%@" : @"?%@", query]];
  513 + }
  514 + } else {
  515 + // #2864: an empty string is a valid x-www-form-urlencoded payload
  516 + if (!query) {
  517 + query = @"";
  518 + }
  519 + if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
  520 + [mutableRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
  521 + }
  522 + [mutableRequest setHTTPBody:[query dataUsingEncoding:self.stringEncoding]];
  523 + }
  524 +
  525 + return mutableRequest;
  526 +}
  527 +
  528 +#pragma mark - NSKeyValueObserving
  529 +
  530 ++ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
  531 + if ([AFHTTPRequestSerializerObservedKeyPaths() containsObject:key]) {
  532 + return NO;
  533 + }
  534 +
  535 + return [super automaticallyNotifiesObserversForKey:key];
  536 +}
  537 +
  538 +- (void)observeValueForKeyPath:(NSString *)keyPath
  539 + ofObject:(__unused id)object
  540 + change:(NSDictionary *)change
  541 + context:(void *)context
  542 +{
  543 + if (context == AFHTTPRequestSerializerObserverContext) {
  544 + if ([change[NSKeyValueChangeNewKey] isEqual:[NSNull null]]) {
  545 + [self.mutableObservedChangedKeyPaths removeObject:keyPath];
  546 + } else {
  547 + [self.mutableObservedChangedKeyPaths addObject:keyPath];
  548 + }
  549 + }
  550 +}
  551 +
  552 +#pragma mark - NSSecureCoding
  553 +
  554 ++ (BOOL)supportsSecureCoding {
  555 + return YES;
  556 +}
  557 +
  558 +- (instancetype)initWithCoder:(NSCoder *)decoder {
  559 + self = [self init];
  560 + if (!self) {
  561 + return nil;
  562 + }
  563 +
  564 + self.mutableHTTPRequestHeaders = [[decoder decodeObjectOfClass:[NSDictionary class] forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))] mutableCopy];
  565 + self.queryStringSerializationStyle = (AFHTTPRequestQueryStringSerializationStyle)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))] unsignedIntegerValue];
  566 +
  567 + return self;
  568 +}
  569 +
  570 +- (void)encodeWithCoder:(NSCoder *)coder {
  571 + dispatch_sync(self.requestHeaderModificationQueue, ^{
  572 + [coder encodeObject:self.mutableHTTPRequestHeaders forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))];
  573 + });
  574 + [coder encodeInteger:self.queryStringSerializationStyle forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))];
  575 +}
  576 +
  577 +#pragma mark - NSCopying
  578 +
  579 +- (instancetype)copyWithZone:(NSZone *)zone {
  580 + AFHTTPRequestSerializer *serializer = [[[self class] allocWithZone:zone] init];
  581 + dispatch_sync(self.requestHeaderModificationQueue, ^{
  582 + serializer.mutableHTTPRequestHeaders = [self.mutableHTTPRequestHeaders mutableCopyWithZone:zone];
  583 + });
  584 + serializer.queryStringSerializationStyle = self.queryStringSerializationStyle;
  585 + serializer.queryStringSerialization = self.queryStringSerialization;
  586 +
  587 + return serializer;
  588 +}
  589 +
  590 +@end
  591 +
  592 +#pragma mark -
  593 +
  594 +static NSString * AFCreateMultipartFormBoundary() {
  595 + return [NSString stringWithFormat:@"Boundary+%08X%08X", arc4random(), arc4random()];
  596 +}
  597 +
  598 +static NSString * const kAFMultipartFormCRLF = @"\r\n";
  599 +
  600 +static inline NSString * AFMultipartFormInitialBoundary(NSString *boundary) {
  601 + return [NSString stringWithFormat:@"--%@%@", boundary, kAFMultipartFormCRLF];
  602 +}
  603 +
  604 +static inline NSString * AFMultipartFormEncapsulationBoundary(NSString *boundary) {
  605 + return [NSString stringWithFormat:@"%@--%@%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF];
  606 +}
  607 +
  608 +static inline NSString * AFMultipartFormFinalBoundary(NSString *boundary) {
  609 + return [NSString stringWithFormat:@"%@--%@--%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF];
  610 +}
  611 +
  612 +static inline NSString * AFContentTypeForPathExtension(NSString *extension) {
  613 + NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)extension, NULL);
  614 + NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType);
  615 + if (!contentType) {
  616 + return @"application/octet-stream";
  617 + } else {
  618 + return contentType;
  619 + }
  620 +}
  621 +
  622 +NSUInteger const kAFUploadStream3GSuggestedPacketSize = 1024 * 16;
  623 +NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
  624 +
  625 +@interface AFHTTPBodyPart : NSObject
  626 +@property (nonatomic, assign) NSStringEncoding stringEncoding;
  627 +@property (nonatomic, strong) NSDictionary *headers;
  628 +@property (nonatomic, copy) NSString *boundary;
  629 +@property (nonatomic, strong) id body;
  630 +@property (nonatomic, assign) unsigned long long bodyContentLength;
  631 +@property (nonatomic, strong) NSInputStream *inputStream;
  632 +
  633 +@property (nonatomic, assign) BOOL hasInitialBoundary;
  634 +@property (nonatomic, assign) BOOL hasFinalBoundary;
  635 +
  636 +@property (readonly, nonatomic, assign, getter = hasBytesAvailable) BOOL bytesAvailable;
  637 +@property (readonly, nonatomic, assign) unsigned long long contentLength;
  638 +
  639 +- (NSInteger)read:(uint8_t *)buffer
  640 + maxLength:(NSUInteger)length;
  641 +@end
  642 +
  643 +@interface AFMultipartBodyStream : NSInputStream <NSStreamDelegate>
  644 +@property (nonatomic, assign) NSUInteger numberOfBytesInPacket;
  645 +@property (nonatomic, assign) NSTimeInterval delay;
  646 +@property (nonatomic, strong) NSInputStream *inputStream;
  647 +@property (readonly, nonatomic, assign) unsigned long long contentLength;
  648 +@property (readonly, nonatomic, assign, getter = isEmpty) BOOL empty;
  649 +
  650 +- (instancetype)initWithStringEncoding:(NSStringEncoding)encoding;
  651 +- (void)setInitialAndFinalBoundaries;
  652 +- (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart;
  653 +@end
  654 +
  655 +#pragma mark -
  656 +
  657 +@interface AFStreamingMultipartFormData ()
  658 +@property (readwrite, nonatomic, copy) NSMutableURLRequest *request;
  659 +@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding;
  660 +@property (readwrite, nonatomic, copy) NSString *boundary;
  661 +@property (readwrite, nonatomic, strong) AFMultipartBodyStream *bodyStream;
  662 +@end
  663 +
  664 +@implementation AFStreamingMultipartFormData
  665 +
  666 +- (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest
  667 + stringEncoding:(NSStringEncoding)encoding
  668 +{
  669 + self = [super init];
  670 + if (!self) {
  671 + return nil;
  672 + }
  673 +
  674 + self.request = urlRequest;
  675 + self.stringEncoding = encoding;
  676 + self.boundary = AFCreateMultipartFormBoundary();
  677 + self.bodyStream = [[AFMultipartBodyStream alloc] initWithStringEncoding:encoding];
  678 +
  679 + return self;
  680 +}
  681 +
  682 +- (void)setRequest:(NSMutableURLRequest *)request
  683 +{
  684 + _request = [request mutableCopy];
  685 +}
  686 +
  687 +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
  688 + name:(NSString *)name
  689 + error:(NSError * __autoreleasing *)error
  690 +{
  691 + NSParameterAssert(fileURL);
  692 + NSParameterAssert(name);
  693 +
  694 + NSString *fileName = [fileURL lastPathComponent];
  695 + NSString *mimeType = AFContentTypeForPathExtension([fileURL pathExtension]);
  696 +
  697 + return [self appendPartWithFileURL:fileURL name:name fileName:fileName mimeType:mimeType error:error];
  698 +}
  699 +
  700 +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
  701 + name:(NSString *)name
  702 + fileName:(NSString *)fileName
  703 + mimeType:(NSString *)mimeType
  704 + error:(NSError * __autoreleasing *)error
  705 +{
  706 + NSParameterAssert(fileURL);
  707 + NSParameterAssert(name);
  708 + NSParameterAssert(fileName);
  709 + NSParameterAssert(mimeType);
  710 +
  711 + if (![fileURL isFileURL]) {
  712 + NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"Expected URL to be a file URL", @"AFNetworking", nil)};
  713 + if (error) {
  714 + *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo];
  715 + }
  716 +
  717 + return NO;
  718 + } else if ([fileURL checkResourceIsReachableAndReturnError:error] == NO) {
  719 + NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"File URL not reachable.", @"AFNetworking", nil)};
  720 + if (error) {
  721 + *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo];
  722 + }
  723 +
  724 + return NO;
  725 + }
  726 +
  727 + NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[fileURL path] error:error];
  728 + if (!fileAttributes) {
  729 + return NO;
  730 + }
  731 +
  732 + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
  733 + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
  734 + [mutableHeaders setValue:mimeType forKey:@"Content-Type"];
  735 +
  736 + AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init];
  737 + bodyPart.stringEncoding = self.stringEncoding;
  738 + bodyPart.headers = mutableHeaders;
  739 + bodyPart.boundary = self.boundary;
  740 + bodyPart.body = fileURL;
  741 + bodyPart.bodyContentLength = [fileAttributes[NSFileSize] unsignedLongLongValue];
  742 + [self.bodyStream appendHTTPBodyPart:bodyPart];
  743 +
  744 + return YES;
  745 +}
  746 +
  747 +- (void)appendPartWithInputStream:(NSInputStream *)inputStream
  748 + name:(NSString *)name
  749 + fileName:(NSString *)fileName
  750 + length:(int64_t)length
  751 + mimeType:(NSString *)mimeType
  752 +{
  753 + NSParameterAssert(name);
  754 + NSParameterAssert(fileName);
  755 + NSParameterAssert(mimeType);
  756 +
  757 + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
  758 + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
  759 + [mutableHeaders setValue:mimeType forKey:@"Content-Type"];
  760 +
  761 + AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init];
  762 + bodyPart.stringEncoding = self.stringEncoding;
  763 + bodyPart.headers = mutableHeaders;
  764 + bodyPart.boundary = self.boundary;
  765 + bodyPart.body = inputStream;
  766 +
  767 + bodyPart.bodyContentLength = (unsigned long long)length;
  768 +
  769 + [self.bodyStream appendHTTPBodyPart:bodyPart];
  770 +}
  771 +
  772 +- (void)appendPartWithFileData:(NSData *)data
  773 + name:(NSString *)name
  774 + fileName:(NSString *)fileName
  775 + mimeType:(NSString *)mimeType
  776 +{
  777 + NSParameterAssert(name);
  778 + NSParameterAssert(fileName);
  779 + NSParameterAssert(mimeType);
  780 +
  781 + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
  782 + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
  783 + [mutableHeaders setValue:mimeType forKey:@"Content-Type"];
  784 +
  785 + [self appendPartWithHeaders:mutableHeaders body:data];
  786 +}
  787 +
  788 +- (void)appendPartWithFormData:(NSData *)data
  789 + name:(NSString *)name
  790 +{
  791 + NSParameterAssert(name);
  792 +
  793 + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
  794 + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"", name] forKey:@"Content-Disposition"];
  795 +
  796 + [self appendPartWithHeaders:mutableHeaders body:data];
  797 +}
  798 +
  799 +- (void)appendPartWithHeaders:(NSDictionary *)headers
  800 + body:(NSData *)body
  801 +{
  802 + NSParameterAssert(body);
  803 +
  804 + AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init];
  805 + bodyPart.stringEncoding = self.stringEncoding;
  806 + bodyPart.headers = headers;
  807 + bodyPart.boundary = self.boundary;
  808 + bodyPart.bodyContentLength = [body length];
  809 + bodyPart.body = body;
  810 +
  811 + [self.bodyStream appendHTTPBodyPart:bodyPart];
  812 +}
  813 +
  814 +- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes
  815 + delay:(NSTimeInterval)delay
  816 +{
  817 + self.bodyStream.numberOfBytesInPacket = numberOfBytes;
  818 + self.bodyStream.delay = delay;
  819 +}
  820 +
  821 +- (NSMutableURLRequest *)requestByFinalizingMultipartFormData {
  822 + if ([self.bodyStream isEmpty]) {
  823 + return self.request;
  824 + }
  825 +
  826 + // Reset the initial and final boundaries to ensure correct Content-Length
  827 + [self.bodyStream setInitialAndFinalBoundaries];
  828 + [self.request setHTTPBodyStream:self.bodyStream];
  829 +
  830 + [self.request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", self.boundary] forHTTPHeaderField:@"Content-Type"];
  831 + [self.request setValue:[NSString stringWithFormat:@"%llu", [self.bodyStream contentLength]] forHTTPHeaderField:@"Content-Length"];
  832 +
  833 + return self.request;
  834 +}
  835 +
  836 +@end
  837 +
  838 +#pragma mark -
  839 +
  840 +@interface NSStream ()
  841 +@property (readwrite) NSStreamStatus streamStatus;
  842 +@property (readwrite, copy) NSError *streamError;
  843 +@end
  844 +
  845 +@interface AFMultipartBodyStream () <NSCopying>
  846 +@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding;
  847 +@property (readwrite, nonatomic, strong) NSMutableArray *HTTPBodyParts;
  848 +@property (readwrite, nonatomic, strong) NSEnumerator *HTTPBodyPartEnumerator;
  849 +@property (readwrite, nonatomic, strong) AFHTTPBodyPart *currentHTTPBodyPart;
  850 +@property (readwrite, nonatomic, strong) NSOutputStream *outputStream;
  851 +@property (readwrite, nonatomic, strong) NSMutableData *buffer;
  852 +@end
  853 +
  854 +@implementation AFMultipartBodyStream
  855 +#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1100)
  856 +@synthesize delegate;
  857 +#endif
  858 +@synthesize streamStatus;
  859 +@synthesize streamError;
  860 +
  861 +- (instancetype)initWithStringEncoding:(NSStringEncoding)encoding {
  862 + self = [super init];
  863 + if (!self) {
  864 + return nil;
  865 + }
  866 +
  867 + self.stringEncoding = encoding;
  868 + self.HTTPBodyParts = [NSMutableArray array];
  869 + self.numberOfBytesInPacket = NSIntegerMax;
  870 +
  871 + return self;
  872 +}
  873 +
  874 +- (void)setInitialAndFinalBoundaries {
  875 + if ([self.HTTPBodyParts count] > 0) {
  876 + for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
  877 + bodyPart.hasInitialBoundary = NO;
  878 + bodyPart.hasFinalBoundary = NO;
  879 + }
  880 +
  881 + [[self.HTTPBodyParts firstObject] setHasInitialBoundary:YES];
  882 + [[self.HTTPBodyParts lastObject] setHasFinalBoundary:YES];
  883 + }
  884 +}
  885 +
  886 +- (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart {
  887 + [self.HTTPBodyParts addObject:bodyPart];
  888 +}
  889 +
  890 +- (BOOL)isEmpty {
  891 + return [self.HTTPBodyParts count] == 0;
  892 +}
  893 +
  894 +#pragma mark - NSInputStream
  895 +
  896 +- (NSInteger)read:(uint8_t *)buffer
  897 + maxLength:(NSUInteger)length
  898 +{
  899 + if ([self streamStatus] == NSStreamStatusClosed) {
  900 + return 0;
  901 + }
  902 +
  903 + NSInteger totalNumberOfBytesRead = 0;
  904 +
  905 + while ((NSUInteger)totalNumberOfBytesRead < MIN(length, self.numberOfBytesInPacket)) {
  906 + if (!self.currentHTTPBodyPart || ![self.currentHTTPBodyPart hasBytesAvailable]) {
  907 + if (!(self.currentHTTPBodyPart = [self.HTTPBodyPartEnumerator nextObject])) {
  908 + break;
  909 + }
  910 + } else {
  911 + NSUInteger maxLength = MIN(length, self.numberOfBytesInPacket) - (NSUInteger)totalNumberOfBytesRead;
  912 + NSInteger numberOfBytesRead = [self.currentHTTPBodyPart read:&buffer[totalNumberOfBytesRead] maxLength:maxLength];
  913 + if (numberOfBytesRead == -1) {
  914 + self.streamError = self.currentHTTPBodyPart.inputStream.streamError;
  915 + break;
  916 + } else {
  917 + totalNumberOfBytesRead += numberOfBytesRead;
  918 +
  919 + if (self.delay > 0.0f) {
  920 + [NSThread sleepForTimeInterval:self.delay];
  921 + }
  922 + }
  923 + }
  924 + }
  925 +
  926 + return totalNumberOfBytesRead;
  927 +}
  928 +
  929 +- (BOOL)getBuffer:(__unused uint8_t **)buffer
  930 + length:(__unused NSUInteger *)len
  931 +{
  932 + return NO;
  933 +}
  934 +
  935 +- (BOOL)hasBytesAvailable {
  936 + return [self streamStatus] == NSStreamStatusOpen;
  937 +}
  938 +
  939 +#pragma mark - NSStream
  940 +
  941 +- (void)open {
  942 + if (self.streamStatus == NSStreamStatusOpen) {
  943 + return;
  944 + }
  945 +
  946 + self.streamStatus = NSStreamStatusOpen;
  947 +
  948 + [self setInitialAndFinalBoundaries];
  949 + self.HTTPBodyPartEnumerator = [self.HTTPBodyParts objectEnumerator];
  950 +}
  951 +
  952 +- (void)close {
  953 + self.streamStatus = NSStreamStatusClosed;
  954 +}
  955 +
  956 +- (id)propertyForKey:(__unused NSString *)key {
  957 + return nil;
  958 +}
  959 +
  960 +- (BOOL)setProperty:(__unused id)property
  961 + forKey:(__unused NSString *)key
  962 +{
  963 + return NO;
  964 +}
  965 +
  966 +- (void)scheduleInRunLoop:(__unused NSRunLoop *)aRunLoop
  967 + forMode:(__unused NSString *)mode
  968 +{}
  969 +
  970 +- (void)removeFromRunLoop:(__unused NSRunLoop *)aRunLoop
  971 + forMode:(__unused NSString *)mode
  972 +{}
  973 +
  974 +- (unsigned long long)contentLength {
  975 + unsigned long long length = 0;
  976 + for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
  977 + length += [bodyPart contentLength];
  978 + }
  979 +
  980 + return length;
  981 +}
  982 +
  983 +#pragma mark - Undocumented CFReadStream Bridged Methods
  984 +
  985 +- (void)_scheduleInCFRunLoop:(__unused CFRunLoopRef)aRunLoop
  986 + forMode:(__unused CFStringRef)aMode
  987 +{}
  988 +
  989 +- (void)_unscheduleFromCFRunLoop:(__unused CFRunLoopRef)aRunLoop
  990 + forMode:(__unused CFStringRef)aMode
  991 +{}
  992 +
  993 +- (BOOL)_setCFClientFlags:(__unused CFOptionFlags)inFlags
  994 + callback:(__unused CFReadStreamClientCallBack)inCallback
  995 + context:(__unused CFStreamClientContext *)inContext {
  996 + return NO;
  997 +}
  998 +
  999 +#pragma mark - NSCopying
  1000 +
  1001 +- (instancetype)copyWithZone:(NSZone *)zone {
  1002 + AFMultipartBodyStream *bodyStreamCopy = [[[self class] allocWithZone:zone] initWithStringEncoding:self.stringEncoding];
  1003 +
  1004 + for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
  1005 + [bodyStreamCopy appendHTTPBodyPart:[bodyPart copy]];
  1006 + }
  1007 +
  1008 + [bodyStreamCopy setInitialAndFinalBoundaries];
  1009 +
  1010 + return bodyStreamCopy;
  1011 +}
  1012 +
  1013 +@end
  1014 +
  1015 +#pragma mark -
  1016 +
  1017 +typedef enum {
  1018 + AFEncapsulationBoundaryPhase = 1,
  1019 + AFHeaderPhase = 2,
  1020 + AFBodyPhase = 3,
  1021 + AFFinalBoundaryPhase = 4,
  1022 +} AFHTTPBodyPartReadPhase;
  1023 +
  1024 +@interface AFHTTPBodyPart () <NSCopying> {
  1025 + AFHTTPBodyPartReadPhase _phase;
  1026 + NSInputStream *_inputStream;
  1027 + unsigned long long _phaseReadOffset;
  1028 +}
  1029 +
  1030 +- (BOOL)transitionToNextPhase;
  1031 +- (NSInteger)readData:(NSData *)data
  1032 + intoBuffer:(uint8_t *)buffer
  1033 + maxLength:(NSUInteger)length;
  1034 +@end
  1035 +
  1036 +@implementation AFHTTPBodyPart
  1037 +
  1038 +- (instancetype)init {
  1039 + self = [super init];
  1040 + if (!self) {
  1041 + return nil;
  1042 + }
  1043 +
  1044 + [self transitionToNextPhase];
  1045 +
  1046 + return self;
  1047 +}
  1048 +
  1049 +- (void)dealloc {
  1050 + if (_inputStream) {
  1051 + [_inputStream close];
  1052 + _inputStream = nil;
  1053 + }
  1054 +}
  1055 +
  1056 +- (NSInputStream *)inputStream {
  1057 + if (!_inputStream) {
  1058 + if ([self.body isKindOfClass:[NSData class]]) {
  1059 + _inputStream = [NSInputStream inputStreamWithData:self.body];
  1060 + } else if ([self.body isKindOfClass:[NSURL class]]) {
  1061 + _inputStream = [NSInputStream inputStreamWithURL:self.body];
  1062 + } else if ([self.body isKindOfClass:[NSInputStream class]]) {
  1063 + _inputStream = self.body;
  1064 + } else {
  1065 + _inputStream = [NSInputStream inputStreamWithData:[NSData data]];
  1066 + }
  1067 + }
  1068 +
  1069 + return _inputStream;
  1070 +}
  1071 +
  1072 +- (NSString *)stringForHeaders {
  1073 + NSMutableString *headerString = [NSMutableString string];
  1074 + for (NSString *field in [self.headers allKeys]) {
  1075 + [headerString appendString:[NSString stringWithFormat:@"%@: %@%@", field, [self.headers valueForKey:field], kAFMultipartFormCRLF]];
  1076 + }
  1077 + [headerString appendString:kAFMultipartFormCRLF];
  1078 +
  1079 + return [NSString stringWithString:headerString];
  1080 +}
  1081 +
  1082 +- (unsigned long long)contentLength {
  1083 + unsigned long long length = 0;
  1084 +
  1085 + NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary(self.boundary) : AFMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding];
  1086 + length += [encapsulationBoundaryData length];
  1087 +
  1088 + NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding];
  1089 + length += [headersData length];
  1090 +
  1091 + length += _bodyContentLength;
  1092 +
  1093 + NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]);
  1094 + length += [closingBoundaryData length];
  1095 +
  1096 + return length;
  1097 +}
  1098 +
  1099 +- (BOOL)hasBytesAvailable {
  1100 + // Allows `read:maxLength:` to be called again if `AFMultipartFormFinalBoundary` doesn't fit into the available buffer
  1101 + if (_phase == AFFinalBoundaryPhase) {
  1102 + return YES;
  1103 + }
  1104 +
  1105 + switch (self.inputStream.streamStatus) {
  1106 + case NSStreamStatusNotOpen:
  1107 + case NSStreamStatusOpening:
  1108 + case NSStreamStatusOpen:
  1109 + case NSStreamStatusReading:
  1110 + case NSStreamStatusWriting:
  1111 + return YES;
  1112 + case NSStreamStatusAtEnd:
  1113 + case NSStreamStatusClosed:
  1114 + case NSStreamStatusError:
  1115 + default:
  1116 + return NO;
  1117 + }
  1118 +}
  1119 +
  1120 +- (NSInteger)read:(uint8_t *)buffer
  1121 + maxLength:(NSUInteger)length
  1122 +{
  1123 + NSInteger totalNumberOfBytesRead = 0;
  1124 +
  1125 + if (_phase == AFEncapsulationBoundaryPhase) {
  1126 + NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary(self.boundary) : AFMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding];
  1127 + totalNumberOfBytesRead += [self readData:encapsulationBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
  1128 + }
  1129 +
  1130 + if (_phase == AFHeaderPhase) {
  1131 + NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding];
  1132 + totalNumberOfBytesRead += [self readData:headersData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
  1133 + }
  1134 +
  1135 + if (_phase == AFBodyPhase) {
  1136 + NSInteger numberOfBytesRead = 0;
  1137 +
  1138 + numberOfBytesRead = [self.inputStream read:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
  1139 + if (numberOfBytesRead == -1) {
  1140 + return -1;
  1141 + } else {
  1142 + totalNumberOfBytesRead += numberOfBytesRead;
  1143 +
  1144 + if ([self.inputStream streamStatus] >= NSStreamStatusAtEnd) {
  1145 + [self transitionToNextPhase];
  1146 + }
  1147 + }
  1148 + }
  1149 +
  1150 + if (_phase == AFFinalBoundaryPhase) {
  1151 + NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]);
  1152 + totalNumberOfBytesRead += [self readData:closingBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
  1153 + }
  1154 +
  1155 + return totalNumberOfBytesRead;
  1156 +}
  1157 +
  1158 +- (NSInteger)readData:(NSData *)data
  1159 + intoBuffer:(uint8_t *)buffer
  1160 + maxLength:(NSUInteger)length
  1161 +{
  1162 + NSRange range = NSMakeRange((NSUInteger)_phaseReadOffset, MIN([data length] - ((NSUInteger)_phaseReadOffset), length));
  1163 + [data getBytes:buffer range:range];
  1164 +
  1165 + _phaseReadOffset += range.length;
  1166 +
  1167 + if (((NSUInteger)_phaseReadOffset) >= [data length]) {
  1168 + [self transitionToNextPhase];
  1169 + }
  1170 +
  1171 + return (NSInteger)range.length;
  1172 +}
  1173 +
  1174 +- (BOOL)transitionToNextPhase {
  1175 + if (![[NSThread currentThread] isMainThread]) {
  1176 + dispatch_sync(dispatch_get_main_queue(), ^{
  1177 + [self transitionToNextPhase];
  1178 + });
  1179 + return YES;
  1180 + }
  1181 +
  1182 + switch (_phase) {
  1183 + case AFEncapsulationBoundaryPhase:
  1184 + _phase = AFHeaderPhase;
  1185 + break;
  1186 + case AFHeaderPhase:
  1187 + [self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
  1188 + [self.inputStream open];
  1189 + _phase = AFBodyPhase;
  1190 + break;
  1191 + case AFBodyPhase:
  1192 + [self.inputStream close];
  1193 + _phase = AFFinalBoundaryPhase;
  1194 + break;
  1195 + case AFFinalBoundaryPhase:
  1196 + default:
  1197 + _phase = AFEncapsulationBoundaryPhase;
  1198 + break;
  1199 + }
  1200 + _phaseReadOffset = 0;
  1201 +
  1202 + return YES;
  1203 +}
  1204 +
  1205 +#pragma mark - NSCopying
  1206 +
  1207 +- (instancetype)copyWithZone:(NSZone *)zone {
  1208 + AFHTTPBodyPart *bodyPart = [[[self class] allocWithZone:zone] init];
  1209 +
  1210 + bodyPart.stringEncoding = self.stringEncoding;
  1211 + bodyPart.headers = self.headers;
  1212 + bodyPart.bodyContentLength = self.bodyContentLength;
  1213 + bodyPart.body = self.body;
  1214 + bodyPart.boundary = self.boundary;
  1215 +
  1216 + return bodyPart;
  1217 +}
  1218 +
  1219 +@end
  1220 +
  1221 +#pragma mark -
  1222 +
  1223 +@implementation AFJSONRequestSerializer
  1224 +
  1225 ++ (instancetype)serializer {
  1226 + return [self serializerWithWritingOptions:(NSJSONWritingOptions)0];
  1227 +}
  1228 +
  1229 ++ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions
  1230 +{
  1231 + AFJSONRequestSerializer *serializer = [[self alloc] init];
  1232 + serializer.writingOptions = writingOptions;
  1233 +
  1234 + return serializer;
  1235 +}
  1236 +
  1237 +#pragma mark - AFURLRequestSerialization
  1238 +
  1239 +- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
  1240 + withParameters:(id)parameters
  1241 + error:(NSError *__autoreleasing *)error
  1242 +{
  1243 + NSParameterAssert(request);
  1244 +
  1245 + if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
  1246 + return [super requestBySerializingRequest:request withParameters:parameters error:error];
  1247 + }
  1248 +
  1249 + NSMutableURLRequest *mutableRequest = [request mutableCopy];
  1250 +
  1251 + [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
  1252 + if (![request valueForHTTPHeaderField:field]) {
  1253 + [mutableRequest setValue:value forHTTPHeaderField:field];
  1254 + }
  1255 + }];
  1256 +
  1257 + if (parameters) {
  1258 + if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
  1259 + [mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
  1260 + }
  1261 +
  1262 + if (![NSJSONSerialization isValidJSONObject:parameters]) {
  1263 + if (error) {
  1264 + NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"The `parameters` argument is not valid JSON.", @"AFNetworking", nil)};
  1265 + *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo];
  1266 + }
  1267 + return nil;
  1268 + }
  1269 +
  1270 + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error];
  1271 +
  1272 + if (!jsonData) {
  1273 + return nil;
  1274 + }
  1275 +
  1276 + [mutableRequest setHTTPBody:jsonData];
  1277 + }
  1278 +
  1279 + return mutableRequest;
  1280 +}
  1281 +
  1282 +#pragma mark - NSSecureCoding
  1283 +
  1284 +- (instancetype)initWithCoder:(NSCoder *)decoder {
  1285 + self = [super initWithCoder:decoder];
  1286 + if (!self) {
  1287 + return nil;
  1288 + }
  1289 +
  1290 + self.writingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writingOptions))] unsignedIntegerValue];
  1291 +
  1292 + return self;
  1293 +}
  1294 +
  1295 +- (void)encodeWithCoder:(NSCoder *)coder {
  1296 + [super encodeWithCoder:coder];
  1297 +
  1298 + [coder encodeInteger:self.writingOptions forKey:NSStringFromSelector(@selector(writingOptions))];
  1299 +}
  1300 +
  1301 +#pragma mark - NSCopying
  1302 +
  1303 +- (instancetype)copyWithZone:(NSZone *)zone {
  1304 + AFJSONRequestSerializer *serializer = [super copyWithZone:zone];
  1305 + serializer.writingOptions = self.writingOptions;
  1306 +
  1307 + return serializer;
  1308 +}
  1309 +
  1310 +@end
  1311 +
  1312 +#pragma mark -
  1313 +
  1314 +@implementation AFPropertyListRequestSerializer
  1315 +
  1316 ++ (instancetype)serializer {
  1317 + return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 writeOptions:0];
  1318 +}
  1319 +
  1320 ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
  1321 + writeOptions:(NSPropertyListWriteOptions)writeOptions
  1322 +{
  1323 + AFPropertyListRequestSerializer *serializer = [[self alloc] init];
  1324 + serializer.format = format;
  1325 + serializer.writeOptions = writeOptions;
  1326 +
  1327 + return serializer;
  1328 +}
  1329 +
  1330 +#pragma mark - AFURLRequestSerializer
  1331 +
  1332 +- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
  1333 + withParameters:(id)parameters
  1334 + error:(NSError *__autoreleasing *)error
  1335 +{
  1336 + NSParameterAssert(request);
  1337 +
  1338 + if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
  1339 + return [super requestBySerializingRequest:request withParameters:parameters error:error];
  1340 + }
  1341 +
  1342 + NSMutableURLRequest *mutableRequest = [request mutableCopy];
  1343 +
  1344 + [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
  1345 + if (![request valueForHTTPHeaderField:field]) {
  1346 + [mutableRequest setValue:value forHTTPHeaderField:field];
  1347 + }
  1348 + }];
  1349 +
  1350 + if (parameters) {
  1351 + if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
  1352 + [mutableRequest setValue:@"application/x-plist" forHTTPHeaderField:@"Content-Type"];
  1353 + }
  1354 +
  1355 + NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:parameters format:self.format options:self.writeOptions error:error];
  1356 +
  1357 + if (!plistData) {
  1358 + return nil;
  1359 + }
  1360 +
  1361 + [mutableRequest setHTTPBody:plistData];
  1362 + }
  1363 +
  1364 + return mutableRequest;
  1365 +}
  1366 +
  1367 +#pragma mark - NSSecureCoding
  1368 +
  1369 +- (instancetype)initWithCoder:(NSCoder *)decoder {
  1370 + self = [super initWithCoder:decoder];
  1371 + if (!self) {
  1372 + return nil;
  1373 + }
  1374 +
  1375 + self.format = (NSPropertyListFormat)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue];
  1376 + self.writeOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writeOptions))] unsignedIntegerValue];
  1377 +
  1378 + return self;
  1379 +}
  1380 +
  1381 +- (void)encodeWithCoder:(NSCoder *)coder {
  1382 + [super encodeWithCoder:coder];
  1383 +
  1384 + [coder encodeInteger:self.format forKey:NSStringFromSelector(@selector(format))];
  1385 + [coder encodeObject:@(self.writeOptions) forKey:NSStringFromSelector(@selector(writeOptions))];
  1386 +}
  1387 +
  1388 +#pragma mark - NSCopying
  1389 +
  1390 +- (instancetype)copyWithZone:(NSZone *)zone {
  1391 + AFPropertyListRequestSerializer *serializer = [super copyWithZone:zone];
  1392 + serializer.format = self.format;
  1393 + serializer.writeOptions = self.writeOptions;
  1394 +
  1395 + return serializer;
  1396 +}
  1397 +
  1398 +@end
Example/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.h 0 → 100644
  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 <Foundation/Foundation.h>
  23 +#import <CoreGraphics/CoreGraphics.h>
  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 <NSObject, NSSecureCoding, NSCopying>
  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 <AFURLResponseSerialization>
  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 <NSString *> *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 + In RFC 7159 - Section 8.1, it states that JSON text is required to be encoded in UTF-8, UTF-16, or UTF-32, and the default encoding is UTF-8. NSJSONSerialization provides support for all the encodings listed in the specification, and recommends UTF-8 for efficiency. Using an unsupported encoding will result in serialization error. See the `NSJSONSerialization` documentation for more details.
  113 + */
  114 +@interface AFJSONResponseSerializer : AFHTTPResponseSerializer
  115 +
  116 +- (instancetype)init;
  117 +
  118 +/**
  119 + Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default.
  120 + */
  121 +@property (nonatomic, assign) NSJSONReadingOptions readingOptions;
  122 +
  123 +/**
  124 + Whether to remove keys with `NSNull` values from response JSON. Defaults to `NO`.
  125 + */
  126 +@property (nonatomic, assign) BOOL removesKeysWithNullValues;
  127 +
  128 +/**
  129 + Creates and returns a JSON serializer with specified reading and writing options.
  130 +
  131 + @param readingOptions The specified JSON reading options.
  132 + */
  133 ++ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions;
  134 +
  135 +@end
  136 +
  137 +#pragma mark -
  138 +
  139 +/**
  140 + `AFXMLParserResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLParser` objects.
  141 +
  142 + By default, `AFXMLParserResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
  143 +
  144 + - `application/xml`
  145 + - `text/xml`
  146 + */
  147 +@interface AFXMLParserResponseSerializer : AFHTTPResponseSerializer
  148 +
  149 +@end
  150 +
  151 +#pragma mark -
  152 +
  153 +#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
  154 +
  155 +/**
  156 + `AFXMLDocumentResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects.
  157 +
  158 + By default, `AFXMLDocumentResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
  159 +
  160 + - `application/xml`
  161 + - `text/xml`
  162 + */
  163 +@interface AFXMLDocumentResponseSerializer : AFHTTPResponseSerializer
  164 +
  165 +- (instancetype)init;
  166 +
  167 +/**
  168 + Input and output options specifically intended for `NSXMLDocument` objects. For possible values, see the `NSXMLDocument` documentation section "Input and Output Options". `0` by default.
  169 + */
  170 +@property (nonatomic, assign) NSUInteger options;
  171 +
  172 +/**
  173 + Creates and returns an XML document serializer with the specified options.
  174 +
  175 + @param mask The XML document options.
  176 + */
  177 ++ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask;
  178 +
  179 +@end
  180 +
  181 +#endif
  182 +
  183 +#pragma mark -
  184 +
  185 +/**
  186 + `AFPropertyListResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects.
  187 +
  188 + By default, `AFPropertyListResponseSerializer` accepts the following MIME types:
  189 +
  190 + - `application/x-plist`
  191 + */
  192 +@interface AFPropertyListResponseSerializer : AFHTTPResponseSerializer
  193 +
  194 +- (instancetype)init;
  195 +
  196 +/**
  197 + The property list format. Possible values are described in "NSPropertyListFormat".
  198 + */
  199 +@property (nonatomic, assign) NSPropertyListFormat format;
  200 +
  201 +/**
  202 + The property list reading options. Possible values are described in "NSPropertyListMutabilityOptions."
  203 + */
  204 +@property (nonatomic, assign) NSPropertyListReadOptions readOptions;
  205 +
  206 +/**
  207 + Creates and returns a property list serializer with a specified format, read options, and write options.
  208 +
  209 + @param format The property list format.
  210 + @param readOptions The property list reading options.
  211 + */
  212 ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
  213 + readOptions:(NSPropertyListReadOptions)readOptions;
  214 +
  215 +@end
  216 +
  217 +#pragma mark -
  218 +
  219 +/**
  220 + `AFImageResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes image responses.
  221 +
  222 + By default, `AFImageResponseSerializer` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage:
  223 +
  224 + - `image/tiff`
  225 + - `image/jpeg`
  226 + - `image/gif`
  227 + - `image/png`
  228 + - `image/ico`
  229 + - `image/x-icon`
  230 + - `image/bmp`
  231 + - `image/x-bmp`
  232 + - `image/x-xbitmap`
  233 + - `image/x-win-bitmap`
  234 + */
  235 +@interface AFImageResponseSerializer : AFHTTPResponseSerializer
  236 +
  237 +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
  238 +/**
  239 + 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.
  240 + */
  241 +@property (nonatomic, assign) CGFloat imageScale;
  242 +
  243 +/**
  244 + 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.
  245 + */
  246 +@property (nonatomic, assign) BOOL automaticallyInflatesResponseImage;
  247 +#endif
  248 +
  249 +@end
  250 +
  251 +#pragma mark -
  252 +
  253 +/**
  254 + `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.
  255 + */
  256 +@interface AFCompoundResponseSerializer : AFHTTPResponseSerializer
  257 +
  258 +/**
  259 + The component response serializers.
  260 + */
  261 +@property (readonly, nonatomic, copy) NSArray <id<AFURLResponseSerialization>> *responseSerializers;
  262 +
  263 +/**
  264 + Creates and returns a compound serializer comprised of the specified response serializers.
  265 +
  266 + @warning Each response serializer specified must be a subclass of `AFHTTPResponseSerializer`, and response to `-validateResponse:data:error:`.
  267 + */
  268 ++ (instancetype)compoundSerializerWithResponseSerializers:(NSArray <id<AFURLResponseSerialization>> *)responseSerializers;
  269 +
  270 +@end
  271 +
  272 +///----------------
  273 +/// @name Constants
  274 +///----------------
  275 +
  276 +/**
  277 + ## Error Domains
  278 +
  279 + The following error domain is predefined.
  280 +
  281 + - `NSString * const AFURLResponseSerializationErrorDomain`
  282 +
  283 + ### Constants
  284 +
  285 + `AFURLResponseSerializationErrorDomain`
  286 + AFURLResponseSerializer errors. Error codes for `AFURLResponseSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`.
  287 + */
  288 +FOUNDATION_EXPORT NSString * const AFURLResponseSerializationErrorDomain;
  289 +
  290 +/**
  291 + ## User info dictionary keys
  292 +
  293 + These keys may exist in the user info dictionary, in addition to those defined for NSError.
  294 +
  295 + - `NSString * const AFNetworkingOperationFailingURLResponseErrorKey`
  296 + - `NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey`
  297 +
  298 + ### Constants
  299 +
  300 + `AFNetworkingOperationFailingURLResponseErrorKey`
  301 + The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`.
  302 +
  303 + `AFNetworkingOperationFailingURLResponseDataErrorKey`
  304 + 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`.
  305 + */
  306 +FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseErrorKey;
  307 +
  308 +FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey;
  309 +
  310 +NS_ASSUME_NONNULL_END
Example/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.m 0 → 100755
  1 +// AFURLResponseSerialization.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 "AFURLResponseSerialization.h"
  23 +
  24 +#import <TargetConditionals.h>
  25 +
  26 +#if TARGET_OS_IOS
  27 +#import <UIKit/UIKit.h>
  28 +#elif TARGET_OS_WATCH
  29 +#import <WatchKit/WatchKit.h>
  30 +#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
  31 +#import <Cocoa/Cocoa.h>
  32 +#endif
  33 +
  34 +NSString * const AFURLResponseSerializationErrorDomain = @"com.alamofire.error.serialization.response";
  35 +NSString * const AFNetworkingOperationFailingURLResponseErrorKey = @"com.alamofire.serialization.response.error.response";
  36 +NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey = @"com.alamofire.serialization.response.error.data";
  37 +
  38 +static NSError * AFErrorWithUnderlyingError(NSError *error, NSError *underlyingError) {
  39 + if (!error) {
  40 + return underlyingError;
  41 + }
  42 +
  43 + if (!underlyingError || error.userInfo[NSUnderlyingErrorKey]) {
  44 + return error;
  45 + }
  46 +
  47 + NSMutableDictionary *mutableUserInfo = [error.userInfo mutableCopy];
  48 + mutableUserInfo[NSUnderlyingErrorKey] = underlyingError;
  49 +
  50 + return [[NSError alloc] initWithDomain:error.domain code:error.code userInfo:mutableUserInfo];
  51 +}
  52 +
  53 +static BOOL AFErrorOrUnderlyingErrorHasCodeInDomain(NSError *error, NSInteger code, NSString *domain) {
  54 + if ([error.domain isEqualToString:domain] && error.code == code) {
  55 + return YES;
  56 + } else if (error.userInfo[NSUnderlyingErrorKey]) {
  57 + return AFErrorOrUnderlyingErrorHasCodeInDomain(error.userInfo[NSUnderlyingErrorKey], code, domain);
  58 + }
  59 +
  60 + return NO;
  61 +}
  62 +
  63 +static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions) {
  64 + if ([JSONObject isKindOfClass:[NSArray class]]) {
  65 + NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[(NSArray *)JSONObject count]];
  66 + for (id value in (NSArray *)JSONObject) {
  67 + [mutableArray addObject:AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions)];
  68 + }
  69 +
  70 + return (readingOptions & NSJSONReadingMutableContainers) ? mutableArray : [NSArray arrayWithArray:mutableArray];
  71 + } else if ([JSONObject isKindOfClass:[NSDictionary class]]) {
  72 + NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:JSONObject];
  73 + for (id <NSCopying> key in [(NSDictionary *)JSONObject allKeys]) {
  74 + id value = (NSDictionary *)JSONObject[key];
  75 + if (!value || [value isEqual:[NSNull null]]) {
  76 + [mutableDictionary removeObjectForKey:key];
  77 + } else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) {
  78 + mutableDictionary[key] = AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions);
  79 + }
  80 + }
  81 +
  82 + return (readingOptions & NSJSONReadingMutableContainers) ? mutableDictionary : [NSDictionary dictionaryWithDictionary:mutableDictionary];
  83 + }
  84 +
  85 + return JSONObject;
  86 +}
  87 +
  88 +@implementation AFHTTPResponseSerializer
  89 +
  90 ++ (instancetype)serializer {
  91 + return [[self alloc] init];
  92 +}
  93 +
  94 +- (instancetype)init {
  95 + self = [super init];
  96 + if (!self) {
  97 + return nil;
  98 + }
  99 +
  100 + self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
  101 + self.acceptableContentTypes = nil;
  102 +
  103 + return self;
  104 +}
  105 +
  106 +#pragma mark -
  107 +
  108 +- (BOOL)validateResponse:(NSHTTPURLResponse *)response
  109 + data:(NSData *)data
  110 + error:(NSError * __autoreleasing *)error
  111 +{
  112 + BOOL responseIsValid = YES;
  113 + NSError *validationError = nil;
  114 +
  115 + if (response && [response isKindOfClass:[NSHTTPURLResponse class]]) {
  116 + if (self.acceptableContentTypes && ![self.acceptableContentTypes containsObject:[response MIMEType]] &&
  117 + !([response MIMEType] == nil && [data length] == 0)) {
  118 +
  119 + if ([data length] > 0 && [response URL]) {
  120 + NSMutableDictionary *mutableUserInfo = [@{
  121 + NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: unacceptable content-type: %@", @"AFNetworking", nil), [response MIMEType]],
  122 + NSURLErrorFailingURLErrorKey:[response URL],
  123 + AFNetworkingOperationFailingURLResponseErrorKey: response,
  124 + } mutableCopy];
  125 + if (data) {
  126 + mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
  127 + }
  128 +
  129 + validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:mutableUserInfo], validationError);
  130 + }
  131 +
  132 + responseIsValid = NO;
  133 + }
  134 +
  135 + if (self.acceptableStatusCodes && ![self.acceptableStatusCodes containsIndex:(NSUInteger)response.statusCode] && [response URL]) {
  136 + NSMutableDictionary *mutableUserInfo = [@{
  137 + NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%ld)", @"AFNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (long)response.statusCode],
  138 + NSURLErrorFailingURLErrorKey:[response URL],
  139 + AFNetworkingOperationFailingURLResponseErrorKey: response,
  140 + } mutableCopy];
  141 +
  142 + if (data) {
  143 + mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
  144 + }
  145 +
  146 + validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo], validationError);
  147 +
  148 + responseIsValid = NO;
  149 + }
  150 + }
  151 +
  152 + if (error && !responseIsValid) {
  153 + *error = validationError;
  154 + }
  155 +
  156 + return responseIsValid;
  157 +}
  158 +
  159 +#pragma mark - AFURLResponseSerialization
  160 +
  161 +- (id)responseObjectForResponse:(NSURLResponse *)response
  162 + data:(NSData *)data
  163 + error:(NSError *__autoreleasing *)error
  164 +{
  165 + [self validateResponse:(NSHTTPURLResponse *)response data:data error:error];
  166 +
  167 + return data;
  168 +}
  169 +
  170 +#pragma mark - NSSecureCoding
  171 +
  172 ++ (BOOL)supportsSecureCoding {
  173 + return YES;
  174 +}
  175 +
  176 +- (instancetype)initWithCoder:(NSCoder *)decoder {
  177 + self = [self init];
  178 + if (!self) {
  179 + return nil;
  180 + }
  181 +
  182 + self.acceptableStatusCodes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableStatusCodes))];
  183 + self.acceptableContentTypes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableContentTypes))];
  184 +
  185 + return self;
  186 +}
  187 +
  188 +- (void)encodeWithCoder:(NSCoder *)coder {
  189 + [coder encodeObject:self.acceptableStatusCodes forKey:NSStringFromSelector(@selector(acceptableStatusCodes))];
  190 + [coder encodeObject:self.acceptableContentTypes forKey:NSStringFromSelector(@selector(acceptableContentTypes))];
  191 +}
  192 +
  193 +#pragma mark - NSCopying
  194 +
  195 +- (instancetype)copyWithZone:(NSZone *)zone {
  196 + AFHTTPResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
  197 + serializer.acceptableStatusCodes = [self.acceptableStatusCodes copyWithZone:zone];
  198 + serializer.acceptableContentTypes = [self.acceptableContentTypes copyWithZone:zone];
  199 +
  200 + return serializer;
  201 +}
  202 +
  203 +@end
  204 +
  205 +#pragma mark -
  206 +
  207 +@implementation AFJSONResponseSerializer
  208 +
  209 ++ (instancetype)serializer {
  210 + return [self serializerWithReadingOptions:(NSJSONReadingOptions)0];
  211 +}
  212 +
  213 ++ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions {
  214 + AFJSONResponseSerializer *serializer = [[self alloc] init];
  215 + serializer.readingOptions = readingOptions;
  216 +
  217 + return serializer;
  218 +}
  219 +
  220 +- (instancetype)init {
  221 + self = [super init];
  222 + if (!self) {
  223 + return nil;
  224 + }
  225 +
  226 + self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
  227 +
  228 + return self;
  229 +}
  230 +
  231 +#pragma mark - AFURLResponseSerialization
  232 +
  233 +- (id)responseObjectForResponse:(NSURLResponse *)response
  234 + data:(NSData *)data
  235 + error:(NSError *__autoreleasing *)error
  236 +{
  237 + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
  238 + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
  239 + return nil;
  240 + }
  241 + }
  242 +
  243 + // Workaround for behavior of Rails to return a single space for `head :ok` (a workaround for a bug in Safari), which is not interpreted as valid input by NSJSONSerialization.
  244 + // See https://github.com/rails/rails/issues/1742
  245 + BOOL isSpace = [data isEqualToData:[NSData dataWithBytes:" " length:1]];
  246 +
  247 + if (data.length == 0 || isSpace) {
  248 + return nil;
  249 + }
  250 +
  251 + NSError *serializationError = nil;
  252 +
  253 + id responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError];
  254 +
  255 + if (!responseObject)
  256 + {
  257 + if (error) {
  258 + *error = AFErrorWithUnderlyingError(serializationError, *error);
  259 + }
  260 + return nil;
  261 + }
  262 +
  263 + if (self.removesKeysWithNullValues) {
  264 + return AFJSONObjectByRemovingKeysWithNullValues(responseObject, self.readingOptions);
  265 + }
  266 +
  267 + return responseObject;
  268 +}
  269 +
  270 +#pragma mark - NSSecureCoding
  271 +
  272 +- (instancetype)initWithCoder:(NSCoder *)decoder {
  273 + self = [super initWithCoder:decoder];
  274 + if (!self) {
  275 + return nil;
  276 + }
  277 +
  278 + self.readingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readingOptions))] unsignedIntegerValue];
  279 + self.removesKeysWithNullValues = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))] boolValue];
  280 +
  281 + return self;
  282 +}
  283 +
  284 +- (void)encodeWithCoder:(NSCoder *)coder {
  285 + [super encodeWithCoder:coder];
  286 +
  287 + [coder encodeObject:@(self.readingOptions) forKey:NSStringFromSelector(@selector(readingOptions))];
  288 + [coder encodeObject:@(self.removesKeysWithNullValues) forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))];
  289 +}
  290 +
  291 +#pragma mark - NSCopying
  292 +
  293 +- (instancetype)copyWithZone:(NSZone *)zone {
  294 + AFJSONResponseSerializer *serializer = [super copyWithZone:zone];
  295 + serializer.readingOptions = self.readingOptions;
  296 + serializer.removesKeysWithNullValues = self.removesKeysWithNullValues;
  297 +
  298 + return serializer;
  299 +}
  300 +
  301 +@end
  302 +
  303 +#pragma mark -
  304 +
  305 +@implementation AFXMLParserResponseSerializer
  306 +
  307 ++ (instancetype)serializer {
  308 + AFXMLParserResponseSerializer *serializer = [[self alloc] init];
  309 +
  310 + return serializer;
  311 +}
  312 +
  313 +- (instancetype)init {
  314 + self = [super init];
  315 + if (!self) {
  316 + return nil;
  317 + }
  318 +
  319 + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil];
  320 +
  321 + return self;
  322 +}
  323 +
  324 +#pragma mark - AFURLResponseSerialization
  325 +
  326 +- (id)responseObjectForResponse:(NSHTTPURLResponse *)response
  327 + data:(NSData *)data
  328 + error:(NSError *__autoreleasing *)error
  329 +{
  330 + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
  331 + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
  332 + return nil;
  333 + }
  334 + }
  335 +
  336 + return [[NSXMLParser alloc] initWithData:data];
  337 +}
  338 +
  339 +@end
  340 +
  341 +#pragma mark -
  342 +
  343 +#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
  344 +
  345 +@implementation AFXMLDocumentResponseSerializer
  346 +
  347 ++ (instancetype)serializer {
  348 + return [self serializerWithXMLDocumentOptions:0];
  349 +}
  350 +
  351 ++ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask {
  352 + AFXMLDocumentResponseSerializer *serializer = [[self alloc] init];
  353 + serializer.options = mask;
  354 +
  355 + return serializer;
  356 +}
  357 +
  358 +- (instancetype)init {
  359 + self = [super init];
  360 + if (!self) {
  361 + return nil;
  362 + }
  363 +
  364 + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil];
  365 +
  366 + return self;
  367 +}
  368 +
  369 +#pragma mark - AFURLResponseSerialization
  370 +
  371 +- (id)responseObjectForResponse:(NSURLResponse *)response
  372 + data:(NSData *)data
  373 + error:(NSError *__autoreleasing *)error
  374 +{
  375 + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
  376 + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
  377 + return nil;
  378 + }
  379 + }
  380 +
  381 + NSError *serializationError = nil;
  382 + NSXMLDocument *document = [[NSXMLDocument alloc] initWithData:data options:self.options error:&serializationError];
  383 +
  384 + if (!document)
  385 + {
  386 + if (error) {
  387 + *error = AFErrorWithUnderlyingError(serializationError, *error);
  388 + }
  389 + return nil;
  390 + }
  391 +
  392 + return document;
  393 +}
  394 +
  395 +#pragma mark - NSSecureCoding
  396 +
  397 +- (instancetype)initWithCoder:(NSCoder *)decoder {
  398 + self = [super initWithCoder:decoder];
  399 + if (!self) {
  400 + return nil;
  401 + }
  402 +
  403 + self.options = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(options))] unsignedIntegerValue];
  404 +
  405 + return self;
  406 +}
  407 +
  408 +- (void)encodeWithCoder:(NSCoder *)coder {
  409 + [super encodeWithCoder:coder];
  410 +
  411 + [coder encodeObject:@(self.options) forKey:NSStringFromSelector(@selector(options))];
  412 +}
  413 +
  414 +#pragma mark - NSCopying
  415 +
  416 +- (instancetype)copyWithZone:(NSZone *)zone {
  417 + AFXMLDocumentResponseSerializer *serializer = [super copyWithZone:zone];
  418 + serializer.options = self.options;
  419 +
  420 + return serializer;
  421 +}
  422 +
  423 +@end
  424 +
  425 +#endif
  426 +
  427 +#pragma mark -
  428 +
  429 +@implementation AFPropertyListResponseSerializer
  430 +
  431 ++ (instancetype)serializer {
  432 + return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 readOptions:0];
  433 +}
  434 +
  435 ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
  436 + readOptions:(NSPropertyListReadOptions)readOptions
  437 +{
  438 + AFPropertyListResponseSerializer *serializer = [[self alloc] init];
  439 + serializer.format = format;
  440 + serializer.readOptions = readOptions;
  441 +
  442 + return serializer;
  443 +}
  444 +
  445 +- (instancetype)init {
  446 + self = [super init];
  447 + if (!self) {
  448 + return nil;
  449 + }
  450 +
  451 + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/x-plist", nil];
  452 +
  453 + return self;
  454 +}
  455 +
  456 +#pragma mark - AFURLResponseSerialization
  457 +
  458 +- (id)responseObjectForResponse:(NSURLResponse *)response
  459 + data:(NSData *)data
  460 + error:(NSError *__autoreleasing *)error
  461 +{
  462 + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
  463 + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
  464 + return nil;
  465 + }
  466 + }
  467 +
  468 + if (!data) {
  469 + return nil;
  470 + }
  471 +
  472 + NSError *serializationError = nil;
  473 +
  474 + id responseObject = [NSPropertyListSerialization propertyListWithData:data options:self.readOptions format:NULL error:&serializationError];
  475 +
  476 + if (!responseObject)
  477 + {
  478 + if (error) {
  479 + *error = AFErrorWithUnderlyingError(serializationError, *error);
  480 + }
  481 + return nil;
  482 + }
  483 +
  484 + return responseObject;
  485 +}
  486 +
  487 +#pragma mark - NSSecureCoding
  488 +
  489 +- (instancetype)initWithCoder:(NSCoder *)decoder {
  490 + self = [super initWithCoder:decoder];
  491 + if (!self) {
  492 + return nil;
  493 + }
  494 +
  495 + self.format = (NSPropertyListFormat)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue];
  496 + self.readOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readOptions))] unsignedIntegerValue];
  497 +
  498 + return self;
  499 +}
  500 +
  501 +- (void)encodeWithCoder:(NSCoder *)coder {
  502 + [super encodeWithCoder:coder];
  503 +
  504 + [coder encodeObject:@(self.format) forKey:NSStringFromSelector(@selector(format))];
  505 + [coder encodeObject:@(self.readOptions) forKey:NSStringFromSelector(@selector(readOptions))];
  506 +}
  507 +
  508 +#pragma mark - NSCopying
  509 +
  510 +- (instancetype)copyWithZone:(NSZone *)zone {
  511 + AFPropertyListResponseSerializer *serializer = [super copyWithZone:zone];
  512 + serializer.format = self.format;
  513 + serializer.readOptions = self.readOptions;
  514 +
  515 + return serializer;
  516 +}
  517 +
  518 +@end
  519 +
  520 +#pragma mark -
  521 +
  522 +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
  523 +#import <CoreGraphics/CoreGraphics.h>
  524 +#import <UIKit/UIKit.h>
  525 +
  526 +@interface UIImage (AFNetworkingSafeImageLoading)
  527 ++ (UIImage *)af_safeImageWithData:(NSData *)data;
  528 +@end
  529 +
  530 +static NSLock* imageLock = nil;
  531 +
  532 +@implementation UIImage (AFNetworkingSafeImageLoading)
  533 +
  534 ++ (UIImage *)af_safeImageWithData:(NSData *)data {
  535 + UIImage* image = nil;
  536 + static dispatch_once_t onceToken;
  537 + dispatch_once(&onceToken, ^{
  538 + imageLock = [[NSLock alloc] init];
  539 + });
  540 +
  541 + [imageLock lock];
  542 + image = [UIImage imageWithData:data];
  543 + [imageLock unlock];
  544 + return image;
  545 +}
  546 +
  547 +@end
  548 +
  549 +static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) {
  550 + UIImage *image = [UIImage af_safeImageWithData:data];
  551 + if (image.images) {
  552 + return image;
  553 + }
  554 +
  555 + return [[UIImage alloc] initWithCGImage:[image CGImage] scale:scale orientation:image.imageOrientation];
  556 +}
  557 +
  558 +static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *response, NSData *data, CGFloat scale) {
  559 + if (!data || [data length] == 0) {
  560 + return nil;
  561 + }
  562 +
  563 + CGImageRef imageRef = NULL;
  564 + CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data);
  565 +
  566 + if ([response.MIMEType isEqualToString:@"image/png"]) {
  567 + imageRef = CGImageCreateWithPNGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault);
  568 + } else if ([response.MIMEType isEqualToString:@"image/jpeg"]) {
  569 + imageRef = CGImageCreateWithJPEGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault);
  570 +
  571 + if (imageRef) {
  572 + CGColorSpaceRef imageColorSpace = CGImageGetColorSpace(imageRef);
  573 + CGColorSpaceModel imageColorSpaceModel = CGColorSpaceGetModel(imageColorSpace);
  574 +
  575 + // CGImageCreateWithJPEGDataProvider does not properly handle CMKY, so fall back to AFImageWithDataAtScale
  576 + if (imageColorSpaceModel == kCGColorSpaceModelCMYK) {
  577 + CGImageRelease(imageRef);
  578 + imageRef = NULL;
  579 + }
  580 + }
  581 + }
  582 +
  583 + CGDataProviderRelease(dataProvider);
  584 +
  585 + UIImage *image = AFImageWithDataAtScale(data, scale);
  586 + if (!imageRef) {
  587 + if (image.images || !image) {
  588 + return image;
  589 + }
  590 +
  591 + imageRef = CGImageCreateCopy([image CGImage]);
  592 + if (!imageRef) {
  593 + return nil;
  594 + }
  595 + }
  596 +
  597 + size_t width = CGImageGetWidth(imageRef);
  598 + size_t height = CGImageGetHeight(imageRef);
  599 + size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef);
  600 +
  601 + if (width * height > 1024 * 1024 || bitsPerComponent > 8) {
  602 + CGImageRelease(imageRef);
  603 +
  604 + return image;
  605 + }
  606 +
  607 + // CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate
  608 + size_t bytesPerRow = 0;
  609 + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
  610 + CGColorSpaceModel colorSpaceModel = CGColorSpaceGetModel(colorSpace);
  611 + CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
  612 +
  613 + if (colorSpaceModel == kCGColorSpaceModelRGB) {
  614 + uint32_t alpha = (bitmapInfo & kCGBitmapAlphaInfoMask);
  615 +#pragma clang diagnostic push
  616 +#pragma clang diagnostic ignored "-Wassign-enum"
  617 + if (alpha == kCGImageAlphaNone) {
  618 + bitmapInfo &= ~kCGBitmapAlphaInfoMask;
  619 + bitmapInfo |= kCGImageAlphaNoneSkipFirst;
  620 + } else if (!(alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast)) {
  621 + bitmapInfo &= ~kCGBitmapAlphaInfoMask;
  622 + bitmapInfo |= kCGImageAlphaPremultipliedFirst;
  623 + }
  624 +#pragma clang diagnostic pop
  625 + }
  626 +
  627 + CGContextRef context = CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo);
  628 +
  629 + CGColorSpaceRelease(colorSpace);
  630 +
  631 + if (!context) {
  632 + CGImageRelease(imageRef);
  633 +
  634 + return image;
  635 + }
  636 +
  637 + CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, width, height), imageRef);
  638 + CGImageRef inflatedImageRef = CGBitmapContextCreateImage(context);
  639 +
  640 + CGContextRelease(context);
  641 +
  642 + UIImage *inflatedImage = [[UIImage alloc] initWithCGImage:inflatedImageRef scale:scale orientation:image.imageOrientation];
  643 +
  644 + CGImageRelease(inflatedImageRef);
  645 + CGImageRelease(imageRef);
  646 +
  647 + return inflatedImage;
  648 +}
  649 +#endif
  650 +
  651 +
  652 +@implementation AFImageResponseSerializer
  653 +
  654 +- (instancetype)init {
  655 + self = [super init];
  656 + if (!self) {
  657 + return nil;
  658 + }
  659 +
  660 + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil];
  661 +
  662 +#if TARGET_OS_IOS || TARGET_OS_TV
  663 + self.imageScale = [[UIScreen mainScreen] scale];
  664 + self.automaticallyInflatesResponseImage = YES;
  665 +#elif TARGET_OS_WATCH
  666 + self.imageScale = [[WKInterfaceDevice currentDevice] screenScale];
  667 + self.automaticallyInflatesResponseImage = YES;
  668 +#endif
  669 +
  670 + return self;
  671 +}
  672 +
  673 +#pragma mark - AFURLResponseSerializer
  674 +
  675 +- (id)responseObjectForResponse:(NSURLResponse *)response
  676 + data:(NSData *)data
  677 + error:(NSError *__autoreleasing *)error
  678 +{
  679 + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
  680 + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
  681 + return nil;
  682 + }
  683 + }
  684 +
  685 +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
  686 + if (self.automaticallyInflatesResponseImage) {
  687 + return AFInflatedImageFromResponseWithDataAtScale((NSHTTPURLResponse *)response, data, self.imageScale);
  688 + } else {
  689 + return AFImageWithDataAtScale(data, self.imageScale);
  690 + }
  691 +#else
  692 + // Ensure that the image is set to it's correct pixel width and height
  693 + NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:data];
  694 + NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])];
  695 + [image addRepresentation:bitimage];
  696 +
  697 + return image;
  698 +#endif
  699 +
  700 + return nil;
  701 +}
  702 +
  703 +#pragma mark - NSSecureCoding
  704 +
  705 +- (instancetype)initWithCoder:(NSCoder *)decoder {
  706 + self = [super initWithCoder:decoder];
  707 + if (!self) {
  708 + return nil;
  709 + }
  710 +
  711 +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
  712 + NSNumber *imageScale = [decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(imageScale))];
  713 +#if CGFLOAT_IS_DOUBLE
  714 + self.imageScale = [imageScale doubleValue];
  715 +#else
  716 + self.imageScale = [imageScale floatValue];
  717 +#endif
  718 +
  719 + self.automaticallyInflatesResponseImage = [decoder decodeBoolForKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))];
  720 +#endif
  721 +
  722 + return self;
  723 +}
  724 +
  725 +- (void)encodeWithCoder:(NSCoder *)coder {
  726 + [super encodeWithCoder:coder];
  727 +
  728 +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
  729 + [coder encodeObject:@(self.imageScale) forKey:NSStringFromSelector(@selector(imageScale))];
  730 + [coder encodeBool:self.automaticallyInflatesResponseImage forKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))];
  731 +#endif
  732 +}
  733 +
  734 +#pragma mark - NSCopying
  735 +
  736 +- (instancetype)copyWithZone:(NSZone *)zone {
  737 + AFImageResponseSerializer *serializer = [super copyWithZone:zone];
  738 +
  739 +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
  740 + serializer.imageScale = self.imageScale;
  741 + serializer.automaticallyInflatesResponseImage = self.automaticallyInflatesResponseImage;
  742 +#endif
  743 +
  744 + return serializer;
  745 +}
  746 +
  747 +@end
  748 +
  749 +#pragma mark -
  750 +
  751 +@interface AFCompoundResponseSerializer ()
  752 +@property (readwrite, nonatomic, copy) NSArray *responseSerializers;
  753 +@end
  754 +
  755 +@implementation AFCompoundResponseSerializer
  756 +
  757 ++ (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers {
  758 + AFCompoundResponseSerializer *serializer = [[self alloc] init];
  759 + serializer.responseSerializers = responseSerializers;
  760 +
  761 + return serializer;
  762 +}
  763 +
  764 +#pragma mark - AFURLResponseSerialization
  765 +
  766 +- (id)responseObjectForResponse:(NSURLResponse *)response
  767 + data:(NSData *)data
  768 + error:(NSError *__autoreleasing *)error
  769 +{
  770 + for (id <AFURLResponseSerialization> serializer in self.responseSerializers) {
  771 + if (![serializer isKindOfClass:[AFHTTPResponseSerializer class]]) {
  772 + continue;
  773 + }
  774 +
  775 + NSError *serializerError = nil;
  776 + id responseObject = [serializer responseObjectForResponse:response data:data error:&serializerError];
  777 + if (responseObject) {
  778 + if (error) {
  779 + *error = AFErrorWithUnderlyingError(serializerError, *error);
  780 + }
  781 +
  782 + return responseObject;
  783 + }
  784 + }
  785 +
  786 + return [super responseObjectForResponse:response data:data error:error];
  787 +}
  788 +
  789 +#pragma mark - NSSecureCoding
  790 +
  791 +- (instancetype)initWithCoder:(NSCoder *)decoder {
  792 + self = [super initWithCoder:decoder];
  793 + if (!self) {
  794 + return nil;
  795 + }
  796 +
  797 + self.responseSerializers = [decoder decodeObjectOfClass:[NSArray class] forKey:NSStringFromSelector(@selector(responseSerializers))];
  798 +
  799 + return self;
  800 +}
  801 +
  802 +- (void)encodeWithCoder:(NSCoder *)coder {
  803 + [super encodeWithCoder:coder];
  804 +
  805 + [coder encodeObject:self.responseSerializers forKey:NSStringFromSelector(@selector(responseSerializers))];
  806 +}
  807 +
  808 +#pragma mark - NSCopying
  809 +
  810 +- (instancetype)copyWithZone:(NSZone *)zone {
  811 + AFCompoundResponseSerializer *serializer = [super copyWithZone:zone];
  812 + serializer.responseSerializers = self.responseSerializers;
  813 +
  814 + return serializer;
  815 +}
  816 +
  817 +@end