liuxiulin пре 1 година
комит
3d8d2ee850
100 измењених фајлова са 21454 додато и 0 уклоњено
  1. BIN
      .DS_Store
  2. 30 0
      Podfile
  3. 70 0
      Podfile.lock
  4. BIN
      Pods/.DS_Store
  5. 49 0
      Pods/AFNetworking/AFNetworking/AFCompatibilityMacros.h
  6. 285 0
      Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.h
  7. 357 0
      Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.m
  8. 216 0
      Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h
  9. 269 0
      Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m
  10. 41 0
      Pods/AFNetworking/AFNetworking/AFNetworking.h
  11. 161 0
      Pods/AFNetworking/AFNetworking/AFSecurityPolicy.h
  12. 341 0
      Pods/AFNetworking/AFNetworking/AFSecurityPolicy.m
  13. 479 0
      Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.h
  14. 1399 0
      Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.m
  15. 313 0
      Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.h
  16. 836 0
      Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.m
  17. 516 0
      Pods/AFNetworking/AFNetworking/AFURLSessionManager.h
  18. 1274 0
      Pods/AFNetworking/AFNetworking/AFURLSessionManager.m
  19. 19 0
      Pods/AFNetworking/LICENSE
  20. 298 0
      Pods/AFNetworking/README.md
  21. 160 0
      Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h
  22. 205 0
      Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.m
  23. 171 0
      Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.h
  24. 421 0
      Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.m
  25. 103 0
      Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h
  26. 239 0
      Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m
  27. 48 0
      Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h
  28. 114 0
      Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m
  29. 175 0
      Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h
  30. 302 0
      Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m
  31. 109 0
      Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h
  32. 159 0
      Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m
  33. 43 0
      Pods/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h
  34. 64 0
      Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h
  35. 126 0
      Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m
  36. 53 0
      Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h
  37. 113 0
      Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m
  38. 80 0
      Pods/AFNetworking/UIKit+AFNetworking/WKWebView+AFNetworking.h
  39. 154 0
      Pods/AFNetworking/UIKit+AFNetworking/WKWebView+AFNetworking.m
  40. 58 0
      Pods/FDFullscreenPopGesture/FDFullscreenPopGesture/UINavigationController+FDFullscreenPopGesture.h
  41. 227 0
      Pods/FDFullscreenPopGesture/FDFullscreenPopGesture/UINavigationController+FDFullscreenPopGesture.m
  42. 22 0
      Pods/FDFullscreenPopGesture/LICENSE
  43. 62 0
      Pods/FDFullscreenPopGesture/README.md
  44. 28 0
      Pods/FMDB/LICENSE.txt
  45. 533 0
      Pods/FMDB/README.markdown
  46. 10 0
      Pods/FMDB/src/fmdb/FMDB.h
  47. 1436 0
      Pods/FMDB/src/fmdb/FMDatabase.h
  48. 1675 0
      Pods/FMDB/src/fmdb/FMDatabase.m
  49. 250 0
      Pods/FMDB/src/fmdb/FMDatabaseAdditions.h
  50. 245 0
      Pods/FMDB/src/fmdb/FMDatabaseAdditions.m
  51. 280 0
      Pods/FMDB/src/fmdb/FMDatabasePool.h
  52. 335 0
      Pods/FMDB/src/fmdb/FMDatabasePool.m
  53. 289 0
      Pods/FMDB/src/fmdb/FMDatabaseQueue.h
  54. 318 0
      Pods/FMDB/src/fmdb/FMDatabaseQueue.m
  55. 467 0
      Pods/FMDB/src/fmdb/FMResultSet.h
  56. 432 0
      Pods/FMDB/src/fmdb/FMResultSet.m
  57. 19 0
      Pods/MJExtension/LICENSE
  58. 27 0
      Pods/MJExtension/MJExtension/MJExtension.h
  59. 111 0
      Pods/MJExtension/MJExtension/MJExtensionConst.h
  60. 27 0
      Pods/MJExtension/MJExtension/MJExtensionConst.m
  61. 16 0
      Pods/MJExtension/MJExtension/MJFoundation.h
  62. 70 0
      Pods/MJExtension/MJExtension/MJFoundation.m
  63. 53 0
      Pods/MJExtension/MJExtension/MJProperty.h
  64. 211 0
      Pods/MJExtension/MJExtension/MJProperty.m
  65. 30 0
      Pods/MJExtension/MJExtension/MJPropertyKey.h
  66. 25 0
      Pods/MJExtension/MJExtension/MJPropertyKey.m
  67. 39 0
      Pods/MJExtension/MJExtension/MJPropertyType.h
  68. 71 0
      Pods/MJExtension/MJExtension/MJPropertyType.m
  69. 90 0
      Pods/MJExtension/MJExtension/NSObject+MJClass.h
  70. 174 0
      Pods/MJExtension/MJExtension/NSObject+MJClass.m
  71. 66 0
      Pods/MJExtension/MJExtension/NSObject+MJCoding.h
  72. 59 0
      Pods/MJExtension/MJExtension/NSObject+MJCoding.m
  73. 194 0
      Pods/MJExtension/MJExtension/NSObject+MJKeyValue.h
  74. 524 0
      Pods/MJExtension/MJExtension/NSObject+MJKeyValue.m
  75. 70 0
      Pods/MJExtension/MJExtension/NSObject+MJProperty.h
  76. 240 0
      Pods/MJExtension/MJExtension/NSObject+MJProperty.m
  77. 33 0
      Pods/MJExtension/MJExtension/NSString+MJExtension.h
  78. 80 0
      Pods/MJExtension/MJExtension/NSString+MJExtension.m
  79. 637 0
      Pods/MJExtension/README.md
  80. 19 0
      Pods/MJRefresh/LICENSE
  81. 34 0
      Pods/MJRefresh/MJRefresh/Base/MJRefreshAutoFooter.h
  82. 216 0
      Pods/MJRefresh/MJRefresh/Base/MJRefreshAutoFooter.m
  83. 21 0
      Pods/MJRefresh/MJRefresh/Base/MJRefreshBackFooter.h
  84. 158 0
      Pods/MJRefresh/MJRefresh/Base/MJRefreshBackFooter.m
  85. 151 0
      Pods/MJRefresh/MJRefresh/Base/MJRefreshComponent.h
  86. 323 0
      Pods/MJRefresh/MJRefresh/Base/MJRefreshComponent.m
  87. 37 0
      Pods/MJRefresh/MJRefresh/Base/MJRefreshFooter.h
  88. 71 0
      Pods/MJRefresh/MJRefresh/Base/MJRefreshFooter.m
  89. 35 0
      Pods/MJRefresh/MJRefresh/Base/MJRefreshHeader.h
  90. 297 0
      Pods/MJRefresh/MJRefresh/Base/MJRefreshHeader.m
  91. 30 0
      Pods/MJRefresh/MJRefresh/Base/MJRefreshTrailer.h
  92. 179 0
      Pods/MJRefresh/MJRefresh/Base/MJRefreshTrailer.m
  93. 25 0
      Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoGifFooter.h
  94. 121 0
      Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoGifFooter.m
  95. 25 0
      Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoNormalFooter.h
  96. 81 0
      Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoNormalFooter.m
  97. 30 0
      Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoStateFooter.h
  98. 119 0
      Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoStateFooter.m
  99. 25 0
      Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackGifFooter.h
  100. 132 0
      Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackGifFooter.m

+ 30 - 0
Podfile

@@ -0,0 +1,30 @@
+
+post_install do |installer|
+  installer.generated_projects.each do |project|
+    project.targets.each do |target|
+      target.build_configurations.each do |config|
+            config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '12.0'
+       end
+    end
+  end
+end
+
+platform :ios, '12.0'
+inhibit_all_warnings!
+
+target 'Temperature' do
+    
+use_frameworks!
+
+pod 'AFNetworking'
+pod 'SDWebImage'
+pod 'SVProgressHUD'
+pod 'FMDB'
+pod 'MJRefresh'
+pod 'MJExtension'
+pod 'Masonry'
+pod 'FDFullscreenPopGesture'   #全屏侧滑返回
+pod 'MMKV'
+
+end
+

+ 70 - 0
Podfile.lock

@@ -0,0 +1,70 @@
+PODS:
+  - AFNetworking (4.0.1):
+    - AFNetworking/NSURLSession (= 4.0.1)
+    - AFNetworking/Reachability (= 4.0.1)
+    - AFNetworking/Security (= 4.0.1)
+    - AFNetworking/Serialization (= 4.0.1)
+    - AFNetworking/UIKit (= 4.0.1)
+  - AFNetworking/NSURLSession (4.0.1):
+    - AFNetworking/Reachability
+    - AFNetworking/Security
+    - AFNetworking/Serialization
+  - AFNetworking/Reachability (4.0.1)
+  - AFNetworking/Security (4.0.1)
+  - AFNetworking/Serialization (4.0.1)
+  - AFNetworking/UIKit (4.0.1):
+    - AFNetworking/NSURLSession
+  - FDFullscreenPopGesture (1.1)
+  - FMDB (2.7.5):
+    - FMDB/standard (= 2.7.5)
+  - FMDB/standard (2.7.5)
+  - Masonry (1.1.0)
+  - MJExtension (3.4.1)
+  - MJRefresh (3.7.5)
+  - MMKV (1.2.14):
+    - MMKVCore (~> 1.2.14)
+  - MMKVCore (1.2.14)
+  - SDWebImage (5.12.5):
+    - SDWebImage/Core (= 5.12.5)
+  - SDWebImage/Core (5.12.5)
+  - SVProgressHUD (2.2.5)
+
+DEPENDENCIES:
+  - AFNetworking
+  - FDFullscreenPopGesture
+  - FMDB
+  - Masonry
+  - MJExtension
+  - MJRefresh
+  - MMKV
+  - SDWebImage
+  - SVProgressHUD
+
+SPEC REPOS:
+  trunk:
+    - AFNetworking
+    - FDFullscreenPopGesture
+    - FMDB
+    - Masonry
+    - MJExtension
+    - MJRefresh
+    - MMKV
+    - MMKVCore
+    - SDWebImage
+    - SVProgressHUD
+
+SPEC CHECKSUMS:
+  AFNetworking: 7864c38297c79aaca1500c33288e429c3451fdce
+  FDFullscreenPopGesture: a8a620179e3d9c40e8e00256dcee1c1a27c6d0f0
+  FMDB: 2ce00b547f966261cd18927a3ddb07cb6f3db82a
+  Masonry: 678fab65091a9290e40e2832a55e7ab731aad201
+  MJExtension: 21c5f6f8c4d5d8844b7ae8fbae08fed0b501f961
+  MJRefresh: fdf5e979eb406a0341468932d1dfc8b7f9fce961
+  MMKV: 9c4663aa7ca255d478ff10f2f5cb7d17c1651ccd
+  MMKVCore: 89f5c8a66bba2dcd551779dea4d412eeec8ff5bb
+  SDWebImage: 0905f1b7760fc8ac4198cae0036600d67478751e
+  SVProgressHUD: 1428aafac632c1f86f62aa4243ec12008d7a51d6
+
+PODFILE CHECKSUM: 07c37e5e20e787e9c692ab63148fe787a0690751
+
+COCOAPODS: 1.11.3


+ 49 - 0
Pods/AFNetworking/AFNetworking/AFCompatibilityMacros.h

@@ -0,0 +1,49 @@
+// AFCompatibilityMacros.h
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#ifndef AFCompatibilityMacros_h
+#define AFCompatibilityMacros_h
+
+#ifdef API_AVAILABLE
+    #define AF_API_AVAILABLE(...) API_AVAILABLE(__VA_ARGS__)
+#else
+    #define AF_API_AVAILABLE(...)
+#endif // API_AVAILABLE
+
+#ifdef API_UNAVAILABLE
+    #define AF_API_UNAVAILABLE(...) API_UNAVAILABLE(__VA_ARGS__)
+#else
+    #define AF_API_UNAVAILABLE(...)
+#endif // API_UNAVAILABLE
+
+#if __has_warning("-Wunguarded-availability-new")
+    #define AF_CAN_USE_AT_AVAILABLE 1
+#else
+    #define AF_CAN_USE_AT_AVAILABLE 0
+#endif
+
+#if ((__IPHONE_OS_VERSION_MAX_ALLOWED && __IPHONE_OS_VERSION_MAX_ALLOWED < 100000) || (__MAC_OS_VERSION_MAX_ALLOWED && __MAC_OS_VERSION_MAX_ALLOWED < 101200) ||(__WATCH_OS_MAX_VERSION_ALLOWED && __WATCH_OS_MAX_VERSION_ALLOWED < 30000) ||(__TV_OS_MAX_VERSION_ALLOWED && __TV_OS_MAX_VERSION_ALLOWED < 100000))
+    #define AF_CAN_INCLUDE_SESSION_TASK_METRICS 0
+#else
+    #define AF_CAN_INCLUDE_SESSION_TASK_METRICS 1
+#endif
+
+#endif /* AFCompatibilityMacros_h */

+ 285 - 0
Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.h

@@ -0,0 +1,285 @@
+// AFHTTPSessionManager.h
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <Foundation/Foundation.h>
+#if !TARGET_OS_WATCH
+#import <SystemConfiguration/SystemConfiguration.h>
+#endif
+#import <TargetConditionals.h>
+
+#import "AFURLSessionManager.h"
+
+/**
+ `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.
+
+ ## Subclassing Notes
+
+ 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.
+
+ ## Methods to Override
+
+ 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:`.
+
+ ## Serialization
+
+ 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>`.
+
+ Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `<AFURLResponseSerialization>`
+
+ ## URL Construction Using Relative Paths
+
+ 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:`.
+
+ Below are a few examples of how `baseURL` and relative paths interact:
+
+    NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"];
+    [NSURL URLWithString:@"foo" relativeToURL:baseURL];                  // http://example.com/v1/foo
+    [NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL];          // http://example.com/v1/foo?bar=baz
+    [NSURL URLWithString:@"/foo" relativeToURL:baseURL];                 // http://example.com/foo
+    [NSURL URLWithString:@"foo/" relativeToURL:baseURL];                 // http://example.com/v1/foo
+    [NSURL URLWithString:@"/foo/" relativeToURL:baseURL];                // http://example.com/foo/
+    [NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/
+
+ 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.
+
+ @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.
+ */
+
+NS_ASSUME_NONNULL_BEGIN
+
+@interface AFHTTPSessionManager : AFURLSessionManager <NSSecureCoding, NSCopying>
+
+/**
+ The URL used to construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods.
+ */
+@property (readonly, nonatomic, strong, nullable) NSURL *baseURL;
+
+/**
+ 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.
+
+ @warning `requestSerializer` must not be `nil`.
+ */
+@property (nonatomic, strong) AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer;
+
+/**
+ 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`.
+
+ @warning `responseSerializer` must not be `nil`.
+ */
+@property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;
+
+///-------------------------------
+/// @name Managing Security Policy
+///-------------------------------
+
+/**
+ 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.
+ */
+@property (nonatomic, strong) AFSecurityPolicy *securityPolicy;
+
+///---------------------
+/// @name Initialization
+///---------------------
+
+/**
+ Creates and returns an `AFHTTPSessionManager` object.
+ */
++ (instancetype)manager;
+
+/**
+ Initializes an `AFHTTPSessionManager` object with the specified base URL.
+
+ @param url The base URL for the HTTP client.
+
+ @return The newly-initialized HTTP client
+ */
+- (instancetype)initWithBaseURL:(nullable NSURL *)url;
+
+/**
+ Initializes an `AFHTTPSessionManager` object with the specified base URL.
+
+ This is the designated initializer.
+
+ @param url The base URL for the HTTP client.
+ @param configuration The configuration used to create the managed session.
+
+ @return The newly-initialized HTTP client
+ */
+- (instancetype)initWithBaseURL:(nullable NSURL *)url
+           sessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER;
+
+///---------------------------
+/// @name Making HTTP Requests
+///---------------------------
+
+/**
+ Creates and runs an `NSURLSessionDataTask` with a `GET` request.
+ 
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded according to the client request serializer.
+ @param headers The headers appended to the default headers for this request.
+ @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.
+ @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.
+ @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.
+ 
+ @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:
+ */
+- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString
+                            parameters:(nullable id)parameters
+                               headers:(nullable NSDictionary <NSString *, NSString *> *)headers
+                              progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgress
+                               success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
+                               failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
+
+/**
+ Creates and runs an `NSURLSessionDataTask` with a `HEAD` request.
+ 
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded according to the client request serializer.
+ @param headers The headers appended to the default headers for this request.
+ @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.
+ @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.
+ 
+ @see -dataTaskWithRequest:completionHandler:
+ */
+- (nullable NSURLSessionDataTask *)HEAD:(NSString *)URLString
+                             parameters:(nullable id)parameters
+                                headers:(nullable NSDictionary <NSString *, NSString *> *)headers
+                                success:(nullable void (^)(NSURLSessionDataTask *task))success
+                                failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
+
+/**
+ Creates and runs an `NSURLSessionDataTask` with a `POST` request.
+ 
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded according to the client request serializer.
+ @param headers The headers appended to the default headers for this request.
+ @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.
+ @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.
+ @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.
+ 
+ @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:
+ */
+- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
+                             parameters:(nullable id)parameters
+                                headers:(nullable NSDictionary <NSString *, NSString *> *)headers
+                               progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
+                                success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
+                                failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
+
+/**
+ Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request.
+ 
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded according to the client request serializer.
+ @param headers The headers appended to the default headers for this request.
+ @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.
+ @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.
+ @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.
+ @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.
+ 
+ @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:
+ */
+- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
+                             parameters:(nullable id)parameters
+                                headers:(nullable NSDictionary <NSString *, NSString *> *)headers
+              constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
+                               progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
+                                success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
+                                failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
+
+/**
+ Creates and runs an `NSURLSessionDataTask` with a `PUT` request.
+ 
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded according to the client request serializer.
+ @param headers The headers appended to the default headers for this request.
+ @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.
+ @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.
+ 
+ @see -dataTaskWithRequest:completionHandler:
+ */
+- (nullable NSURLSessionDataTask *)PUT:(NSString *)URLString
+                            parameters:(nullable id)parameters
+                               headers:(nullable NSDictionary <NSString *, NSString *> *)headers
+                               success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
+                               failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
+
+/**
+ Creates and runs an `NSURLSessionDataTask` with a `PATCH` request.
+ 
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded according to the client request serializer.
+ @param headers The headers appended to the default headers for this request.
+ @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.
+ @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.
+ 
+ @see -dataTaskWithRequest:completionHandler:
+ */
+- (nullable NSURLSessionDataTask *)PATCH:(NSString *)URLString
+                              parameters:(nullable id)parameters
+                                 headers:(nullable NSDictionary <NSString *, NSString *> *)headers
+                                 success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
+                                 failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
+
+/**
+ Creates and runs an `NSURLSessionDataTask` with a `DELETE` request.
+ 
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded according to the client request serializer.
+ @param headers The headers appended to the default headers for this request.
+ @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.
+ @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.
+ 
+ @see -dataTaskWithRequest:completionHandler:
+ */
+- (nullable NSURLSessionDataTask *)DELETE:(NSString *)URLString
+                               parameters:(nullable id)parameters
+                                  headers:(nullable NSDictionary <NSString *, NSString *> *)headers
+                                  success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
+                                  failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
+
+/**
+ Creates an `NSURLSessionDataTask` with a custom `HTTPMethod` request.
+
+ @param method The HTTPMethod string used to create the request.
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded according to the client request serializer.
+ @param headers The headers appended to the default headers for this request.
+ @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.
+ @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.
+ @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.
+ @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.
+
+ @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:
+ */
+- (nullable NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
+                                                URLString:(NSString *)URLString
+                                               parameters:(nullable id)parameters
+                                                  headers:(nullable NSDictionary <NSString *, NSString *> *)headers
+                                           uploadProgress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
+                                         downloadProgress:(nullable void (^)(NSProgress *downloadProgress))downloadProgress
+                                                  success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
+                                                  failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 357 - 0
Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.m

@@ -0,0 +1,357 @@
+// AFHTTPSessionManager.m
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import "AFHTTPSessionManager.h"
+
+#import "AFURLRequestSerialization.h"
+#import "AFURLResponseSerialization.h"
+
+#import <Availability.h>
+#import <TargetConditionals.h>
+#import <Security/Security.h>
+
+#import <netinet/in.h>
+#import <netinet6/in6.h>
+#import <arpa/inet.h>
+#import <ifaddrs.h>
+#import <netdb.h>
+
+#if TARGET_OS_IOS || TARGET_OS_TV
+#import <UIKit/UIKit.h>
+#elif TARGET_OS_WATCH
+#import <WatchKit/WatchKit.h>
+#endif
+
+@interface AFHTTPSessionManager ()
+@property (readwrite, nonatomic, strong) NSURL *baseURL;
+@end
+
+@implementation AFHTTPSessionManager
+@dynamic responseSerializer;
+
++ (instancetype)manager {
+    return [[[self class] alloc] initWithBaseURL:nil];
+}
+
+- (instancetype)init {
+    return [self initWithBaseURL:nil];
+}
+
+- (instancetype)initWithBaseURL:(NSURL *)url {
+    return [self initWithBaseURL:url sessionConfiguration:nil];
+}
+
+- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration {
+    return [self initWithBaseURL:nil sessionConfiguration:configuration];
+}
+
+- (instancetype)initWithBaseURL:(NSURL *)url
+           sessionConfiguration:(NSURLSessionConfiguration *)configuration
+{
+    self = [super initWithSessionConfiguration:configuration];
+    if (!self) {
+        return nil;
+    }
+
+    // Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected
+    if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) {
+        url = [url URLByAppendingPathComponent:@""];
+    }
+
+    self.baseURL = url;
+
+    self.requestSerializer = [AFHTTPRequestSerializer serializer];
+    self.responseSerializer = [AFJSONResponseSerializer serializer];
+
+    return self;
+}
+
+#pragma mark -
+
+- (void)setRequestSerializer:(AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializer {
+    NSParameterAssert(requestSerializer);
+
+    _requestSerializer = requestSerializer;
+}
+
+- (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer {
+    NSParameterAssert(responseSerializer);
+
+    [super setResponseSerializer:responseSerializer];
+}
+
+@dynamic securityPolicy;
+
+- (void)setSecurityPolicy:(AFSecurityPolicy *)securityPolicy {
+    if (securityPolicy.SSLPinningMode != AFSSLPinningModeNone && ![self.baseURL.scheme isEqualToString:@"https"]) {
+        NSString *pinningMode = @"Unknown Pinning Mode";
+        switch (securityPolicy.SSLPinningMode) {
+            case AFSSLPinningModeNone:        pinningMode = @"AFSSLPinningModeNone"; break;
+            case AFSSLPinningModeCertificate: pinningMode = @"AFSSLPinningModeCertificate"; break;
+            case AFSSLPinningModePublicKey:   pinningMode = @"AFSSLPinningModePublicKey"; break;
+        }
+        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];
+        @throw [NSException exceptionWithName:@"Invalid Security Policy" reason:reason userInfo:nil];
+    }
+
+    [super setSecurityPolicy:securityPolicy];
+}
+
+#pragma mark -
+
+- (NSURLSessionDataTask *)GET:(NSString *)URLString
+                   parameters:(nullable id)parameters
+                      headers:(nullable NSDictionary <NSString *, NSString *> *)headers
+                     progress:(nullable void (^)(NSProgress * _Nonnull))downloadProgress
+                      success:(nullable void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
+                      failure:(nullable void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
+{
+    
+    NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET"
+                                                        URLString:URLString
+                                                       parameters:parameters
+                                                          headers:headers
+                                                   uploadProgress:nil
+                                                 downloadProgress:downloadProgress
+                                                          success:success
+                                                          failure:failure];
+    
+    [dataTask resume];
+    
+    return dataTask;
+}
+
+- (NSURLSessionDataTask *)HEAD:(NSString *)URLString
+                    parameters:(nullable id)parameters
+                       headers:(nullable NSDictionary<NSString *,NSString *> *)headers
+                       success:(nullable void (^)(NSURLSessionDataTask * _Nonnull))success
+                       failure:(nullable void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
+{
+    NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters headers:headers uploadProgress:nil downloadProgress:nil success:^(NSURLSessionDataTask *task, __unused id responseObject) {
+        if (success) {
+            success(task);
+        }
+    } failure:failure];
+    
+    [dataTask resume];
+    
+    return dataTask;
+}
+
+- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
+                             parameters:(nullable id)parameters
+                                headers:(nullable NSDictionary <NSString *, NSString *> *)headers
+                               progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
+                                success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
+                                failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure
+{
+    NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters headers:headers uploadProgress:uploadProgress downloadProgress:nil success:success failure:failure];
+    
+    [dataTask resume];
+    
+    return dataTask;
+}
+
+- (NSURLSessionDataTask *)POST:(NSString *)URLString
+                    parameters:(nullable id)parameters
+                       headers:(nullable NSDictionary<NSString *,NSString *> *)headers
+     constructingBodyWithBlock:(nullable void (^)(id<AFMultipartFormData> _Nonnull))block
+                      progress:(nullable void (^)(NSProgress * _Nonnull))uploadProgress
+                       success:(nullable void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
+{
+    NSError *serializationError = nil;
+    NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError];
+    for (NSString *headerField in headers.keyEnumerator) {
+        [request setValue:headers[headerField] forHTTPHeaderField:headerField];
+    }
+    if (serializationError) {
+        if (failure) {
+            dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
+                failure(nil, serializationError);
+            });
+        }
+        
+        return nil;
+    }
+    
+    __block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:uploadProgress completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
+        if (error) {
+            if (failure) {
+                failure(task, error);
+            }
+        } else {
+            if (success) {
+                success(task, responseObject);
+            }
+        }
+    }];
+    
+    [task resume];
+    
+    return task;
+}
+
+- (NSURLSessionDataTask *)PUT:(NSString *)URLString
+                   parameters:(nullable id)parameters
+                      headers:(nullable NSDictionary<NSString *,NSString *> *)headers
+                      success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success
+                      failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure
+{
+    NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters headers:headers uploadProgress:nil downloadProgress:nil success:success failure:failure];
+    
+    [dataTask resume];
+    
+    return dataTask;
+}
+
+- (NSURLSessionDataTask *)PATCH:(NSString *)URLString
+                     parameters:(nullable id)parameters
+                        headers:(nullable NSDictionary<NSString *,NSString *> *)headers
+                        success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success
+                        failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure
+{
+    NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters headers:headers uploadProgress:nil downloadProgress:nil success:success failure:failure];
+    
+    [dataTask resume];
+    
+    return dataTask;
+}
+
+- (NSURLSessionDataTask *)DELETE:(NSString *)URLString
+                      parameters:(nullable id)parameters
+                         headers:(nullable NSDictionary<NSString *,NSString *> *)headers
+                         success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success
+                         failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure
+{
+    NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters headers:headers uploadProgress:nil downloadProgress:nil success:success failure:failure];
+    
+    [dataTask resume];
+    
+    return dataTask;
+}
+
+
+- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
+                                       URLString:(NSString *)URLString
+                                      parameters:(nullable id)parameters
+                                         headers:(nullable NSDictionary <NSString *, NSString *> *)headers
+                                  uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
+                                downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
+                                         success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
+                                         failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure
+{
+    NSError *serializationError = nil;
+    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];
+    for (NSString *headerField in headers.keyEnumerator) {
+        [request setValue:headers[headerField] forHTTPHeaderField:headerField];
+    }
+    if (serializationError) {
+        if (failure) {
+            dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
+                failure(nil, serializationError);
+            });
+        }
+
+        return nil;
+    }
+
+    __block NSURLSessionDataTask *dataTask = nil;
+    dataTask = [self dataTaskWithRequest:request
+                          uploadProgress:uploadProgress
+                        downloadProgress:downloadProgress
+                       completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
+        if (error) {
+            if (failure) {
+                failure(dataTask, error);
+            }
+        } else {
+            if (success) {
+                success(dataTask, responseObject);
+            }
+        }
+    }];
+
+    return dataTask;
+}
+
+#pragma mark - NSObject
+
+- (NSString *)description {
+    return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.session, self.operationQueue];
+}
+
+#pragma mark - NSSecureCoding
+
++ (BOOL)supportsSecureCoding {
+    return YES;
+}
+
+- (instancetype)initWithCoder:(NSCoder *)decoder {
+    NSURL *baseURL = [decoder decodeObjectOfClass:[NSURL class] forKey:NSStringFromSelector(@selector(baseURL))];
+    NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"];
+    if (!configuration) {
+        NSString *configurationIdentifier = [decoder decodeObjectOfClass:[NSString class] forKey:@"identifier"];
+        if (configurationIdentifier) {
+            configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configurationIdentifier];
+        }
+    }
+
+    self = [self initWithBaseURL:baseURL sessionConfiguration:configuration];
+    if (!self) {
+        return nil;
+    }
+
+    self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))];
+    self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))];
+    AFSecurityPolicy *decodedPolicy = [decoder decodeObjectOfClass:[AFSecurityPolicy class] forKey:NSStringFromSelector(@selector(securityPolicy))];
+    if (decodedPolicy) {
+        self.securityPolicy = decodedPolicy;
+    }
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)coder {
+    [super encodeWithCoder:coder];
+
+    [coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))];
+    if ([self.session.configuration conformsToProtocol:@protocol(NSCoding)]) {
+        [coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"];
+    } else {
+        [coder encodeObject:self.session.configuration.identifier forKey:@"identifier"];
+    }
+    [coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))];
+    [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))];
+    [coder encodeObject:self.securityPolicy forKey:NSStringFromSelector(@selector(securityPolicy))];
+}
+
+#pragma mark - NSCopying
+
+- (instancetype)copyWithZone:(NSZone *)zone {
+    AFHTTPSessionManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL sessionConfiguration:self.session.configuration];
+
+    HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone];
+    HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone];
+    HTTPClient.securityPolicy = [self.securityPolicy copyWithZone:zone];
+    return HTTPClient;
+}
+
+@end

+ 216 - 0
Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h

@@ -0,0 +1,216 @@
+// AFNetworkReachabilityManager.h
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <Foundation/Foundation.h>
+
+#if !TARGET_OS_WATCH
+#import <SystemConfiguration/SystemConfiguration.h>
+
+typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
+    AFNetworkReachabilityStatusUnknown          = -1,
+    AFNetworkReachabilityStatusNotReachable     = 0,
+    AFNetworkReachabilityStatusReachableViaWWAN = 1,
+    AFNetworkReachabilityStatusReachableViaWiFi = 2,
+};
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ `AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.
+
+ 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.
+
+ See Apple's Reachability Sample Code ( https://developer.apple.com/library/ios/samplecode/reachability/ )
+
+ @warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined.
+ */
+@interface AFNetworkReachabilityManager : NSObject
+
+/**
+ The current network reachability status.
+ */
+@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
+
+/**
+ Whether or not the network is currently reachable.
+ */
+@property (readonly, nonatomic, assign, getter = isReachable) BOOL reachable;
+
+/**
+ Whether or not the network is currently reachable via WWAN.
+ */
+@property (readonly, nonatomic, assign, getter = isReachableViaWWAN) BOOL reachableViaWWAN;
+
+/**
+ Whether or not the network is currently reachable via WiFi.
+ */
+@property (readonly, nonatomic, assign, getter = isReachableViaWiFi) BOOL reachableViaWiFi;
+
+///---------------------
+/// @name Initialization
+///---------------------
+
+/**
+ Returns the shared network reachability manager.
+ */
++ (instancetype)sharedManager;
+
+/**
+ Creates and returns a network reachability manager with the default socket address.
+ 
+ @return An initialized network reachability manager, actively monitoring the default socket address.
+ */
++ (instancetype)manager;
+
+/**
+ Creates and returns a network reachability manager for the specified domain.
+
+ @param domain The domain used to evaluate network reachability.
+
+ @return An initialized network reachability manager, actively monitoring the specified domain.
+ */
++ (instancetype)managerForDomain:(NSString *)domain;
+
+/**
+ Creates and returns a network reachability manager for the socket address.
+
+ @param address The socket address (`sockaddr_in6`) used to evaluate network reachability.
+
+ @return An initialized network reachability manager, actively monitoring the specified socket address.
+ */
++ (instancetype)managerForAddress:(const void *)address;
+
+/**
+ Initializes an instance of a network reachability manager from the specified reachability object.
+
+ @param reachability The reachability object to monitor.
+
+ @return An initialized network reachability manager, actively monitoring the specified reachability.
+ */
+- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability NS_DESIGNATED_INITIALIZER;
+
+/**
+ *  Unavailable initializer
+ */
++ (instancetype)new NS_UNAVAILABLE;
+
+/**
+ *  Unavailable initializer
+ */
+- (instancetype)init NS_UNAVAILABLE;
+
+///--------------------------------------------------
+/// @name Starting & Stopping Reachability Monitoring
+///--------------------------------------------------
+
+/**
+ Starts monitoring for changes in network reachability status.
+ */
+- (void)startMonitoring;
+
+/**
+ Stops monitoring for changes in network reachability status.
+ */
+- (void)stopMonitoring;
+
+///-------------------------------------------------
+/// @name Getting Localized Reachability Description
+///-------------------------------------------------
+
+/**
+ Returns a localized string representation of the current network reachability status.
+ */
+- (NSString *)localizedNetworkReachabilityStatusString;
+
+///---------------------------------------------------
+/// @name Setting Network Reachability Change Callback
+///---------------------------------------------------
+
+/**
+ Sets a callback to be executed when the network availability of the `baseURL` host changes.
+
+ @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`.
+ */
+- (void)setReachabilityStatusChangeBlock:(nullable void (^)(AFNetworkReachabilityStatus status))block;
+
+@end
+
+///----------------
+/// @name Constants
+///----------------
+
+/**
+ ## Network Reachability
+
+ The following constants are provided by `AFNetworkReachabilityManager` as possible network reachability statuses.
+
+ enum {
+ AFNetworkReachabilityStatusUnknown,
+ AFNetworkReachabilityStatusNotReachable,
+ AFNetworkReachabilityStatusReachableViaWWAN,
+ AFNetworkReachabilityStatusReachableViaWiFi,
+ }
+
+ `AFNetworkReachabilityStatusUnknown`
+ The `baseURL` host reachability is not known.
+
+ `AFNetworkReachabilityStatusNotReachable`
+ The `baseURL` host cannot be reached.
+
+ `AFNetworkReachabilityStatusReachableViaWWAN`
+ The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS.
+
+ `AFNetworkReachabilityStatusReachableViaWiFi`
+ The `baseURL` host can be reached via a Wi-Fi connection.
+
+ ### Keys for Notification UserInfo Dictionary
+
+ Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification.
+
+ `AFNetworkingReachabilityNotificationStatusItem`
+ A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification.
+ The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status.
+ */
+
+///--------------------
+/// @name Notifications
+///--------------------
+
+/**
+ Posted when network reachability changes.
+ 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.
+
+ @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`).
+ */
+FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityDidChangeNotification;
+FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityNotificationStatusItem;
+
+///--------------------
+/// @name Functions
+///--------------------
+
+/**
+ Returns a localized string representation of an `AFNetworkReachabilityStatus` value.
+ */
+FOUNDATION_EXPORT NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status);
+
+NS_ASSUME_NONNULL_END
+#endif

+ 269 - 0
Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m

@@ -0,0 +1,269 @@
+// AFNetworkReachabilityManager.m
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import "AFNetworkReachabilityManager.h"
+#if !TARGET_OS_WATCH
+
+#import <netinet/in.h>
+#import <netinet6/in6.h>
+#import <arpa/inet.h>
+#import <ifaddrs.h>
+#import <netdb.h>
+
+NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change";
+NSString * const AFNetworkingReachabilityNotificationStatusItem = @"AFNetworkingReachabilityNotificationStatusItem";
+
+typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status);
+typedef AFNetworkReachabilityManager * (^AFNetworkReachabilityStatusCallback)(AFNetworkReachabilityStatus status);
+
+NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status) {
+    switch (status) {
+        case AFNetworkReachabilityStatusNotReachable:
+            return NSLocalizedStringFromTable(@"Not Reachable", @"AFNetworking", nil);
+        case AFNetworkReachabilityStatusReachableViaWWAN:
+            return NSLocalizedStringFromTable(@"Reachable via WWAN", @"AFNetworking", nil);
+        case AFNetworkReachabilityStatusReachableViaWiFi:
+            return NSLocalizedStringFromTable(@"Reachable via WiFi", @"AFNetworking", nil);
+        case AFNetworkReachabilityStatusUnknown:
+        default:
+            return NSLocalizedStringFromTable(@"Unknown", @"AFNetworking", nil);
+    }
+}
+
+static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) {
+    BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0);
+    BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0);
+    BOOL canConnectionAutomatically = (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0));
+    BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0);
+    BOOL isNetworkReachable = (isReachable && (!needsConnection || canConnectWithoutUserInteraction));
+
+    AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown;
+    if (isNetworkReachable == NO) {
+        status = AFNetworkReachabilityStatusNotReachable;
+    }
+#if	TARGET_OS_IPHONE
+    else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) {
+        status = AFNetworkReachabilityStatusReachableViaWWAN;
+    }
+#endif
+    else {
+        status = AFNetworkReachabilityStatusReachableViaWiFi;
+    }
+
+    return status;
+}
+
+/**
+ * Queue a status change notification for the main thread.
+ *
+ * This is done to ensure that the notifications are received in the same order
+ * as they are sent. If notifications are sent directly, it is possible that
+ * a queued notification (for an earlier status condition) is processed after
+ * the later update, resulting in the listener being left in the wrong state.
+ */
+static void AFPostReachabilityStatusChange(SCNetworkReachabilityFlags flags, AFNetworkReachabilityStatusCallback block) {
+    AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags);
+    dispatch_async(dispatch_get_main_queue(), ^{
+        AFNetworkReachabilityManager *manager = nil;
+        if (block) {
+            manager = block(status);
+        }
+        NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
+        NSDictionary *userInfo = @{ AFNetworkingReachabilityNotificationStatusItem: @(status) };
+        [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:manager userInfo:userInfo];
+    });
+}
+
+static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) {
+    AFPostReachabilityStatusChange(flags, (__bridge AFNetworkReachabilityStatusCallback)info);
+}
+
+
+static const void * AFNetworkReachabilityRetainCallback(const void *info) {
+    return Block_copy(info);
+}
+
+static void AFNetworkReachabilityReleaseCallback(const void *info) {
+    if (info) {
+        Block_release(info);
+    }
+}
+
+@interface AFNetworkReachabilityManager ()
+@property (readonly, nonatomic, assign) SCNetworkReachabilityRef networkReachability;
+@property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
+@property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock;
+@end
+
+@implementation AFNetworkReachabilityManager
+
++ (instancetype)sharedManager {
+    static AFNetworkReachabilityManager *_sharedManager = nil;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        _sharedManager = [self manager];
+    });
+
+    return _sharedManager;
+}
+
++ (instancetype)managerForDomain:(NSString *)domain {
+    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]);
+
+    AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability];
+    
+    CFRelease(reachability);
+
+    return manager;
+}
+
++ (instancetype)managerForAddress:(const void *)address {
+    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address);
+    AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability];
+
+    CFRelease(reachability);
+    
+    return manager;
+}
+
++ (instancetype)manager
+{
+#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)
+    struct sockaddr_in6 address;
+    bzero(&address, sizeof(address));
+    address.sin6_len = sizeof(address);
+    address.sin6_family = AF_INET6;
+#else
+    struct sockaddr_in address;
+    bzero(&address, sizeof(address));
+    address.sin_len = sizeof(address);
+    address.sin_family = AF_INET;
+#endif
+    return [self managerForAddress:&address];
+}
+
+- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    _networkReachability = CFRetain(reachability);
+    self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown;
+
+    return self;
+}
+
+- (instancetype)init
+{
+    @throw [NSException exceptionWithName:NSGenericException
+                                   reason:@"`-init` unavailable. Use `-initWithReachability:` instead"
+                                 userInfo:nil];
+    return nil;
+}
+
+- (void)dealloc {
+    [self stopMonitoring];
+    
+    if (_networkReachability != NULL) {
+        CFRelease(_networkReachability);
+    }
+}
+
+#pragma mark -
+
+- (BOOL)isReachable {
+    return [self isReachableViaWWAN] || [self isReachableViaWiFi];
+}
+
+- (BOOL)isReachableViaWWAN {
+    return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN;
+}
+
+- (BOOL)isReachableViaWiFi {
+    return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi;
+}
+
+#pragma mark -
+
+- (void)startMonitoring {
+    [self stopMonitoring];
+
+    if (!self.networkReachability) {
+        return;
+    }
+
+    __weak __typeof(self)weakSelf = self;
+    AFNetworkReachabilityStatusCallback callback = ^(AFNetworkReachabilityStatus status) {
+        __strong __typeof(weakSelf)strongSelf = weakSelf;
+
+        strongSelf.networkReachabilityStatus = status;
+        if (strongSelf.networkReachabilityStatusBlock) {
+            strongSelf.networkReachabilityStatusBlock(status);
+        }
+        
+        return strongSelf;
+    };
+
+    SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL};
+    SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context);
+    SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
+
+    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{
+        SCNetworkReachabilityFlags flags;
+        if (SCNetworkReachabilityGetFlags(self.networkReachability, &flags)) {
+            AFPostReachabilityStatusChange(flags, callback);
+        }
+    });
+}
+
+- (void)stopMonitoring {
+    if (!self.networkReachability) {
+        return;
+    }
+
+    SCNetworkReachabilityUnscheduleFromRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
+}
+
+#pragma mark -
+
+- (NSString *)localizedNetworkReachabilityStatusString {
+    return AFStringFromNetworkReachabilityStatus(self.networkReachabilityStatus);
+}
+
+#pragma mark -
+
+- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block {
+    self.networkReachabilityStatusBlock = block;
+}
+
+#pragma mark - NSKeyValueObserving
+
++ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key {
+    if ([key isEqualToString:@"reachable"] || [key isEqualToString:@"reachableViaWWAN"] || [key isEqualToString:@"reachableViaWiFi"]) {
+        return [NSSet setWithObject:@"networkReachabilityStatus"];
+    }
+
+    return [super keyPathsForValuesAffectingValueForKey:key];
+}
+
+@end
+#endif

+ 41 - 0
Pods/AFNetworking/AFNetworking/AFNetworking.h

@@ -0,0 +1,41 @@
+// AFNetworking.h
+//
+// Copyright (c) 2013 AFNetworking (http://afnetworking.com/)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <Foundation/Foundation.h>
+#import <Availability.h>
+#import <TargetConditionals.h>
+
+#ifndef _AFNETWORKING_
+    #define _AFNETWORKING_
+
+    #import "AFURLRequestSerialization.h"
+    #import "AFURLResponseSerialization.h"
+    #import "AFSecurityPolicy.h"
+
+#if !TARGET_OS_WATCH
+    #import "AFNetworkReachabilityManager.h"
+#endif
+
+    #import "AFURLSessionManager.h"
+    #import "AFHTTPSessionManager.h"
+
+#endif /* _AFNETWORKING_ */

+ 161 - 0
Pods/AFNetworking/AFNetworking/AFSecurityPolicy.h

@@ -0,0 +1,161 @@
+// AFSecurityPolicy.h
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <Foundation/Foundation.h>
+#import <Security/Security.h>
+
+typedef NS_ENUM(NSUInteger, AFSSLPinningMode) {
+    AFSSLPinningModeNone,
+    AFSSLPinningModePublicKey,
+    AFSSLPinningModeCertificate,
+};
+
+/**
+ `AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections.
+
+ 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.
+ */
+
+NS_ASSUME_NONNULL_BEGIN
+
+@interface AFSecurityPolicy : NSObject <NSSecureCoding, NSCopying>
+
+/**
+ The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `AFSSLPinningModeNone`.
+ */
+@property (readonly, nonatomic, assign) AFSSLPinningMode SSLPinningMode;
+
+/**
+ The certificates used to evaluate server trust according to the SSL pinning mode. 
+ 
+ Note that if pinning is enabled, `evaluateServerTrust:forDomain:` will return true if any pinned certificate matches.
+
+ @see policyWithPinningMode:withPinnedCertificates:
+ */
+@property (nonatomic, strong, nullable) NSSet <NSData *> *pinnedCertificates;
+
+/**
+ Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`.
+ */
+@property (nonatomic, assign) BOOL allowInvalidCertificates;
+
+/**
+ Whether or not to validate the domain name in the certificate's CN field. Defaults to `YES`.
+ */
+@property (nonatomic, assign) BOOL validatesDomainName;
+
+///-----------------------------------------
+/// @name Getting Certificates from the Bundle
+///-----------------------------------------
+
+/**
+ 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`.
+
+ @return The certificates included in the given bundle.
+ */
++ (NSSet <NSData *> *)certificatesInBundle:(NSBundle *)bundle;
+
+///-----------------------------------------
+/// @name Getting Specific Security Policies
+///-----------------------------------------
+
+/**
+ 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.
+
+ @return The default security policy.
+ */
++ (instancetype)defaultPolicy;
+
+///---------------------
+/// @name Initialization
+///---------------------
+
+/**
+ Creates and returns a security policy with the specified pinning mode.
+ 
+ Certificates with the `.cer` extension found in the main bundle will be pinned. If you want more control over which certificates are pinned, please use `policyWithPinningMode:withPinnedCertificates:` instead.
+
+ @param pinningMode The SSL pinning mode.
+
+ @return A new security policy.
+
+ @see -policyWithPinningMode:withPinnedCertificates:
+ */
++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode;
+
+/**
+ Creates and returns a security policy with the specified pinning mode.
+
+ @param pinningMode The SSL pinning mode.
+ @param pinnedCertificates The certificates to pin against.
+
+ @return A new security policy.
+
+ @see +certificatesInBundle:
+ @see -pinnedCertificates
+*/
++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet <NSData *> *)pinnedCertificates;
+
+///------------------------------
+/// @name Evaluating Server Trust
+///------------------------------
+
+/**
+ Whether or not the specified server trust should be accepted, based on the security policy.
+
+ This method should be used when responding to an authentication challenge from a server.
+
+ @param serverTrust The X.509 certificate trust of the server.
+ @param domain The domain of serverTrust. If `nil`, the domain will not be validated.
+
+ @return Whether or not to trust the server.
+ */
+- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
+                  forDomain:(nullable NSString *)domain;
+
+@end
+
+NS_ASSUME_NONNULL_END
+
+///----------------
+/// @name Constants
+///----------------
+
+/**
+ ## SSL Pinning Modes
+
+ The following constants are provided by `AFSSLPinningMode` as possible SSL pinning modes.
+
+ enum {
+ AFSSLPinningModeNone,
+ AFSSLPinningModePublicKey,
+ AFSSLPinningModeCertificate,
+ }
+
+ `AFSSLPinningModeNone`
+ Do not used pinned certificates to validate servers.
+
+ `AFSSLPinningModePublicKey`
+ Validate host certificates against public keys of pinned certificates.
+
+ `AFSSLPinningModeCertificate`
+ Validate host certificates against pinned certificates.
+*/

+ 341 - 0
Pods/AFNetworking/AFNetworking/AFSecurityPolicy.m

@@ -0,0 +1,341 @@
+// AFSecurityPolicy.m
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import "AFSecurityPolicy.h"
+
+#import <AssertMacros.h>
+
+#if !TARGET_OS_IOS && !TARGET_OS_WATCH && !TARGET_OS_TV
+static NSData * AFSecKeyGetData(SecKeyRef key) {
+    CFDataRef data = NULL;
+
+    __Require_noErr_Quiet(SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data), _out);
+
+    return (__bridge_transfer NSData *)data;
+
+_out:
+    if (data) {
+        CFRelease(data);
+    }
+
+    return nil;
+}
+#endif
+
+static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
+#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV
+    return [(__bridge id)key1 isEqual:(__bridge id)key2];
+#else
+    return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)];
+#endif
+}
+
+static id AFPublicKeyForCertificate(NSData *certificate) {
+    id allowedPublicKey = nil;
+    SecCertificateRef allowedCertificate;
+    SecPolicyRef policy = nil;
+    SecTrustRef allowedTrust = nil;
+    SecTrustResultType result;
+
+    allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate);
+    __Require_Quiet(allowedCertificate != NULL, _out);
+
+    policy = SecPolicyCreateBasicX509();
+    __Require_noErr_Quiet(SecTrustCreateWithCertificates(allowedCertificate, policy, &allowedTrust), _out);
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+    __Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out);
+#pragma clang diagnostic pop
+
+    allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust);
+
+_out:
+    if (allowedTrust) {
+        CFRelease(allowedTrust);
+    }
+
+    if (policy) {
+        CFRelease(policy);
+    }
+
+    if (allowedCertificate) {
+        CFRelease(allowedCertificate);
+    }
+
+    return allowedPublicKey;
+}
+
+static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) {
+    BOOL isValid = NO;
+    SecTrustResultType result;
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+    __Require_noErr_Quiet(SecTrustEvaluate(serverTrust, &result), _out);
+#pragma clang diagnostic pop
+
+    isValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed);
+
+_out:
+    return isValid;
+}
+
+static NSArray * AFCertificateTrustChainForServerTrust(SecTrustRef serverTrust) {
+    CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
+    NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
+
+    for (CFIndex i = 0; i < certificateCount; i++) {
+        SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
+        [trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)];
+    }
+
+    return [NSArray arrayWithArray:trustChain];
+}
+
+static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
+    SecPolicyRef policy = SecPolicyCreateBasicX509();
+    CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
+    NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
+    for (CFIndex i = 0; i < certificateCount; i++) {
+        SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
+
+        SecCertificateRef someCertificates[] = {certificate};
+        CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL);
+
+        SecTrustRef trust;
+        __Require_noErr_Quiet(SecTrustCreateWithCertificates(certificates, policy, &trust), _out);
+        SecTrustResultType result;
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+        __Require_noErr_Quiet(SecTrustEvaluate(trust, &result), _out);
+#pragma clang diagnostic pop
+        [trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)];
+
+    _out:
+        if (trust) {
+            CFRelease(trust);
+        }
+
+        if (certificates) {
+            CFRelease(certificates);
+        }
+
+        continue;
+    }
+    CFRelease(policy);
+
+    return [NSArray arrayWithArray:trustChain];
+}
+
+#pragma mark -
+
+@interface AFSecurityPolicy()
+@property (readwrite, nonatomic, assign) AFSSLPinningMode SSLPinningMode;
+@property (readwrite, nonatomic, strong) NSSet *pinnedPublicKeys;
+@end
+
+@implementation AFSecurityPolicy
+
++ (NSSet *)certificatesInBundle:(NSBundle *)bundle {
+    NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."];
+
+    NSMutableSet *certificates = [NSMutableSet setWithCapacity:[paths count]];
+    for (NSString *path in paths) {
+        NSData *certificateData = [NSData dataWithContentsOfFile:path];
+        [certificates addObject:certificateData];
+    }
+
+    return [NSSet setWithSet:certificates];
+}
+
++ (instancetype)defaultPolicy {
+    AFSecurityPolicy *securityPolicy = [[self alloc] init];
+    securityPolicy.SSLPinningMode = AFSSLPinningModeNone;
+
+    return securityPolicy;
+}
+
++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode {
+    NSSet <NSData *> *defaultPinnedCertificates = [self certificatesInBundle:[NSBundle mainBundle]];
+    return [self policyWithPinningMode:pinningMode withPinnedCertificates:defaultPinnedCertificates];
+}
+
++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates {
+    AFSecurityPolicy *securityPolicy = [[self alloc] init];
+    securityPolicy.SSLPinningMode = pinningMode;
+
+    [securityPolicy setPinnedCertificates:pinnedCertificates];
+
+    return securityPolicy;
+}
+
+- (instancetype)init {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    self.validatesDomainName = YES;
+
+    return self;
+}
+
+- (void)setPinnedCertificates:(NSSet *)pinnedCertificates {
+    _pinnedCertificates = pinnedCertificates;
+
+    if (self.pinnedCertificates) {
+        NSMutableSet *mutablePinnedPublicKeys = [NSMutableSet setWithCapacity:[self.pinnedCertificates count]];
+        for (NSData *certificate in self.pinnedCertificates) {
+            id publicKey = AFPublicKeyForCertificate(certificate);
+            if (!publicKey) {
+                continue;
+            }
+            [mutablePinnedPublicKeys addObject:publicKey];
+        }
+        self.pinnedPublicKeys = [NSSet setWithSet:mutablePinnedPublicKeys];
+    } else {
+        self.pinnedPublicKeys = nil;
+    }
+}
+
+#pragma mark -
+
+- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
+                  forDomain:(NSString *)domain
+{
+    if (domain && self.allowInvalidCertificates && self.validatesDomainName && (self.SSLPinningMode == AFSSLPinningModeNone || [self.pinnedCertificates count] == 0)) {
+        // https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/OverridingSSLChainValidationCorrectly.html
+        //  According to the docs, you should only trust your provided certs for evaluation.
+        //  Pinned certificates are added to the trust. Without pinned certificates,
+        //  there is nothing to evaluate against.
+        //
+        //  From Apple Docs:
+        //          "Do not implicitly trust self-signed certificates as anchors (kSecTrustOptionImplicitAnchors).
+        //           Instead, add your own (self-signed) CA certificate to the list of trusted anchors."
+        NSLog(@"In order to validate a domain name for self signed certificates, you MUST use pinning.");
+        return NO;
+    }
+
+    NSMutableArray *policies = [NSMutableArray array];
+    if (self.validatesDomainName) {
+        [policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)];
+    } else {
+        [policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()];
+    }
+
+    SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies);
+
+    if (self.SSLPinningMode == AFSSLPinningModeNone) {
+        return self.allowInvalidCertificates || AFServerTrustIsValid(serverTrust);
+    } else if (!self.allowInvalidCertificates && !AFServerTrustIsValid(serverTrust)) {
+        return NO;
+    }
+
+    switch (self.SSLPinningMode) {
+        case AFSSLPinningModeCertificate: {
+            NSMutableArray *pinnedCertificates = [NSMutableArray array];
+            for (NSData *certificateData in self.pinnedCertificates) {
+                [pinnedCertificates addObject:(__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData)];
+            }
+            SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)pinnedCertificates);
+
+            if (!AFServerTrustIsValid(serverTrust)) {
+                return NO;
+            }
+
+            // obtain the chain after being validated, which *should* contain the pinned certificate in the last position (if it's the Root CA)
+            NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust);
+            
+            for (NSData *trustChainCertificate in [serverCertificates reverseObjectEnumerator]) {
+                if ([self.pinnedCertificates containsObject:trustChainCertificate]) {
+                    return YES;
+                }
+            }
+            
+            return NO;
+        }
+        case AFSSLPinningModePublicKey: {
+            NSUInteger trustedPublicKeyCount = 0;
+            NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust);
+
+            for (id trustChainPublicKey in publicKeys) {
+                for (id pinnedPublicKey in self.pinnedPublicKeys) {
+                    if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)trustChainPublicKey, (__bridge SecKeyRef)pinnedPublicKey)) {
+                        trustedPublicKeyCount += 1;
+                    }
+                }
+            }
+            return trustedPublicKeyCount > 0;
+        }
+            
+        default:
+            return NO;
+    }
+    
+    return NO;
+}
+
+#pragma mark - NSKeyValueObserving
+
++ (NSSet *)keyPathsForValuesAffectingPinnedPublicKeys {
+    return [NSSet setWithObject:@"pinnedCertificates"];
+}
+
+#pragma mark - NSSecureCoding
+
++ (BOOL)supportsSecureCoding {
+    return YES;
+}
+
+- (instancetype)initWithCoder:(NSCoder *)decoder {
+
+    self = [self init];
+    if (!self) {
+        return nil;
+    }
+
+    self.SSLPinningMode = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(SSLPinningMode))] unsignedIntegerValue];
+    self.allowInvalidCertificates = [decoder decodeBoolForKey:NSStringFromSelector(@selector(allowInvalidCertificates))];
+    self.validatesDomainName = [decoder decodeBoolForKey:NSStringFromSelector(@selector(validatesDomainName))];
+    self.pinnedCertificates = [decoder decodeObjectOfClass:[NSSet class] forKey:NSStringFromSelector(@selector(pinnedCertificates))];
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)coder {
+    [coder encodeObject:[NSNumber numberWithUnsignedInteger:self.SSLPinningMode] forKey:NSStringFromSelector(@selector(SSLPinningMode))];
+    [coder encodeBool:self.allowInvalidCertificates forKey:NSStringFromSelector(@selector(allowInvalidCertificates))];
+    [coder encodeBool:self.validatesDomainName forKey:NSStringFromSelector(@selector(validatesDomainName))];
+    [coder encodeObject:self.pinnedCertificates forKey:NSStringFromSelector(@selector(pinnedCertificates))];
+}
+
+#pragma mark - NSCopying
+
+- (instancetype)copyWithZone:(NSZone *)zone {
+    AFSecurityPolicy *securityPolicy = [[[self class] allocWithZone:zone] init];
+    securityPolicy.SSLPinningMode = self.SSLPinningMode;
+    securityPolicy.allowInvalidCertificates = self.allowInvalidCertificates;
+    securityPolicy.validatesDomainName = self.validatesDomainName;
+    securityPolicy.pinnedCertificates = [self.pinnedCertificates copyWithZone:zone];
+
+    return securityPolicy;
+}
+
+@end

+ 479 - 0
Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.h

@@ -0,0 +1,479 @@
+// AFURLRequestSerialization.h
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <Foundation/Foundation.h>
+#import <TargetConditionals.h>
+
+#if TARGET_OS_IOS || TARGET_OS_TV
+#import <UIKit/UIKit.h>
+#elif TARGET_OS_WATCH
+#import <WatchKit/WatchKit.h>
+#endif
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Returns a percent-escaped string following RFC 3986 for a query string key or value.
+ RFC 3986 states that the following characters are "reserved" characters.
+ - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
+ - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
+
+ In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
+ query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
+ should be percent-escaped in the query string.
+ 
+ @param string The string to be percent-escaped.
+ 
+ @return The percent-escaped string.
+ */
+FOUNDATION_EXPORT NSString * AFPercentEscapedStringFromString(NSString *string);
+
+/**
+ A helper method to generate encoded url query parameters for appending to the end of a URL.
+
+ @param parameters A dictionary of key/values to be encoded.
+
+ @return A url encoded query string
+ */
+FOUNDATION_EXPORT NSString * AFQueryStringFromParameters(NSDictionary *parameters);
+
+/**
+ 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.
+
+ 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`.
+ */
+@protocol AFURLRequestSerialization <NSObject, NSSecureCoding, NSCopying>
+
+/**
+ Returns a request with the specified parameters encoded into a copy of the original request.
+
+ @param request The original request.
+ @param parameters The parameters to be encoded.
+ @param error The error that occurred while attempting to encode the request parameters.
+
+ @return A serialized request.
+ */
+- (nullable NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
+                               withParameters:(nullable id)parameters
+                                        error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW;
+
+@end
+
+#pragma mark -
+
+/**
+
+ */
+typedef NS_ENUM(NSUInteger, AFHTTPRequestQueryStringSerializationStyle) {
+    AFHTTPRequestQueryStringDefaultStyle = 0,
+};
+
+@protocol AFMultipartFormData;
+
+/**
+ `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.
+
+ Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPRequestSerializer` in order to ensure consistent default behavior.
+ */
+@interface AFHTTPRequestSerializer : NSObject <AFURLRequestSerialization>
+
+/**
+ The string encoding used to serialize parameters. `NSUTF8StringEncoding` by default.
+ */
+@property (nonatomic, assign) NSStringEncoding stringEncoding;
+
+/**
+ Whether created requests can use the device’s cellular radio (if present). `YES` by default.
+
+ @see NSMutableURLRequest -setAllowsCellularAccess:
+ */
+@property (nonatomic, assign) BOOL allowsCellularAccess;
+
+/**
+ The cache policy of created requests. `NSURLRequestUseProtocolCachePolicy` by default.
+
+ @see NSMutableURLRequest -setCachePolicy:
+ */
+@property (nonatomic, assign) NSURLRequestCachePolicy cachePolicy;
+
+/**
+ Whether created requests should use the default cookie handling. `YES` by default.
+
+ @see NSMutableURLRequest -setHTTPShouldHandleCookies:
+ */
+@property (nonatomic, assign) BOOL HTTPShouldHandleCookies;
+
+/**
+ Whether created requests can continue transmitting data before receiving a response from an earlier transmission. `NO` by default
+
+ @see NSMutableURLRequest -setHTTPShouldUsePipelining:
+ */
+@property (nonatomic, assign) BOOL HTTPShouldUsePipelining;
+
+/**
+ The network service type for created requests. `NSURLNetworkServiceTypeDefault` by default.
+
+ @see NSMutableURLRequest -setNetworkServiceType:
+ */
+@property (nonatomic, assign) NSURLRequestNetworkServiceType networkServiceType;
+
+/**
+ The timeout interval, in seconds, for created requests. The default timeout interval is 60 seconds.
+
+ @see NSMutableURLRequest -setTimeoutInterval:
+ */
+@property (nonatomic, assign) NSTimeInterval timeoutInterval;
+
+///---------------------------------------
+/// @name Configuring HTTP Request Headers
+///---------------------------------------
+
+/**
+ Default HTTP header field values to be applied to serialized requests. By default, these include the following:
+
+ - `Accept-Language` with the contents of `NSLocale +preferredLanguages`
+ - `User-Agent` with the contents of various bundle identifiers and OS designations
+
+ @discussion To add or remove default request headers, use `setValue:forHTTPHeaderField:`.
+ */
+@property (readonly, nonatomic, strong) NSDictionary <NSString *, NSString *> *HTTPRequestHeaders;
+
+/**
+ Creates and returns a serializer with default configuration.
+ */
++ (instancetype)serializer;
+
+/**
+ 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.
+
+ @param field The HTTP header to set a default value for
+ @param value The value set as default for the specified header, or `nil`
+ */
+- (void)setValue:(nullable NSString *)value
+forHTTPHeaderField:(NSString *)field;
+
+/**
+ Returns the value for the HTTP headers set in the request serializer.
+
+ @param field The HTTP header to retrieve the default value for
+
+ @return The value set as default for the specified header, or `nil`
+ */
+- (nullable NSString *)valueForHTTPHeaderField:(NSString *)field;
+
+/**
+ 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.
+
+ @param username The HTTP basic auth username
+ @param password The HTTP basic auth password
+ */
+- (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username
+                                       password:(NSString *)password;
+
+/**
+ Clears any existing value for the "Authorization" HTTP header.
+ */
+- (void)clearAuthorizationHeader;
+
+///-------------------------------------------------------
+/// @name Configuring Query String Parameter Serialization
+///-------------------------------------------------------
+
+/**
+ HTTP methods for which serialized requests will encode parameters as a query string. `GET`, `HEAD`, and `DELETE` by default.
+ */
+@property (nonatomic, strong) NSSet <NSString *> *HTTPMethodsEncodingParametersInURI;
+
+/**
+ Set the method of query string serialization according to one of the pre-defined styles.
+
+ @param style The serialization style.
+
+ @see AFHTTPRequestQueryStringSerializationStyle
+ */
+- (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style;
+
+/**
+ Set the a custom method of query string serialization according to the specified block.
+
+ @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.
+ */
+- (void)setQueryStringSerializationWithBlock:(nullable NSString * _Nullable (^)(NSURLRequest *request, id parameters, NSError * __autoreleasing *error))block;
+
+///-------------------------------
+/// @name Creating Request Objects
+///-------------------------------
+
+/**
+ Creates an `NSMutableURLRequest` object with the specified HTTP method and URL string.
+
+ 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.
+
+ @param method The HTTP method for the request, such as `GET`, `POST`, `PUT`, or `DELETE`. This parameter must not be `nil`.
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body.
+ @param error The error that occurred while constructing the request.
+
+ @return An `NSMutableURLRequest` object.
+ */
+- (nullable NSMutableURLRequest *)requestWithMethod:(NSString *)method
+                                          URLString:(NSString *)URLString
+                                         parameters:(nullable id)parameters
+                                              error:(NSError * _Nullable __autoreleasing *)error;
+
+/**
+ 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
+
+ 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.
+
+ @param method The HTTP method for the request. This parameter must not be `GET` or `HEAD`, or `nil`.
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded and set in the request HTTP body.
+ @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.
+ @param error The error that occurred while constructing the request.
+
+ @return An `NSMutableURLRequest` object
+ */
+- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
+                                              URLString:(NSString *)URLString
+                                             parameters:(nullable NSDictionary <NSString *, id> *)parameters
+                              constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
+                                                  error:(NSError * _Nullable __autoreleasing *)error;
+
+/**
+ 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.
+
+ @param request The multipart form request. The `HTTPBodyStream` property of `request` must not be `nil`.
+ @param fileURL The file URL to write multipart form contents to.
+ @param handler A handler block to execute.
+
+ @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.
+
+ @see https://github.com/AFNetworking/AFNetworking/issues/1398
+ */
+- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request
+                             writingStreamContentsToFile:(NSURL *)fileURL
+                                       completionHandler:(nullable void (^)(NSError * _Nullable error))handler;
+
+@end
+
+#pragma mark -
+
+/**
+ The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `AFHTTPRequestSerializer -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:`.
+ */
+@protocol AFMultipartFormData
+
+/**
+ 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.
+
+ 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.
+
+ @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`.
+ @param name The name to be associated with the specified data. This parameter must not be `nil`.
+ @param error If an error occurs, upon return contains an `NSError` object that describes the problem.
+
+ @return `YES` if the file data was successfully appended, otherwise `NO`.
+ */
+- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
+                         name:(NSString *)name
+                        error:(NSError * _Nullable __autoreleasing *)error;
+
+/**
+ 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.
+
+ @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`.
+ @param name The name to be associated with the specified data. This parameter must not be `nil`.
+ @param fileName The file name to be used in the `Content-Disposition` header. This parameter must not be `nil`.
+ @param mimeType The declared MIME type of the file data. This parameter must not be `nil`.
+ @param error If an error occurs, upon return contains an `NSError` object that describes the problem.
+
+ @return `YES` if the file data was successfully appended otherwise `NO`.
+ */
+- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
+                         name:(NSString *)name
+                     fileName:(NSString *)fileName
+                     mimeType:(NSString *)mimeType
+                        error:(NSError * _Nullable __autoreleasing *)error;
+
+/**
+ 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.
+
+ @param inputStream The input stream to be appended to the form data
+ @param name The name to be associated with the specified input stream. This parameter must not be `nil`.
+ @param fileName The filename to be associated with the specified input stream. This parameter must not be `nil`.
+ @param length The length of the specified input stream in bytes.
+ @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`.
+ */
+- (void)appendPartWithInputStream:(nullable NSInputStream *)inputStream
+                             name:(NSString *)name
+                         fileName:(NSString *)fileName
+                           length:(int64_t)length
+                         mimeType:(NSString *)mimeType;
+
+/**
+ 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.
+
+ @param data The data to be encoded and appended to the form data.
+ @param name The name to be associated with the specified data. This parameter must not be `nil`.
+ @param fileName The filename to be associated with the specified data. This parameter must not be `nil`.
+ @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`.
+ */
+- (void)appendPartWithFileData:(NSData *)data
+                          name:(NSString *)name
+                      fileName:(NSString *)fileName
+                      mimeType:(NSString *)mimeType;
+
+/**
+ Appends the HTTP headers `Content-Disposition: form-data; name=#{name}"`, followed by the encoded data and the multipart form boundary.
+
+ @param data The data to be encoded and appended to the form data.
+ @param name The name to be associated with the specified data. This parameter must not be `nil`.
+ */
+
+- (void)appendPartWithFormData:(NSData *)data
+                          name:(NSString *)name;
+
+
+/**
+ Appends HTTP headers, followed by the encoded data and the multipart form boundary.
+
+ @param headers The HTTP headers to be appended to the form data.
+ @param body The data to be encoded and appended to the form data. This parameter must not be `nil`.
+ */
+- (void)appendPartWithHeaders:(nullable NSDictionary <NSString *, NSString *> *)headers
+                         body:(NSData *)body;
+
+/**
+ Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream.
+
+ 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.
+
+ @param numberOfBytes Maximum packet size, in number of bytes. The default packet size for an input stream is 16kb.
+ @param delay Duration of delay each time a packet is read. By default, no delay is set.
+ */
+- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes
+                                  delay:(NSTimeInterval)delay;
+
+@end
+
+#pragma mark -
+
+/**
+ `AFJSONRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSJSONSerialization`, setting the `Content-Type` of the encoded request to `application/json`.
+ */
+@interface AFJSONRequestSerializer : AFHTTPRequestSerializer
+
+/**
+ Options for writing the request JSON data from Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONWritingOptions". `0` by default.
+ */
+@property (nonatomic, assign) NSJSONWritingOptions writingOptions;
+
+/**
+ Creates and returns a JSON serializer with specified reading and writing options.
+
+ @param writingOptions The specified JSON writing options.
+ */
++ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions;
+
+@end
+
+#pragma mark -
+
+/**
+ `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`.
+ */
+@interface AFPropertyListRequestSerializer : AFHTTPRequestSerializer
+
+/**
+ The property list format. Possible values are described in "NSPropertyListFormat".
+ */
+@property (nonatomic, assign) NSPropertyListFormat format;
+
+/**
+ @warning The `writeOptions` property is currently unused.
+ */
+@property (nonatomic, assign) NSPropertyListWriteOptions writeOptions;
+
+/**
+ Creates and returns a property list serializer with a specified format, read options, and write options.
+
+ @param format The property list format.
+ @param writeOptions The property list write options.
+
+ @warning The `writeOptions` property is currently unused.
+ */
++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
+                        writeOptions:(NSPropertyListWriteOptions)writeOptions;
+
+@end
+
+#pragma mark -
+
+///----------------
+/// @name Constants
+///----------------
+
+/**
+ ## Error Domains
+
+ The following error domain is predefined.
+
+ - `NSString * const AFURLRequestSerializationErrorDomain`
+
+ ### Constants
+
+ `AFURLRequestSerializationErrorDomain`
+ AFURLRequestSerializer errors. Error codes for `AFURLRequestSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`.
+ */
+FOUNDATION_EXPORT NSString * const AFURLRequestSerializationErrorDomain;
+
+/**
+ ## User info dictionary keys
+
+ These keys may exist in the user info dictionary, in addition to those defined for NSError.
+
+ - `NSString * const AFNetworkingOperationFailingURLRequestErrorKey`
+
+ ### Constants
+
+ `AFNetworkingOperationFailingURLRequestErrorKey`
+ The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `AFURLRequestSerializationErrorDomain`.
+ */
+FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLRequestErrorKey;
+
+/**
+ ## Throttling Bandwidth for HTTP Request Input Streams
+
+ @see -throttleBandwidthWithPacketSize:delay:
+
+ ### Constants
+
+ `kAFUploadStream3GSuggestedPacketSize`
+ Maximum packet size, in number of bytes. Equal to 16kb.
+
+ `kAFUploadStream3GSuggestedDelay`
+ Duration of delay each time a packet is read. Equal to 0.2 seconds.
+ */
+FOUNDATION_EXPORT NSUInteger const kAFUploadStream3GSuggestedPacketSize;
+FOUNDATION_EXPORT NSTimeInterval const kAFUploadStream3GSuggestedDelay;
+
+NS_ASSUME_NONNULL_END

+ 1399 - 0
Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.m

@@ -0,0 +1,1399 @@
+// AFURLRequestSerialization.m
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import "AFURLRequestSerialization.h"
+
+#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV
+#import <MobileCoreServices/MobileCoreServices.h>
+#else
+#import <CoreServices/CoreServices.h>
+#endif
+
+NSString * const AFURLRequestSerializationErrorDomain = @"com.alamofire.error.serialization.request";
+NSString * const AFNetworkingOperationFailingURLRequestErrorKey = @"com.alamofire.serialization.request.error.response";
+
+typedef NSString * (^AFQueryStringSerializationBlock)(NSURLRequest *request, id parameters, NSError *__autoreleasing *error);
+
+/**
+ Returns a percent-escaped string following RFC 3986 for a query string key or value.
+ RFC 3986 states that the following characters are "reserved" characters.
+    - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
+    - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
+
+ In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
+ query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
+ should be percent-escaped in the query string.
+    - parameter string: The string to be percent-escaped.
+    - returns: The percent-escaped string.
+ */
+NSString * AFPercentEscapedStringFromString(NSString *string) {
+    static NSString * const kAFCharactersGeneralDelimitersToEncode = @":#[]@"; // does not include "?" or "/" due to RFC 3986 - Section 3.4
+    static NSString * const kAFCharactersSubDelimitersToEncode = @"!$&'()*+,;=";
+
+    NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
+    [allowedCharacterSet removeCharactersInString:[kAFCharactersGeneralDelimitersToEncode stringByAppendingString:kAFCharactersSubDelimitersToEncode]];
+
+	// FIXME: https://github.com/AFNetworking/AFNetworking/pull/3028
+    // return [string stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
+
+    static NSUInteger const batchSize = 50;
+
+    NSUInteger index = 0;
+    NSMutableString *escaped = @"".mutableCopy;
+
+    while (index < string.length) {
+        NSUInteger length = MIN(string.length - index, batchSize);
+        NSRange range = NSMakeRange(index, length);
+
+        // To avoid breaking up character sequences such as 👴🏻👮🏽
+        range = [string rangeOfComposedCharacterSequencesForRange:range];
+
+        NSString *substring = [string substringWithRange:range];
+        NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
+        [escaped appendString:encoded];
+
+        index += range.length;
+    }
+
+	return escaped;
+}
+
+#pragma mark -
+
+@interface AFQueryStringPair : NSObject
+@property (readwrite, nonatomic, strong) id field;
+@property (readwrite, nonatomic, strong) id value;
+
+- (instancetype)initWithField:(id)field value:(id)value;
+
+- (NSString *)URLEncodedStringValue;
+@end
+
+@implementation AFQueryStringPair
+
+- (instancetype)initWithField:(id)field value:(id)value {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    self.field = field;
+    self.value = value;
+
+    return self;
+}
+
+- (NSString *)URLEncodedStringValue {
+    if (!self.value || [self.value isEqual:[NSNull null]]) {
+        return AFPercentEscapedStringFromString([self.field description]);
+    } else {
+        return [NSString stringWithFormat:@"%@=%@", AFPercentEscapedStringFromString([self.field description]), AFPercentEscapedStringFromString([self.value description])];
+    }
+}
+
+@end
+
+#pragma mark -
+
+FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary);
+FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value);
+
+NSString * AFQueryStringFromParameters(NSDictionary *parameters) {
+    NSMutableArray *mutablePairs = [NSMutableArray array];
+    for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
+        [mutablePairs addObject:[pair URLEncodedStringValue]];
+    }
+
+    return [mutablePairs componentsJoinedByString:@"&"];
+}
+
+NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary) {
+    return AFQueryStringPairsFromKeyAndValue(nil, dictionary);
+}
+
+NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
+    NSMutableArray *mutableQueryStringComponents = [NSMutableArray array];
+
+    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(compare:)];
+
+    if ([value isKindOfClass:[NSDictionary class]]) {
+        NSDictionary *dictionary = value;
+        // Sort dictionary keys to ensure consistent ordering in query string, which is important when deserializing potentially ambiguous sequences, such as an array of dictionaries
+        for (id nestedKey in [dictionary.allKeys sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
+            id nestedValue = dictionary[nestedKey];
+            if (nestedValue) {
+                [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)];
+            }
+        }
+    } else if ([value isKindOfClass:[NSArray class]]) {
+        NSArray *array = value;
+        for (id nestedValue in array) {
+            [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue([NSString stringWithFormat:@"%@[]", key], nestedValue)];
+        }
+    } else if ([value isKindOfClass:[NSSet class]]) {
+        NSSet *set = value;
+        for (id obj in [set sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
+            [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue(key, obj)];
+        }
+    } else {
+        [mutableQueryStringComponents addObject:[[AFQueryStringPair alloc] initWithField:key value:value]];
+    }
+
+    return mutableQueryStringComponents;
+}
+
+#pragma mark -
+
+@interface AFStreamingMultipartFormData : NSObject <AFMultipartFormData>
+- (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest
+                    stringEncoding:(NSStringEncoding)encoding;
+
+- (NSMutableURLRequest *)requestByFinalizingMultipartFormData;
+@end
+
+#pragma mark -
+
+static NSArray * AFHTTPRequestSerializerObservedKeyPaths() {
+    static NSArray *_AFHTTPRequestSerializerObservedKeyPaths = nil;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        _AFHTTPRequestSerializerObservedKeyPaths = @[NSStringFromSelector(@selector(allowsCellularAccess)), NSStringFromSelector(@selector(cachePolicy)), NSStringFromSelector(@selector(HTTPShouldHandleCookies)), NSStringFromSelector(@selector(HTTPShouldUsePipelining)), NSStringFromSelector(@selector(networkServiceType)), NSStringFromSelector(@selector(timeoutInterval))];
+    });
+
+    return _AFHTTPRequestSerializerObservedKeyPaths;
+}
+
+static void *AFHTTPRequestSerializerObserverContext = &AFHTTPRequestSerializerObserverContext;
+
+@interface AFHTTPRequestSerializer ()
+@property (readwrite, nonatomic, strong) NSMutableSet *mutableObservedChangedKeyPaths;
+@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableHTTPRequestHeaders;
+@property (readwrite, nonatomic, strong) dispatch_queue_t requestHeaderModificationQueue;
+@property (readwrite, nonatomic, assign) AFHTTPRequestQueryStringSerializationStyle queryStringSerializationStyle;
+@property (readwrite, nonatomic, copy) AFQueryStringSerializationBlock queryStringSerialization;
+@end
+
+@implementation AFHTTPRequestSerializer
+
++ (instancetype)serializer {
+    return [[self alloc] init];
+}
+
+- (instancetype)init {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    self.stringEncoding = NSUTF8StringEncoding;
+
+    self.mutableHTTPRequestHeaders = [NSMutableDictionary dictionary];
+    self.requestHeaderModificationQueue = dispatch_queue_create("requestHeaderModificationQueue", DISPATCH_QUEUE_CONCURRENT);
+
+    // Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
+    NSMutableArray *acceptLanguagesComponents = [NSMutableArray array];
+    [[NSLocale preferredLanguages] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
+        float q = 1.0f - (idx * 0.1f);
+        [acceptLanguagesComponents addObject:[NSString stringWithFormat:@"%@;q=%0.1g", obj, q]];
+        *stop = q <= 0.5f;
+    }];
+    [self setValue:[acceptLanguagesComponents componentsJoinedByString:@", "] forHTTPHeaderField:@"Accept-Language"];
+
+    // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
+    NSString *userAgent = nil;
+#if TARGET_OS_IOS
+    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]];
+#elif TARGET_OS_TV
+    userAgent = [NSString stringWithFormat:@"%@/%@ (%@; tvOS %@; 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]];
+#elif TARGET_OS_WATCH
+    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]];
+#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
+    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]];
+#endif
+    if (userAgent) {
+        if (![userAgent canBeConvertedToEncoding:NSASCIIStringEncoding]) {
+            NSMutableString *mutableUserAgent = [userAgent mutableCopy];
+            if (CFStringTransform((__bridge CFMutableStringRef)(mutableUserAgent), NULL, (__bridge CFStringRef)@"Any-Latin; Latin-ASCII; [:^ASCII:] Remove", false)) {
+                userAgent = mutableUserAgent;
+            }
+        }
+        [self setValue:userAgent forHTTPHeaderField:@"User-Agent"];
+    }
+
+    // HTTP Method Definitions; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
+    self.HTTPMethodsEncodingParametersInURI = [NSSet setWithObjects:@"GET", @"HEAD", @"DELETE", nil];
+
+    self.mutableObservedChangedKeyPaths = [NSMutableSet set];
+    for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) {
+        if ([self respondsToSelector:NSSelectorFromString(keyPath)]) {
+            [self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:AFHTTPRequestSerializerObserverContext];
+        }
+    }
+
+    return self;
+}
+
+- (void)dealloc {
+    for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) {
+        if ([self respondsToSelector:NSSelectorFromString(keyPath)]) {
+            [self removeObserver:self forKeyPath:keyPath context:AFHTTPRequestSerializerObserverContext];
+        }
+    }
+}
+
+#pragma mark -
+
+// Workarounds for crashing behavior using Key-Value Observing with XCTest
+// See https://github.com/AFNetworking/AFNetworking/issues/2523
+
+- (void)setAllowsCellularAccess:(BOOL)allowsCellularAccess {
+    [self willChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))];
+    _allowsCellularAccess = allowsCellularAccess;
+    [self didChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))];
+}
+
+- (void)setCachePolicy:(NSURLRequestCachePolicy)cachePolicy {
+    [self willChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))];
+    _cachePolicy = cachePolicy;
+    [self didChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))];
+}
+
+- (void)setHTTPShouldHandleCookies:(BOOL)HTTPShouldHandleCookies {
+    [self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))];
+    _HTTPShouldHandleCookies = HTTPShouldHandleCookies;
+    [self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))];
+}
+
+- (void)setHTTPShouldUsePipelining:(BOOL)HTTPShouldUsePipelining {
+    [self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))];
+    _HTTPShouldUsePipelining = HTTPShouldUsePipelining;
+    [self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))];
+}
+
+- (void)setNetworkServiceType:(NSURLRequestNetworkServiceType)networkServiceType {
+    [self willChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))];
+    _networkServiceType = networkServiceType;
+    [self didChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))];
+}
+
+- (void)setTimeoutInterval:(NSTimeInterval)timeoutInterval {
+    [self willChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))];
+    _timeoutInterval = timeoutInterval;
+    [self didChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))];
+}
+
+#pragma mark -
+
+- (NSDictionary *)HTTPRequestHeaders {
+    NSDictionary __block *value;
+    dispatch_sync(self.requestHeaderModificationQueue, ^{
+        value = [NSDictionary dictionaryWithDictionary:self.mutableHTTPRequestHeaders];
+    });
+    return value;
+}
+
+- (void)setValue:(NSString *)value
+forHTTPHeaderField:(NSString *)field
+{
+    dispatch_barrier_sync(self.requestHeaderModificationQueue, ^{
+        [self.mutableHTTPRequestHeaders setValue:value forKey:field];
+    });
+}
+
+- (NSString *)valueForHTTPHeaderField:(NSString *)field {
+    NSString __block *value;
+    dispatch_sync(self.requestHeaderModificationQueue, ^{
+        value = [self.mutableHTTPRequestHeaders valueForKey:field];
+    });
+    return value;
+}
+
+- (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username
+                                       password:(NSString *)password
+{
+    NSData *basicAuthCredentials = [[NSString stringWithFormat:@"%@:%@", username, password] dataUsingEncoding:NSUTF8StringEncoding];
+    NSString *base64AuthCredentials = [basicAuthCredentials base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0];
+    [self setValue:[NSString stringWithFormat:@"Basic %@", base64AuthCredentials] forHTTPHeaderField:@"Authorization"];
+}
+
+- (void)clearAuthorizationHeader {
+    dispatch_barrier_sync(self.requestHeaderModificationQueue, ^{
+        [self.mutableHTTPRequestHeaders removeObjectForKey:@"Authorization"];
+    });
+}
+
+#pragma mark -
+
+- (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style {
+    self.queryStringSerializationStyle = style;
+    self.queryStringSerialization = nil;
+}
+
+- (void)setQueryStringSerializationWithBlock:(NSString *(^)(NSURLRequest *, id, NSError *__autoreleasing *))block {
+    self.queryStringSerialization = block;
+}
+
+#pragma mark -
+
+- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
+                                 URLString:(NSString *)URLString
+                                parameters:(id)parameters
+                                     error:(NSError *__autoreleasing *)error
+{
+    NSParameterAssert(method);
+    NSParameterAssert(URLString);
+
+    NSURL *url = [NSURL URLWithString:URLString];
+
+    NSParameterAssert(url);
+
+    NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url];
+    mutableRequest.HTTPMethod = method;
+
+    for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) {
+        if ([self.mutableObservedChangedKeyPaths containsObject:keyPath]) {
+            [mutableRequest setValue:[self valueForKeyPath:keyPath] forKey:keyPath];
+        }
+    }
+
+    mutableRequest = [[self requestBySerializingRequest:mutableRequest withParameters:parameters error:error] mutableCopy];
+
+	return mutableRequest;
+}
+
+- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
+                                              URLString:(NSString *)URLString
+                                             parameters:(NSDictionary *)parameters
+                              constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
+                                                  error:(NSError *__autoreleasing *)error
+{
+    NSParameterAssert(method);
+    NSParameterAssert(![method isEqualToString:@"GET"] && ![method isEqualToString:@"HEAD"]);
+
+    NSMutableURLRequest *mutableRequest = [self requestWithMethod:method URLString:URLString parameters:nil error:error];
+
+    __block AFStreamingMultipartFormData *formData = [[AFStreamingMultipartFormData alloc] initWithURLRequest:mutableRequest stringEncoding:NSUTF8StringEncoding];
+
+    if (parameters) {
+        for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
+            NSData *data = nil;
+            if ([pair.value isKindOfClass:[NSData class]]) {
+                data = pair.value;
+            } else if ([pair.value isEqual:[NSNull null]]) {
+                data = [NSData data];
+            } else {
+                data = [[pair.value description] dataUsingEncoding:self.stringEncoding];
+            }
+
+            if (data) {
+                [formData appendPartWithFormData:data name:[pair.field description]];
+            }
+        }
+    }
+
+    if (block) {
+        block(formData);
+    }
+
+    return [formData requestByFinalizingMultipartFormData];
+}
+
+- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request
+                             writingStreamContentsToFile:(NSURL *)fileURL
+                                       completionHandler:(void (^)(NSError *error))handler
+{
+    NSParameterAssert(request.HTTPBodyStream);
+    NSParameterAssert([fileURL isFileURL]);
+
+    NSInputStream *inputStream = request.HTTPBodyStream;
+    NSOutputStream *outputStream = [[NSOutputStream alloc] initWithURL:fileURL append:NO];
+    __block NSError *error = nil;
+
+    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
+        [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
+        [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
+
+        [inputStream open];
+        [outputStream open];
+
+        while ([inputStream hasBytesAvailable] && [outputStream hasSpaceAvailable]) {
+            uint8_t buffer[1024];
+
+            NSInteger bytesRead = [inputStream read:buffer maxLength:1024];
+            if (inputStream.streamError || bytesRead < 0) {
+                error = inputStream.streamError;
+                break;
+            }
+
+            NSInteger bytesWritten = [outputStream write:buffer maxLength:(NSUInteger)bytesRead];
+            if (outputStream.streamError || bytesWritten < 0) {
+                error = outputStream.streamError;
+                break;
+            }
+
+            if (bytesRead == 0 && bytesWritten == 0) {
+                break;
+            }
+        }
+
+        [outputStream close];
+        [inputStream close];
+
+        if (handler) {
+            dispatch_async(dispatch_get_main_queue(), ^{
+                handler(error);
+            });
+        }
+    });
+
+    NSMutableURLRequest *mutableRequest = [request mutableCopy];
+    mutableRequest.HTTPBodyStream = nil;
+
+    return mutableRequest;
+}
+
+#pragma mark - AFURLRequestSerialization
+
+- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
+                               withParameters:(id)parameters
+                                        error:(NSError *__autoreleasing *)error
+{
+    NSParameterAssert(request);
+
+    NSMutableURLRequest *mutableRequest = [request mutableCopy];
+
+    [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
+        if (![request valueForHTTPHeaderField:field]) {
+            [mutableRequest setValue:value forHTTPHeaderField:field];
+        }
+    }];
+
+    NSString *query = nil;
+    if (parameters) {
+        if (self.queryStringSerialization) {
+            NSError *serializationError;
+            query = self.queryStringSerialization(request, parameters, &serializationError);
+
+            if (serializationError) {
+                if (error) {
+                    *error = serializationError;
+                }
+
+                return nil;
+            }
+        } else {
+            switch (self.queryStringSerializationStyle) {
+                case AFHTTPRequestQueryStringDefaultStyle:
+                    query = AFQueryStringFromParameters(parameters);
+                    break;
+            }
+        }
+    }
+
+    if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
+        if (query && query.length > 0) {
+            mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? @"&%@" : @"?%@", query]];
+        }
+    } else {
+        // #2864: an empty string is a valid x-www-form-urlencoded payload
+        if (!query) {
+            query = @"";
+        }
+        if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
+            [mutableRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
+        }
+        [mutableRequest setHTTPBody:[query dataUsingEncoding:self.stringEncoding]];
+    }
+
+    return mutableRequest;
+}
+
+#pragma mark - NSKeyValueObserving
+
++ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
+    if ([AFHTTPRequestSerializerObservedKeyPaths() containsObject:key]) {
+        return NO;
+    }
+
+    return [super automaticallyNotifiesObserversForKey:key];
+}
+
+- (void)observeValueForKeyPath:(NSString *)keyPath
+                      ofObject:(__unused id)object
+                        change:(NSDictionary *)change
+                       context:(void *)context
+{
+    if (context == AFHTTPRequestSerializerObserverContext) {
+        if ([change[NSKeyValueChangeNewKey] isEqual:[NSNull null]]) {
+            [self.mutableObservedChangedKeyPaths removeObject:keyPath];
+        } else {
+            [self.mutableObservedChangedKeyPaths addObject:keyPath];
+        }
+    }
+}
+
+#pragma mark - NSSecureCoding
+
++ (BOOL)supportsSecureCoding {
+    return YES;
+}
+
+- (instancetype)initWithCoder:(NSCoder *)decoder {
+    self = [self init];
+    if (!self) {
+        return nil;
+    }
+
+    self.mutableHTTPRequestHeaders = [[decoder decodeObjectOfClass:[NSDictionary class] forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))] mutableCopy];
+    self.queryStringSerializationStyle = (AFHTTPRequestQueryStringSerializationStyle)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))] unsignedIntegerValue];
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)coder {
+    dispatch_sync(self.requestHeaderModificationQueue, ^{
+        [coder encodeObject:self.mutableHTTPRequestHeaders forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))];
+    });
+    [coder encodeObject:@(self.queryStringSerializationStyle) forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))];
+}
+
+#pragma mark - NSCopying
+
+- (instancetype)copyWithZone:(NSZone *)zone {
+    AFHTTPRequestSerializer *serializer = [[[self class] allocWithZone:zone] init];
+    dispatch_sync(self.requestHeaderModificationQueue, ^{
+        serializer.mutableHTTPRequestHeaders = [self.mutableHTTPRequestHeaders mutableCopyWithZone:zone];
+    });
+    serializer.queryStringSerializationStyle = self.queryStringSerializationStyle;
+    serializer.queryStringSerialization = self.queryStringSerialization;
+
+    return serializer;
+}
+
+@end
+
+#pragma mark -
+
+static NSString * AFCreateMultipartFormBoundary() {
+    return [NSString stringWithFormat:@"Boundary+%08X%08X", arc4random(), arc4random()];
+}
+
+static NSString * const kAFMultipartFormCRLF = @"\r\n";
+
+static inline NSString * AFMultipartFormInitialBoundary(NSString *boundary) {
+    return [NSString stringWithFormat:@"--%@%@", boundary, kAFMultipartFormCRLF];
+}
+
+static inline NSString * AFMultipartFormEncapsulationBoundary(NSString *boundary) {
+    return [NSString stringWithFormat:@"%@--%@%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF];
+}
+
+static inline NSString * AFMultipartFormFinalBoundary(NSString *boundary) {
+    return [NSString stringWithFormat:@"%@--%@--%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF];
+}
+
+static inline NSString * AFContentTypeForPathExtension(NSString *extension) {
+    NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)extension, NULL);
+    NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType);
+    if (!contentType) {
+        return @"application/octet-stream";
+    } else {
+        return contentType;
+    }
+}
+
+NSUInteger const kAFUploadStream3GSuggestedPacketSize = 1024 * 16;
+NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
+
+@interface AFHTTPBodyPart : NSObject
+@property (nonatomic, assign) NSStringEncoding stringEncoding;
+@property (nonatomic, strong) NSDictionary *headers;
+@property (nonatomic, copy) NSString *boundary;
+@property (nonatomic, strong) id body;
+@property (nonatomic, assign) unsigned long long bodyContentLength;
+@property (nonatomic, strong) NSInputStream *inputStream;
+
+@property (nonatomic, assign) BOOL hasInitialBoundary;
+@property (nonatomic, assign) BOOL hasFinalBoundary;
+
+@property (readonly, nonatomic, assign, getter = hasBytesAvailable) BOOL bytesAvailable;
+@property (readonly, nonatomic, assign) unsigned long long contentLength;
+
+- (NSInteger)read:(uint8_t *)buffer
+        maxLength:(NSUInteger)length;
+@end
+
+@interface AFMultipartBodyStream : NSInputStream <NSStreamDelegate>
+@property (nonatomic, assign) NSUInteger numberOfBytesInPacket;
+@property (nonatomic, assign) NSTimeInterval delay;
+@property (nonatomic, strong) NSInputStream *inputStream;
+@property (readonly, nonatomic, assign) unsigned long long contentLength;
+@property (readonly, nonatomic, assign, getter = isEmpty) BOOL empty;
+
+- (instancetype)initWithStringEncoding:(NSStringEncoding)encoding;
+- (void)setInitialAndFinalBoundaries;
+- (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart;
+@end
+
+#pragma mark -
+
+@interface AFStreamingMultipartFormData ()
+@property (readwrite, nonatomic, copy) NSMutableURLRequest *request;
+@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding;
+@property (readwrite, nonatomic, copy) NSString *boundary;
+@property (readwrite, nonatomic, strong) AFMultipartBodyStream *bodyStream;
+@end
+
+@implementation AFStreamingMultipartFormData
+
+- (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest
+                    stringEncoding:(NSStringEncoding)encoding
+{
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    self.request = urlRequest;
+    self.stringEncoding = encoding;
+    self.boundary = AFCreateMultipartFormBoundary();
+    self.bodyStream = [[AFMultipartBodyStream alloc] initWithStringEncoding:encoding];
+
+    return self;
+}
+
+- (void)setRequest:(NSMutableURLRequest *)request
+{
+    _request = [request mutableCopy];
+}
+
+- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
+                         name:(NSString *)name
+                        error:(NSError * __autoreleasing *)error
+{
+    NSParameterAssert(fileURL);
+    NSParameterAssert(name);
+
+    NSString *fileName = [fileURL lastPathComponent];
+    NSString *mimeType = AFContentTypeForPathExtension([fileURL pathExtension]);
+
+    return [self appendPartWithFileURL:fileURL name:name fileName:fileName mimeType:mimeType error:error];
+}
+
+- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
+                         name:(NSString *)name
+                     fileName:(NSString *)fileName
+                     mimeType:(NSString *)mimeType
+                        error:(NSError * __autoreleasing *)error
+{
+    NSParameterAssert(fileURL);
+    NSParameterAssert(name);
+    NSParameterAssert(fileName);
+    NSParameterAssert(mimeType);
+
+    if (![fileURL isFileURL]) {
+        NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"Expected URL to be a file URL", @"AFNetworking", nil)};
+        if (error) {
+            *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo];
+        }
+
+        return NO;
+    } else if ([fileURL checkResourceIsReachableAndReturnError:error] == NO) {
+        NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"File URL not reachable.", @"AFNetworking", nil)};
+        if (error) {
+            *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo];
+        }
+
+        return NO;
+    }
+
+    NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[fileURL path] error:error];
+    if (!fileAttributes) {
+        return NO;
+    }
+
+    NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
+    [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
+    [mutableHeaders setValue:mimeType forKey:@"Content-Type"];
+
+    AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init];
+    bodyPart.stringEncoding = self.stringEncoding;
+    bodyPart.headers = mutableHeaders;
+    bodyPart.boundary = self.boundary;
+    bodyPart.body = fileURL;
+    bodyPart.bodyContentLength = [fileAttributes[NSFileSize] unsignedLongLongValue];
+    [self.bodyStream appendHTTPBodyPart:bodyPart];
+
+    return YES;
+}
+
+- (void)appendPartWithInputStream:(NSInputStream *)inputStream
+                             name:(NSString *)name
+                         fileName:(NSString *)fileName
+                           length:(int64_t)length
+                         mimeType:(NSString *)mimeType
+{
+    NSParameterAssert(name);
+    NSParameterAssert(fileName);
+    NSParameterAssert(mimeType);
+
+    NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
+    [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
+    [mutableHeaders setValue:mimeType forKey:@"Content-Type"];
+
+    AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init];
+    bodyPart.stringEncoding = self.stringEncoding;
+    bodyPart.headers = mutableHeaders;
+    bodyPart.boundary = self.boundary;
+    bodyPart.body = inputStream;
+
+    bodyPart.bodyContentLength = (unsigned long long)length;
+
+    [self.bodyStream appendHTTPBodyPart:bodyPart];
+}
+
+- (void)appendPartWithFileData:(NSData *)data
+                          name:(NSString *)name
+                      fileName:(NSString *)fileName
+                      mimeType:(NSString *)mimeType
+{
+    NSParameterAssert(name);
+    NSParameterAssert(fileName);
+    NSParameterAssert(mimeType);
+
+    NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
+    [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
+    [mutableHeaders setValue:mimeType forKey:@"Content-Type"];
+
+    [self appendPartWithHeaders:mutableHeaders body:data];
+}
+
+- (void)appendPartWithFormData:(NSData *)data
+                          name:(NSString *)name
+{
+    NSParameterAssert(name);
+
+    NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
+    [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"", name] forKey:@"Content-Disposition"];
+
+    [self appendPartWithHeaders:mutableHeaders body:data];
+}
+
+- (void)appendPartWithHeaders:(NSDictionary *)headers
+                         body:(NSData *)body
+{
+    NSParameterAssert(body);
+
+    AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init];
+    bodyPart.stringEncoding = self.stringEncoding;
+    bodyPart.headers = headers;
+    bodyPart.boundary = self.boundary;
+    bodyPart.bodyContentLength = [body length];
+    bodyPart.body = body;
+
+    [self.bodyStream appendHTTPBodyPart:bodyPart];
+}
+
+- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes
+                                  delay:(NSTimeInterval)delay
+{
+    self.bodyStream.numberOfBytesInPacket = numberOfBytes;
+    self.bodyStream.delay = delay;
+}
+
+- (NSMutableURLRequest *)requestByFinalizingMultipartFormData {
+    if ([self.bodyStream isEmpty]) {
+        return self.request;
+    }
+
+    // Reset the initial and final boundaries to ensure correct Content-Length
+    [self.bodyStream setInitialAndFinalBoundaries];
+    [self.request setHTTPBodyStream:self.bodyStream];
+
+    [self.request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", self.boundary] forHTTPHeaderField:@"Content-Type"];
+    [self.request setValue:[NSString stringWithFormat:@"%llu", [self.bodyStream contentLength]] forHTTPHeaderField:@"Content-Length"];
+
+    return self.request;
+}
+
+@end
+
+#pragma mark -
+
+@interface NSStream ()
+@property (readwrite) NSStreamStatus streamStatus;
+@property (readwrite, copy) NSError *streamError;
+@end
+
+@interface AFMultipartBodyStream () <NSCopying>
+@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding;
+@property (readwrite, nonatomic, strong) NSMutableArray *HTTPBodyParts;
+@property (readwrite, nonatomic, strong) NSEnumerator *HTTPBodyPartEnumerator;
+@property (readwrite, nonatomic, strong) AFHTTPBodyPart *currentHTTPBodyPart;
+@property (readwrite, nonatomic, strong) NSOutputStream *outputStream;
+@property (readwrite, nonatomic, strong) NSMutableData *buffer;
+@end
+
+@implementation AFMultipartBodyStream
+#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)
+@synthesize delegate;
+#endif
+@synthesize streamStatus;
+@synthesize streamError;
+
+- (instancetype)initWithStringEncoding:(NSStringEncoding)encoding {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    self.stringEncoding = encoding;
+    self.HTTPBodyParts = [NSMutableArray array];
+    self.numberOfBytesInPacket = NSIntegerMax;
+
+    return self;
+}
+
+- (void)setInitialAndFinalBoundaries {
+    if ([self.HTTPBodyParts count] > 0) {
+        for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
+            bodyPart.hasInitialBoundary = NO;
+            bodyPart.hasFinalBoundary = NO;
+        }
+
+        [[self.HTTPBodyParts firstObject] setHasInitialBoundary:YES];
+        [[self.HTTPBodyParts lastObject] setHasFinalBoundary:YES];
+    }
+}
+
+- (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart {
+    [self.HTTPBodyParts addObject:bodyPart];
+}
+
+- (BOOL)isEmpty {
+    return [self.HTTPBodyParts count] == 0;
+}
+
+#pragma mark - NSInputStream
+
+- (NSInteger)read:(uint8_t *)buffer
+        maxLength:(NSUInteger)length
+{
+    if ([self streamStatus] == NSStreamStatusClosed) {
+        return 0;
+    }
+
+    NSInteger totalNumberOfBytesRead = 0;
+
+    while ((NSUInteger)totalNumberOfBytesRead < MIN(length, self.numberOfBytesInPacket)) {
+        if (!self.currentHTTPBodyPart || ![self.currentHTTPBodyPart hasBytesAvailable]) {
+            if (!(self.currentHTTPBodyPart = [self.HTTPBodyPartEnumerator nextObject])) {
+                break;
+            }
+        } else {
+            NSUInteger maxLength = MIN(length, self.numberOfBytesInPacket) - (NSUInteger)totalNumberOfBytesRead;
+            NSInteger numberOfBytesRead = [self.currentHTTPBodyPart read:&buffer[totalNumberOfBytesRead] maxLength:maxLength];
+            if (numberOfBytesRead == -1) {
+                self.streamError = self.currentHTTPBodyPart.inputStream.streamError;
+                break;
+            } else {
+                totalNumberOfBytesRead += numberOfBytesRead;
+
+                if (self.delay > 0.0f) {
+                    [NSThread sleepForTimeInterval:self.delay];
+                }
+            }
+        }
+    }
+
+    return totalNumberOfBytesRead;
+}
+
+- (BOOL)getBuffer:(__unused uint8_t **)buffer
+           length:(__unused NSUInteger *)len
+{
+    return NO;
+}
+
+- (BOOL)hasBytesAvailable {
+    return [self streamStatus] == NSStreamStatusOpen;
+}
+
+#pragma mark - NSStream
+
+- (void)open {
+    if (self.streamStatus == NSStreamStatusOpen) {
+        return;
+    }
+
+    self.streamStatus = NSStreamStatusOpen;
+
+    [self setInitialAndFinalBoundaries];
+    self.HTTPBodyPartEnumerator = [self.HTTPBodyParts objectEnumerator];
+}
+
+- (void)close {
+    self.streamStatus = NSStreamStatusClosed;
+}
+
+- (id)propertyForKey:(__unused NSString *)key {
+    return nil;
+}
+
+- (BOOL)setProperty:(__unused id)property
+             forKey:(__unused NSString *)key
+{
+    return NO;
+}
+
+- (void)scheduleInRunLoop:(__unused NSRunLoop *)aRunLoop
+                  forMode:(__unused NSString *)mode
+{}
+
+- (void)removeFromRunLoop:(__unused NSRunLoop *)aRunLoop
+                  forMode:(__unused NSString *)mode
+{}
+
+- (unsigned long long)contentLength {
+    unsigned long long length = 0;
+    for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
+        length += [bodyPart contentLength];
+    }
+
+    return length;
+}
+
+#pragma mark - Undocumented CFReadStream Bridged Methods
+
+- (void)_scheduleInCFRunLoop:(__unused CFRunLoopRef)aRunLoop
+                     forMode:(__unused CFStringRef)aMode
+{}
+
+- (void)_unscheduleFromCFRunLoop:(__unused CFRunLoopRef)aRunLoop
+                         forMode:(__unused CFStringRef)aMode
+{}
+
+- (BOOL)_setCFClientFlags:(__unused CFOptionFlags)inFlags
+                 callback:(__unused CFReadStreamClientCallBack)inCallback
+                  context:(__unused CFStreamClientContext *)inContext {
+    return NO;
+}
+
+#pragma mark - NSCopying
+
+- (instancetype)copyWithZone:(NSZone *)zone {
+    AFMultipartBodyStream *bodyStreamCopy = [[[self class] allocWithZone:zone] initWithStringEncoding:self.stringEncoding];
+
+    for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
+        [bodyStreamCopy appendHTTPBodyPart:[bodyPart copy]];
+    }
+
+    [bodyStreamCopy setInitialAndFinalBoundaries];
+
+    return bodyStreamCopy;
+}
+
+@end
+
+#pragma mark -
+
+typedef enum {
+    AFEncapsulationBoundaryPhase = 1,
+    AFHeaderPhase                = 2,
+    AFBodyPhase                  = 3,
+    AFFinalBoundaryPhase         = 4,
+} AFHTTPBodyPartReadPhase;
+
+@interface AFHTTPBodyPart () <NSCopying> {
+    AFHTTPBodyPartReadPhase _phase;
+    NSInputStream *_inputStream;
+    unsigned long long _phaseReadOffset;
+}
+
+- (BOOL)transitionToNextPhase;
+- (NSInteger)readData:(NSData *)data
+           intoBuffer:(uint8_t *)buffer
+            maxLength:(NSUInteger)length;
+@end
+
+@implementation AFHTTPBodyPart
+
+- (instancetype)init {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    [self transitionToNextPhase];
+
+    return self;
+}
+
+- (void)dealloc {
+    if (_inputStream) {
+        [_inputStream close];
+        _inputStream = nil;
+    }
+}
+
+- (NSInputStream *)inputStream {
+    if (!_inputStream) {
+        if ([self.body isKindOfClass:[NSData class]]) {
+            _inputStream = [NSInputStream inputStreamWithData:self.body];
+        } else if ([self.body isKindOfClass:[NSURL class]]) {
+            _inputStream = [NSInputStream inputStreamWithURL:self.body];
+        } else if ([self.body isKindOfClass:[NSInputStream class]]) {
+            _inputStream = self.body;
+        } else {
+            _inputStream = [NSInputStream inputStreamWithData:[NSData data]];
+        }
+    }
+
+    return _inputStream;
+}
+
+- (NSString *)stringForHeaders {
+    NSMutableString *headerString = [NSMutableString string];
+    for (NSString *field in [self.headers allKeys]) {
+        [headerString appendString:[NSString stringWithFormat:@"%@: %@%@", field, [self.headers valueForKey:field], kAFMultipartFormCRLF]];
+    }
+    [headerString appendString:kAFMultipartFormCRLF];
+
+    return [NSString stringWithString:headerString];
+}
+
+- (unsigned long long)contentLength {
+    unsigned long long length = 0;
+
+    NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary(self.boundary) : AFMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding];
+    length += [encapsulationBoundaryData length];
+
+    NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding];
+    length += [headersData length];
+
+    length += _bodyContentLength;
+
+    NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]);
+    length += [closingBoundaryData length];
+
+    return length;
+}
+
+- (BOOL)hasBytesAvailable {
+    // Allows `read:maxLength:` to be called again if `AFMultipartFormFinalBoundary` doesn't fit into the available buffer
+    if (_phase == AFFinalBoundaryPhase) {
+        return YES;
+    }
+
+    switch (self.inputStream.streamStatus) {
+        case NSStreamStatusNotOpen:
+        case NSStreamStatusOpening:
+        case NSStreamStatusOpen:
+        case NSStreamStatusReading:
+        case NSStreamStatusWriting:
+            return YES;
+        case NSStreamStatusAtEnd:
+        case NSStreamStatusClosed:
+        case NSStreamStatusError:
+        default:
+            return NO;
+    }
+}
+
+- (NSInteger)read:(uint8_t *)buffer
+        maxLength:(NSUInteger)length
+{
+    NSInteger totalNumberOfBytesRead = 0;
+
+    if (_phase == AFEncapsulationBoundaryPhase) {
+        NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary(self.boundary) : AFMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding];
+        totalNumberOfBytesRead += [self readData:encapsulationBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
+    }
+
+    if (_phase == AFHeaderPhase) {
+        NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding];
+        totalNumberOfBytesRead += [self readData:headersData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
+    }
+
+    if (_phase == AFBodyPhase) {
+        NSInteger numberOfBytesRead = 0;
+
+        numberOfBytesRead = [self.inputStream read:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
+        if (numberOfBytesRead == -1) {
+            return -1;
+        } else {
+            totalNumberOfBytesRead += numberOfBytesRead;
+
+            if ([self.inputStream streamStatus] >= NSStreamStatusAtEnd) {
+                [self transitionToNextPhase];
+            }
+        }
+    }
+
+    if (_phase == AFFinalBoundaryPhase) {
+        NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]);
+        totalNumberOfBytesRead += [self readData:closingBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
+    }
+
+    return totalNumberOfBytesRead;
+}
+
+- (NSInteger)readData:(NSData *)data
+           intoBuffer:(uint8_t *)buffer
+            maxLength:(NSUInteger)length
+{
+    NSRange range = NSMakeRange((NSUInteger)_phaseReadOffset, MIN([data length] - ((NSUInteger)_phaseReadOffset), length));
+    [data getBytes:buffer range:range];
+
+    _phaseReadOffset += range.length;
+
+    if (((NSUInteger)_phaseReadOffset) >= [data length]) {
+        [self transitionToNextPhase];
+    }
+
+    return (NSInteger)range.length;
+}
+
+- (BOOL)transitionToNextPhase {
+    if (![[NSThread currentThread] isMainThread]) {
+        dispatch_sync(dispatch_get_main_queue(), ^{
+            [self transitionToNextPhase];
+        });
+        return YES;
+    }
+
+    switch (_phase) {
+        case AFEncapsulationBoundaryPhase:
+            _phase = AFHeaderPhase;
+            break;
+        case AFHeaderPhase:
+            [self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
+            [self.inputStream open];
+            _phase = AFBodyPhase;
+            break;
+        case AFBodyPhase:
+            [self.inputStream close];
+            _phase = AFFinalBoundaryPhase;
+            break;
+        case AFFinalBoundaryPhase:
+        default:
+            _phase = AFEncapsulationBoundaryPhase;
+            break;
+    }
+    _phaseReadOffset = 0;
+
+    return YES;
+}
+
+#pragma mark - NSCopying
+
+- (instancetype)copyWithZone:(NSZone *)zone {
+    AFHTTPBodyPart *bodyPart = [[[self class] allocWithZone:zone] init];
+
+    bodyPart.stringEncoding = self.stringEncoding;
+    bodyPart.headers = self.headers;
+    bodyPart.bodyContentLength = self.bodyContentLength;
+    bodyPart.body = self.body;
+    bodyPart.boundary = self.boundary;
+
+    return bodyPart;
+}
+
+@end
+
+#pragma mark -
+
+@implementation AFJSONRequestSerializer
+
++ (instancetype)serializer {
+    return [self serializerWithWritingOptions:(NSJSONWritingOptions)0];
+}
+
++ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions
+{
+    AFJSONRequestSerializer *serializer = [[self alloc] init];
+    serializer.writingOptions = writingOptions;
+
+    return serializer;
+}
+
+#pragma mark - AFURLRequestSerialization
+
+- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
+                               withParameters:(id)parameters
+                                        error:(NSError *__autoreleasing *)error
+{
+    NSParameterAssert(request);
+
+    if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
+        return [super requestBySerializingRequest:request withParameters:parameters error:error];
+    }
+
+    NSMutableURLRequest *mutableRequest = [request mutableCopy];
+
+    [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
+        if (![request valueForHTTPHeaderField:field]) {
+            [mutableRequest setValue:value forHTTPHeaderField:field];
+        }
+    }];
+
+    if (parameters) {
+        if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
+            [mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
+        }
+
+        if (![NSJSONSerialization isValidJSONObject:parameters]) {
+            if (error) {
+                NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"The `parameters` argument is not valid JSON.", @"AFNetworking", nil)};
+                *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo];
+            }
+            return nil;
+        }
+
+        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error];
+        
+        if (!jsonData) {
+            return nil;
+        }
+        
+        [mutableRequest setHTTPBody:jsonData];
+    }
+
+    return mutableRequest;
+}
+
+#pragma mark - NSSecureCoding
+
+- (instancetype)initWithCoder:(NSCoder *)decoder {
+    self = [super initWithCoder:decoder];
+    if (!self) {
+        return nil;
+    }
+
+    self.writingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writingOptions))] unsignedIntegerValue];
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)coder {
+    [super encodeWithCoder:coder];
+
+    [coder encodeObject:@(self.writingOptions) forKey:NSStringFromSelector(@selector(writingOptions))];
+}
+
+#pragma mark - NSCopying
+
+- (instancetype)copyWithZone:(NSZone *)zone {
+    AFJSONRequestSerializer *serializer = [super copyWithZone:zone];
+    serializer.writingOptions = self.writingOptions;
+
+    return serializer;
+}
+
+@end
+
+#pragma mark -
+
+@implementation AFPropertyListRequestSerializer
+
++ (instancetype)serializer {
+    return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 writeOptions:0];
+}
+
++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
+                        writeOptions:(NSPropertyListWriteOptions)writeOptions
+{
+    AFPropertyListRequestSerializer *serializer = [[self alloc] init];
+    serializer.format = format;
+    serializer.writeOptions = writeOptions;
+
+    return serializer;
+}
+
+#pragma mark - AFURLRequestSerializer
+
+- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
+                               withParameters:(id)parameters
+                                        error:(NSError *__autoreleasing *)error
+{
+    NSParameterAssert(request);
+
+    if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
+        return [super requestBySerializingRequest:request withParameters:parameters error:error];
+    }
+
+    NSMutableURLRequest *mutableRequest = [request mutableCopy];
+
+    [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
+        if (![request valueForHTTPHeaderField:field]) {
+            [mutableRequest setValue:value forHTTPHeaderField:field];
+        }
+    }];
+
+    if (parameters) {
+        if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
+            [mutableRequest setValue:@"application/x-plist" forHTTPHeaderField:@"Content-Type"];
+        }
+
+        NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:parameters format:self.format options:self.writeOptions error:error];
+        
+        if (!plistData) {
+            return nil;
+        }
+        
+        [mutableRequest setHTTPBody:plistData];
+    }
+
+    return mutableRequest;
+}
+
+#pragma mark - NSSecureCoding
+
+- (instancetype)initWithCoder:(NSCoder *)decoder {
+    self = [super initWithCoder:decoder];
+    if (!self) {
+        return nil;
+    }
+
+    self.format = (NSPropertyListFormat)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue];
+    self.writeOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writeOptions))] unsignedIntegerValue];
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)coder {
+    [super encodeWithCoder:coder];
+
+    [coder encodeObject:@(self.format) forKey:NSStringFromSelector(@selector(format))];
+    [coder encodeObject:@(self.writeOptions) forKey:NSStringFromSelector(@selector(writeOptions))];
+}
+
+#pragma mark - NSCopying
+
+- (instancetype)copyWithZone:(NSZone *)zone {
+    AFPropertyListRequestSerializer *serializer = [super copyWithZone:zone];
+    serializer.format = self.format;
+    serializer.writeOptions = self.writeOptions;
+
+    return serializer;
+}
+
+@end

+ 313 - 0
Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.h

@@ -0,0 +1,313 @@
+// AFURLResponseSerialization.h
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <Foundation/Foundation.h>
+#import <CoreGraphics/CoreGraphics.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ Recursively removes `NSNull` values from a JSON object.
+*/
+FOUNDATION_EXPORT id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions);
+
+/**
+ 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.
+
+ 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.
+ */
+@protocol AFURLResponseSerialization <NSObject, NSSecureCoding, NSCopying>
+
+/**
+ The response object decoded from the data associated with a specified response.
+
+ @param response The response to be processed.
+ @param data The response data to be decoded.
+ @param error The error that occurred while attempting to decode the response data.
+
+ @return The object decoded from the specified response data.
+ */
+- (nullable id)responseObjectForResponse:(nullable NSURLResponse *)response
+                           data:(nullable NSData *)data
+                          error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW;
+
+@end
+
+#pragma mark -
+
+/**
+ `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.
+
+ Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPResponseSerializer` in order to ensure consistent default behavior.
+ */
+@interface AFHTTPResponseSerializer : NSObject <AFURLResponseSerialization>
+
+- (instancetype)init;
+
+/**
+ Creates and returns a serializer with default configuration.
+ */
++ (instancetype)serializer;
+
+///-----------------------------------------
+/// @name Configuring Response Serialization
+///-----------------------------------------
+
+/**
+ 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.
+
+ See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
+ */
+@property (nonatomic, copy, nullable) NSIndexSet *acceptableStatusCodes;
+
+/**
+ 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.
+ */
+@property (nonatomic, copy, nullable) NSSet <NSString *> *acceptableContentTypes;
+
+/**
+ Validates the specified response and data.
+
+ In its base implementation, this method checks for an acceptable status code and content type. Subclasses may wish to add other domain-specific checks.
+
+ @param response The response to be validated.
+ @param data The data associated with the response.
+ @param error The error that occurred while attempting to validate the response.
+
+ @return `YES` if the response is valid, otherwise `NO`.
+ */
+- (BOOL)validateResponse:(nullable NSHTTPURLResponse *)response
+                    data:(nullable NSData *)data
+                   error:(NSError * _Nullable __autoreleasing *)error;
+
+@end
+
+#pragma mark -
+
+
+/**
+ `AFJSONResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes JSON responses.
+
+ By default, `AFJSONResponseSerializer` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types:
+
+ - `application/json`
+ - `text/json`
+ - `text/javascript`
+
+ 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.
+ */
+@interface AFJSONResponseSerializer : AFHTTPResponseSerializer
+
+- (instancetype)init;
+
+/**
+ Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default.
+ */
+@property (nonatomic, assign) NSJSONReadingOptions readingOptions;
+
+/**
+ Whether to remove keys with `NSNull` values from response JSON. Defaults to `NO`.
+ */
+@property (nonatomic, assign) BOOL removesKeysWithNullValues;
+
+/**
+ Creates and returns a JSON serializer with specified reading and writing options.
+
+ @param readingOptions The specified JSON reading options.
+ */
++ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions;
+
+@end
+
+#pragma mark -
+
+/**
+ `AFXMLParserResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLParser` objects.
+
+ By default, `AFXMLParserResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
+
+ - `application/xml`
+ - `text/xml`
+ */
+@interface AFXMLParserResponseSerializer : AFHTTPResponseSerializer
+
+@end
+
+#pragma mark -
+
+#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
+
+/**
+ `AFXMLDocumentResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects.
+
+ By default, `AFXMLDocumentResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
+
+ - `application/xml`
+ - `text/xml`
+ */
+@interface AFXMLDocumentResponseSerializer : AFHTTPResponseSerializer
+
+- (instancetype)init;
+
+/**
+ Input and output options specifically intended for `NSXMLDocument` objects. For possible values, see the `NSXMLDocument` documentation section "Input and Output Options". `0` by default.
+ */
+@property (nonatomic, assign) NSUInteger options;
+
+/**
+ Creates and returns an XML document serializer with the specified options.
+
+ @param mask The XML document options.
+ */
++ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask;
+
+@end
+
+#endif
+
+#pragma mark -
+
+/**
+ `AFPropertyListResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects.
+
+ By default, `AFPropertyListResponseSerializer` accepts the following MIME types:
+
+ - `application/x-plist`
+ */
+@interface AFPropertyListResponseSerializer : AFHTTPResponseSerializer
+
+- (instancetype)init;
+
+/**
+ The property list format. Possible values are described in "NSPropertyListFormat".
+ */
+@property (nonatomic, assign) NSPropertyListFormat format;
+
+/**
+ The property list reading options. Possible values are described in "NSPropertyListMutabilityOptions."
+ */
+@property (nonatomic, assign) NSPropertyListReadOptions readOptions;
+
+/**
+ Creates and returns a property list serializer with a specified format, read options, and write options.
+
+ @param format The property list format.
+ @param readOptions The property list reading options.
+ */
++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
+                         readOptions:(NSPropertyListReadOptions)readOptions;
+
+@end
+
+#pragma mark -
+
+/**
+ `AFImageResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes image responses.
+
+ By default, `AFImageResponseSerializer` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage:
+
+ - `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`
+ */
+@interface AFImageResponseSerializer : AFHTTPResponseSerializer
+
+#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
+/**
+ 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.
+ */
+@property (nonatomic, assign) CGFloat imageScale;
+
+/**
+ 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.
+ */
+@property (nonatomic, assign) BOOL automaticallyInflatesResponseImage;
+#endif
+
+@end
+
+#pragma mark -
+
+/**
+ `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.
+ */
+@interface AFCompoundResponseSerializer : AFHTTPResponseSerializer
+
+/**
+ The component response serializers.
+ */
+@property (readonly, nonatomic, copy) NSArray <id<AFURLResponseSerialization>> *responseSerializers;
+
+/**
+ Creates and returns a compound serializer comprised of the specified response serializers.
+
+ @warning Each response serializer specified must be a subclass of `AFHTTPResponseSerializer`, and response to `-validateResponse:data:error:`.
+ */
++ (instancetype)compoundSerializerWithResponseSerializers:(NSArray <id<AFURLResponseSerialization>> *)responseSerializers;
+
+@end
+
+///----------------
+/// @name Constants
+///----------------
+
+/**
+ ## Error Domains
+
+ The following error domain is predefined.
+
+ - `NSString * const AFURLResponseSerializationErrorDomain`
+
+ ### Constants
+
+ `AFURLResponseSerializationErrorDomain`
+ AFURLResponseSerializer errors. Error codes for `AFURLResponseSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`.
+ */
+FOUNDATION_EXPORT NSString * const AFURLResponseSerializationErrorDomain;
+
+/**
+ ## User info dictionary keys
+
+ These keys may exist in the user info dictionary, in addition to those defined for NSError.
+
+ - `NSString * const AFNetworkingOperationFailingURLResponseErrorKey`
+ - `NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey`
+
+ ### Constants
+
+ `AFNetworkingOperationFailingURLResponseErrorKey`
+ The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`.
+
+ `AFNetworkingOperationFailingURLResponseDataErrorKey`
+ 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`.
+ */
+FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseErrorKey;
+
+FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey;
+
+NS_ASSUME_NONNULL_END

+ 836 - 0
Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.m

@@ -0,0 +1,836 @@
+// AFURLResponseSerialization.m
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import "AFURLResponseSerialization.h"
+
+#import <TargetConditionals.h>
+
+#if TARGET_OS_IOS
+#import <UIKit/UIKit.h>
+#elif TARGET_OS_WATCH
+#import <WatchKit/WatchKit.h>
+#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
+#import <Cocoa/Cocoa.h>
+#endif
+
+NSString * const AFURLResponseSerializationErrorDomain = @"com.alamofire.error.serialization.response";
+NSString * const AFNetworkingOperationFailingURLResponseErrorKey = @"com.alamofire.serialization.response.error.response";
+NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey = @"com.alamofire.serialization.response.error.data";
+
+static NSError * AFErrorWithUnderlyingError(NSError *error, NSError *underlyingError) {
+    if (!error) {
+        return underlyingError;
+    }
+
+    if (!underlyingError || error.userInfo[NSUnderlyingErrorKey]) {
+        return error;
+    }
+
+    NSMutableDictionary *mutableUserInfo = [error.userInfo mutableCopy];
+    mutableUserInfo[NSUnderlyingErrorKey] = underlyingError;
+
+    return [[NSError alloc] initWithDomain:error.domain code:error.code userInfo:mutableUserInfo];
+}
+
+static BOOL AFErrorOrUnderlyingErrorHasCodeInDomain(NSError *error, NSInteger code, NSString *domain) {
+    if ([error.domain isEqualToString:domain] && error.code == code) {
+        return YES;
+    } else if (error.userInfo[NSUnderlyingErrorKey]) {
+        return AFErrorOrUnderlyingErrorHasCodeInDomain(error.userInfo[NSUnderlyingErrorKey], code, domain);
+    }
+
+    return NO;
+}
+
+id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions) {
+    if ([JSONObject isKindOfClass:[NSArray class]]) {
+        NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[(NSArray *)JSONObject count]];
+        for (id value in (NSArray *)JSONObject) {
+            if (![value isEqual:[NSNull null]]) {
+                [mutableArray addObject:AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions)];
+            }
+        }
+
+        return (readingOptions & NSJSONReadingMutableContainers) ? mutableArray : [NSArray arrayWithArray:mutableArray];
+    } else if ([JSONObject isKindOfClass:[NSDictionary class]]) {
+        NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:JSONObject];
+        for (id <NSCopying> key in [(NSDictionary *)JSONObject allKeys]) {
+            id value = (NSDictionary *)JSONObject[key];
+            if (!value || [value isEqual:[NSNull null]]) {
+                [mutableDictionary removeObjectForKey:key];
+            } else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) {
+                mutableDictionary[key] = AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions);
+            }
+        }
+
+        return (readingOptions & NSJSONReadingMutableContainers) ? mutableDictionary : [NSDictionary dictionaryWithDictionary:mutableDictionary];
+    }
+
+    return JSONObject;
+}
+
+@implementation AFHTTPResponseSerializer
+
++ (instancetype)serializer {
+    return [[self alloc] init];
+}
+
+- (instancetype)init {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
+    self.acceptableContentTypes = nil;
+
+    return self;
+}
+
+#pragma mark -
+
+- (BOOL)validateResponse:(NSHTTPURLResponse *)response
+                    data:(NSData *)data
+                   error:(NSError * __autoreleasing *)error
+{
+    BOOL responseIsValid = YES;
+    NSError *validationError = nil;
+
+    if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
+        if (self.acceptableContentTypes && ![self.acceptableContentTypes containsObject:[response MIMEType]] &&
+            !([response MIMEType] == nil && [data length] == 0)) {
+
+            if ([data length] > 0 && [response URL]) {
+                NSMutableDictionary *mutableUserInfo = [@{
+                                                          NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: unacceptable content-type: %@", @"AFNetworking", nil), [response MIMEType]],
+                                                          NSURLErrorFailingURLErrorKey:[response URL],
+                                                          AFNetworkingOperationFailingURLResponseErrorKey: response,
+                                                        } mutableCopy];
+                if (data) {
+                    mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
+                }
+
+                validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:mutableUserInfo], validationError);
+            }
+
+            responseIsValid = NO;
+        }
+
+        if (self.acceptableStatusCodes && ![self.acceptableStatusCodes containsIndex:(NSUInteger)response.statusCode] && [response URL]) {
+            NSMutableDictionary *mutableUserInfo = [@{
+                                               NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%ld)", @"AFNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (long)response.statusCode],
+                                               NSURLErrorFailingURLErrorKey:[response URL],
+                                               AFNetworkingOperationFailingURLResponseErrorKey: response,
+                                       } mutableCopy];
+
+            if (data) {
+                mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
+            }
+
+            validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo], validationError);
+
+            responseIsValid = NO;
+        }
+    }
+
+    if (error && !responseIsValid) {
+        *error = validationError;
+    }
+
+    return responseIsValid;
+}
+
+#pragma mark - AFURLResponseSerialization
+
+- (id)responseObjectForResponse:(NSURLResponse *)response
+                           data:(NSData *)data
+                          error:(NSError *__autoreleasing *)error
+{
+    [self validateResponse:(NSHTTPURLResponse *)response data:data error:error];
+
+    return data;
+}
+
+#pragma mark - NSSecureCoding
+
++ (BOOL)supportsSecureCoding {
+    return YES;
+}
+
+- (instancetype)initWithCoder:(NSCoder *)decoder {
+    self = [self init];
+    if (!self) {
+        return nil;
+    }
+
+    self.acceptableStatusCodes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableStatusCodes))];
+    self.acceptableContentTypes = [decoder decodeObjectOfClass:[NSSet class] forKey:NSStringFromSelector(@selector(acceptableContentTypes))];
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)coder {
+    [coder encodeObject:self.acceptableStatusCodes forKey:NSStringFromSelector(@selector(acceptableStatusCodes))];
+    [coder encodeObject:self.acceptableContentTypes forKey:NSStringFromSelector(@selector(acceptableContentTypes))];
+}
+
+#pragma mark - NSCopying
+
+- (instancetype)copyWithZone:(NSZone *)zone {
+    AFHTTPResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
+    serializer.acceptableStatusCodes = [self.acceptableStatusCodes copyWithZone:zone];
+    serializer.acceptableContentTypes = [self.acceptableContentTypes copyWithZone:zone];
+
+    return serializer;
+}
+
+@end
+
+#pragma mark -
+
+@implementation AFJSONResponseSerializer
+
++ (instancetype)serializer {
+    return [self serializerWithReadingOptions:(NSJSONReadingOptions)0];
+}
+
++ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions {
+    AFJSONResponseSerializer *serializer = [[self alloc] init];
+    serializer.readingOptions = readingOptions;
+
+    return serializer;
+}
+
+- (instancetype)init {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
+
+    return self;
+}
+
+#pragma mark - AFURLResponseSerialization
+
+- (id)responseObjectForResponse:(NSURLResponse *)response
+                           data:(NSData *)data
+                          error:(NSError *__autoreleasing *)error
+{
+    if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
+        if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
+            return nil;
+        }
+    }
+
+    // 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.
+    // See https://github.com/rails/rails/issues/1742
+    BOOL isSpace = [data isEqualToData:[NSData dataWithBytes:" " length:1]];
+    
+    if (data.length == 0 || isSpace) {
+        return nil;
+    }
+    
+    NSError *serializationError = nil;
+    
+    id responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError];
+
+    if (!responseObject)
+    {
+        if (error) {
+            *error = AFErrorWithUnderlyingError(serializationError, *error);
+        }
+        return nil;
+    }
+    
+    if (self.removesKeysWithNullValues) {
+        return AFJSONObjectByRemovingKeysWithNullValues(responseObject, self.readingOptions);
+    }
+
+    return responseObject;
+}
+
+#pragma mark - NSSecureCoding
+
++ (BOOL)supportsSecureCoding {
+    return YES;
+}
+
+- (instancetype)initWithCoder:(NSCoder *)decoder {
+    self = [super initWithCoder:decoder];
+    if (!self) {
+        return nil;
+    }
+
+    self.readingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readingOptions))] unsignedIntegerValue];
+    self.removesKeysWithNullValues = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))] boolValue];
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)coder {
+    [super encodeWithCoder:coder];
+
+    [coder encodeObject:@(self.readingOptions) forKey:NSStringFromSelector(@selector(readingOptions))];
+    [coder encodeObject:@(self.removesKeysWithNullValues) forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))];
+}
+
+#pragma mark - NSCopying
+
+- (instancetype)copyWithZone:(NSZone *)zone {
+    AFJSONResponseSerializer *serializer = [super copyWithZone:zone];
+    serializer.readingOptions = self.readingOptions;
+    serializer.removesKeysWithNullValues = self.removesKeysWithNullValues;
+
+    return serializer;
+}
+
+@end
+
+#pragma mark -
+
+@implementation AFXMLParserResponseSerializer
+
++ (instancetype)serializer {
+    AFXMLParserResponseSerializer *serializer = [[self alloc] init];
+
+    return serializer;
+}
+
+- (instancetype)init {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil];
+
+    return self;
+}
+
+#pragma mark - AFURLResponseSerialization
+
+- (id)responseObjectForResponse:(NSHTTPURLResponse *)response
+                           data:(NSData *)data
+                          error:(NSError *__autoreleasing *)error
+{
+    if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
+        if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
+            return nil;
+        }
+    }
+
+    return [[NSXMLParser alloc] initWithData:data];
+}
+
+@end
+
+#pragma mark -
+
+#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
+
+@implementation AFXMLDocumentResponseSerializer
+
++ (instancetype)serializer {
+    return [self serializerWithXMLDocumentOptions:0];
+}
+
++ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask {
+    AFXMLDocumentResponseSerializer *serializer = [[self alloc] init];
+    serializer.options = mask;
+
+    return serializer;
+}
+
+- (instancetype)init {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil];
+
+    return self;
+}
+
+#pragma mark - AFURLResponseSerialization
+
+- (id)responseObjectForResponse:(NSURLResponse *)response
+                           data:(NSData *)data
+                          error:(NSError *__autoreleasing *)error
+{
+    if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
+        if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
+            return nil;
+        }
+    }
+
+    NSError *serializationError = nil;
+    NSXMLDocument *document = [[NSXMLDocument alloc] initWithData:data options:self.options error:&serializationError];
+
+    if (!document)
+    {
+        if (error) {
+            *error = AFErrorWithUnderlyingError(serializationError, *error);
+        }
+        return nil;
+    }
+    
+    return document;
+}
+
+#pragma mark - NSSecureCoding
+
+- (instancetype)initWithCoder:(NSCoder *)decoder {
+    self = [super initWithCoder:decoder];
+    if (!self) {
+        return nil;
+    }
+
+    self.options = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(options))] unsignedIntegerValue];
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)coder {
+    [super encodeWithCoder:coder];
+
+    [coder encodeObject:@(self.options) forKey:NSStringFromSelector(@selector(options))];
+}
+
+#pragma mark - NSCopying
+
+- (instancetype)copyWithZone:(NSZone *)zone {
+    AFXMLDocumentResponseSerializer *serializer = [super copyWithZone:zone];
+    serializer.options = self.options;
+
+    return serializer;
+}
+
+@end
+
+#endif
+
+#pragma mark -
+
+@implementation AFPropertyListResponseSerializer
+
++ (instancetype)serializer {
+    return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 readOptions:0];
+}
+
++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
+                         readOptions:(NSPropertyListReadOptions)readOptions
+{
+    AFPropertyListResponseSerializer *serializer = [[self alloc] init];
+    serializer.format = format;
+    serializer.readOptions = readOptions;
+
+    return serializer;
+}
+
+- (instancetype)init {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/x-plist", nil];
+
+    return self;
+}
+
+#pragma mark - AFURLResponseSerialization
+
+- (id)responseObjectForResponse:(NSURLResponse *)response
+                           data:(NSData *)data
+                          error:(NSError *__autoreleasing *)error
+{
+    if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
+        if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
+            return nil;
+        }
+    }
+
+    if (!data) {
+        return nil;
+    }
+    
+    NSError *serializationError = nil;
+    
+    id responseObject = [NSPropertyListSerialization propertyListWithData:data options:self.readOptions format:NULL error:&serializationError];
+    
+    if (!responseObject)
+    {
+        if (error) {
+            *error = AFErrorWithUnderlyingError(serializationError, *error);
+        }
+        return nil;
+    }
+
+    return responseObject;
+}
+
+#pragma mark - NSSecureCoding
+
++ (BOOL)supportsSecureCoding {
+    return YES;
+}
+
+- (instancetype)initWithCoder:(NSCoder *)decoder {
+    self = [super initWithCoder:decoder];
+    if (!self) {
+        return nil;
+    }
+
+    self.format = (NSPropertyListFormat)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue];
+    self.readOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readOptions))] unsignedIntegerValue];
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)coder {
+    [super encodeWithCoder:coder];
+
+    [coder encodeObject:@(self.format) forKey:NSStringFromSelector(@selector(format))];
+    [coder encodeObject:@(self.readOptions) forKey:NSStringFromSelector(@selector(readOptions))];
+}
+
+#pragma mark - NSCopying
+
+- (instancetype)copyWithZone:(NSZone *)zone {
+    AFPropertyListResponseSerializer *serializer = [super copyWithZone:zone];
+    serializer.format = self.format;
+    serializer.readOptions = self.readOptions;
+
+    return serializer;
+}
+
+@end
+
+#pragma mark -
+
+#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
+#import <CoreGraphics/CoreGraphics.h>
+#import <UIKit/UIKit.h>
+
+@interface UIImage (AFNetworkingSafeImageLoading)
++ (UIImage *)af_safeImageWithData:(NSData *)data;
+@end
+
+static NSLock* imageLock = nil;
+
+@implementation UIImage (AFNetworkingSafeImageLoading)
+
++ (UIImage *)af_safeImageWithData:(NSData *)data {
+    UIImage* image = nil;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        imageLock = [[NSLock alloc] init];
+    });
+    
+    [imageLock lock];
+    image = [UIImage imageWithData:data];
+    [imageLock unlock];
+    return image;
+}
+
+@end
+
+static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) {
+    UIImage *image = [UIImage af_safeImageWithData:data];
+    if (image.images) {
+        return image;
+    }
+    
+    return [[UIImage alloc] initWithCGImage:[image CGImage] scale:scale orientation:image.imageOrientation];
+}
+
+static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *response, NSData *data, CGFloat scale) {
+    if (!data || [data length] == 0) {
+        return nil;
+    }
+
+    CGImageRef imageRef = NULL;
+    CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data);
+
+    if ([response.MIMEType isEqualToString:@"image/png"]) {
+        imageRef = CGImageCreateWithPNGDataProvider(dataProvider,  NULL, true, kCGRenderingIntentDefault);
+    } else if ([response.MIMEType isEqualToString:@"image/jpeg"]) {
+        imageRef = CGImageCreateWithJPEGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault);
+
+        if (imageRef) {
+            CGColorSpaceRef imageColorSpace = CGImageGetColorSpace(imageRef);
+            CGColorSpaceModel imageColorSpaceModel = CGColorSpaceGetModel(imageColorSpace);
+
+            // CGImageCreateWithJPEGDataProvider does not properly handle CMKY, so fall back to AFImageWithDataAtScale
+            if (imageColorSpaceModel == kCGColorSpaceModelCMYK) {
+                CGImageRelease(imageRef);
+                imageRef = NULL;
+            }
+        }
+    }
+
+    CGDataProviderRelease(dataProvider);
+
+    UIImage *image = AFImageWithDataAtScale(data, scale);
+    if (!imageRef) {
+        if (image.images || !image) {
+            return image;
+        }
+
+        imageRef = CGImageCreateCopy([image CGImage]);
+        if (!imageRef) {
+            return nil;
+        }
+    }
+
+    size_t width = CGImageGetWidth(imageRef);
+    size_t height = CGImageGetHeight(imageRef);
+    size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef);
+
+    if (width * height > 1024 * 1024 || bitsPerComponent > 8) {
+        CGImageRelease(imageRef);
+
+        return image;
+    }
+
+    // CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate
+    size_t bytesPerRow = 0;
+    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
+    CGColorSpaceModel colorSpaceModel = CGColorSpaceGetModel(colorSpace);
+    CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
+
+    if (colorSpaceModel == kCGColorSpaceModelRGB) {
+        uint32_t alpha = (bitmapInfo & kCGBitmapAlphaInfoMask);
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wassign-enum"
+        if (alpha == kCGImageAlphaNone) {
+            bitmapInfo &= ~kCGBitmapAlphaInfoMask;
+            bitmapInfo |= kCGImageAlphaNoneSkipFirst;
+        } else if (!(alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast)) {
+            bitmapInfo &= ~kCGBitmapAlphaInfoMask;
+            bitmapInfo |= kCGImageAlphaPremultipliedFirst;
+        }
+#pragma clang diagnostic pop
+    }
+
+    CGContextRef context = CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo);
+
+    CGColorSpaceRelease(colorSpace);
+
+    if (!context) {
+        CGImageRelease(imageRef);
+
+        return image;
+    }
+
+    CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, width, height), imageRef);
+    CGImageRef inflatedImageRef = CGBitmapContextCreateImage(context);
+
+    CGContextRelease(context);
+
+    UIImage *inflatedImage = [[UIImage alloc] initWithCGImage:inflatedImageRef scale:scale orientation:image.imageOrientation];
+
+    CGImageRelease(inflatedImageRef);
+    CGImageRelease(imageRef);
+
+    return inflatedImage;
+}
+#endif
+
+
+@implementation AFImageResponseSerializer
+
+- (instancetype)init {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    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];
+
+#if TARGET_OS_IOS || TARGET_OS_TV
+    self.imageScale = [[UIScreen mainScreen] scale];
+    self.automaticallyInflatesResponseImage = YES;
+#elif TARGET_OS_WATCH
+    self.imageScale = [[WKInterfaceDevice currentDevice] screenScale];
+    self.automaticallyInflatesResponseImage = YES;
+#endif
+
+    return self;
+}
+
+#pragma mark - AFURLResponseSerializer
+
+- (id)responseObjectForResponse:(NSURLResponse *)response
+                           data:(NSData *)data
+                          error:(NSError *__autoreleasing *)error
+{
+    if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
+        if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
+            return nil;
+        }
+    }
+
+#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
+    if (self.automaticallyInflatesResponseImage) {
+        return AFInflatedImageFromResponseWithDataAtScale((NSHTTPURLResponse *)response, data, self.imageScale);
+    } else {
+        return AFImageWithDataAtScale(data, self.imageScale);
+    }
+#else
+    // Ensure that the image is set to it's correct pixel width and height
+    NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:data];
+    NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])];
+    [image addRepresentation:bitimage];
+
+    return image;
+#endif
+
+    return nil;
+}
+
+#pragma mark - NSSecureCoding
+
++ (BOOL)supportsSecureCoding {
+    return YES;
+}
+
+- (instancetype)initWithCoder:(NSCoder *)decoder {
+    self = [super initWithCoder:decoder];
+    if (!self) {
+        return nil;
+    }
+
+#if TARGET_OS_IOS  || TARGET_OS_TV || TARGET_OS_WATCH
+    NSNumber *imageScale = [decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(imageScale))];
+#if CGFLOAT_IS_DOUBLE
+    self.imageScale = [imageScale doubleValue];
+#else
+    self.imageScale = [imageScale floatValue];
+#endif
+
+    self.automaticallyInflatesResponseImage = [decoder decodeBoolForKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))];
+#endif
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)coder {
+    [super encodeWithCoder:coder];
+
+#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
+    [coder encodeObject:@(self.imageScale) forKey:NSStringFromSelector(@selector(imageScale))];
+    [coder encodeBool:self.automaticallyInflatesResponseImage forKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))];
+#endif
+}
+
+#pragma mark - NSCopying
+
+- (instancetype)copyWithZone:(NSZone *)zone {
+    AFImageResponseSerializer *serializer = [super copyWithZone:zone];
+
+#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
+    serializer.imageScale = self.imageScale;
+    serializer.automaticallyInflatesResponseImage = self.automaticallyInflatesResponseImage;
+#endif
+
+    return serializer;
+}
+
+@end
+
+#pragma mark -
+
+@interface AFCompoundResponseSerializer ()
+@property (readwrite, nonatomic, copy) NSArray *responseSerializers;
+@end
+
+@implementation AFCompoundResponseSerializer
+
++ (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers {
+    AFCompoundResponseSerializer *serializer = [[self alloc] init];
+    serializer.responseSerializers = responseSerializers;
+
+    return serializer;
+}
+
+#pragma mark - AFURLResponseSerialization
+
+- (id)responseObjectForResponse:(NSURLResponse *)response
+                           data:(NSData *)data
+                          error:(NSError *__autoreleasing *)error
+{
+    for (id <AFURLResponseSerialization> serializer in self.responseSerializers) {
+        if (![serializer isKindOfClass:[AFHTTPResponseSerializer class]]) {
+            continue;
+        }
+
+        NSError *serializerError = nil;
+        id responseObject = [serializer responseObjectForResponse:response data:data error:&serializerError];
+        if (responseObject) {
+            if (error) {
+                *error = AFErrorWithUnderlyingError(serializerError, *error);
+            }
+
+            return responseObject;
+        }
+    }
+
+    return [super responseObjectForResponse:response data:data error:error];
+}
+
+#pragma mark - NSSecureCoding
+
++ (BOOL)supportsSecureCoding {
+    return YES;
+}
+
+- (instancetype)initWithCoder:(NSCoder *)decoder {
+    self = [super initWithCoder:decoder];
+    if (!self) {
+        return nil;
+    }
+
+    NSSet *classes = [NSSet setWithArray:@[[NSArray class], [AFHTTPResponseSerializer <AFURLResponseSerialization> class]]];
+    self.responseSerializers = [decoder decodeObjectOfClasses:classes forKey:NSStringFromSelector(@selector(responseSerializers))];
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)coder {
+    [super encodeWithCoder:coder];
+
+    [coder encodeObject:self.responseSerializers forKey:NSStringFromSelector(@selector(responseSerializers))];
+}
+
+#pragma mark - NSCopying
+
+- (instancetype)copyWithZone:(NSZone *)zone {
+    AFCompoundResponseSerializer *serializer = [super copyWithZone:zone];
+    serializer.responseSerializers = self.responseSerializers;
+
+    return serializer;
+}
+
+@end

+ 516 - 0
Pods/AFNetworking/AFNetworking/AFURLSessionManager.h

@@ -0,0 +1,516 @@
+// AFURLSessionManager.h
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+
+#import <Foundation/Foundation.h>
+
+#import "AFURLResponseSerialization.h"
+#import "AFURLRequestSerialization.h"
+#import "AFSecurityPolicy.h"
+#import "AFCompatibilityMacros.h"
+#if !TARGET_OS_WATCH
+#import "AFNetworkReachabilityManager.h"
+#endif
+
+/**
+ `AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to `<NSURLSessionTaskDelegate>`, `<NSURLSessionDataDelegate>`, `<NSURLSessionDownloadDelegate>`, and `<NSURLSessionDelegate>`.
+
+ ## Subclassing Notes
+
+ This is the base class for `AFHTTPSessionManager`, which adds functionality specific to making HTTP requests. If you are looking to extend `AFURLSessionManager` specifically for HTTP, consider subclassing `AFHTTPSessionManager` instead.
+
+ ## NSURLSession & NSURLSessionTask Delegate Methods
+
+ `AFURLSessionManager` implements the following delegate methods:
+
+ ### `NSURLSessionDelegate`
+
+ - `URLSession:didBecomeInvalidWithError:`
+ - `URLSession:didReceiveChallenge:completionHandler:`
+ - `URLSessionDidFinishEventsForBackgroundURLSession:`
+
+ ### `NSURLSessionTaskDelegate`
+
+ - `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`
+ - `URLSession:task:didReceiveChallenge:completionHandler:`
+ - `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`
+ - `URLSession:task:needNewBodyStream:`
+ - `URLSession:task:didCompleteWithError:`
+
+ ### `NSURLSessionDataDelegate`
+
+ - `URLSession:dataTask:didReceiveResponse:completionHandler:`
+ - `URLSession:dataTask:didBecomeDownloadTask:`
+ - `URLSession:dataTask:didReceiveData:`
+ - `URLSession:dataTask:willCacheResponse:completionHandler:`
+
+ ### `NSURLSessionDownloadDelegate`
+
+ - `URLSession:downloadTask:didFinishDownloadingToURL:`
+ - `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`
+ - `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`
+
+ If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first.
+
+ ## Network Reachability Monitoring
+
+ Network reachability status and change monitoring is available through the `reachabilityManager` property. Applications may choose to monitor network reachability conditions in order to prevent or suspend any outbound requests. See `AFNetworkReachabilityManager` for more details.
+
+ ## NSCoding Caveats
+
+ - Encoded managers do not include any block properties. Be sure to set delegate callback blocks when using `-initWithCoder:` or `NSKeyedUnarchiver`.
+
+ ## NSCopying Caveats
+
+ - `-copy` and `-copyWithZone:` return a new manager with a new `NSURLSession` created from the configuration of the original.
+ - Operation copies do not include any delegate callback blocks, as they often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ session manager when copied.
+
+ @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.
+ */
+
+NS_ASSUME_NONNULL_BEGIN
+
+@interface AFURLSessionManager : NSObject <NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate, NSSecureCoding, NSCopying>
+
+/**
+ The managed session.
+ */
+@property (readonly, nonatomic, strong) NSURLSession *session;
+
+/**
+ The operation queue on which delegate callbacks are run.
+ */
+@property (readonly, nonatomic, strong) NSOperationQueue *operationQueue;
+
+/**
+ 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`.
+
+ @warning `responseSerializer` must not be `nil`.
+ */
+@property (nonatomic, strong) id <AFURLResponseSerialization> responseSerializer;
+
+///-------------------------------
+/// @name Managing Security Policy
+///-------------------------------
+
+/**
+ The security policy used by created session to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified.
+ */
+@property (nonatomic, strong) AFSecurityPolicy *securityPolicy;
+
+#if !TARGET_OS_WATCH
+///--------------------------------------
+/// @name Monitoring Network Reachability
+///--------------------------------------
+
+/**
+ The network reachability manager. `AFURLSessionManager` uses the `sharedManager` by default.
+ */
+@property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager;
+#endif
+
+///----------------------------
+/// @name Getting Session Tasks
+///----------------------------
+
+/**
+ The data, upload, and download tasks currently run by the managed session.
+ */
+@property (readonly, nonatomic, strong) NSArray <NSURLSessionTask *> *tasks;
+
+/**
+ The data tasks currently run by the managed session.
+ */
+@property (readonly, nonatomic, strong) NSArray <NSURLSessionDataTask *> *dataTasks;
+
+/**
+ The upload tasks currently run by the managed session.
+ */
+@property (readonly, nonatomic, strong) NSArray <NSURLSessionUploadTask *> *uploadTasks;
+
+/**
+ The download tasks currently run by the managed session.
+ */
+@property (readonly, nonatomic, strong) NSArray <NSURLSessionDownloadTask *> *downloadTasks;
+
+///-------------------------------
+/// @name Managing Callback Queues
+///-------------------------------
+
+/**
+ The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used.
+ */
+@property (nonatomic, strong, nullable) dispatch_queue_t completionQueue;
+
+/**
+ The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used.
+ */
+@property (nonatomic, strong, nullable) dispatch_group_t completionGroup;
+
+///---------------------
+/// @name Initialization
+///---------------------
+
+/**
+ Creates and returns a manager for a session created with the specified configuration. This is the designated initializer.
+
+ @param configuration The configuration used to create the managed session.
+
+ @return A manager for a newly-created session.
+ */
+- (instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER;
+
+/**
+ Invalidates the managed session, optionally canceling pending tasks and optionally resets given session.
+ 
+ @param cancelPendingTasks  Whether or not to cancel pending tasks.
+ @param resetSession        Whether or not to reset the session of the manager.
+ */
+- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks resetSession:(BOOL)resetSession;
+
+///-------------------------
+/// @name Running Data Tasks
+///-------------------------
+
+/**
+ Creates an `NSURLSessionDataTask` with the specified request.
+
+ @param request The HTTP request for the request.
+ @param uploadProgressBlock 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.
+ @param downloadProgressBlock 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.
+ @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
+ */
+- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
+                               uploadProgress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
+                             downloadProgress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock
+                            completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject,  NSError * _Nullable error))completionHandler;
+
+///---------------------------
+/// @name Running Upload Tasks
+///---------------------------
+
+/**
+ Creates an `NSURLSessionUploadTask` with the specified request for a local file.
+
+ @param request The HTTP request for the request.
+ @param fileURL A URL to the local file to be uploaded.
+ @param uploadProgressBlock 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.
+ @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
+
+ @see `attemptsToRecreateUploadTasksForBackgroundSessions`
+ */
+- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
+                                         fromFile:(NSURL *)fileURL
+                                         progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
+                                completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError  * _Nullable error))completionHandler;
+
+/**
+ Creates an `NSURLSessionUploadTask` with the specified request for an HTTP body.
+
+ @param request The HTTP request for the request.
+ @param bodyData A data object containing the HTTP body to be uploaded.
+ @param uploadProgressBlock 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.
+ @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
+ */
+- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
+                                         fromData:(nullable NSData *)bodyData
+                                         progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
+                                completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler;
+
+/**
+ Creates an `NSURLSessionUploadTask` with the specified streaming request.
+
+ @param request The HTTP request for the request.
+ @param uploadProgressBlock 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.
+ @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
+ */
+- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request
+                                                 progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
+                                        completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler;
+
+///-----------------------------
+/// @name Running Download Tasks
+///-----------------------------
+
+/**
+ Creates an `NSURLSessionDownloadTask` with the specified request.
+
+ @param request The HTTP request for the request.
+ @param downloadProgressBlock 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.
+ @param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL.
+ @param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any.
+
+ @warning If using a background `NSURLSessionConfiguration` on iOS, these blocks will be lost when the app is terminated. Background sessions may prefer to use `-setDownloadTaskDidFinishDownloadingBlock:` to specify the URL for saving the downloaded file, rather than the destination block of this method.
+ */
+- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request
+                                             progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock
+                                          destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
+                                    completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler;
+
+/**
+ Creates an `NSURLSessionDownloadTask` with the specified resume data.
+
+ @param resumeData The data used to resume downloading.
+ @param downloadProgressBlock 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.
+ @param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL.
+ @param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any.
+ */
+- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData
+                                                progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock
+                                             destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
+                                       completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler;
+
+///---------------------------------
+/// @name Getting Progress for Tasks
+///---------------------------------
+
+/**
+ Returns the upload progress of the specified task.
+
+ @param task The session task. Must not be `nil`.
+
+ @return An `NSProgress` object reporting the upload progress of a task, or `nil` if the progress is unavailable.
+ */
+- (nullable NSProgress *)uploadProgressForTask:(NSURLSessionTask *)task;
+
+/**
+ Returns the download progress of the specified task.
+
+ @param task The session task. Must not be `nil`.
+
+ @return An `NSProgress` object reporting the download progress of a task, or `nil` if the progress is unavailable.
+ */
+- (nullable NSProgress *)downloadProgressForTask:(NSURLSessionTask *)task;
+
+///-----------------------------------------
+/// @name Setting Session Delegate Callbacks
+///-----------------------------------------
+
+/**
+ Sets a block to be executed when the managed session becomes invalid, as handled by the `NSURLSessionDelegate` method `URLSession:didBecomeInvalidWithError:`.
+
+ @param block A block object to be executed when the managed session becomes invalid. The block has no return value, and takes two arguments: the session, and the error related to the cause of invalidation.
+ */
+- (void)setSessionDidBecomeInvalidBlock:(nullable void (^)(NSURLSession *session, NSError *error))block;
+
+/**
+ Sets a block to be executed when a connection level authentication challenge has occurred, as handled by the `NSURLSessionDelegate` method `URLSession:didReceiveChallenge:completionHandler:`.
+
+ @param block A block object to be executed when a connection level authentication challenge has occurred. The block returns the disposition of the authentication challenge, and takes three arguments: the session, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge.
+
+ @warning Implementing a session authentication challenge handler yourself totally bypasses AFNetworking's security policy defined in `AFSecurityPolicy`. Make sure you fully understand the implications before implementing a custom session authentication challenge handler. If you do not want to bypass AFNetworking's security policy, use `setTaskDidReceiveAuthenticationChallengeBlock:` instead.
+
+ @see -securityPolicy
+ @see -setTaskDidReceiveAuthenticationChallengeBlock:
+ */
+- (void)setSessionDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential))block;
+
+///--------------------------------------
+/// @name Setting Task Delegate Callbacks
+///--------------------------------------
+
+/**
+ Sets a block to be executed when a task requires a new request body stream to send to the remote server, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:needNewBodyStream:`.
+
+ @param block A block object to be executed when a task requires a new request body stream.
+ */
+- (void)setTaskNeedNewBodyStreamBlock:(nullable NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block;
+
+/**
+ Sets a block to be executed when an HTTP request is attempting to perform a redirection to a different URL, as handled by the `NSURLSessionTaskDelegate` method `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`.
+
+ @param block A block object to be executed when an HTTP request is attempting to perform a redirection to a different URL. The block returns the request to be made for the redirection, and takes four arguments: the session, the task, the redirection response, and the request corresponding to the redirection response.
+ */
+- (void)setTaskWillPerformHTTPRedirectionBlock:(nullable NSURLRequest * _Nullable (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block;
+
+/**
+ Sets a block to be executed when a session task has received a request specific authentication challenge, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didReceiveChallenge:completionHandler:`.
+ 
+ @param authenticationChallengeHandler A block object to be executed when a session task has received a request specific authentication challenge.
+ 
+ When implementing an authentication challenge handler, you should check the authentication method first (`challenge.protectionSpace.authenticationMethod `) to decide if you want to handle the authentication challenge yourself or if you want AFNetworking to handle it. If you want AFNetworking to handle the authentication challenge, just return `@(NSURLSessionAuthChallengePerformDefaultHandling)`. For example, you certainly want AFNetworking to handle certificate validation (i.e. authentication method == `NSURLAuthenticationMethodServerTrust`) as defined by the security policy. If you want to handle the challenge yourself, you have four options:
+ 
+ 1. Return `nil` from the authentication challenge handler. You **MUST** call the completion handler with a disposition and credentials yourself. Use this if you need to present a user interface to let the user enter their credentials.
+ 2. Return an `NSError` object from the authentication challenge handler. You **MUST NOT** call the completion handler when returning an `NSError `. The returned error will be reported in the completion handler of the task. Use this if you need to abort an authentication challenge with a specific error.
+ 3. Return an `NSURLCredential` object from the authentication challenge handler. You **MUST NOT** call the completion handler when returning an `NSURLCredential`. The returned credentials will be used to fulfil the challenge. Use this when you can get credentials without presenting a user interface.
+ 4. Return an `NSNumber` object wrapping an `NSURLSessionAuthChallengeDisposition`. Supported values are `@(NSURLSessionAuthChallengePerformDefaultHandling)`, `@(NSURLSessionAuthChallengeCancelAuthenticationChallenge)` and `@(NSURLSessionAuthChallengeRejectProtectionSpace)`. You **MUST NOT** call the completion handler when returning an `NSNumber`.
+ 
+ If you return anything else from the authentication challenge handler, an exception will be thrown.
+ 
+ For more information about how URL sessions handle the different types of authentication challenges, see [NSURLSession](https://developer.apple.com/reference/foundation/nsurlsession?language=objc) and [URL Session Programming Guide](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html).
+ 
+ @see -securityPolicy
+ */
+- (void)setAuthenticationChallengeHandler:(id (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, void (^completionHandler)(NSURLSessionAuthChallengeDisposition , NSURLCredential * _Nullable)))authenticationChallengeHandler;
+
+/**
+ Sets a block to be executed periodically to track upload progress, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.
+
+ @param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes five arguments: the session, the task, the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times, and will execute on the main thread.
+ */
+- (void)setTaskDidSendBodyDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block;
+
+/**
+ Sets a block to be executed as the last message related to a specific task, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didCompleteWithError:`.
+
+ @param block A block object to be executed when a session task is completed. The block has no return value, and takes three arguments: the session, the task, and any error that occurred in the process of executing the task.
+ */
+- (void)setTaskDidCompleteBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, NSError * _Nullable error))block;
+
+/**
+ Sets a block to be executed when metrics are finalized related to a specific task, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didFinishCollectingMetrics:`.
+
+ @param block A block object to be executed when a session task is completed. The block has no return value, and takes three arguments: the session, the task, and any metrics that were collected in the process of executing the task.
+ */
+#if AF_CAN_INCLUDE_SESSION_TASK_METRICS
+- (void)setTaskDidFinishCollectingMetricsBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, NSURLSessionTaskMetrics * _Nullable metrics))block AF_API_AVAILABLE(ios(10), macosx(10.12), watchos(3), tvos(10));
+#endif
+///-------------------------------------------
+/// @name Setting Data Task Delegate Callbacks
+///-------------------------------------------
+
+/**
+ Sets a block to be executed when a data task has received a response, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveResponse:completionHandler:`.
+
+ @param block A block object to be executed when a data task has received a response. The block returns the disposition of the session response, and takes three arguments: the session, the data task, and the received response.
+ */
+- (void)setDataTaskDidReceiveResponseBlock:(nullable NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block;
+
+/**
+ Sets a block to be executed when a data task has become a download task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didBecomeDownloadTask:`.
+
+ @param block A block object to be executed when a data task has become a download task. The block has no return value, and takes three arguments: the session, the data task, and the download task it has become.
+ */
+- (void)setDataTaskDidBecomeDownloadTaskBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block;
+
+/**
+ Sets a block to be executed when a data task receives data, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveData:`.
+
+ @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the session, the data task, and the data received. This block may be called multiple times, and will execute on the session manager operation queue.
+ */
+- (void)setDataTaskDidReceiveDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block;
+
+/**
+ Sets a block to be executed to determine the caching behavior of a data task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:willCacheResponse:completionHandler:`.
+
+ @param block A block object to be executed to determine the caching behavior of a data task. The block returns the response to cache, and takes three arguments: the session, the data task, and the proposed cached URL response.
+ */
+- (void)setDataTaskWillCacheResponseBlock:(nullable NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block;
+
+/**
+ Sets a block to be executed once all messages enqueued for a session have been delivered, as handled by the `NSURLSessionDataDelegate` method `URLSessionDidFinishEventsForBackgroundURLSession:`.
+
+ @param block A block object to be executed once all messages enqueued for a session have been delivered. The block has no return value and takes a single argument: the session.
+ */
+- (void)setDidFinishEventsForBackgroundURLSessionBlock:(nullable void (^)(NSURLSession *session))block AF_API_UNAVAILABLE(macos);
+
+///-----------------------------------------------
+/// @name Setting Download Task Delegate Callbacks
+///-----------------------------------------------
+
+/**
+ Sets a block to be executed when a download task has completed a download, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didFinishDownloadingToURL:`.
+
+ @param block A block object to be executed when a download task has completed. The block returns the URL the download should be moved to, and takes three arguments: the session, the download task, and the temporary location of the downloaded file. If the file manager encounters an error while attempting to move the temporary file to the destination, an `AFURLSessionDownloadTaskDidFailToMoveFileNotification` will be posted, with the download task as its object, and the user info of the error.
+ */
+- (void)setDownloadTaskDidFinishDownloadingBlock:(nullable NSURL * _Nullable  (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block;
+
+/**
+ Sets a block to be executed periodically to track download progress, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`.
+
+ @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes five arguments: the session, the download task, the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the session manager operation queue.
+ */
+- (void)setDownloadTaskDidWriteDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block;
+
+/**
+ Sets a block to be executed when a download task has been resumed, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`.
+
+ @param block A block object to be executed when a download task has been resumed. The block has no return value and takes four arguments: the session, the download task, the file offset of the resumed download, and the total number of bytes expected to be downloaded.
+ */
+- (void)setDownloadTaskDidResumeBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block;
+
+@end
+
+///--------------------
+/// @name Notifications
+///--------------------
+
+/**
+ Posted when a task resumes.
+ */
+FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidResumeNotification;
+
+/**
+ Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task.
+ */
+FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteNotification;
+
+/**
+ Posted when a task suspends its execution.
+ */
+FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidSuspendNotification;
+
+/**
+ Posted when a session is invalidated.
+ */
+FOUNDATION_EXPORT NSString * const AFURLSessionDidInvalidateNotification;
+
+/**
+ Posted when a session download task finished moving the temporary download file to a specified destination successfully.
+ */
+FOUNDATION_EXPORT NSString * const AFURLSessionDownloadTaskDidMoveFileSuccessfullyNotification;
+
+/**
+ Posted when a session download task encountered an error when moving the temporary download file to a specified destination.
+ */
+FOUNDATION_EXPORT NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification;
+
+/**
+ The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if response data exists for the task.
+ */
+FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseDataKey;
+
+/**
+ The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the response was serialized.
+ */
+FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey;
+
+/**
+ The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the task has an associated response serializer.
+ */
+FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey;
+
+/**
+ The file path associated with the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an the response data has been stored directly to disk.
+ */
+FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteAssetPathKey;
+
+/**
+ Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an error exists.
+ */
+FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteErrorKey;
+
+/**
+ The session task metrics taken from the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteSessionTaskMetrics`
+ */
+FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteSessionTaskMetrics;
+
+NS_ASSUME_NONNULL_END

+ 1274 - 0
Pods/AFNetworking/AFNetworking/AFURLSessionManager.m

@@ -0,0 +1,1274 @@
+// AFURLSessionManager.m
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import "AFURLSessionManager.h"
+#import <objc/runtime.h>
+
+static dispatch_queue_t url_session_manager_processing_queue() {
+    static dispatch_queue_t af_url_session_manager_processing_queue;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        af_url_session_manager_processing_queue = dispatch_queue_create("com.alamofire.networking.session.manager.processing", DISPATCH_QUEUE_CONCURRENT);
+    });
+
+    return af_url_session_manager_processing_queue;
+}
+
+static dispatch_group_t url_session_manager_completion_group() {
+    static dispatch_group_t af_url_session_manager_completion_group;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        af_url_session_manager_completion_group = dispatch_group_create();
+    });
+
+    return af_url_session_manager_completion_group;
+}
+
+NSString * const AFNetworkingTaskDidResumeNotification = @"com.alamofire.networking.task.resume";
+NSString * const AFNetworkingTaskDidCompleteNotification = @"com.alamofire.networking.task.complete";
+NSString * const AFNetworkingTaskDidSuspendNotification = @"com.alamofire.networking.task.suspend";
+NSString * const AFURLSessionDidInvalidateNotification = @"com.alamofire.networking.session.invalidate";
+NSString * const AFURLSessionDownloadTaskDidMoveFileSuccessfullyNotification = @"com.alamofire.networking.session.download.file-manager-succeed";
+NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification = @"com.alamofire.networking.session.download.file-manager-error";
+
+NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey = @"com.alamofire.networking.task.complete.serializedresponse";
+NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey = @"com.alamofire.networking.task.complete.responseserializer";
+NSString * const AFNetworkingTaskDidCompleteResponseDataKey = @"com.alamofire.networking.complete.finish.responsedata";
+NSString * const AFNetworkingTaskDidCompleteErrorKey = @"com.alamofire.networking.task.complete.error";
+NSString * const AFNetworkingTaskDidCompleteAssetPathKey = @"com.alamofire.networking.task.complete.assetpath";
+NSString * const AFNetworkingTaskDidCompleteSessionTaskMetrics = @"com.alamofire.networking.complete.sessiontaskmetrics";
+
+static NSString * const AFURLSessionManagerLockName = @"com.alamofire.networking.session.manager.lock";
+
+typedef void (^AFURLSessionDidBecomeInvalidBlock)(NSURLSession *session, NSError *error);
+typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential);
+
+typedef NSURLRequest * (^AFURLSessionTaskWillPerformHTTPRedirectionBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request);
+typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionTaskDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential);
+typedef id (^AFURLSessionTaskAuthenticationChallengeBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, void (^completionHandler)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential));
+typedef void (^AFURLSessionDidFinishEventsForBackgroundURLSessionBlock)(NSURLSession *session);
+
+typedef NSInputStream * (^AFURLSessionTaskNeedNewBodyStreamBlock)(NSURLSession *session, NSURLSessionTask *task);
+typedef void (^AFURLSessionTaskDidSendBodyDataBlock)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend);
+typedef void (^AFURLSessionTaskDidCompleteBlock)(NSURLSession *session, NSURLSessionTask *task, NSError *error);
+#if AF_CAN_INCLUDE_SESSION_TASK_METRICS
+typedef void (^AFURLSessionTaskDidFinishCollectingMetricsBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLSessionTaskMetrics * metrics) AF_API_AVAILABLE(ios(10), macosx(10.12), watchos(3), tvos(10));
+#endif
+
+typedef NSURLSessionResponseDisposition (^AFURLSessionDataTaskDidReceiveResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response);
+typedef void (^AFURLSessionDataTaskDidBecomeDownloadTaskBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask);
+typedef void (^AFURLSessionDataTaskDidReceiveDataBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data);
+typedef NSCachedURLResponse * (^AFURLSessionDataTaskWillCacheResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse);
+
+typedef NSURL * (^AFURLSessionDownloadTaskDidFinishDownloadingBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location);
+typedef void (^AFURLSessionDownloadTaskDidWriteDataBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite);
+typedef void (^AFURLSessionDownloadTaskDidResumeBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes);
+typedef void (^AFURLSessionTaskProgressBlock)(NSProgress *);
+
+typedef void (^AFURLSessionTaskCompletionHandler)(NSURLResponse *response, id responseObject, NSError *error);
+
+#pragma mark -
+
+@interface AFURLSessionManagerTaskDelegate : NSObject <NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate>
+- (instancetype)initWithTask:(NSURLSessionTask *)task;
+@property (nonatomic, weak) AFURLSessionManager *manager;
+@property (nonatomic, strong) NSMutableData *mutableData;
+@property (nonatomic, strong) NSProgress *uploadProgress;
+@property (nonatomic, strong) NSProgress *downloadProgress;
+@property (nonatomic, copy) NSURL *downloadFileURL;
+#if AF_CAN_INCLUDE_SESSION_TASK_METRICS
+@property (nonatomic, strong) NSURLSessionTaskMetrics *sessionTaskMetrics AF_API_AVAILABLE(ios(10), macosx(10.12), watchos(3), tvos(10));
+#endif
+@property (nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading;
+@property (nonatomic, copy) AFURLSessionTaskProgressBlock uploadProgressBlock;
+@property (nonatomic, copy) AFURLSessionTaskProgressBlock downloadProgressBlock;
+@property (nonatomic, copy) AFURLSessionTaskCompletionHandler completionHandler;
+@end
+
+@implementation AFURLSessionManagerTaskDelegate
+
+- (instancetype)initWithTask:(NSURLSessionTask *)task {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+    
+    _mutableData = [NSMutableData data];
+    _uploadProgress = [[NSProgress alloc] initWithParent:nil userInfo:nil];
+    _downloadProgress = [[NSProgress alloc] initWithParent:nil userInfo:nil];
+    
+    __weak __typeof__(task) weakTask = task;
+    for (NSProgress *progress in @[ _uploadProgress, _downloadProgress ])
+    {
+        progress.totalUnitCount = NSURLSessionTransferSizeUnknown;
+        progress.cancellable = YES;
+        progress.cancellationHandler = ^{
+            [weakTask cancel];
+        };
+        progress.pausable = YES;
+        progress.pausingHandler = ^{
+            [weakTask suspend];
+        };
+#if AF_CAN_USE_AT_AVAILABLE
+        if (@available(macOS 10.11, *))
+#else
+        if ([progress respondsToSelector:@selector(setResumingHandler:)])
+#endif
+        {
+            progress.resumingHandler = ^{
+                [weakTask resume];
+            };
+        }
+        
+        [progress addObserver:self
+                   forKeyPath:NSStringFromSelector(@selector(fractionCompleted))
+                      options:NSKeyValueObservingOptionNew
+                      context:NULL];
+    }
+    return self;
+}
+
+- (void)dealloc {
+    [self.downloadProgress removeObserver:self forKeyPath:NSStringFromSelector(@selector(fractionCompleted))];
+    [self.uploadProgress removeObserver:self forKeyPath:NSStringFromSelector(@selector(fractionCompleted))];
+}
+
+#pragma mark - NSProgress Tracking
+
+- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
+   if ([object isEqual:self.downloadProgress]) {
+        if (self.downloadProgressBlock) {
+            self.downloadProgressBlock(object);
+        }
+    }
+    else if ([object isEqual:self.uploadProgress]) {
+        if (self.uploadProgressBlock) {
+            self.uploadProgressBlock(object);
+        }
+    }
+}
+
+static const void * const AuthenticationChallengeErrorKey = &AuthenticationChallengeErrorKey;
+
+#pragma mark - NSURLSessionTaskDelegate
+
+- (void)URLSession:(__unused NSURLSession *)session
+              task:(NSURLSessionTask *)task
+didCompleteWithError:(NSError *)error
+{
+    error = objc_getAssociatedObject(task, AuthenticationChallengeErrorKey) ?: error;
+    __strong AFURLSessionManager *manager = self.manager;
+
+    __block id responseObject = nil;
+
+    NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
+    userInfo[AFNetworkingTaskDidCompleteResponseSerializerKey] = manager.responseSerializer;
+
+    //Performance Improvement from #2672
+    NSData *data = nil;
+    if (self.mutableData) {
+        data = [self.mutableData copy];
+        //We no longer need the reference, so nil it out to gain back some memory.
+        self.mutableData = nil;
+    }
+
+#if AF_CAN_USE_AT_AVAILABLE && AF_CAN_INCLUDE_SESSION_TASK_METRICS
+    if (@available(iOS 10, macOS 10.12, watchOS 3, tvOS 10, *)) {
+        if (self.sessionTaskMetrics) {
+            userInfo[AFNetworkingTaskDidCompleteSessionTaskMetrics] = self.sessionTaskMetrics;
+        }
+    }
+#endif
+
+    if (self.downloadFileURL) {
+        userInfo[AFNetworkingTaskDidCompleteAssetPathKey] = self.downloadFileURL;
+    } else if (data) {
+        userInfo[AFNetworkingTaskDidCompleteResponseDataKey] = data;
+    }
+
+    if (error) {
+        userInfo[AFNetworkingTaskDidCompleteErrorKey] = error;
+
+        dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
+            if (self.completionHandler) {
+                self.completionHandler(task.response, responseObject, error);
+            }
+
+            dispatch_async(dispatch_get_main_queue(), ^{
+                [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
+            });
+        });
+    } else {
+        dispatch_async(url_session_manager_processing_queue(), ^{
+            NSError *serializationError = nil;
+            responseObject = [manager.responseSerializer responseObjectForResponse:task.response data:data error:&serializationError];
+
+            if (self.downloadFileURL) {
+                responseObject = self.downloadFileURL;
+            }
+
+            if (responseObject) {
+                userInfo[AFNetworkingTaskDidCompleteSerializedResponseKey] = responseObject;
+            }
+
+            if (serializationError) {
+                userInfo[AFNetworkingTaskDidCompleteErrorKey] = serializationError;
+            }
+
+            dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
+                if (self.completionHandler) {
+                    self.completionHandler(task.response, responseObject, serializationError);
+                }
+
+                dispatch_async(dispatch_get_main_queue(), ^{
+                    [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
+                });
+            });
+        });
+    }
+}
+
+#if AF_CAN_INCLUDE_SESSION_TASK_METRICS
+- (void)URLSession:(NSURLSession *)session
+              task:(NSURLSessionTask *)task
+didFinishCollectingMetrics:(NSURLSessionTaskMetrics *)metrics AF_API_AVAILABLE(ios(10), macosx(10.12), watchos(3), tvos(10)) {
+    self.sessionTaskMetrics = metrics;
+}
+#endif
+
+#pragma mark - NSURLSessionDataDelegate
+
+- (void)URLSession:(__unused NSURLSession *)session
+          dataTask:(__unused NSURLSessionDataTask *)dataTask
+    didReceiveData:(NSData *)data
+{
+    self.downloadProgress.totalUnitCount = dataTask.countOfBytesExpectedToReceive;
+    self.downloadProgress.completedUnitCount = dataTask.countOfBytesReceived;
+
+    [self.mutableData appendData:data];
+}
+
+- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
+   didSendBodyData:(int64_t)bytesSent
+    totalBytesSent:(int64_t)totalBytesSent
+totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend{
+    
+    self.uploadProgress.totalUnitCount = task.countOfBytesExpectedToSend;
+    self.uploadProgress.completedUnitCount = task.countOfBytesSent;
+}
+
+#pragma mark - NSURLSessionDownloadDelegate
+
+- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
+      didWriteData:(int64_t)bytesWritten
+ totalBytesWritten:(int64_t)totalBytesWritten
+totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
+    
+    self.downloadProgress.totalUnitCount = totalBytesExpectedToWrite;
+    self.downloadProgress.completedUnitCount = totalBytesWritten;
+}
+
+- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
+ didResumeAtOffset:(int64_t)fileOffset
+expectedTotalBytes:(int64_t)expectedTotalBytes{
+    
+    self.downloadProgress.totalUnitCount = expectedTotalBytes;
+    self.downloadProgress.completedUnitCount = fileOffset;
+}
+
+- (void)URLSession:(NSURLSession *)session
+      downloadTask:(NSURLSessionDownloadTask *)downloadTask
+didFinishDownloadingToURL:(NSURL *)location
+{
+    self.downloadFileURL = nil;
+
+    if (self.downloadTaskDidFinishDownloading) {
+        self.downloadFileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location);
+        if (self.downloadFileURL) {
+            NSError *fileManagerError = nil;
+
+            if (![[NSFileManager defaultManager] moveItemAtURL:location toURL:self.downloadFileURL error:&fileManagerError]) {
+                [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:fileManagerError.userInfo];
+            } else {
+                [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidMoveFileSuccessfullyNotification object:downloadTask userInfo:nil];
+            }
+        }
+    }
+}
+
+@end
+
+#pragma mark -
+
+/**
+ *  A workaround for issues related to key-value observing the `state` of an `NSURLSessionTask`.
+ *
+ *  See:
+ *  - https://github.com/AFNetworking/AFNetworking/issues/1477
+ *  - https://github.com/AFNetworking/AFNetworking/issues/2638
+ *  - https://github.com/AFNetworking/AFNetworking/pull/2702
+ */
+
+static inline void af_swizzleSelector(Class theClass, SEL originalSelector, SEL swizzledSelector) {
+    Method originalMethod = class_getInstanceMethod(theClass, originalSelector);
+    Method swizzledMethod = class_getInstanceMethod(theClass, swizzledSelector);
+    method_exchangeImplementations(originalMethod, swizzledMethod);
+}
+
+static inline BOOL af_addMethod(Class theClass, SEL selector, Method method) {
+    return class_addMethod(theClass, selector,  method_getImplementation(method),  method_getTypeEncoding(method));
+}
+
+static NSString * const AFNSURLSessionTaskDidResumeNotification  = @"com.alamofire.networking.nsurlsessiontask.resume";
+static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofire.networking.nsurlsessiontask.suspend";
+
+@interface _AFURLSessionTaskSwizzling : NSObject
+
+@end
+
+@implementation _AFURLSessionTaskSwizzling
+
++ (void)load {
+    /**
+     WARNING: Trouble Ahead
+     https://github.com/AFNetworking/AFNetworking/pull/2702
+     */
+
+    if (NSClassFromString(@"NSURLSessionTask")) {
+        /**
+         iOS 7 and iOS 8 differ in NSURLSessionTask implementation, which makes the next bit of code a bit tricky.
+         Many Unit Tests have been built to validate as much of this behavior has possible.
+         Here is what we know:
+            - NSURLSessionTasks are implemented with class clusters, meaning the class you request from the API isn't actually the type of class you will get back.
+            - Simply referencing `[NSURLSessionTask class]` will not work. You need to ask an `NSURLSession` to actually create an object, and grab the class from there.
+            - On iOS 7, `localDataTask` is a `__NSCFLocalDataTask`, which inherits from `__NSCFLocalSessionTask`, which inherits from `__NSCFURLSessionTask`.
+            - On iOS 8, `localDataTask` is a `__NSCFLocalDataTask`, which inherits from `__NSCFLocalSessionTask`, which inherits from `NSURLSessionTask`.
+            - On iOS 7, `__NSCFLocalSessionTask` and `__NSCFURLSessionTask` are the only two classes that have their own implementations of `resume` and `suspend`, and `__NSCFLocalSessionTask` DOES NOT CALL SUPER. This means both classes need to be swizzled.
+            - On iOS 8, `NSURLSessionTask` is the only class that implements `resume` and `suspend`. This means this is the only class that needs to be swizzled.
+            - Because `NSURLSessionTask` is not involved in the class hierarchy for every version of iOS, its easier to add the swizzled methods to a dummy class and manage them there.
+        
+         Some Assumptions:
+            - No implementations of `resume` or `suspend` call super. If this were to change in a future version of iOS, we'd need to handle it.
+            - No background task classes override `resume` or `suspend`
+         
+         The current solution:
+            1) Grab an instance of `__NSCFLocalDataTask` by asking an instance of `NSURLSession` for a data task.
+            2) Grab a pointer to the original implementation of `af_resume`
+            3) Check to see if the current class has an implementation of resume. If so, continue to step 4.
+            4) Grab the super class of the current class.
+            5) Grab a pointer for the current class to the current implementation of `resume`.
+            6) Grab a pointer for the super class to the current implementation of `resume`.
+            7) If the current class implementation of `resume` is not equal to the super class implementation of `resume` AND the current implementation of `resume` is not equal to the original implementation of `af_resume`, THEN swizzle the methods
+            8) Set the current class to the super class, and repeat steps 3-8
+         */
+        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
+        NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wnonnull"
+        NSURLSessionDataTask *localDataTask = [session dataTaskWithURL:nil];
+#pragma clang diagnostic pop
+        IMP originalAFResumeIMP = method_getImplementation(class_getInstanceMethod([self class], @selector(af_resume)));
+        Class currentClass = [localDataTask class];
+        
+        while (class_getInstanceMethod(currentClass, @selector(resume))) {
+            Class superClass = [currentClass superclass];
+            IMP classResumeIMP = method_getImplementation(class_getInstanceMethod(currentClass, @selector(resume)));
+            IMP superclassResumeIMP = method_getImplementation(class_getInstanceMethod(superClass, @selector(resume)));
+            if (classResumeIMP != superclassResumeIMP &&
+                originalAFResumeIMP != classResumeIMP) {
+                [self swizzleResumeAndSuspendMethodForClass:currentClass];
+            }
+            currentClass = [currentClass superclass];
+        }
+        
+        [localDataTask cancel];
+        [session finishTasksAndInvalidate];
+    }
+}
+
++ (void)swizzleResumeAndSuspendMethodForClass:(Class)theClass {
+    Method afResumeMethod = class_getInstanceMethod(self, @selector(af_resume));
+    Method afSuspendMethod = class_getInstanceMethod(self, @selector(af_suspend));
+
+    if (af_addMethod(theClass, @selector(af_resume), afResumeMethod)) {
+        af_swizzleSelector(theClass, @selector(resume), @selector(af_resume));
+    }
+
+    if (af_addMethod(theClass, @selector(af_suspend), afSuspendMethod)) {
+        af_swizzleSelector(theClass, @selector(suspend), @selector(af_suspend));
+    }
+}
+
+- (NSURLSessionTaskState)state {
+    NSAssert(NO, @"State method should never be called in the actual dummy class");
+    return NSURLSessionTaskStateCanceling;
+}
+
+- (void)af_resume {
+    NSAssert([self respondsToSelector:@selector(state)], @"Does not respond to state");
+    NSURLSessionTaskState state = [self state];
+    [self af_resume];
+    
+    if (state != NSURLSessionTaskStateRunning) {
+        [[NSNotificationCenter defaultCenter] postNotificationName:AFNSURLSessionTaskDidResumeNotification object:self];
+    }
+}
+
+- (void)af_suspend {
+    NSAssert([self respondsToSelector:@selector(state)], @"Does not respond to state");
+    NSURLSessionTaskState state = [self state];
+    [self af_suspend];
+    
+    if (state != NSURLSessionTaskStateSuspended) {
+        [[NSNotificationCenter defaultCenter] postNotificationName:AFNSURLSessionTaskDidSuspendNotification object:self];
+    }
+}
+@end
+
+#pragma mark -
+
+@interface AFURLSessionManager ()
+@property (readwrite, nonatomic, strong) NSURLSessionConfiguration *sessionConfiguration;
+@property (readwrite, nonatomic, strong) NSOperationQueue *operationQueue;
+@property (readwrite, nonatomic, strong) NSURLSession *session;
+@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableTaskDelegatesKeyedByTaskIdentifier;
+@property (readonly, nonatomic, copy) NSString *taskDescriptionForSessionTasks;
+@property (readwrite, nonatomic, strong) NSLock *lock;
+@property (readwrite, nonatomic, copy) AFURLSessionDidBecomeInvalidBlock sessionDidBecomeInvalid;
+@property (readwrite, nonatomic, copy) AFURLSessionDidReceiveAuthenticationChallengeBlock sessionDidReceiveAuthenticationChallenge;
+@property (readwrite, nonatomic, copy) AFURLSessionDidFinishEventsForBackgroundURLSessionBlock didFinishEventsForBackgroundURLSession AF_API_UNAVAILABLE(macos);
+@property (readwrite, nonatomic, copy) AFURLSessionTaskWillPerformHTTPRedirectionBlock taskWillPerformHTTPRedirection;
+@property (readwrite, nonatomic, copy) AFURLSessionTaskAuthenticationChallengeBlock authenticationChallengeHandler;
+@property (readwrite, nonatomic, copy) AFURLSessionTaskNeedNewBodyStreamBlock taskNeedNewBodyStream;
+@property (readwrite, nonatomic, copy) AFURLSessionTaskDidSendBodyDataBlock taskDidSendBodyData;
+@property (readwrite, nonatomic, copy) AFURLSessionTaskDidCompleteBlock taskDidComplete;
+#if AF_CAN_INCLUDE_SESSION_TASK_METRICS
+@property (readwrite, nonatomic, copy) AFURLSessionTaskDidFinishCollectingMetricsBlock taskDidFinishCollectingMetrics AF_API_AVAILABLE(ios(10), macosx(10.12), watchos(3), tvos(10));
+#endif
+@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidReceiveResponseBlock dataTaskDidReceiveResponse;
+@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidBecomeDownloadTaskBlock dataTaskDidBecomeDownloadTask;
+@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidReceiveDataBlock dataTaskDidReceiveData;
+@property (readwrite, nonatomic, copy) AFURLSessionDataTaskWillCacheResponseBlock dataTaskWillCacheResponse;
+@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading;
+@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidWriteDataBlock downloadTaskDidWriteData;
+@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidResumeBlock downloadTaskDidResume;
+@end
+
+@implementation AFURLSessionManager
+
+- (instancetype)init {
+    return [self initWithSessionConfiguration:nil];
+}
+
+- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    if (!configuration) {
+        configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
+    }
+
+    self.sessionConfiguration = configuration;
+
+    self.operationQueue = [[NSOperationQueue alloc] init];
+    self.operationQueue.maxConcurrentOperationCount = 1;
+
+    self.responseSerializer = [AFJSONResponseSerializer serializer];
+
+    self.securityPolicy = [AFSecurityPolicy defaultPolicy];
+
+#if !TARGET_OS_WATCH
+    self.reachabilityManager = [AFNetworkReachabilityManager sharedManager];
+#endif
+
+    self.mutableTaskDelegatesKeyedByTaskIdentifier = [[NSMutableDictionary alloc] init];
+
+    self.lock = [[NSLock alloc] init];
+    self.lock.name = AFURLSessionManagerLockName;
+
+    [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
+        for (NSURLSessionDataTask *task in dataTasks) {
+            [self addDelegateForDataTask:task uploadProgress:nil downloadProgress:nil completionHandler:nil];
+        }
+
+        for (NSURLSessionUploadTask *uploadTask in uploadTasks) {
+            [self addDelegateForUploadTask:uploadTask progress:nil completionHandler:nil];
+        }
+
+        for (NSURLSessionDownloadTask *downloadTask in downloadTasks) {
+            [self addDelegateForDownloadTask:downloadTask progress:nil destination:nil completionHandler:nil];
+        }
+    }];
+
+    return self;
+}
+
+- (void)dealloc {
+    [[NSNotificationCenter defaultCenter] removeObserver:self];
+}
+
+#pragma mark -
+
+- (NSURLSession *)session {
+    
+    @synchronized (self) {
+        if (!_session) {
+            _session = [NSURLSession sessionWithConfiguration:self.sessionConfiguration delegate:self delegateQueue:self.operationQueue];
+        }
+    }
+    return _session;
+}
+
+#pragma mark -
+
+
+- (NSString *)taskDescriptionForSessionTasks {
+    return [NSString stringWithFormat:@"%p", self];
+}
+
+- (void)taskDidResume:(NSNotification *)notification {
+    NSURLSessionTask *task = notification.object;
+    if ([task respondsToSelector:@selector(taskDescription)]) {
+        if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) {
+            dispatch_async(dispatch_get_main_queue(), ^{
+                [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidResumeNotification object:task];
+            });
+        }
+    }
+}
+
+- (void)taskDidSuspend:(NSNotification *)notification {
+    NSURLSessionTask *task = notification.object;
+    if ([task respondsToSelector:@selector(taskDescription)]) {
+        if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) {
+            dispatch_async(dispatch_get_main_queue(), ^{
+                [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidSuspendNotification object:task];
+            });
+        }
+    }
+}
+
+#pragma mark -
+
+- (AFURLSessionManagerTaskDelegate *)delegateForTask:(NSURLSessionTask *)task {
+    NSParameterAssert(task);
+
+    AFURLSessionManagerTaskDelegate *delegate = nil;
+    [self.lock lock];
+    delegate = self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)];
+    [self.lock unlock];
+
+    return delegate;
+}
+
+- (void)setDelegate:(AFURLSessionManagerTaskDelegate *)delegate
+            forTask:(NSURLSessionTask *)task
+{
+    NSParameterAssert(task);
+    NSParameterAssert(delegate);
+
+    [self.lock lock];
+    self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)] = delegate;
+    [self addNotificationObserverForTask:task];
+    [self.lock unlock];
+}
+
+- (void)addDelegateForDataTask:(NSURLSessionDataTask *)dataTask
+                uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock
+              downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock
+             completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
+{
+    AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] initWithTask:dataTask];
+    delegate.manager = self;
+    delegate.completionHandler = completionHandler;
+
+    dataTask.taskDescription = self.taskDescriptionForSessionTasks;
+    [self setDelegate:delegate forTask:dataTask];
+
+    delegate.uploadProgressBlock = uploadProgressBlock;
+    delegate.downloadProgressBlock = downloadProgressBlock;
+}
+
+- (void)addDelegateForUploadTask:(NSURLSessionUploadTask *)uploadTask
+                        progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock
+               completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
+{
+    AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] initWithTask:uploadTask];
+    delegate.manager = self;
+    delegate.completionHandler = completionHandler;
+
+    uploadTask.taskDescription = self.taskDescriptionForSessionTasks;
+
+    [self setDelegate:delegate forTask:uploadTask];
+
+    delegate.uploadProgressBlock = uploadProgressBlock;
+}
+
+- (void)addDelegateForDownloadTask:(NSURLSessionDownloadTask *)downloadTask
+                          progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock
+                       destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
+                 completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
+{
+    AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] initWithTask:downloadTask];
+    delegate.manager = self;
+    delegate.completionHandler = completionHandler;
+
+    if (destination) {
+        delegate.downloadTaskDidFinishDownloading = ^NSURL * (NSURLSession * __unused session, NSURLSessionDownloadTask *task, NSURL *location) {
+            return destination(location, task.response);
+        };
+    }
+
+    downloadTask.taskDescription = self.taskDescriptionForSessionTasks;
+
+    [self setDelegate:delegate forTask:downloadTask];
+
+    delegate.downloadProgressBlock = downloadProgressBlock;
+}
+
+- (void)removeDelegateForTask:(NSURLSessionTask *)task {
+    NSParameterAssert(task);
+
+    [self.lock lock];
+    [self removeNotificationObserverForTask:task];
+    [self.mutableTaskDelegatesKeyedByTaskIdentifier removeObjectForKey:@(task.taskIdentifier)];
+    [self.lock unlock];
+}
+
+#pragma mark -
+
+- (NSArray *)tasksForKeyPath:(NSString *)keyPath {
+    __block NSArray *tasks = nil;
+    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
+    [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
+        if ([keyPath isEqualToString:NSStringFromSelector(@selector(dataTasks))]) {
+            tasks = dataTasks;
+        } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(uploadTasks))]) {
+            tasks = uploadTasks;
+        } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(downloadTasks))]) {
+            tasks = downloadTasks;
+        } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(tasks))]) {
+            tasks = [@[dataTasks, uploadTasks, downloadTasks] valueForKeyPath:@"@unionOfArrays.self"];
+        }
+
+        dispatch_semaphore_signal(semaphore);
+    }];
+
+    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
+
+    return tasks;
+}
+
+- (NSArray *)tasks {
+    return [self tasksForKeyPath:NSStringFromSelector(_cmd)];
+}
+
+- (NSArray *)dataTasks {
+    return [self tasksForKeyPath:NSStringFromSelector(_cmd)];
+}
+
+- (NSArray *)uploadTasks {
+    return [self tasksForKeyPath:NSStringFromSelector(_cmd)];
+}
+
+- (NSArray *)downloadTasks {
+    return [self tasksForKeyPath:NSStringFromSelector(_cmd)];
+}
+
+#pragma mark -
+
+- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks resetSession:(BOOL)resetSession {
+    if (cancelPendingTasks) {
+        [self.session invalidateAndCancel];
+    } else {
+        [self.session finishTasksAndInvalidate];
+    }
+    if (resetSession) {
+        self.session = nil;
+    }
+}
+
+#pragma mark -
+
+- (void)setResponseSerializer:(id <AFURLResponseSerialization>)responseSerializer {
+    NSParameterAssert(responseSerializer);
+
+    _responseSerializer = responseSerializer;
+}
+
+#pragma mark -
+- (void)addNotificationObserverForTask:(NSURLSessionTask *)task {
+    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidResume:) name:AFNSURLSessionTaskDidResumeNotification object:task];
+    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidSuspend:) name:AFNSURLSessionTaskDidSuspendNotification object:task];
+}
+
+- (void)removeNotificationObserverForTask:(NSURLSessionTask *)task {
+    [[NSNotificationCenter defaultCenter] removeObserver:self name:AFNSURLSessionTaskDidSuspendNotification object:task];
+    [[NSNotificationCenter defaultCenter] removeObserver:self name:AFNSURLSessionTaskDidResumeNotification object:task];
+}
+
+#pragma mark -
+
+- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
+                               uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock
+                             downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock
+                            completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject,  NSError * _Nullable error))completionHandler {
+
+    NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:request];
+
+    [self addDelegateForDataTask:dataTask uploadProgress:uploadProgressBlock downloadProgress:downloadProgressBlock completionHandler:completionHandler];
+
+    return dataTask;
+}
+
+#pragma mark -
+
+- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
+                                         fromFile:(NSURL *)fileURL
+                                         progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock
+                                completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
+{
+    NSURLSessionUploadTask *uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL];
+    
+    if (uploadTask) {
+        [self addDelegateForUploadTask:uploadTask
+                              progress:uploadProgressBlock
+                     completionHandler:completionHandler];
+    }
+
+    return uploadTask;
+}
+
+- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
+                                         fromData:(NSData *)bodyData
+                                         progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock
+                                completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
+{
+    NSURLSessionUploadTask *uploadTask = [self.session uploadTaskWithRequest:request fromData:bodyData];
+    
+    [self addDelegateForUploadTask:uploadTask progress:uploadProgressBlock completionHandler:completionHandler];
+
+    return uploadTask;
+}
+
+- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request
+                                                 progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock
+                                        completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
+{
+    NSURLSessionUploadTask *uploadTask = [self.session uploadTaskWithStreamedRequest:request];
+
+    [self addDelegateForUploadTask:uploadTask progress:uploadProgressBlock completionHandler:completionHandler];
+
+    return uploadTask;
+}
+
+#pragma mark -
+
+- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request
+                                             progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock
+                                          destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
+                                    completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
+{
+    NSURLSessionDownloadTask *downloadTask = [self.session downloadTaskWithRequest:request];
+    
+    [self addDelegateForDownloadTask:downloadTask progress:downloadProgressBlock destination:destination completionHandler:completionHandler];
+
+    return downloadTask;
+}
+
+- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData
+                                                progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock
+                                             destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
+                                       completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
+{
+    NSURLSessionDownloadTask *downloadTask = [self.session downloadTaskWithResumeData:resumeData];
+
+    [self addDelegateForDownloadTask:downloadTask progress:downloadProgressBlock destination:destination completionHandler:completionHandler];
+
+    return downloadTask;
+}
+
+#pragma mark -
+- (NSProgress *)uploadProgressForTask:(NSURLSessionTask *)task {
+    return [[self delegateForTask:task] uploadProgress];
+}
+
+- (NSProgress *)downloadProgressForTask:(NSURLSessionTask *)task {
+    return [[self delegateForTask:task] downloadProgress];
+}
+
+#pragma mark -
+
+- (void)setSessionDidBecomeInvalidBlock:(void (^)(NSURLSession *session, NSError *error))block {
+    self.sessionDidBecomeInvalid = block;
+}
+
+- (void)setSessionDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block {
+    self.sessionDidReceiveAuthenticationChallenge = block;
+}
+
+#if !TARGET_OS_OSX
+- (void)setDidFinishEventsForBackgroundURLSessionBlock:(void (^)(NSURLSession *session))block {
+    self.didFinishEventsForBackgroundURLSession = block;
+}
+#endif
+
+#pragma mark -
+
+- (void)setTaskNeedNewBodyStreamBlock:(NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block {
+    self.taskNeedNewBodyStream = block;
+}
+
+- (void)setTaskWillPerformHTTPRedirectionBlock:(NSURLRequest * (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block {
+    self.taskWillPerformHTTPRedirection = block;
+}
+
+- (void)setTaskDidSendBodyDataBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block {
+    self.taskDidSendBodyData = block;
+}
+
+- (void)setTaskDidCompleteBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, NSError *error))block {
+    self.taskDidComplete = block;
+}
+
+#if AF_CAN_INCLUDE_SESSION_TASK_METRICS
+- (void)setTaskDidFinishCollectingMetricsBlock:(void (^)(NSURLSession * _Nonnull, NSURLSessionTask * _Nonnull, NSURLSessionTaskMetrics * _Nullable))block AF_API_AVAILABLE(ios(10), macosx(10.12), watchos(3), tvos(10)) {
+    self.taskDidFinishCollectingMetrics = block;
+}
+#endif
+
+#pragma mark -
+
+- (void)setDataTaskDidReceiveResponseBlock:(NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block {
+    self.dataTaskDidReceiveResponse = block;
+}
+
+- (void)setDataTaskDidBecomeDownloadTaskBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block {
+    self.dataTaskDidBecomeDownloadTask = block;
+}
+
+- (void)setDataTaskDidReceiveDataBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block {
+    self.dataTaskDidReceiveData = block;
+}
+
+- (void)setDataTaskWillCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block {
+    self.dataTaskWillCacheResponse = block;
+}
+
+#pragma mark -
+
+- (void)setDownloadTaskDidFinishDownloadingBlock:(NSURL * (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block {
+    self.downloadTaskDidFinishDownloading = block;
+}
+
+- (void)setDownloadTaskDidWriteDataBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block {
+    self.downloadTaskDidWriteData = block;
+}
+
+- (void)setDownloadTaskDidResumeBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block {
+    self.downloadTaskDidResume = block;
+}
+
+#pragma mark - NSObject
+
+- (NSString *)description {
+    return [NSString stringWithFormat:@"<%@: %p, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, self.session, self.operationQueue];
+}
+
+- (BOOL)respondsToSelector:(SEL)selector {
+    if (selector == @selector(URLSession:didReceiveChallenge:completionHandler:)) {
+        return self.sessionDidReceiveAuthenticationChallenge != nil;
+    } else if (selector == @selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)) {
+        return self.taskWillPerformHTTPRedirection != nil;
+    } else if (selector == @selector(URLSession:dataTask:didReceiveResponse:completionHandler:)) {
+        return self.dataTaskDidReceiveResponse != nil;
+    } else if (selector == @selector(URLSession:dataTask:willCacheResponse:completionHandler:)) {
+        return self.dataTaskWillCacheResponse != nil;
+    }
+#if !TARGET_OS_OSX
+    else if (selector == @selector(URLSessionDidFinishEventsForBackgroundURLSession:)) {
+        return self.didFinishEventsForBackgroundURLSession != nil;
+    }
+#endif
+
+    return [[self class] instancesRespondToSelector:selector];
+}
+
+#pragma mark - NSURLSessionDelegate
+
+- (void)URLSession:(NSURLSession *)session
+didBecomeInvalidWithError:(NSError *)error
+{
+    if (self.sessionDidBecomeInvalid) {
+        self.sessionDidBecomeInvalid(session, error);
+    }
+
+    [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDidInvalidateNotification object:session];
+}
+
+- (void)URLSession:(NSURLSession *)session
+didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
+ completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
+{
+    NSAssert(self.sessionDidReceiveAuthenticationChallenge != nil, @"`respondsToSelector:` implementation forces `URLSession:didReceiveChallenge:completionHandler:` to be called only if `self.sessionDidReceiveAuthenticationChallenge` is not nil");
+
+    NSURLCredential *credential = nil;
+    NSURLSessionAuthChallengeDisposition disposition = self.sessionDidReceiveAuthenticationChallenge(session, challenge, &credential);
+
+    if (completionHandler) {
+        completionHandler(disposition, credential);
+    }
+}
+
+#pragma mark - NSURLSessionTaskDelegate
+
+- (void)URLSession:(NSURLSession *)session
+              task:(NSURLSessionTask *)task
+willPerformHTTPRedirection:(NSHTTPURLResponse *)response
+        newRequest:(NSURLRequest *)request
+ completionHandler:(void (^)(NSURLRequest *))completionHandler
+{
+    NSURLRequest *redirectRequest = request;
+
+    if (self.taskWillPerformHTTPRedirection) {
+        redirectRequest = self.taskWillPerformHTTPRedirection(session, task, response, request);
+    }
+
+    if (completionHandler) {
+        completionHandler(redirectRequest);
+    }
+}
+
+- (void)URLSession:(NSURLSession *)session
+              task:(NSURLSessionTask *)task
+didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
+ completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
+{
+    BOOL evaluateServerTrust = NO;
+    NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
+    NSURLCredential *credential = nil;
+
+    if (self.authenticationChallengeHandler) {
+        id result = self.authenticationChallengeHandler(session, task, challenge, completionHandler);
+        if (result == nil) {
+            return;
+        } else if ([result isKindOfClass:NSError.class]) {
+            objc_setAssociatedObject(task, AuthenticationChallengeErrorKey, result, OBJC_ASSOCIATION_RETAIN);
+            disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
+        } else if ([result isKindOfClass:NSURLCredential.class]) {
+            credential = result;
+            disposition = NSURLSessionAuthChallengeUseCredential;
+        } else if ([result isKindOfClass:NSNumber.class]) {
+            disposition = [result integerValue];
+            NSAssert(disposition == NSURLSessionAuthChallengePerformDefaultHandling || disposition == NSURLSessionAuthChallengeCancelAuthenticationChallenge || disposition == NSURLSessionAuthChallengeRejectProtectionSpace, @"");
+            evaluateServerTrust = disposition == NSURLSessionAuthChallengePerformDefaultHandling && [challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
+        } else {
+            @throw [NSException exceptionWithName:@"Invalid Return Value" reason:@"The return value from the authentication challenge handler must be nil, an NSError, an NSURLCredential or an NSNumber." userInfo:nil];
+        }
+    } else {
+        evaluateServerTrust = [challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
+    }
+
+    if (evaluateServerTrust) {
+        if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
+            disposition = NSURLSessionAuthChallengeUseCredential;
+            credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
+        } else {
+            objc_setAssociatedObject(task, AuthenticationChallengeErrorKey,
+                                     [self serverTrustErrorForServerTrust:challenge.protectionSpace.serverTrust url:task.currentRequest.URL],
+                                     OBJC_ASSOCIATION_RETAIN);
+            disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
+        }
+    }
+
+    if (completionHandler) {
+        completionHandler(disposition, credential);
+    }
+}
+
+- (nonnull NSError *)serverTrustErrorForServerTrust:(nullable SecTrustRef)serverTrust url:(nullable NSURL *)url
+{
+    NSBundle *CFNetworkBundle = [NSBundle bundleWithIdentifier:@"com.apple.CFNetwork"];
+    NSString *defaultValue = @"The certificate for this server is invalid. You might be connecting to a server that is pretending to be “%@” which could put your confidential information at risk.";
+    NSString *descriptionFormat = NSLocalizedStringWithDefaultValue(@"Err-1202.w", nil, CFNetworkBundle, defaultValue, @"") ?: defaultValue;
+    NSString *localizedDescription = [descriptionFormat componentsSeparatedByString:@"%@"].count <= 2 ? [NSString localizedStringWithFormat:descriptionFormat, url.host] : descriptionFormat;
+    NSMutableDictionary *userInfo = [@{
+        NSLocalizedDescriptionKey: localizedDescription
+    } mutableCopy];
+
+    if (serverTrust) {
+        userInfo[NSURLErrorFailingURLPeerTrustErrorKey] = (__bridge id)serverTrust;
+    }
+
+    if (url) {
+        userInfo[NSURLErrorFailingURLErrorKey] = url;
+
+        if (url.absoluteString) {
+            userInfo[NSURLErrorFailingURLStringErrorKey] = url.absoluteString;
+        }
+    }
+
+    return [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorServerCertificateUntrusted userInfo:userInfo];
+}
+
+- (void)URLSession:(NSURLSession *)session
+              task:(NSURLSessionTask *)task
+ needNewBodyStream:(void (^)(NSInputStream *bodyStream))completionHandler
+{
+    NSInputStream *inputStream = nil;
+
+    if (self.taskNeedNewBodyStream) {
+        inputStream = self.taskNeedNewBodyStream(session, task);
+    } else if (task.originalRequest.HTTPBodyStream && [task.originalRequest.HTTPBodyStream conformsToProtocol:@protocol(NSCopying)]) {
+        inputStream = [task.originalRequest.HTTPBodyStream copy];
+    }
+
+    if (completionHandler) {
+        completionHandler(inputStream);
+    }
+}
+
+- (void)URLSession:(NSURLSession *)session
+              task:(NSURLSessionTask *)task
+   didSendBodyData:(int64_t)bytesSent
+    totalBytesSent:(int64_t)totalBytesSent
+totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
+{
+
+    int64_t totalUnitCount = totalBytesExpectedToSend;
+    if (totalUnitCount == NSURLSessionTransferSizeUnknown) {
+        NSString *contentLength = [task.originalRequest valueForHTTPHeaderField:@"Content-Length"];
+        if (contentLength) {
+            totalUnitCount = (int64_t) [contentLength longLongValue];
+        }
+    }
+    
+    AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task];
+    
+    if (delegate) {
+        [delegate URLSession:session task:task didSendBodyData:bytesSent totalBytesSent:totalBytesSent totalBytesExpectedToSend:totalBytesExpectedToSend];
+    }
+
+    if (self.taskDidSendBodyData) {
+        self.taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalUnitCount);
+    }
+}
+
+- (void)URLSession:(NSURLSession *)session
+              task:(NSURLSessionTask *)task
+didCompleteWithError:(NSError *)error
+{
+    AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task];
+
+    // delegate may be nil when completing a task in the background
+    if (delegate) {
+        [delegate URLSession:session task:task didCompleteWithError:error];
+
+        [self removeDelegateForTask:task];
+    }
+
+    if (self.taskDidComplete) {
+        self.taskDidComplete(session, task, error);
+    }
+}
+
+#if AF_CAN_INCLUDE_SESSION_TASK_METRICS
+- (void)URLSession:(NSURLSession *)session
+              task:(NSURLSessionTask *)task
+didFinishCollectingMetrics:(NSURLSessionTaskMetrics *)metrics AF_API_AVAILABLE(ios(10), macosx(10.12), watchos(3), tvos(10))
+{
+    AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task];
+    // Metrics may fire after URLSession:task:didCompleteWithError: is called, delegate may be nil
+    if (delegate) {
+        [delegate URLSession:session task:task didFinishCollectingMetrics:metrics];
+    }
+
+    if (self.taskDidFinishCollectingMetrics) {
+        self.taskDidFinishCollectingMetrics(session, task, metrics);
+    }
+}
+#endif
+
+#pragma mark - NSURLSessionDataDelegate
+
+- (void)URLSession:(NSURLSession *)session
+          dataTask:(NSURLSessionDataTask *)dataTask
+didReceiveResponse:(NSURLResponse *)response
+ completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler
+{
+    NSURLSessionResponseDisposition disposition = NSURLSessionResponseAllow;
+
+    if (self.dataTaskDidReceiveResponse) {
+        disposition = self.dataTaskDidReceiveResponse(session, dataTask, response);
+    }
+
+    if (completionHandler) {
+        completionHandler(disposition);
+    }
+}
+
+- (void)URLSession:(NSURLSession *)session
+          dataTask:(NSURLSessionDataTask *)dataTask
+didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask
+{
+    AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask];
+    if (delegate) {
+        [self removeDelegateForTask:dataTask];
+        [self setDelegate:delegate forTask:downloadTask];
+    }
+
+    if (self.dataTaskDidBecomeDownloadTask) {
+        self.dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask);
+    }
+}
+
+- (void)URLSession:(NSURLSession *)session
+          dataTask:(NSURLSessionDataTask *)dataTask
+    didReceiveData:(NSData *)data
+{
+
+    AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask];
+    [delegate URLSession:session dataTask:dataTask didReceiveData:data];
+
+    if (self.dataTaskDidReceiveData) {
+        self.dataTaskDidReceiveData(session, dataTask, data);
+    }
+}
+
+- (void)URLSession:(NSURLSession *)session
+          dataTask:(NSURLSessionDataTask *)dataTask
+ willCacheResponse:(NSCachedURLResponse *)proposedResponse
+ completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler
+{
+    NSCachedURLResponse *cachedResponse = proposedResponse;
+
+    if (self.dataTaskWillCacheResponse) {
+        cachedResponse = self.dataTaskWillCacheResponse(session, dataTask, proposedResponse);
+    }
+
+    if (completionHandler) {
+        completionHandler(cachedResponse);
+    }
+}
+
+#if !TARGET_OS_OSX
+- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session {
+    if (self.didFinishEventsForBackgroundURLSession) {
+        dispatch_async(dispatch_get_main_queue(), ^{
+            self.didFinishEventsForBackgroundURLSession(session);
+        });
+    }
+}
+#endif
+
+#pragma mark - NSURLSessionDownloadDelegate
+
+- (void)URLSession:(NSURLSession *)session
+      downloadTask:(NSURLSessionDownloadTask *)downloadTask
+didFinishDownloadingToURL:(NSURL *)location
+{
+    AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask];
+    if (self.downloadTaskDidFinishDownloading) {
+        NSURL *fileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location);
+        if (fileURL) {
+            delegate.downloadFileURL = fileURL;
+            NSError *error = nil;
+            
+            if (![[NSFileManager defaultManager] moveItemAtURL:location toURL:fileURL error:&error]) {
+                [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:error.userInfo];
+            } else {
+                [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidMoveFileSuccessfullyNotification object:downloadTask userInfo:nil];
+            }
+
+            return;
+        }
+    }
+
+    if (delegate) {
+        [delegate URLSession:session downloadTask:downloadTask didFinishDownloadingToURL:location];
+    }
+}
+
+- (void)URLSession:(NSURLSession *)session
+      downloadTask:(NSURLSessionDownloadTask *)downloadTask
+      didWriteData:(int64_t)bytesWritten
+ totalBytesWritten:(int64_t)totalBytesWritten
+totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
+{
+    
+    AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask];
+    
+    if (delegate) {
+        [delegate URLSession:session downloadTask:downloadTask didWriteData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite];
+    }
+
+    if (self.downloadTaskDidWriteData) {
+        self.downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
+    }
+}
+
+- (void)URLSession:(NSURLSession *)session
+      downloadTask:(NSURLSessionDownloadTask *)downloadTask
+ didResumeAtOffset:(int64_t)fileOffset
+expectedTotalBytes:(int64_t)expectedTotalBytes
+{
+    
+    AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask];
+    
+    if (delegate) {
+        [delegate URLSession:session downloadTask:downloadTask didResumeAtOffset:fileOffset expectedTotalBytes:expectedTotalBytes];
+    }
+
+    if (self.downloadTaskDidResume) {
+        self.downloadTaskDidResume(session, downloadTask, fileOffset, expectedTotalBytes);
+    }
+}
+
+#pragma mark - NSSecureCoding
+
++ (BOOL)supportsSecureCoding {
+    return YES;
+}
+
+- (instancetype)initWithCoder:(NSCoder *)decoder {
+    NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"];
+
+    self = [self initWithSessionConfiguration:configuration];
+    if (!self) {
+        return nil;
+    }
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)coder {
+    [coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"];
+}
+
+#pragma mark - NSCopying
+
+- (instancetype)copyWithZone:(NSZone *)zone {
+    return [[[self class] allocWithZone:zone] initWithSessionConfiguration:self.session.configuration];
+}
+
+@end

+ 19 - 0
Pods/AFNetworking/LICENSE

@@ -0,0 +1,19 @@
+Copyright (c) 2011-2020 Alamofire Software Foundation (http://alamofire.org/)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.

+ 298 - 0
Pods/AFNetworking/README.md

@@ -0,0 +1,298 @@
+<p align="center" >
+  <img src="https://raw.github.com/AFNetworking/AFNetworking/assets/afnetworking-logo.png" alt="AFNetworking" title="AFNetworking">
+</p>
+
+[![Build Status](https://github.com/AFNetworking/AFNetworking/workflows/AFNetworking%20CI/badge.svg?branch=master)](https://github.com/AFNetworking/AFNetworking/actions)
+[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/AFNetworking.svg)](https://img.shields.io/cocoapods/v/AFNetworking.svg)
+[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)
+[![Platform](https://img.shields.io/cocoapods/p/AFNetworking.svg?style=flat)](http://cocoadocs.org/docsets/AFNetworking)
+[![Twitter](https://img.shields.io/badge/twitter-@AFNetworking-blue.svg?style=flat)](http://twitter.com/AFNetworking)
+
+AFNetworking is a delightful networking library for iOS, macOS, watchOS, and tvOS. It's built on top of the [Foundation URL Loading System](https://developer.apple.com/documentation/foundation/url_loading_system), extending the powerful high-level networking abstractions built into Cocoa. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use.
+
+Perhaps the most important feature of all, however, is the amazing community of developers who use and contribute to AFNetworking every day. AFNetworking powers some of the most popular and critically-acclaimed apps on the iPhone, iPad, and Mac.
+
+## How To Get Started
+
+- [Download AFNetworking](https://github.com/AFNetworking/AFNetworking/archive/master.zip) and try out the included Mac and iPhone example apps
+- Read the ["Getting Started" guide](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking), [FAQ](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ), or [other articles on the Wiki](https://github.com/AFNetworking/AFNetworking/wiki)
+
+## Communication
+
+- If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking). (Tag 'afnetworking')
+- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking).
+- If you **found a bug**, _and can provide steps to reliably reproduce it_, open an issue.
+- If you **have a feature request**, open an issue.
+- If you **want to contribute**, submit a pull request.
+
+## Installation
+AFNetworking supports multiple methods for installing the library in a project.
+
+## Installation with CocoaPods
+
+To integrate AFNetworking into your Xcode project using CocoaPods, specify it in your `Podfile`:
+
+```ruby
+pod 'AFNetworking', '~> 4.0'
+```
+
+### Installation with Swift Package Manager
+
+Once you have your Swift package set up, adding AFNetworking as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`.
+
+```swift
+dependencies: [
+    .package(url: "https://github.com/AFNetworking/AFNetworking.git", .upToNextMajor(from: "4.0.0"))
+]
+```
+
+> Note: AFNetworking's Swift package does not include it's UIKit extensions.
+
+### Installation with Carthage
+
+[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate AFNetworking, add the following to your `Cartfile`.
+
+```ogdl
+github "AFNetworking/AFNetworking" ~> 4.0
+```
+
+## Requirements
+
+| AFNetworking Version | Minimum iOS Target  | Minimum macOS Target  | Minimum watchOS Target  | Minimum tvOS Target  |                                   Notes                                   |
+|:--------------------:|:---------------------------:|:----------------------------:|:----------------------------:|:----------------------------:|:-------------------------------------------------------------------------:|
+| 4.x | iOS 9 | macOS 10.10 | watchOS 2.0 | tvOS 9.0 | Xcode 11+ is required. |
+| 3.x | iOS 7 | OS X 10.9 | watchOS 2.0 | tvOS 9.0 | Xcode 7+ is required. `NSURLConnectionOperation` support has been removed. |
+| 2.6 -> 2.6.3 | iOS 7 | OS X 10.9 | watchOS 2.0 | n/a | Xcode 7+ is required. |
+| 2.0 -> 2.5.4 | iOS 6 | OS X 10.8 | n/a | n/a | Xcode 5+ is required. `NSURLSession` subspec requires iOS 7 or OS X 10.9. |
+| 1.x | iOS 5 | Mac OS X 10.7 | n/a | n/a |
+| 0.10.x | iOS 4 | Mac OS X 10.6 | n/a | n/a |
+
+(macOS projects must support [64-bit with modern Cocoa runtime](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtVersionsPlatforms.html)).
+
+> Programming in Swift? Try [Alamofire](https://github.com/Alamofire/Alamofire) for a more conventional set of APIs.
+
+## Architecture
+
+### NSURLSession
+
+- `AFURLSessionManager`
+- `AFHTTPSessionManager`
+
+### Serialization
+
+* `<AFURLRequestSerialization>`
+  - `AFHTTPRequestSerializer`
+  - `AFJSONRequestSerializer`
+  - `AFPropertyListRequestSerializer`
+* `<AFURLResponseSerialization>`
+  - `AFHTTPResponseSerializer`
+  - `AFJSONResponseSerializer`
+  - `AFXMLParserResponseSerializer`
+  - `AFXMLDocumentResponseSerializer` _(macOS)_
+  - `AFPropertyListResponseSerializer`
+  - `AFImageResponseSerializer`
+  - `AFCompoundResponseSerializer`
+
+### Additional Functionality
+
+- `AFSecurityPolicy`
+- `AFNetworkReachabilityManager`
+
+## Usage
+
+### AFURLSessionManager
+
+`AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to `<NSURLSessionTaskDelegate>`, `<NSURLSessionDataDelegate>`, `<NSURLSessionDownloadDelegate>`, and `<NSURLSessionDelegate>`.
+
+#### Creating a Download Task
+
+```objective-c
+NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
+AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
+
+NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];
+NSURLRequest *request = [NSURLRequest requestWithURL:URL];
+
+NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
+    NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
+    return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
+} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
+    NSLog(@"File downloaded to: %@", filePath);
+}];
+[downloadTask resume];
+```
+
+#### Creating an Upload Task
+
+```objective-c
+NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
+AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
+
+NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
+NSURLRequest *request = [NSURLRequest requestWithURL:URL];
+
+NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
+NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
+    if (error) {
+        NSLog(@"Error: %@", error);
+    } else {
+        NSLog(@"Success: %@ %@", response, responseObject);
+    }
+}];
+[uploadTask resume];
+```
+
+#### Creating an Upload Task for a Multi-Part Request, with Progress
+
+```objective-c
+NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
+        [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
+    } error:nil];
+
+AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
+
+NSURLSessionUploadTask *uploadTask;
+uploadTask = [manager
+              uploadTaskWithStreamedRequest:request
+              progress:^(NSProgress * _Nonnull uploadProgress) {
+                  // This is not called back on the main queue.
+                  // You are responsible for dispatching to the main queue for UI updates
+                  dispatch_async(dispatch_get_main_queue(), ^{
+                      //Update the progress view
+                      [progressView setProgress:uploadProgress.fractionCompleted];
+                  });
+              }
+              completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
+                  if (error) {
+                      NSLog(@"Error: %@", error);
+                  } else {
+                      NSLog(@"%@ %@", response, responseObject);
+                  }
+              }];
+
+[uploadTask resume];
+```
+
+#### Creating a Data Task
+
+```objective-c
+NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
+AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
+
+NSURL *URL = [NSURL URLWithString:@"http://httpbin.org/get"];
+NSURLRequest *request = [NSURLRequest requestWithURL:URL];
+
+NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
+    if (error) {
+        NSLog(@"Error: %@", error);
+    } else {
+        NSLog(@"%@ %@", response, responseObject);
+    }
+}];
+[dataTask resume];
+```
+
+---
+
+### Request Serialization
+
+Request serializers create requests from URL strings, encoding parameters as either a query string or HTTP body.
+
+```objective-c
+NSString *URLString = @"http://example.com";
+NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};
+```
+
+#### Query String Parameter Encoding
+
+```objective-c
+[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
+```
+
+    GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3
+
+#### URL Form Parameter Encoding
+
+```objective-c
+[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
+```
+
+    POST http://example.com/
+    Content-Type: application/x-www-form-urlencoded
+
+    foo=bar&baz[]=1&baz[]=2&baz[]=3
+
+#### JSON Parameter Encoding
+
+```objective-c
+[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
+```
+
+    POST http://example.com/
+    Content-Type: application/json
+
+    {"foo": "bar", "baz": [1,2,3]}
+
+---
+
+### Network Reachability Manager
+
+`AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.
+
+* Do not use Reachability to determine if the original request should be sent.
+	* You should try to send it.
+* You can use Reachability to determine when a request should be automatically retried.
+	* Although it may still fail, a Reachability notification that the connectivity is available is a good time to retry something.
+* Network reachability is a useful tool for determining why a request might have failed.
+	* After a network request has failed, telling the user they're offline is better than giving them a more technical but accurate error, such as "request timed out."
+
+See also [WWDC 2012 session 706, "Networking Best Practices."](https://developer.apple.com/videos/play/wwdc2012-706/).
+
+#### Shared Network Reachability
+
+```objective-c
+[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
+    NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
+}];
+
+[[AFNetworkReachabilityManager sharedManager] startMonitoring];
+```
+
+---
+
+### Security Policy
+
+`AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections.
+
+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.
+
+#### Allowing Invalid SSL Certificates
+
+```objective-c
+AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
+manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production
+```
+
+---
+
+## Unit Tests
+
+AFNetworking includes a suite of unit tests within the Tests subdirectory. These tests can be run simply be executed the test action on the platform framework you would like to test.
+
+## Credits
+
+AFNetworking is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org).
+
+AFNetworking was originally created by [Scott Raymond](https://github.com/sco/) and [Mattt Thompson](https://github.com/mattt/) in the development of [Gowalla for iPhone](http://en.wikipedia.org/wiki/Gowalla).
+
+AFNetworking's logo was designed by [Alan Defibaugh](http://www.alandefibaugh.com/).
+
+And most of all, thanks to AFNetworking's [growing list of contributors](https://github.com/AFNetworking/AFNetworking/contributors).
+
+### Security Disclosure
+
+If you believe you have identified a security vulnerability with AFNetworking, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker.
+
+## License
+
+AFNetworking is released under the MIT license. See [LICENSE](https://github.com/AFNetworking/AFNetworking/blob/master/LICENSE) for details.

+ 160 - 0
Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h

@@ -0,0 +1,160 @@
+// AFAutoPurgingImageCache.h
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <TargetConditionals.h>
+#import <Foundation/Foundation.h>
+
+#if TARGET_OS_IOS || TARGET_OS_TV
+#import <UIKit/UIKit.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ The `AFImageCache` protocol defines a set of APIs for adding, removing and fetching images from a cache synchronously.
+ */
+@protocol AFImageCache <NSObject>
+
+/**
+ Adds the image to the cache with the given identifier.
+
+ @param image The image to cache.
+ @param identifier The unique identifier for the image in the cache.
+ */
+- (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier;
+
+/**
+ Removes the image from the cache matching the given identifier.
+
+ @param identifier The unique identifier for the image in the cache.
+
+ @return A BOOL indicating whether or not the image was removed from the cache.
+ */
+- (BOOL)removeImageWithIdentifier:(NSString *)identifier;
+
+/**
+ Removes all images from the cache.
+
+ @return A BOOL indicating whether or not all images were removed from the cache.
+ */
+- (BOOL)removeAllImages;
+
+/**
+ Returns the image in the cache associated with the given identifier.
+
+ @param identifier The unique identifier for the image in the cache.
+
+ @return An image for the matching identifier, or nil.
+ */
+- (nullable UIImage *)imageWithIdentifier:(NSString *)identifier;
+@end
+
+
+/**
+ The `ImageRequestCache` protocol extends the `ImageCache` protocol by adding methods for adding, removing and fetching images from a cache given an `NSURLRequest` and additional identifier.
+ */
+@protocol AFImageRequestCache <AFImageCache>
+
+/**
+ Asks if the image should be cached using an identifier created from the request and additional identifier.
+ 
+ @param image The image to be cached.
+ @param request The unique URL request identifing the image asset.
+ @param identifier The additional identifier to apply to the URL request to identify the image.
+ 
+ @return A BOOL indicating whether or not the image should be added to the cache. YES will cache, NO will prevent caching.
+ */
+- (BOOL)shouldCacheImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
+
+/**
+ Adds the image to the cache using an identifier created from the request and additional identifier.
+
+ @param image The image to cache.
+ @param request The unique URL request identifing the image asset.
+ @param identifier The additional identifier to apply to the URL request to identify the image.
+ */
+- (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
+
+/**
+ Removes the image from the cache using an identifier created from the request and additional identifier.
+
+ @param request The unique URL request identifing the image asset.
+ @param identifier The additional identifier to apply to the URL request to identify the image.
+ 
+ @return A BOOL indicating whether or not all images were removed from the cache.
+ */
+- (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
+
+/**
+ Returns the image from the cache associated with an identifier created from the request and additional identifier.
+
+ @param request The unique URL request identifing the image asset.
+ @param identifier The additional identifier to apply to the URL request to identify the image.
+
+ @return An image for the matching request and identifier, or nil.
+ */
+- (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
+
+@end
+
+/**
+ The `AutoPurgingImageCache` in an in-memory image cache used to store images up to a given memory capacity. When the memory capacity is reached, the image cache is sorted by last access date, then the oldest image is continuously purged until the preferred memory usage after purge is met. Each time an image is accessed through the cache, the internal access date of the image is updated.
+ */
+@interface AFAutoPurgingImageCache : NSObject <AFImageRequestCache>
+
+/**
+ The total memory capacity of the cache in bytes.
+ */
+@property (nonatomic, assign) UInt64 memoryCapacity;
+
+/**
+ The preferred memory usage after purge in bytes. During a purge, images will be purged until the memory capacity drops below this limit.
+ */
+@property (nonatomic, assign) UInt64 preferredMemoryUsageAfterPurge;
+
+/**
+ The current total memory usage in bytes of all images stored within the cache.
+ */
+@property (nonatomic, assign, readonly) UInt64 memoryUsage;
+
+/**
+ Initialies the `AutoPurgingImageCache` instance with default values for memory capacity and preferred memory usage after purge limit. `memoryCapcity` defaults to `100 MB`. `preferredMemoryUsageAfterPurge` defaults to `60 MB`.
+
+ @return The new `AutoPurgingImageCache` instance.
+ */
+- (instancetype)init;
+
+/**
+ Initialies the `AutoPurgingImageCache` instance with the given memory capacity and preferred memory usage
+ after purge limit.
+
+ @param memoryCapacity The total memory capacity of the cache in bytes.
+ @param preferredMemoryCapacity The preferred memory usage after purge in bytes.
+
+ @return The new `AutoPurgingImageCache` instance.
+ */
+- (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity;
+
+@end
+
+NS_ASSUME_NONNULL_END
+
+#endif
+

+ 205 - 0
Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.m

@@ -0,0 +1,205 @@
+// AFAutoPurgingImageCache.m
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <TargetConditionals.h>
+
+#if TARGET_OS_IOS || TARGET_OS_TV 
+
+#import "AFAutoPurgingImageCache.h"
+
+@interface AFCachedImage : NSObject
+
+@property (nonatomic, strong) UIImage *image;
+@property (nonatomic, copy) NSString *identifier;
+@property (nonatomic, assign) UInt64 totalBytes;
+@property (nonatomic, strong) NSDate *lastAccessDate;
+@property (nonatomic, assign) UInt64 currentMemoryUsage;
+
+@end
+
+@implementation AFCachedImage
+
+- (instancetype)initWithImage:(UIImage *)image identifier:(NSString *)identifier {
+    if (self = [self init]) {
+        self.image = image;
+        self.identifier = identifier;
+
+        CGSize imageSize = CGSizeMake(image.size.width * image.scale, image.size.height * image.scale);
+        CGFloat bytesPerPixel = 4.0;
+        CGFloat bytesPerSize = imageSize.width * imageSize.height;
+        self.totalBytes = (UInt64)bytesPerPixel * (UInt64)bytesPerSize;
+        self.lastAccessDate = [NSDate date];
+    }
+    return self;
+}
+
+- (UIImage *)accessImage {
+    self.lastAccessDate = [NSDate date];
+    return self.image;
+}
+
+- (NSString *)description {
+    NSString *descriptionString = [NSString stringWithFormat:@"Idenfitier: %@  lastAccessDate: %@ ", self.identifier, self.lastAccessDate];
+    return descriptionString;
+
+}
+
+@end
+
+@interface AFAutoPurgingImageCache ()
+@property (nonatomic, strong) NSMutableDictionary <NSString* , AFCachedImage*> *cachedImages;
+@property (nonatomic, assign) UInt64 currentMemoryUsage;
+@property (nonatomic, strong) dispatch_queue_t synchronizationQueue;
+@end
+
+@implementation AFAutoPurgingImageCache
+
+- (instancetype)init {
+    return [self initWithMemoryCapacity:100 * 1024 * 1024 preferredMemoryCapacity:60 * 1024 * 1024];
+}
+
+- (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity {
+    if (self = [super init]) {
+        self.memoryCapacity = memoryCapacity;
+        self.preferredMemoryUsageAfterPurge = preferredMemoryCapacity;
+        self.cachedImages = [[NSMutableDictionary alloc] init];
+
+        NSString *queueName = [NSString stringWithFormat:@"com.alamofire.autopurgingimagecache-%@", [[NSUUID UUID] UUIDString]];
+        self.synchronizationQueue = dispatch_queue_create([queueName cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT);
+
+        [[NSNotificationCenter defaultCenter]
+         addObserver:self
+         selector:@selector(removeAllImages)
+         name:UIApplicationDidReceiveMemoryWarningNotification
+         object:nil];
+
+    }
+    return self;
+}
+
+- (void)dealloc {
+    [[NSNotificationCenter defaultCenter] removeObserver:self];
+}
+
+- (UInt64)memoryUsage {
+    __block UInt64 result = 0;
+    dispatch_sync(self.synchronizationQueue, ^{
+        result = self.currentMemoryUsage;
+    });
+    return result;
+}
+
+- (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier {
+    dispatch_barrier_async(self.synchronizationQueue, ^{
+        AFCachedImage *cacheImage = [[AFCachedImage alloc] initWithImage:image identifier:identifier];
+
+        AFCachedImage *previousCachedImage = self.cachedImages[identifier];
+        if (previousCachedImage != nil) {
+            self.currentMemoryUsage -= previousCachedImage.totalBytes;
+        }
+
+        self.cachedImages[identifier] = cacheImage;
+        self.currentMemoryUsage += cacheImage.totalBytes;
+    });
+
+    dispatch_barrier_async(self.synchronizationQueue, ^{
+        if (self.currentMemoryUsage > self.memoryCapacity) {
+            UInt64 bytesToPurge = self.currentMemoryUsage - self.preferredMemoryUsageAfterPurge;
+            NSMutableArray <AFCachedImage*> *sortedImages = [NSMutableArray arrayWithArray:self.cachedImages.allValues];
+            NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastAccessDate"
+                                                                           ascending:YES];
+            [sortedImages sortUsingDescriptors:@[sortDescriptor]];
+
+            UInt64 bytesPurged = 0;
+
+            for (AFCachedImage *cachedImage in sortedImages) {
+                [self.cachedImages removeObjectForKey:cachedImage.identifier];
+                bytesPurged += cachedImage.totalBytes;
+                if (bytesPurged >= bytesToPurge) {
+                    break;
+                }
+            }
+            self.currentMemoryUsage -= bytesPurged;
+        }
+    });
+}
+
+- (BOOL)removeImageWithIdentifier:(NSString *)identifier {
+    __block BOOL removed = NO;
+    dispatch_barrier_sync(self.synchronizationQueue, ^{
+        AFCachedImage *cachedImage = self.cachedImages[identifier];
+        if (cachedImage != nil) {
+            [self.cachedImages removeObjectForKey:identifier];
+            self.currentMemoryUsage -= cachedImage.totalBytes;
+            removed = YES;
+        }
+    });
+    return removed;
+}
+
+- (BOOL)removeAllImages {
+    __block BOOL removed = NO;
+    dispatch_barrier_sync(self.synchronizationQueue, ^{
+        if (self.cachedImages.count > 0) {
+            [self.cachedImages removeAllObjects];
+            self.currentMemoryUsage = 0;
+            removed = YES;
+        }
+    });
+    return removed;
+}
+
+- (nullable UIImage *)imageWithIdentifier:(NSString *)identifier {
+    __block UIImage *image = nil;
+    dispatch_sync(self.synchronizationQueue, ^{
+        AFCachedImage *cachedImage = self.cachedImages[identifier];
+        image = [cachedImage accessImage];
+    });
+    return image;
+}
+
+- (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier {
+    [self addImage:image withIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]];
+}
+
+- (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier {
+    return [self removeImageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]];
+}
+
+- (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier {
+    return [self imageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]];
+}
+
+- (NSString *)imageCacheKeyFromURLRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)additionalIdentifier {
+    NSString *key = request.URL.absoluteString;
+    if (additionalIdentifier != nil) {
+        key = [key stringByAppendingString:additionalIdentifier];
+    }
+    return key;
+}
+
+- (BOOL)shouldCacheImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier {
+    return YES;
+}
+
+@end
+
+#endif

+ 171 - 0
Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.h

@@ -0,0 +1,171 @@
+// AFImageDownloader.h
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <TargetConditionals.h>
+
+#if TARGET_OS_IOS || TARGET_OS_TV 
+
+#import <Foundation/Foundation.h>
+#import "AFAutoPurgingImageCache.h"
+#import "AFHTTPSessionManager.h"
+
+NS_ASSUME_NONNULL_BEGIN
+
+typedef NS_ENUM(NSInteger, AFImageDownloadPrioritization) {
+    AFImageDownloadPrioritizationFIFO,
+    AFImageDownloadPrioritizationLIFO
+};
+
+/**
+ The `AFImageDownloadReceipt` is an object vended by the `AFImageDownloader` when starting a data task. It can be used to cancel active tasks running on the `AFImageDownloader` session. As a general rule, image data tasks should be cancelled using the `AFImageDownloadReceipt` instead of calling `cancel` directly on the `task` itself. The `AFImageDownloader` is optimized to handle duplicate task scenarios as well as pending versus active downloads.
+ */
+@interface AFImageDownloadReceipt : NSObject
+
+/**
+ The data task created by the `AFImageDownloader`.
+*/
+@property (nonatomic, strong) NSURLSessionDataTask *task;
+
+/**
+ The unique identifier for the success and failure blocks when duplicate requests are made.
+ */
+@property (nonatomic, strong) NSUUID *receiptID;
+@end
+
+/** The `AFImageDownloader` class is responsible for downloading images in parallel on a prioritized queue. Incoming downloads are added to the front or back of the queue depending on the download prioritization. Each downloaded image is cached in the underlying `NSURLCache` as well as the in-memory image cache. By default, any download request with a cached image equivalent in the image cache will automatically be served the cached image representation.
+ */
+@interface AFImageDownloader : NSObject
+
+/**
+ The image cache used to store all downloaded images in. `AFAutoPurgingImageCache` by default.
+ */
+@property (nonatomic, strong, nullable) id <AFImageRequestCache> imageCache;
+
+/**
+ The `AFHTTPSessionManager` used to download images. By default, this is configured with an `AFImageResponseSerializer`, and a shared `NSURLCache` for all image downloads.
+ */
+@property (nonatomic, strong) AFHTTPSessionManager *sessionManager;
+
+/**
+ Defines the order prioritization of incoming download requests being inserted into the queue. `AFImageDownloadPrioritizationFIFO` by default.
+ */
+@property (nonatomic, assign) AFImageDownloadPrioritization downloadPrioritization;
+
+/**
+ The shared default instance of `AFImageDownloader` initialized with default values.
+ */
++ (instancetype)defaultInstance;
+
+/**
+ Creates a default `NSURLCache` with common usage parameter values.
+
+ @returns The default `NSURLCache` instance.
+ */
++ (NSURLCache *)defaultURLCache;
+
+/**
+ The default `NSURLSessionConfiguration` with common usage parameter values.
+ */
++ (NSURLSessionConfiguration *)defaultURLSessionConfiguration;
+
+/**
+ Default initializer
+
+ @return An instance of `AFImageDownloader` initialized with default values.
+ */
+- (instancetype)init;
+
+/**
+ Initializer with specific `URLSessionConfiguration`
+ 
+ @param configuration The `NSURLSessionConfiguration` to be be used
+ 
+ @return An instance of `AFImageDownloader` initialized with default values and custom `NSURLSessionConfiguration`
+ */
+- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration;
+
+/**
+ Initializes the `AFImageDownloader` instance with the given session manager, download prioritization, maximum active download count and image cache.
+
+ @param sessionManager The session manager to use to download images.
+ @param downloadPrioritization The download prioritization of the download queue.
+ @param maximumActiveDownloads  The maximum number of active downloads allowed at any given time. Recommend `4`.
+ @param imageCache The image cache used to store all downloaded images in.
+
+ @return The new `AFImageDownloader` instance.
+ */
+- (instancetype)initWithSessionManager:(AFHTTPSessionManager *)sessionManager
+                downloadPrioritization:(AFImageDownloadPrioritization)downloadPrioritization
+                maximumActiveDownloads:(NSInteger)maximumActiveDownloads
+                            imageCache:(nullable id <AFImageRequestCache>)imageCache;
+
+/**
+ Creates a data task using the `sessionManager` instance for the specified URL request.
+
+ If the same data task is already in the queue or currently being downloaded, the success and failure blocks are
+ appended to the already existing task. Once the task completes, all success or failure blocks attached to the
+ task are executed in the order they were added.
+
+ @param request The URL request.
+ @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`.
+ @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
+
+ @return The image download receipt for the data task if available. `nil` if the image is stored in the cache.
+ cache and the URL request cache policy allows the cache to be used.
+ */
+- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
+                                                        success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse  * _Nullable response, UIImage *responseObject))success
+                                                        failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
+
+/**
+ Creates a data task using the `sessionManager` instance for the specified URL request.
+
+ If the same data task is already in the queue or currently being downloaded, the success and failure blocks are
+ appended to the already existing task. Once the task completes, all success or failure blocks attached to the
+ task are executed in the order they were added.
+
+ @param request The URL request.
+ @param receiptID The identifier to use for the download receipt that will be created for this request. This must be a unique identifier that does not represent any other request.
+ @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`.
+ @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
+
+ @return The image download receipt for the data task if available. `nil` if the image is stored in the cache.
+ cache and the URL request cache policy allows the cache to be used.
+ */
+- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
+                                                 withReceiptID:(NSUUID *)receiptID
+                                                        success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse  * _Nullable response, UIImage *responseObject))success
+                                                        failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
+
+/**
+ Cancels the data task in the receipt by removing the corresponding success and failure blocks and cancelling the data task if necessary.
+
+ If the data task is pending in the queue, it will be cancelled if no other success and failure blocks are registered with the data task. If the data task is currently executing or is already completed, the success and failure blocks are removed and will not be called when the task finishes.
+
+ @param imageDownloadReceipt The image download receipt to cancel.
+ */
+- (void)cancelTaskForImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt;
+
+@end
+
+#endif
+
+NS_ASSUME_NONNULL_END

+ 421 - 0
Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.m

@@ -0,0 +1,421 @@
+// AFImageDownloader.m
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <TargetConditionals.h>
+
+#if TARGET_OS_IOS || TARGET_OS_TV
+
+#import "AFImageDownloader.h"
+#import "AFHTTPSessionManager.h"
+
+@interface AFImageDownloaderResponseHandler : NSObject
+@property (nonatomic, strong) NSUUID *uuid;
+@property (nonatomic, copy) void (^successBlock)(NSURLRequest *, NSHTTPURLResponse *, UIImage *);
+@property (nonatomic, copy) void (^failureBlock)(NSURLRequest *, NSHTTPURLResponse *, NSError *);
+@end
+
+@implementation AFImageDownloaderResponseHandler
+
+- (instancetype)initWithUUID:(NSUUID *)uuid
+                     success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success
+                     failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure {
+    if (self = [self init]) {
+        self.uuid = uuid;
+        self.successBlock = success;
+        self.failureBlock = failure;
+    }
+    return self;
+}
+
+- (NSString *)description {
+    return [NSString stringWithFormat: @"<AFImageDownloaderResponseHandler>UUID: %@", [self.uuid UUIDString]];
+}
+
+@end
+
+@interface AFImageDownloaderMergedTask : NSObject
+@property (nonatomic, strong) NSString *URLIdentifier;
+@property (nonatomic, strong) NSUUID *identifier;
+@property (nonatomic, strong) NSURLSessionDataTask *task;
+@property (nonatomic, strong) NSMutableArray <AFImageDownloaderResponseHandler*> *responseHandlers;
+
+@end
+
+@implementation AFImageDownloaderMergedTask
+
+- (instancetype)initWithURLIdentifier:(NSString *)URLIdentifier identifier:(NSUUID *)identifier task:(NSURLSessionDataTask *)task {
+    if (self = [self init]) {
+        self.URLIdentifier = URLIdentifier;
+        self.task = task;
+        self.identifier = identifier;
+        self.responseHandlers = [[NSMutableArray alloc] init];
+    }
+    return self;
+}
+
+- (void)addResponseHandler:(AFImageDownloaderResponseHandler *)handler {
+    [self.responseHandlers addObject:handler];
+}
+
+- (void)removeResponseHandler:(AFImageDownloaderResponseHandler *)handler {
+    [self.responseHandlers removeObject:handler];
+}
+
+@end
+
+@implementation AFImageDownloadReceipt
+
+- (instancetype)initWithReceiptID:(NSUUID *)receiptID task:(NSURLSessionDataTask *)task {
+    if (self = [self init]) {
+        self.receiptID = receiptID;
+        self.task = task;
+    }
+    return self;
+}
+
+@end
+
+@interface AFImageDownloader ()
+
+@property (nonatomic, strong) dispatch_queue_t synchronizationQueue;
+@property (nonatomic, strong) dispatch_queue_t responseQueue;
+
+@property (nonatomic, assign) NSInteger maximumActiveDownloads;
+@property (nonatomic, assign) NSInteger activeRequestCount;
+
+@property (nonatomic, strong) NSMutableArray *queuedMergedTasks;
+@property (nonatomic, strong) NSMutableDictionary *mergedTasks;
+
+@end
+
+@implementation AFImageDownloader
+
++ (NSURLCache *)defaultURLCache {
+    NSUInteger memoryCapacity = 20 * 1024 * 1024; // 20MB
+    NSUInteger diskCapacity = 150 * 1024 * 1024; // 150MB
+    NSURL *cacheURL = [[[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory
+                                                              inDomain:NSUserDomainMask
+                                                     appropriateForURL:nil
+                                                                create:YES
+                                                                 error:nil]
+                       URLByAppendingPathComponent:@"com.alamofire.imagedownloader"];
+    
+#if TARGET_OS_MACCATALYST
+    return [[NSURLCache alloc] initWithMemoryCapacity:memoryCapacity
+                                         diskCapacity:diskCapacity
+                                         directoryURL:cacheURL];
+#else
+    return [[NSURLCache alloc] initWithMemoryCapacity:memoryCapacity
+                                         diskCapacity:diskCapacity
+                                             diskPath:[cacheURL path]];
+#endif
+}
+
++ (NSURLSessionConfiguration *)defaultURLSessionConfiguration {
+    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
+
+    //TODO set the default HTTP headers
+
+    configuration.HTTPShouldSetCookies = YES;
+    configuration.HTTPShouldUsePipelining = NO;
+
+    configuration.requestCachePolicy = NSURLRequestUseProtocolCachePolicy;
+    configuration.allowsCellularAccess = YES;
+    configuration.timeoutIntervalForRequest = 60.0;
+    configuration.URLCache = [AFImageDownloader defaultURLCache];
+
+    return configuration;
+}
+
+- (instancetype)init {
+    NSURLSessionConfiguration *defaultConfiguration = [self.class defaultURLSessionConfiguration];
+    return [self initWithSessionConfiguration:defaultConfiguration];
+}
+
+- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration {
+    AFHTTPSessionManager *sessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
+    sessionManager.responseSerializer = [AFImageResponseSerializer serializer];
+
+    return [self initWithSessionManager:sessionManager
+                 downloadPrioritization:AFImageDownloadPrioritizationFIFO
+                 maximumActiveDownloads:4
+                             imageCache:[[AFAutoPurgingImageCache alloc] init]];
+}
+
+- (instancetype)initWithSessionManager:(AFHTTPSessionManager *)sessionManager
+                downloadPrioritization:(AFImageDownloadPrioritization)downloadPrioritization
+                maximumActiveDownloads:(NSInteger)maximumActiveDownloads
+                            imageCache:(id <AFImageRequestCache>)imageCache {
+    if (self = [super init]) {
+        self.sessionManager = sessionManager;
+
+        self.downloadPrioritization = downloadPrioritization;
+        self.maximumActiveDownloads = maximumActiveDownloads;
+        self.imageCache = imageCache;
+
+        self.queuedMergedTasks = [[NSMutableArray alloc] init];
+        self.mergedTasks = [[NSMutableDictionary alloc] init];
+        self.activeRequestCount = 0;
+
+        NSString *name = [NSString stringWithFormat:@"com.alamofire.imagedownloader.synchronizationqueue-%@", [[NSUUID UUID] UUIDString]];
+        self.synchronizationQueue = dispatch_queue_create([name cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_SERIAL);
+
+        name = [NSString stringWithFormat:@"com.alamofire.imagedownloader.responsequeue-%@", [[NSUUID UUID] UUIDString]];
+        self.responseQueue = dispatch_queue_create([name cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT);
+    }
+
+    return self;
+}
+
++ (instancetype)defaultInstance {
+    static AFImageDownloader *sharedInstance = nil;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        sharedInstance = [[self alloc] init];
+    });
+    return sharedInstance;
+}
+
+- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
+                                                        success:(void (^)(NSURLRequest * _Nonnull, NSHTTPURLResponse * _Nullable, UIImage * _Nonnull))success
+                                                        failure:(void (^)(NSURLRequest * _Nonnull, NSHTTPURLResponse * _Nullable, NSError * _Nonnull))failure {
+    return [self downloadImageForURLRequest:request withReceiptID:[NSUUID UUID] success:success failure:failure];
+}
+
+- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
+                                                  withReceiptID:(nonnull NSUUID *)receiptID
+                                                        success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse  * _Nullable response, UIImage *responseObject))success
+                                                        failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure {
+    __block NSURLSessionDataTask *task = nil;
+    dispatch_sync(self.synchronizationQueue, ^{
+        NSString *URLIdentifier = request.URL.absoluteString;
+        if (URLIdentifier == nil) {
+            if (failure) {
+                NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadURL userInfo:nil];
+                dispatch_async(dispatch_get_main_queue(), ^{
+                    failure(request, nil, error);
+                });
+            }
+            return;
+        }
+
+        // 1) Append the success and failure blocks to a pre-existing request if it already exists
+        AFImageDownloaderMergedTask *existingMergedTask = self.mergedTasks[URLIdentifier];
+        if (existingMergedTask != nil) {
+            AFImageDownloaderResponseHandler *handler = [[AFImageDownloaderResponseHandler alloc] initWithUUID:receiptID success:success failure:failure];
+            [existingMergedTask addResponseHandler:handler];
+            task = existingMergedTask.task;
+            return;
+        }
+
+        // 2) Attempt to load the image from the image cache if the cache policy allows it
+        switch (request.cachePolicy) {
+            case NSURLRequestUseProtocolCachePolicy:
+            case NSURLRequestReturnCacheDataElseLoad:
+            case NSURLRequestReturnCacheDataDontLoad: {
+                UIImage *cachedImage = [self.imageCache imageforRequest:request withAdditionalIdentifier:nil];
+                if (cachedImage != nil) {
+                    if (success) {
+                        dispatch_async(dispatch_get_main_queue(), ^{
+                            success(request, nil, cachedImage);
+                        });
+                    }
+                    return;
+                }
+                break;
+            }
+            default:
+                break;
+        }
+
+        // 3) Create the request and set up authentication, validation and response serialization
+        NSUUID *mergedTaskIdentifier = [NSUUID UUID];
+        NSURLSessionDataTask *createdTask;
+        __weak __typeof__(self) weakSelf = self;
+
+        createdTask = [self.sessionManager
+                       dataTaskWithRequest:request
+                       uploadProgress:nil
+                       downloadProgress:nil
+                       completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
+                           dispatch_async(self.responseQueue, ^{
+                               __strong __typeof__(weakSelf) strongSelf = weakSelf;
+                               AFImageDownloaderMergedTask *mergedTask = [strongSelf safelyGetMergedTask:URLIdentifier];
+                               if ([mergedTask.identifier isEqual:mergedTaskIdentifier]) {
+                                   mergedTask = [strongSelf safelyRemoveMergedTaskWithURLIdentifier:URLIdentifier];
+                                   if (error) {
+                                       for (AFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) {
+                                           if (handler.failureBlock) {
+                                               dispatch_async(dispatch_get_main_queue(), ^{
+                                                   handler.failureBlock(request, (NSHTTPURLResponse *)response, error);
+                                               });
+                                           }
+                                       }
+                                   } else {
+                                       if ([strongSelf.imageCache shouldCacheImage:responseObject forRequest:request withAdditionalIdentifier:nil]) {
+                                           [strongSelf.imageCache addImage:responseObject forRequest:request withAdditionalIdentifier:nil];
+                                       }
+
+                                       for (AFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) {
+                                           if (handler.successBlock) {
+                                               dispatch_async(dispatch_get_main_queue(), ^{
+                                                   handler.successBlock(request, (NSHTTPURLResponse *)response, responseObject);
+                                               });
+                                           }
+                                       }
+                                       
+                                   }
+                               }
+                               [strongSelf safelyDecrementActiveTaskCount];
+                               [strongSelf safelyStartNextTaskIfNecessary];
+                           });
+                       }];
+
+        // 4) Store the response handler for use when the request completes
+        AFImageDownloaderResponseHandler *handler = [[AFImageDownloaderResponseHandler alloc] initWithUUID:receiptID
+                                                                                                   success:success
+                                                                                                   failure:failure];
+        AFImageDownloaderMergedTask *mergedTask = [[AFImageDownloaderMergedTask alloc]
+                                                   initWithURLIdentifier:URLIdentifier
+                                                   identifier:mergedTaskIdentifier
+                                                   task:createdTask];
+        [mergedTask addResponseHandler:handler];
+        self.mergedTasks[URLIdentifier] = mergedTask;
+
+        // 5) Either start the request or enqueue it depending on the current active request count
+        if ([self isActiveRequestCountBelowMaximumLimit]) {
+            [self startMergedTask:mergedTask];
+        } else {
+            [self enqueueMergedTask:mergedTask];
+        }
+
+        task = mergedTask.task;
+    });
+    if (task) {
+        return [[AFImageDownloadReceipt alloc] initWithReceiptID:receiptID task:task];
+    } else {
+        return nil;
+    }
+}
+
+- (void)cancelTaskForImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt {
+    dispatch_sync(self.synchronizationQueue, ^{
+        NSString *URLIdentifier = imageDownloadReceipt.task.originalRequest.URL.absoluteString;
+        AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier];
+        NSUInteger index = [mergedTask.responseHandlers indexOfObjectPassingTest:^BOOL(AFImageDownloaderResponseHandler * _Nonnull handler, __unused NSUInteger idx, __unused BOOL * _Nonnull stop) {
+            return handler.uuid == imageDownloadReceipt.receiptID;
+        }];
+
+        if (index != NSNotFound) {
+            AFImageDownloaderResponseHandler *handler = mergedTask.responseHandlers[index];
+            [mergedTask removeResponseHandler:handler];
+            NSString *failureReason = [NSString stringWithFormat:@"ImageDownloader cancelled URL request: %@",imageDownloadReceipt.task.originalRequest.URL.absoluteString];
+            NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey:failureReason};
+            NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo];
+            if (handler.failureBlock) {
+                dispatch_async(dispatch_get_main_queue(), ^{
+                    handler.failureBlock(imageDownloadReceipt.task.originalRequest, nil, error);
+                });
+            }
+        }
+
+        if (mergedTask.responseHandlers.count == 0) {
+            [mergedTask.task cancel];
+            [self removeMergedTaskWithURLIdentifier:URLIdentifier];
+        }
+    });
+}
+
+- (AFImageDownloaderMergedTask *)safelyRemoveMergedTaskWithURLIdentifier:(NSString *)URLIdentifier {
+    __block AFImageDownloaderMergedTask *mergedTask = nil;
+    dispatch_sync(self.synchronizationQueue, ^{
+        mergedTask = [self removeMergedTaskWithURLIdentifier:URLIdentifier];
+    });
+    return mergedTask;
+}
+
+//This method should only be called from safely within the synchronizationQueue
+- (AFImageDownloaderMergedTask *)removeMergedTaskWithURLIdentifier:(NSString *)URLIdentifier {
+    AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier];
+    [self.mergedTasks removeObjectForKey:URLIdentifier];
+    return mergedTask;
+}
+
+- (void)safelyDecrementActiveTaskCount {
+    dispatch_sync(self.synchronizationQueue, ^{
+        if (self.activeRequestCount > 0) {
+            self.activeRequestCount -= 1;
+        }
+    });
+}
+
+- (void)safelyStartNextTaskIfNecessary {
+    dispatch_sync(self.synchronizationQueue, ^{
+        if ([self isActiveRequestCountBelowMaximumLimit]) {
+            while (self.queuedMergedTasks.count > 0) {
+                AFImageDownloaderMergedTask *mergedTask = [self dequeueMergedTask];
+                if (mergedTask.task.state == NSURLSessionTaskStateSuspended) {
+                    [self startMergedTask:mergedTask];
+                    break;
+                }
+            }
+        }
+    });
+}
+
+- (void)startMergedTask:(AFImageDownloaderMergedTask *)mergedTask {
+    [mergedTask.task resume];
+    ++self.activeRequestCount;
+}
+
+- (void)enqueueMergedTask:(AFImageDownloaderMergedTask *)mergedTask {
+    switch (self.downloadPrioritization) {
+        case AFImageDownloadPrioritizationFIFO:
+            [self.queuedMergedTasks addObject:mergedTask];
+            break;
+        case AFImageDownloadPrioritizationLIFO:
+            [self.queuedMergedTasks insertObject:mergedTask atIndex:0];
+            break;
+    }
+}
+
+- (AFImageDownloaderMergedTask *)dequeueMergedTask {
+    AFImageDownloaderMergedTask *mergedTask = nil;
+    mergedTask = [self.queuedMergedTasks firstObject];
+    [self.queuedMergedTasks removeObject:mergedTask];
+    return mergedTask;
+}
+
+- (BOOL)isActiveRequestCountBelowMaximumLimit {
+    return self.activeRequestCount < self.maximumActiveDownloads;
+}
+
+- (AFImageDownloaderMergedTask *)safelyGetMergedTask:(NSString *)URLIdentifier {
+    __block AFImageDownloaderMergedTask *mergedTask;
+    dispatch_sync(self.synchronizationQueue, ^(){
+        mergedTask = self.mergedTasks[URLIdentifier];
+    });
+    return mergedTask;
+}
+
+@end
+
+#endif

+ 103 - 0
Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h

@@ -0,0 +1,103 @@
+// AFNetworkActivityIndicatorManager.h
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <Foundation/Foundation.h>
+
+#import <TargetConditionals.h>
+
+#if TARGET_OS_IOS
+
+#import <UIKit/UIKit.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ `AFNetworkActivityIndicatorManager` manages the state of the network activity indicator in the status bar. When enabled, it will listen for notifications indicating that a session task has started or finished, and start or stop animating the indicator accordingly. The number of active requests is incremented and decremented much like a stack or a semaphore, and the activity indicator will animate so long as that number is greater than zero.
+
+ You should enable the shared instance of `AFNetworkActivityIndicatorManager` when your application finishes launching. In `AppDelegate application:didFinishLaunchingWithOptions:` you can do so with the following code:
+
+    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
+
+ By setting `enabled` to `YES` for `sharedManager`, the network activity indicator will show and hide automatically as requests start and finish. You should not ever need to call `incrementActivityCount` or `decrementActivityCount` yourself.
+
+ See the Apple Human Interface Guidelines section about the Network Activity Indicator for more information:
+ http://developer.apple.com/library/iOS/#documentation/UserExperience/Conceptual/MobileHIG/UIElementGuidelines/UIElementGuidelines.html#//apple_ref/doc/uid/TP40006556-CH13-SW44
+ */
+NS_EXTENSION_UNAVAILABLE_IOS("Use view controller based solutions where appropriate instead.")
+@interface AFNetworkActivityIndicatorManager : NSObject
+
+/**
+ A Boolean value indicating whether the manager is enabled.
+
+ If YES, the manager will change status bar network activity indicator according to network operation notifications it receives. The default value is NO.
+ */
+@property (nonatomic, assign, getter = isEnabled) BOOL enabled;
+
+/**
+ A Boolean value indicating whether the network activity indicator manager is currently active.
+*/
+@property (readonly, nonatomic, assign, getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible;
+
+/**
+ A time interval indicating the minimum duration of networking activity that should occur before the activity indicator is displayed. The default value 1 second. If the network activity indicator should be displayed immediately when network activity occurs, this value should be set to 0 seconds.
+ 
+ Apple's HIG describes the following:
+
+ > Display the network activity indicator to provide feedback when your app accesses the network for more than a couple of seconds. If the operation finishes sooner than that, you don’t have to show the network activity indicator, because the indicator is likely to disappear before users notice its presence.
+
+ */
+@property (nonatomic, assign) NSTimeInterval activationDelay;
+
+/**
+ A time interval indicating the duration of time of no networking activity required before the activity indicator is disabled. This allows for continuous display of the network activity indicator across multiple requests. The default value is 0.17 seconds.
+ */
+
+@property (nonatomic, assign) NSTimeInterval completionDelay;
+
+/**
+ Returns the shared network activity indicator manager object for the system.
+
+ @return The systemwide network activity indicator manager.
+ */
++ (instancetype)sharedManager;
+
+/**
+ Increments the number of active network requests. If this number was zero before incrementing, this will start animating the status bar network activity indicator.
+ */
+- (void)incrementActivityCount;
+
+/**
+ Decrements the number of active network requests. If this number becomes zero after decrementing, this will stop animating the status bar network activity indicator.
+ */
+- (void)decrementActivityCount;
+
+/**
+ Set the a custom method to be executed when the network activity indicator manager should be hidden/shown. By default, this is null, and the UIApplication Network Activity Indicator will be managed automatically. If this block is set, it is the responsiblity of the caller to manager the network activity indicator going forward.
+
+ @param block A block to be executed when the network activity indicator status changes.
+ */
+- (void)setNetworkingActivityActionWithBlock:(nullable void (^)(BOOL networkActivityIndicatorVisible))block;
+
+@end
+
+NS_ASSUME_NONNULL_END
+
+#endif

+ 239 - 0
Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m

@@ -0,0 +1,239 @@
+// AFNetworkActivityIndicatorManager.m
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import "AFNetworkActivityIndicatorManager.h"
+
+#if TARGET_OS_IOS
+#import "AFURLSessionManager.h"
+
+typedef NS_ENUM(NSInteger, AFNetworkActivityManagerState) {
+    AFNetworkActivityManagerStateNotActive,
+    AFNetworkActivityManagerStateDelayingStart,
+    AFNetworkActivityManagerStateActive,
+    AFNetworkActivityManagerStateDelayingEnd
+};
+
+static NSTimeInterval const kDefaultAFNetworkActivityManagerActivationDelay = 1.0;
+static NSTimeInterval const kDefaultAFNetworkActivityManagerCompletionDelay = 0.17;
+
+static NSURLRequest * AFNetworkRequestFromNotification(NSNotification *notification) {
+    if ([[notification object] respondsToSelector:@selector(originalRequest)]) {
+        return [(NSURLSessionTask *)[notification object] originalRequest];
+    } else {
+        return nil;
+    }
+}
+
+typedef void (^AFNetworkActivityActionBlock)(BOOL networkActivityIndicatorVisible);
+
+@interface AFNetworkActivityIndicatorManager ()
+@property (readwrite, nonatomic, assign) NSInteger activityCount;
+@property (readwrite, nonatomic, strong) NSTimer *activationDelayTimer;
+@property (readwrite, nonatomic, strong) NSTimer *completionDelayTimer;
+@property (readonly, nonatomic, getter = isNetworkActivityOccurring) BOOL networkActivityOccurring;
+@property (nonatomic, copy) AFNetworkActivityActionBlock networkActivityActionBlock;
+@property (nonatomic, assign) AFNetworkActivityManagerState currentState;
+@property (nonatomic, assign, getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible;
+
+- (void)updateCurrentStateForNetworkActivityChange;
+@end
+
+@implementation AFNetworkActivityIndicatorManager
+
++ (instancetype)sharedManager {
+    static AFNetworkActivityIndicatorManager *_sharedManager = nil;
+    static dispatch_once_t oncePredicate;
+    dispatch_once(&oncePredicate, ^{
+        _sharedManager = [[self alloc] init];
+    });
+
+    return _sharedManager;
+}
+
+- (instancetype)init {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+    self.currentState = AFNetworkActivityManagerStateNotActive;
+    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidStart:) name:AFNetworkingTaskDidResumeNotification object:nil];
+    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidSuspendNotification object:nil];
+    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidCompleteNotification object:nil];
+    self.activationDelay = kDefaultAFNetworkActivityManagerActivationDelay;
+    self.completionDelay = kDefaultAFNetworkActivityManagerCompletionDelay;
+
+    return self;
+}
+
+- (void)dealloc {
+    [[NSNotificationCenter defaultCenter] removeObserver:self];
+
+    [_activationDelayTimer invalidate];
+    [_completionDelayTimer invalidate];
+}
+
+- (void)setEnabled:(BOOL)enabled {
+    _enabled = enabled;
+    if (enabled == NO) {
+        [self setCurrentState:AFNetworkActivityManagerStateNotActive];
+    }
+}
+
+- (void)setNetworkingActivityActionWithBlock:(void (^)(BOOL networkActivityIndicatorVisible))block {
+    self.networkActivityActionBlock = block;
+}
+
+- (BOOL)isNetworkActivityOccurring {
+    @synchronized(self) {
+        return self.activityCount > 0;
+    }
+}
+
+- (void)setNetworkActivityIndicatorVisible:(BOOL)networkActivityIndicatorVisible {
+    if (_networkActivityIndicatorVisible != networkActivityIndicatorVisible) {
+        @synchronized(self) {
+            _networkActivityIndicatorVisible = networkActivityIndicatorVisible;
+        }
+        if (self.networkActivityActionBlock) {
+            self.networkActivityActionBlock(networkActivityIndicatorVisible);
+        } else {
+            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:networkActivityIndicatorVisible];
+        }
+    }
+}
+
+
+- (void)incrementActivityCount {
+    @synchronized(self) {
+        self.activityCount++;
+    }
+    dispatch_async(dispatch_get_main_queue(), ^{
+        [self updateCurrentStateForNetworkActivityChange];
+    });
+}
+
+- (void)decrementActivityCount {
+    @synchronized(self) {
+        self.activityCount = MAX(_activityCount - 1, 0);
+    }
+    dispatch_async(dispatch_get_main_queue(), ^{
+        [self updateCurrentStateForNetworkActivityChange];
+    });
+}
+
+- (void)networkRequestDidStart:(NSNotification *)notification {
+    if ([AFNetworkRequestFromNotification(notification) URL]) {
+        [self incrementActivityCount];
+    }
+}
+
+- (void)networkRequestDidFinish:(NSNotification *)notification {
+    if ([AFNetworkRequestFromNotification(notification) URL]) {
+        [self decrementActivityCount];
+    }
+}
+
+#pragma mark - Internal State Management
+- (void)setCurrentState:(AFNetworkActivityManagerState)currentState {
+    @synchronized(self) {
+        if (_currentState != currentState) {
+            _currentState = currentState;
+            switch (currentState) {
+                case AFNetworkActivityManagerStateNotActive:
+                    [self cancelActivationDelayTimer];
+                    [self cancelCompletionDelayTimer];
+                    [self setNetworkActivityIndicatorVisible:NO];
+                    break;
+                case AFNetworkActivityManagerStateDelayingStart:
+                    [self startActivationDelayTimer];
+                    break;
+                case AFNetworkActivityManagerStateActive:
+                    [self cancelCompletionDelayTimer];
+                    [self setNetworkActivityIndicatorVisible:YES];
+                    break;
+                case AFNetworkActivityManagerStateDelayingEnd:
+                    [self startCompletionDelayTimer];
+                    break;
+            }
+        }
+    }
+}
+
+- (void)updateCurrentStateForNetworkActivityChange {
+    if (self.enabled) {
+        switch (self.currentState) {
+            case AFNetworkActivityManagerStateNotActive:
+                if (self.isNetworkActivityOccurring) {
+                    [self setCurrentState:AFNetworkActivityManagerStateDelayingStart];
+                }
+                break;
+            case AFNetworkActivityManagerStateDelayingStart:
+                //No op. Let the delay timer finish out.
+                break;
+            case AFNetworkActivityManagerStateActive:
+                if (!self.isNetworkActivityOccurring) {
+                    [self setCurrentState:AFNetworkActivityManagerStateDelayingEnd];
+                }
+                break;
+            case AFNetworkActivityManagerStateDelayingEnd:
+                if (self.isNetworkActivityOccurring) {
+                    [self setCurrentState:AFNetworkActivityManagerStateActive];
+                }
+                break;
+        }
+    }
+}
+
+- (void)startActivationDelayTimer {
+    self.activationDelayTimer = [NSTimer
+                                 timerWithTimeInterval:self.activationDelay target:self selector:@selector(activationDelayTimerFired) userInfo:nil repeats:NO];
+    [[NSRunLoop mainRunLoop] addTimer:self.activationDelayTimer forMode:NSRunLoopCommonModes];
+}
+
+- (void)activationDelayTimerFired {
+    if (self.networkActivityOccurring) {
+        [self setCurrentState:AFNetworkActivityManagerStateActive];
+    } else {
+        [self setCurrentState:AFNetworkActivityManagerStateNotActive];
+    }
+}
+
+- (void)startCompletionDelayTimer {
+    [self.completionDelayTimer invalidate];
+    self.completionDelayTimer = [NSTimer timerWithTimeInterval:self.completionDelay target:self selector:@selector(completionDelayTimerFired) userInfo:nil repeats:NO];
+    [[NSRunLoop mainRunLoop] addTimer:self.completionDelayTimer forMode:NSRunLoopCommonModes];
+}
+
+- (void)completionDelayTimerFired {
+    [self setCurrentState:AFNetworkActivityManagerStateNotActive];
+}
+
+- (void)cancelActivationDelayTimer {
+    [self.activationDelayTimer invalidate];
+}
+
+- (void)cancelCompletionDelayTimer {
+    [self.completionDelayTimer invalidate];
+}
+
+@end
+
+#endif

+ 48 - 0
Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h

@@ -0,0 +1,48 @@
+// UIActivityIndicatorView+AFNetworking.h
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <Foundation/Foundation.h>
+
+#import <TargetConditionals.h>
+
+#if TARGET_OS_IOS || TARGET_OS_TV
+
+#import <UIKit/UIKit.h>
+
+/**
+ This category adds methods to the UIKit framework's `UIActivityIndicatorView` class. The methods in this category provide support for automatically starting and stopping animation depending on the loading state of a session task.
+ */
+@interface UIActivityIndicatorView (AFNetworking)
+
+///----------------------------------
+/// @name Animating for Session Tasks
+///----------------------------------
+
+/**
+ Binds the animating state to the state of the specified task.
+
+ @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled.
+ */
+- (void)setAnimatingWithStateOfTask:(nullable NSURLSessionTask *)task;
+
+@end
+
+#endif

+ 114 - 0
Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m

@@ -0,0 +1,114 @@
+// UIActivityIndicatorView+AFNetworking.m
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import "UIActivityIndicatorView+AFNetworking.h"
+#import <objc/runtime.h>
+
+#if TARGET_OS_IOS || TARGET_OS_TV
+
+#import "AFURLSessionManager.h"
+
+@interface AFActivityIndicatorViewNotificationObserver : NSObject
+@property (readonly, nonatomic, weak) UIActivityIndicatorView *activityIndicatorView;
+- (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView;
+
+- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task;
+
+@end
+
+@implementation UIActivityIndicatorView (AFNetworking)
+
+- (AFActivityIndicatorViewNotificationObserver *)af_notificationObserver {
+    AFActivityIndicatorViewNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver));
+    if (notificationObserver == nil) {
+        notificationObserver = [[AFActivityIndicatorViewNotificationObserver alloc] initWithActivityIndicatorView:self];
+        objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+    }
+    return notificationObserver;
+}
+
+- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task {
+    [[self af_notificationObserver] setAnimatingWithStateOfTask:task];
+}
+
+@end
+
+@implementation AFActivityIndicatorViewNotificationObserver
+
+- (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView
+{
+    self = [super init];
+    if (self) {
+        _activityIndicatorView = activityIndicatorView;
+    }
+    return self;
+}
+
+- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task {
+    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
+
+    [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil];
+    [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil];
+    [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
+    
+    if (task) {
+        if (task.state != NSURLSessionTaskStateCompleted) {
+            UIActivityIndicatorView *activityIndicatorView = self.activityIndicatorView;
+            if (task.state == NSURLSessionTaskStateRunning) {
+                [activityIndicatorView startAnimating];
+            } else {
+                [activityIndicatorView stopAnimating];
+            }
+
+            [notificationCenter addObserver:self selector:@selector(af_startAnimating) name:AFNetworkingTaskDidResumeNotification object:task];
+            [notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidCompleteNotification object:task];
+            [notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidSuspendNotification object:task];
+        }
+    }
+}
+
+#pragma mark -
+
+- (void)af_startAnimating {
+    dispatch_async(dispatch_get_main_queue(), ^{
+        [self.activityIndicatorView startAnimating];
+    });
+}
+
+- (void)af_stopAnimating {
+    dispatch_async(dispatch_get_main_queue(), ^{
+        [self.activityIndicatorView stopAnimating];
+    });
+}
+
+#pragma mark -
+
+- (void)dealloc {
+    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
+    
+    [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
+    [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil];
+    [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil];
+}
+
+@end
+
+#endif

+ 175 - 0
Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h

@@ -0,0 +1,175 @@
+// UIButton+AFNetworking.h
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <Foundation/Foundation.h>
+
+#import <TargetConditionals.h>
+
+#if TARGET_OS_IOS || TARGET_OS_TV
+
+#import <UIKit/UIKit.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+@class AFImageDownloader;
+
+/**
+ This category adds methods to the UIKit framework's `UIButton` class. The methods in this category provide support for loading remote images and background images asynchronously from a URL.
+
+ @warning Compound values for control `state` (such as `UIControlStateHighlighted | UIControlStateDisabled`) are unsupported.
+ */
+@interface UIButton (AFNetworking)
+
+///------------------------------------
+/// @name Accessing the Image Downloader
+///------------------------------------
+
+/**
+ Set the shared image downloader used to download images.
+
+ @param imageDownloader The shared image downloader used to download images.
+*/
++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader;
+
+/**
+ The shared image downloader used to download images.
+ */
++ (AFImageDownloader *)sharedImageDownloader;
+
+///--------------------
+/// @name Setting Image
+///--------------------
+
+/**
+ Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
+
+  If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
+
+ @param state The control state.
+ @param url The URL used for the image request.
+ */
+- (void)setImageForState:(UIControlState)state
+                 withURL:(NSURL *)url;
+
+/**
+ Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
+
+ If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
+
+ @param state The control state.
+ @param url The URL used for the image request.
+ @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes.
+ */
+- (void)setImageForState:(UIControlState)state
+                 withURL:(NSURL *)url
+        placeholderImage:(nullable UIImage *)placeholderImage;
+
+/**
+ Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
+
+ If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
+
+ If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setImage:forState:` is applied.
+
+ @param state The control state.
+ @param urlRequest The URL request used for the image request.
+ @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes.
+ @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`.
+ @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
+ */
+- (void)setImageForState:(UIControlState)state
+          withURLRequest:(NSURLRequest *)urlRequest
+        placeholderImage:(nullable UIImage *)placeholderImage
+                 success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
+                 failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
+
+
+///-------------------------------
+/// @name Setting Background Image
+///-------------------------------
+
+/**
+ Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous background image request for the receiver will be cancelled.
+
+ If the background image is cached locally, the background image is set immediately, otherwise the specified placeholder background image will be set immediately, and then the remote background image will be set once the request is finished.
+
+ @param state The control state.
+ @param url The URL used for the background image request.
+ */
+- (void)setBackgroundImageForState:(UIControlState)state
+                           withURL:(NSURL *)url;
+
+/**
+ Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
+
+ If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
+
+ @param state The control state.
+ @param url The URL used for the background image request.
+ @param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes.
+ */
+- (void)setBackgroundImageForState:(UIControlState)state
+                           withURL:(NSURL *)url
+                  placeholderImage:(nullable UIImage *)placeholderImage;
+
+/**
+ Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
+
+ If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
+
+ If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setBackgroundImage:forState:` is applied.
+
+ @param state The control state.
+ @param urlRequest The URL request used for the image request.
+ @param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes.
+ @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`.
+ @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
+ */
+- (void)setBackgroundImageForState:(UIControlState)state
+                    withURLRequest:(NSURLRequest *)urlRequest
+                  placeholderImage:(nullable UIImage *)placeholderImage
+                           success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
+                           failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
+
+
+///------------------------------
+/// @name Canceling Image Loading
+///------------------------------
+
+/**
+ Cancels any executing image task for the specified control state of the receiver, if one exists.
+
+ @param state The control state.
+ */
+- (void)cancelImageDownloadTaskForState:(UIControlState)state;
+
+/**
+ Cancels any executing background image task for the specified control state of the receiver, if one exists.
+
+ @param state The control state.
+ */
+- (void)cancelBackgroundImageDownloadTaskForState:(UIControlState)state;
+
+@end
+
+NS_ASSUME_NONNULL_END
+
+#endif

+ 302 - 0
Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m

@@ -0,0 +1,302 @@
+// UIButton+AFNetworking.m
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import "UIButton+AFNetworking.h"
+
+#import <objc/runtime.h>
+
+#if TARGET_OS_IOS || TARGET_OS_TV
+
+#import "UIImageView+AFNetworking.h"
+#import "AFImageDownloader.h"
+
+@interface UIButton (_AFNetworking)
+@end
+
+@implementation UIButton (_AFNetworking)
+
+#pragma mark -
+
+static char AFImageDownloadReceiptNormal;
+static char AFImageDownloadReceiptHighlighted;
+static char AFImageDownloadReceiptSelected;
+static char AFImageDownloadReceiptDisabled;
+
+static const char * af_imageDownloadReceiptKeyForState(UIControlState state) {
+    switch (state) {
+        case UIControlStateHighlighted:
+            return &AFImageDownloadReceiptHighlighted;
+        case UIControlStateSelected:
+            return &AFImageDownloadReceiptSelected;
+        case UIControlStateDisabled:
+            return &AFImageDownloadReceiptDisabled;
+        case UIControlStateNormal:
+        default:
+            return &AFImageDownloadReceiptNormal;
+    }
+}
+
+- (AFImageDownloadReceipt *)af_imageDownloadReceiptForState:(UIControlState)state {
+    return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, af_imageDownloadReceiptKeyForState(state));
+}
+
+- (void)af_setImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt
+                           forState:(UIControlState)state
+{
+    objc_setAssociatedObject(self, af_imageDownloadReceiptKeyForState(state), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+}
+
+#pragma mark -
+
+static char AFBackgroundImageDownloadReceiptNormal;
+static char AFBackgroundImageDownloadReceiptHighlighted;
+static char AFBackgroundImageDownloadReceiptSelected;
+static char AFBackgroundImageDownloadReceiptDisabled;
+
+static const char * af_backgroundImageDownloadReceiptKeyForState(UIControlState state) {
+    switch (state) {
+        case UIControlStateHighlighted:
+            return &AFBackgroundImageDownloadReceiptHighlighted;
+        case UIControlStateSelected:
+            return &AFBackgroundImageDownloadReceiptSelected;
+        case UIControlStateDisabled:
+            return &AFBackgroundImageDownloadReceiptDisabled;
+        case UIControlStateNormal:
+        default:
+            return &AFBackgroundImageDownloadReceiptNormal;
+    }
+}
+
+- (AFImageDownloadReceipt *)af_backgroundImageDownloadReceiptForState:(UIControlState)state {
+    return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, af_backgroundImageDownloadReceiptKeyForState(state));
+}
+
+- (void)af_setBackgroundImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt
+                                     forState:(UIControlState)state
+{
+    objc_setAssociatedObject(self, af_backgroundImageDownloadReceiptKeyForState(state), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+}
+
+@end
+
+#pragma mark -
+
+@implementation UIButton (AFNetworking)
+
++ (AFImageDownloader *)sharedImageDownloader {
+
+    return objc_getAssociatedObject([UIButton class], @selector(sharedImageDownloader)) ?: [AFImageDownloader defaultInstance];
+}
+
++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader {
+    objc_setAssociatedObject([UIButton class], @selector(sharedImageDownloader), imageDownloader, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+}
+
+#pragma mark -
+
+- (void)setImageForState:(UIControlState)state
+                 withURL:(NSURL *)url
+{
+    [self setImageForState:state withURL:url placeholderImage:nil];
+}
+
+- (void)setImageForState:(UIControlState)state
+                 withURL:(NSURL *)url
+        placeholderImage:(UIImage *)placeholderImage
+{
+    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
+    [request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
+
+    [self setImageForState:state withURLRequest:request placeholderImage:placeholderImage success:nil failure:nil];
+}
+
+- (void)setImageForState:(UIControlState)state
+          withURLRequest:(NSURLRequest *)urlRequest
+        placeholderImage:(nullable UIImage *)placeholderImage
+                 success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
+                 failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure
+{
+    if ([self isActiveTaskURLEqualToURLRequest:urlRequest forState:state]) {
+        return;
+    }
+
+    [self cancelImageDownloadTaskForState:state];
+
+    AFImageDownloader *downloader = [[self class] sharedImageDownloader];
+    id <AFImageRequestCache> imageCache = downloader.imageCache;
+
+    //Use the image from the image cache if it exists
+    UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil];
+    if (cachedImage) {
+        if (success) {
+            success(urlRequest, nil, cachedImage);
+        } else {
+            [self setImage:cachedImage forState:state];
+        }
+        [self af_setImageDownloadReceipt:nil forState:state];
+    } else {
+        if (placeholderImage) {
+            [self setImage:placeholderImage forState:state];
+        }
+
+        __weak __typeof(self)weakSelf = self;
+        NSUUID *downloadID = [NSUUID UUID];
+        AFImageDownloadReceipt *receipt;
+        receipt = [downloader
+                   downloadImageForURLRequest:urlRequest
+                   withReceiptID:downloadID
+                   success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) {
+                       __strong __typeof(weakSelf)strongSelf = weakSelf;
+                       if ([[strongSelf af_imageDownloadReceiptForState:state].receiptID isEqual:downloadID]) {
+                           if (success) {
+                               success(request, response, responseObject);
+                           } else if (responseObject) {
+                               [strongSelf setImage:responseObject forState:state];
+                           }
+                           [strongSelf af_setImageDownloadReceipt:nil forState:state];
+                       }
+
+                   }
+                   failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
+                       __strong __typeof(weakSelf)strongSelf = weakSelf;
+                       if ([[strongSelf af_imageDownloadReceiptForState:state].receiptID isEqual:downloadID]) {
+                           if (failure) {
+                               failure(request, response, error);
+                           }
+                           [strongSelf  af_setImageDownloadReceipt:nil forState:state];
+                       }
+                   }];
+
+        [self af_setImageDownloadReceipt:receipt forState:state];
+    }
+}
+
+#pragma mark -
+
+- (void)setBackgroundImageForState:(UIControlState)state
+                           withURL:(NSURL *)url
+{
+    [self setBackgroundImageForState:state withURL:url placeholderImage:nil];
+}
+
+- (void)setBackgroundImageForState:(UIControlState)state
+                           withURL:(NSURL *)url
+                  placeholderImage:(nullable UIImage *)placeholderImage
+{
+    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
+    [request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
+
+    [self setBackgroundImageForState:state withURLRequest:request placeholderImage:placeholderImage success:nil failure:nil];
+}
+
+- (void)setBackgroundImageForState:(UIControlState)state
+                    withURLRequest:(NSURLRequest *)urlRequest
+                  placeholderImage:(nullable UIImage *)placeholderImage
+                           success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
+                           failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure
+{
+    if ([self isActiveBackgroundTaskURLEqualToURLRequest:urlRequest forState:state]) {
+        return;
+    }
+
+    [self cancelBackgroundImageDownloadTaskForState:state];
+
+    AFImageDownloader *downloader = [[self class] sharedImageDownloader];
+    id <AFImageRequestCache> imageCache = downloader.imageCache;
+
+    //Use the image from the image cache if it exists
+    UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil];
+    if (cachedImage) {
+        if (success) {
+            success(urlRequest, nil, cachedImage);
+        } else {
+            [self setBackgroundImage:cachedImage forState:state];
+        }
+        [self af_setBackgroundImageDownloadReceipt:nil forState:state];
+    } else {
+        if (placeholderImage) {
+            [self setBackgroundImage:placeholderImage forState:state];
+        }
+
+        __weak __typeof(self)weakSelf = self;
+        NSUUID *downloadID = [NSUUID UUID];
+        AFImageDownloadReceipt *receipt;
+        receipt = [downloader
+                   downloadImageForURLRequest:urlRequest
+                   withReceiptID:downloadID
+                   success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) {
+                       __strong __typeof(weakSelf)strongSelf = weakSelf;
+                       if ([[strongSelf af_backgroundImageDownloadReceiptForState:state].receiptID isEqual:downloadID]) {
+                           if (success) {
+                               success(request, response, responseObject);
+                           } else if (responseObject) {
+                               [strongSelf setBackgroundImage:responseObject forState:state];
+                           }
+                           [strongSelf af_setBackgroundImageDownloadReceipt:nil forState:state];
+                       }
+
+                   }
+                   failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
+                       __strong __typeof(weakSelf)strongSelf = weakSelf;
+                       if ([[strongSelf af_backgroundImageDownloadReceiptForState:state].receiptID isEqual:downloadID]) {
+                           if (failure) {
+                               failure(request, response, error);
+                           }
+                           [strongSelf  af_setBackgroundImageDownloadReceipt:nil forState:state];
+                       }
+                   }];
+
+        [self af_setBackgroundImageDownloadReceipt:receipt forState:state];
+    }
+}
+
+#pragma mark -
+
+- (void)cancelImageDownloadTaskForState:(UIControlState)state {
+    AFImageDownloadReceipt *receipt = [self af_imageDownloadReceiptForState:state];
+    if (receipt != nil) {
+        [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:receipt];
+        [self af_setImageDownloadReceipt:nil forState:state];
+    }
+}
+
+- (void)cancelBackgroundImageDownloadTaskForState:(UIControlState)state {
+    AFImageDownloadReceipt *receipt = [self af_backgroundImageDownloadReceiptForState:state];
+    if (receipt != nil) {
+        [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:receipt];
+        [self af_setBackgroundImageDownloadReceipt:nil forState:state];
+    }
+}
+
+- (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest forState:(UIControlState)state {
+    AFImageDownloadReceipt *receipt = [self af_imageDownloadReceiptForState:state];
+    return [receipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString];
+}
+
+- (BOOL)isActiveBackgroundTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest forState:(UIControlState)state {
+    AFImageDownloadReceipt *receipt = [self af_backgroundImageDownloadReceiptForState:state];
+    return [receipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString];
+}
+
+
+@end
+
+#endif

+ 109 - 0
Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h

@@ -0,0 +1,109 @@
+// UIImageView+AFNetworking.h
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <Foundation/Foundation.h>
+
+#import <TargetConditionals.h>
+
+#if TARGET_OS_IOS || TARGET_OS_TV
+
+#import <UIKit/UIKit.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+@class AFImageDownloader;
+
+/**
+ This category adds methods to the UIKit framework's `UIImageView` class. The methods in this category provide support for loading remote images asynchronously from a URL.
+ */
+@interface UIImageView (AFNetworking)
+
+///------------------------------------
+/// @name Accessing the Image Downloader
+///------------------------------------
+
+/**
+ Set the shared image downloader used to download images.
+
+ @param imageDownloader The shared image downloader used to download images.
+ */
++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader;
+
+/**
+ The shared image downloader used to download images.
+ */
++ (AFImageDownloader *)sharedImageDownloader;
+
+///--------------------
+/// @name Setting Image
+///--------------------
+
+/**
+ Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled.
+
+ If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
+
+ By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:`
+
+ @param url The URL used for the image request.
+ */
+- (void)setImageWithURL:(NSURL *)url;
+
+/**
+ Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled.
+
+ If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
+
+ By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:`
+
+ @param url The URL used for the image request.
+ @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes.
+ */
+- (void)setImageWithURL:(NSURL *)url
+       placeholderImage:(nullable UIImage *)placeholderImage;
+
+/**
+ Asynchronously downloads an image from the specified URL request, and sets it once the request is finished. Any previous image request for the receiver will be cancelled.
+
+ If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
+
+ If a success block is specified, it is the responsibility of the block to set the image of the image view before returning. If no success block is specified, the default behavior of setting the image with `self.image = image` is applied.
+
+ @param urlRequest The URL request used for the image request.
+ @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes.
+ @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`.
+ @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
+ */
+- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
+              placeholderImage:(nullable UIImage *)placeholderImage
+                       success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
+                       failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
+
+/**
+ Cancels any executing image operation for the receiver, if one exists.
+ */
+- (void)cancelImageDownloadTask;
+
+@end
+
+NS_ASSUME_NONNULL_END
+
+#endif

+ 159 - 0
Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m

@@ -0,0 +1,159 @@
+// UIImageView+AFNetworking.m
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import "UIImageView+AFNetworking.h"
+
+#import <objc/runtime.h>
+
+#if TARGET_OS_IOS || TARGET_OS_TV
+
+#import "AFImageDownloader.h"
+
+@interface UIImageView (_AFNetworking)
+@property (readwrite, nonatomic, strong, setter = af_setActiveImageDownloadReceipt:) AFImageDownloadReceipt *af_activeImageDownloadReceipt;
+@end
+
+@implementation UIImageView (_AFNetworking)
+
+- (AFImageDownloadReceipt *)af_activeImageDownloadReceipt {
+    return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, @selector(af_activeImageDownloadReceipt));
+}
+
+- (void)af_setActiveImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt {
+    objc_setAssociatedObject(self, @selector(af_activeImageDownloadReceipt), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+}
+
+@end
+
+#pragma mark -
+
+@implementation UIImageView (AFNetworking)
+
++ (AFImageDownloader *)sharedImageDownloader {
+    return objc_getAssociatedObject([UIImageView class], @selector(sharedImageDownloader)) ?: [AFImageDownloader defaultInstance];
+}
+
++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader {
+    objc_setAssociatedObject([UIImageView class], @selector(sharedImageDownloader), imageDownloader, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+}
+
+#pragma mark -
+
+- (void)setImageWithURL:(NSURL *)url {
+    [self setImageWithURL:url placeholderImage:nil];
+}
+
+- (void)setImageWithURL:(NSURL *)url
+       placeholderImage:(UIImage *)placeholderImage
+{
+    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
+    [request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
+
+    [self setImageWithURLRequest:request placeholderImage:placeholderImage success:nil failure:nil];
+}
+
+- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
+              placeholderImage:(UIImage *)placeholderImage
+                       success:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
+                       failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure
+{
+    if ([urlRequest URL] == nil) {
+        self.image = placeholderImage;
+        if (failure) {
+            NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadURL userInfo:nil];
+            failure(urlRequest, nil, error);
+        }
+        return;
+    }
+    
+    if ([self isActiveTaskURLEqualToURLRequest:urlRequest]) {
+        return;
+    }
+    
+    [self cancelImageDownloadTask];
+
+    AFImageDownloader *downloader = [[self class] sharedImageDownloader];
+    id <AFImageRequestCache> imageCache = downloader.imageCache;
+
+    //Use the image from the image cache if it exists
+    UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil];
+    if (cachedImage) {
+        if (success) {
+            success(urlRequest, nil, cachedImage);
+        } else {
+            self.image = cachedImage;
+        }
+        [self clearActiveDownloadInformation];
+    } else {
+        if (placeholderImage) {
+            self.image = placeholderImage;
+        }
+
+        __weak __typeof(self)weakSelf = self;
+        NSUUID *downloadID = [NSUUID UUID];
+        AFImageDownloadReceipt *receipt;
+        receipt = [downloader
+                   downloadImageForURLRequest:urlRequest
+                   withReceiptID:downloadID
+                   success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) {
+                       __strong __typeof(weakSelf)strongSelf = weakSelf;
+                       if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) {
+                           if (success) {
+                               success(request, response, responseObject);
+                           } else if (responseObject) {
+                               strongSelf.image = responseObject;
+                           }
+                           [strongSelf clearActiveDownloadInformation];
+                       }
+
+                   }
+                   failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
+                       __strong __typeof(weakSelf)strongSelf = weakSelf;
+                        if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) {
+                            if (failure) {
+                                failure(request, response, error);
+                            }
+                            [strongSelf clearActiveDownloadInformation];
+                        }
+                   }];
+
+        self.af_activeImageDownloadReceipt = receipt;
+    }
+}
+
+- (void)cancelImageDownloadTask {
+    if (self.af_activeImageDownloadReceipt != nil) {
+        [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:self.af_activeImageDownloadReceipt];
+        [self clearActiveDownloadInformation];
+     }
+}
+
+- (void)clearActiveDownloadInformation {
+    self.af_activeImageDownloadReceipt = nil;
+}
+
+- (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest {
+    return [self.af_activeImageDownloadReceipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString];
+}
+
+@end
+
+#endif

+ 43 - 0
Pods/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h

@@ -0,0 +1,43 @@
+// UIKit+AFNetworking.h
+//
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <TargetConditionals.h>
+
+#ifndef _UIKIT_AFNETWORKING_
+    #define _UIKIT_AFNETWORKING_
+
+#if TARGET_OS_IOS || TARGET_OS_TV
+    #import "AFAutoPurgingImageCache.h"
+    #import "AFImageDownloader.h"
+    #import "UIActivityIndicatorView+AFNetworking.h"
+    #import "UIButton+AFNetworking.h"
+    #import "UIImageView+AFNetworking.h"
+    #import "UIProgressView+AFNetworking.h"
+#endif
+
+#if TARGET_OS_IOS
+    #import "AFNetworkActivityIndicatorManager.h"
+    #import "UIRefreshControl+AFNetworking.h"
+    #import "WKWebView+AFNetworking.h"
+#endif
+
+#endif /* _UIKIT_AFNETWORKING_ */

+ 64 - 0
Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h

@@ -0,0 +1,64 @@
+// UIProgressView+AFNetworking.h
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <Foundation/Foundation.h>
+
+#import <TargetConditionals.h>
+
+#if TARGET_OS_IOS || TARGET_OS_TV
+
+#import <UIKit/UIKit.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+
+/**
+ This category adds methods to the UIKit framework's `UIProgressView` class. The methods in this category provide support for binding the progress to the upload and download progress of a session task.
+ */
+@interface UIProgressView (AFNetworking)
+
+///------------------------------------
+/// @name Setting Session Task Progress
+///------------------------------------
+
+/**
+ Binds the progress to the upload progress of the specified session task.
+
+ @param task The session task.
+ @param animated `YES` if the change should be animated, `NO` if the change should happen immediately.
+ */
+- (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task
+                                   animated:(BOOL)animated;
+
+/**
+ Binds the progress to the download progress of the specified session task.
+
+ @param task The session task.
+ @param animated `YES` if the change should be animated, `NO` if the change should happen immediately.
+ */
+- (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task
+                                     animated:(BOOL)animated;
+
+@end
+
+NS_ASSUME_NONNULL_END
+
+#endif

+ 126 - 0
Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m

@@ -0,0 +1,126 @@
+// UIProgressView+AFNetworking.m
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import "UIProgressView+AFNetworking.h"
+
+#import <objc/runtime.h>
+
+#if TARGET_OS_IOS || TARGET_OS_TV
+
+#import "AFURLSessionManager.h"
+
+static void * AFTaskCountOfBytesSentContext = &AFTaskCountOfBytesSentContext;
+static void * AFTaskCountOfBytesReceivedContext = &AFTaskCountOfBytesReceivedContext;
+
+#pragma mark -
+
+@implementation UIProgressView (AFNetworking)
+
+- (BOOL)af_uploadProgressAnimated {
+    return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_uploadProgressAnimated)) boolValue];
+}
+
+- (void)af_setUploadProgressAnimated:(BOOL)animated {
+    objc_setAssociatedObject(self, @selector(af_uploadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+}
+
+- (BOOL)af_downloadProgressAnimated {
+    return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_downloadProgressAnimated)) boolValue];
+}
+
+- (void)af_setDownloadProgressAnimated:(BOOL)animated {
+    objc_setAssociatedObject(self, @selector(af_downloadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+}
+
+#pragma mark -
+
+- (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task
+                                   animated:(BOOL)animated
+{
+    if (task.state == NSURLSessionTaskStateCompleted) {
+        return;
+    }
+    
+    [task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext];
+    [task addObserver:self forKeyPath:@"countOfBytesSent" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext];
+
+    [self af_setUploadProgressAnimated:animated];
+}
+
+- (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task
+                                     animated:(BOOL)animated
+{
+    if (task.state == NSURLSessionTaskStateCompleted) {
+        return;
+    }
+    
+    [task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext];
+    [task addObserver:self forKeyPath:@"countOfBytesReceived" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext];
+
+    [self af_setDownloadProgressAnimated:animated];
+}
+
+#pragma mark - NSKeyValueObserving
+
+- (void)observeValueForKeyPath:(NSString *)keyPath
+                      ofObject:(id)object
+                        change:(__unused NSDictionary *)change
+                       context:(void *)context
+{
+    if (context == AFTaskCountOfBytesSentContext || context == AFTaskCountOfBytesReceivedContext) {
+        if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesSent))]) {
+            if ([object countOfBytesExpectedToSend] > 0) {
+                dispatch_async(dispatch_get_main_queue(), ^{
+                    [self setProgress:[object countOfBytesSent] / ([object countOfBytesExpectedToSend] * 1.0f) animated:self.af_uploadProgressAnimated];
+                });
+            }
+        }
+
+        if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesReceived))]) {
+            if ([object countOfBytesExpectedToReceive] > 0) {
+                dispatch_async(dispatch_get_main_queue(), ^{
+                    [self setProgress:[object countOfBytesReceived] / ([object countOfBytesExpectedToReceive] * 1.0f) animated:self.af_downloadProgressAnimated];
+                });
+            }
+        }
+
+        if ([keyPath isEqualToString:NSStringFromSelector(@selector(state))]) {
+            if ([(NSURLSessionTask *)object state] == NSURLSessionTaskStateCompleted) {
+                @try {
+                    [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(state))];
+
+                    if (context == AFTaskCountOfBytesSentContext) {
+                        [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesSent))];
+                    }
+
+                    if (context == AFTaskCountOfBytesReceivedContext) {
+                        [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesReceived))];
+                    }
+                }
+                @catch (NSException * __unused exception) {}
+            }
+        }
+    }
+}
+
+@end
+
+#endif

+ 53 - 0
Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h

@@ -0,0 +1,53 @@
+// UIRefreshControl+AFNetworking.m
+//
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <Foundation/Foundation.h>
+
+#import <TargetConditionals.h>
+
+#if TARGET_OS_IOS
+
+#import <UIKit/UIKit.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ This category adds methods to the UIKit framework's `UIRefreshControl` class. The methods in this category provide support for automatically beginning and ending refreshing depending on the loading state of a session task.
+ */
+@interface UIRefreshControl (AFNetworking)
+
+///-----------------------------------
+/// @name Refreshing for Session Tasks
+///-----------------------------------
+
+/**
+ Binds the refreshing state to the state of the specified task.
+ 
+ @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled.
+ */
+- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task;
+
+@end
+
+NS_ASSUME_NONNULL_END
+
+#endif

+ 113 - 0
Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m

@@ -0,0 +1,113 @@
+// UIRefreshControl+AFNetworking.m
+//
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import "UIRefreshControl+AFNetworking.h"
+#import <objc/runtime.h>
+
+#if TARGET_OS_IOS
+
+#import "AFURLSessionManager.h"
+
+@interface AFRefreshControlNotificationObserver : NSObject
+@property (readonly, nonatomic, weak) UIRefreshControl *refreshControl;
+- (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl;
+
+- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task;
+
+@end
+
+@implementation UIRefreshControl (AFNetworking)
+
+- (AFRefreshControlNotificationObserver *)af_notificationObserver {
+    AFRefreshControlNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver));
+    if (notificationObserver == nil) {
+        notificationObserver = [[AFRefreshControlNotificationObserver alloc] initWithActivityRefreshControl:self];
+        objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+    }
+    return notificationObserver;
+}
+
+- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task {
+    [[self af_notificationObserver] setRefreshingWithStateOfTask:task];
+}
+
+@end
+
+@implementation AFRefreshControlNotificationObserver
+
+- (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl
+{
+    self = [super init];
+    if (self) {
+        _refreshControl = refreshControl;
+    }
+    return self;
+}
+
+- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task {
+    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
+
+    [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil];
+    [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil];
+    [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
+
+    if (task) {
+        UIRefreshControl *refreshControl = self.refreshControl;
+        if (task.state == NSURLSessionTaskStateRunning) {
+            [refreshControl beginRefreshing];
+
+            [notificationCenter addObserver:self selector:@selector(af_beginRefreshing) name:AFNetworkingTaskDidResumeNotification object:task];
+            [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidCompleteNotification object:task];
+            [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidSuspendNotification object:task];
+        } else {
+            [refreshControl endRefreshing];
+        }
+    }
+}
+
+#pragma mark -
+
+- (void)af_beginRefreshing {
+    dispatch_async(dispatch_get_main_queue(), ^{
+        [self.refreshControl beginRefreshing];
+    });
+}
+
+- (void)af_endRefreshing {
+    dispatch_async(dispatch_get_main_queue(), ^{
+        [self.refreshControl endRefreshing];
+    });
+}
+
+#pragma mark -
+
+- (void)dealloc {
+    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
+    
+    [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
+    [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil];
+    [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil];
+}
+
+@end
+
+#endif

+ 80 - 0
Pods/AFNetworking/UIKit+AFNetworking/WKWebView+AFNetworking.h

@@ -0,0 +1,80 @@
+// WkWebView+AFNetworking.h
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <Foundation/Foundation.h>
+
+#import <TargetConditionals.h>
+
+#if TARGET_OS_IOS
+
+#import <UIKit/UIKit.h>
+#import <WebKit/WebKit.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+@class AFHTTPSessionManager;
+
+@interface WKWebView (AFNetworking)
+
+/**
+ The session manager used to download all request
+ */
+@property (nonatomic, strong) AFHTTPSessionManager *sessionManager;
+
+/**
+ Asynchronously loads the specified request.
+ 
+ @param request A URL request identifying the location of the content to load. This must not be `nil`.
+ @param navigation The WKNavigation object that containts information for tracking the loading progress of a webpage. This must not be `nil`.
+ @param progress A progress object monitoring the current download progress.
+ @param success A block object to be executed when the request finishes loading successfully. This block returns the HTML string to be loaded by the web view, and takes two arguments: the response, and the response string.
+ @param failure A block object to be executed when the data 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 single argument: the error that occurred.
+ */
+- (void)loadRequest:(NSURLRequest *)request
+         navigation:(WKNavigation * _Nonnull)navigation
+           progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress
+            success:(nullable NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success
+            failure:(nullable void (^)(NSError *error))failure;
+
+/**
+ Asynchronously loads the data associated with a particular request with a specified MIME type and text encoding.
+ 
+ @param request A URL request identifying the location of the content to load. This must not be `nil`.
+ @param navigation The WKNavigation object that containts information for tracking the loading progress of a webpage.  This must not be `nil`.
+ @param MIMEType The MIME type of the content. Defaults to the content type of the response if not specified.
+ @param textEncodingName The IANA encoding name, as in `utf-8` or `utf-16`. Defaults to the response text encoding if not specified.
+ @param progress A progress object monitoring the current download progress.
+ @param success A block object to be executed when the request finishes loading successfully. This block returns the data to be loaded by the web view and takes two arguments: the response, and the downloaded data.
+ @param failure A block object to be executed when the data 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 single argument: the error that occurred.
+ */
+- (void)loadRequest:(NSURLRequest *)request
+         navigation:(WKNavigation * _Nonnull)navigation
+           MIMEType:(nullable NSString *)MIMEType
+   textEncodingName:(nullable NSString *)textEncodingName
+           progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress
+            success:(nullable NSData * (^)(NSHTTPURLResponse *response, NSData *data))success
+            failure:(nullable void (^)(NSError *error))failure;
+
+@end
+
+NS_ASSUME_NONNULL_END
+
+#endif

+ 154 - 0
Pods/AFNetworking/UIKit+AFNetworking/WKWebView+AFNetworking.m

@@ -0,0 +1,154 @@
+// WkWebView+AFNetworking.m
+// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import "WKWebView+AFNetworking.h"
+
+#import <objc/runtime.h>
+
+#if TARGET_OS_IOS
+
+#import "AFHTTPSessionManager.h"
+#import "AFURLResponseSerialization.h"
+#import "AFURLRequestSerialization.h"
+
+@interface WKWebView (_AFNetworking)
+@property (readwrite, nonatomic, strong, setter = af_setURLSessionTask:) NSURLSessionDataTask *af_URLSessionTask;
+@end
+
+@implementation WKWebView (_AFNetworking)
+
+- (NSURLSessionDataTask *)af_URLSessionTask {
+    return (NSURLSessionDataTask *)objc_getAssociatedObject(self, @selector(af_URLSessionTask));
+}
+
+- (void)af_setURLSessionTask:(NSURLSessionDataTask *)af_URLSessionTask {
+    objc_setAssociatedObject(self, @selector(af_URLSessionTask), af_URLSessionTask, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+}
+
+@end
+
+#pragma mark -
+
+@implementation WKWebView (AFNetworking)
+
+- (AFHTTPSessionManager *)sessionManager {
+    static AFHTTPSessionManager *_af_defaultHTTPSessionManager = nil;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        _af_defaultHTTPSessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
+        _af_defaultHTTPSessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
+        _af_defaultHTTPSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
+    });
+    
+    return objc_getAssociatedObject(self, @selector(sessionManager)) ?: _af_defaultHTTPSessionManager;
+}
+
+- (void)setSessionManager:(AFHTTPSessionManager *)sessionManager {
+    objc_setAssociatedObject(self, @selector(sessionManager), sessionManager, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+}
+
+- (AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer {
+    static AFHTTPResponseSerializer <AFURLResponseSerialization> *_af_defaultResponseSerializer = nil;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        _af_defaultResponseSerializer = [AFHTTPResponseSerializer serializer];
+    });
+    
+    return objc_getAssociatedObject(self, @selector(responseSerializer)) ?: _af_defaultResponseSerializer;
+}
+
+- (void)setResponseSerializer:(AFHTTPResponseSerializer<AFURLResponseSerialization> *)responseSerializer {
+    objc_setAssociatedObject(self, @selector(responseSerializer), responseSerializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+}
+
+#pragma mark -
+
+- (void)loadRequest:(NSURLRequest *)request
+         navigation:(WKNavigation * _Nonnull)navigation
+           progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress
+            success:(nullable NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success
+            failure:(nullable void (^)(NSError *error))failure {
+    [self loadRequest:request navigation:navigation MIMEType:nil textEncodingName:nil progress:progress success:^NSData * _Nonnull(NSHTTPURLResponse * _Nonnull response, NSData * _Nonnull data) {
+        NSStringEncoding stringEncoding = NSUTF8StringEncoding;
+        if (response.textEncodingName) {
+            CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName);
+            if (encoding != kCFStringEncodingInvalidId) {
+                stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding);
+            }
+        }
+        
+        NSString *string = [[NSString alloc] initWithData:data encoding:stringEncoding];
+        if (success) {
+            string = success(response, string);
+        }
+        
+        return [string dataUsingEncoding:stringEncoding];
+    } failure:failure];
+}
+
+- (void)loadRequest:(NSURLRequest *)request
+         navigation:(WKNavigation * _Nonnull)navigation
+           MIMEType:(nullable NSString *)MIMEType
+   textEncodingName:(nullable NSString *)textEncodingName
+           progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress
+            success:(nullable NSData * (^)(NSHTTPURLResponse *response, NSData *data))success
+            failure:(nullable void (^)(NSError *error))failure {
+    NSParameterAssert(request);
+    
+    if (self.af_URLSessionTask.state == NSURLSessionTaskStateRunning || self.af_URLSessionTask.state == NSURLSessionTaskStateSuspended) {
+        [self.af_URLSessionTask cancel];
+    }
+    self.af_URLSessionTask = nil;
+    
+    __weak __typeof(self)weakSelf = self;
+    __block NSURLSessionDataTask *dataTask;
+    __strong __typeof(weakSelf) strongSelf = weakSelf;
+    __strong __typeof(weakSelf.navigationDelegate) strongSelfDelegate = strongSelf.navigationDelegate;
+    dataTask = [self.sessionManager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
+        if (error) {
+            if (failure) {
+                failure(error);
+            }
+        } else {
+            if (success) {
+                success((NSHTTPURLResponse *)response, responseObject);
+            }
+            [strongSelf loadData:responseObject MIMEType:MIMEType characterEncodingName:textEncodingName baseURL:[dataTask.currentRequest URL]];
+            
+            if ([strongSelfDelegate respondsToSelector:@selector(webView:didFinishNavigation:)]) {
+                [strongSelfDelegate webView:strongSelf didFinishNavigation:navigation];
+            }
+        }
+    }];
+    self.af_URLSessionTask = dataTask;
+    if (progress != nil) {
+        *progress = [self.sessionManager downloadProgressForTask:dataTask];
+    }
+    [self.af_URLSessionTask resume];
+    
+    if ([strongSelfDelegate respondsToSelector:@selector(webView:didStartProvisionalNavigation:)]) {
+        [strongSelfDelegate webView:self didStartProvisionalNavigation:navigation];
+    }
+}
+
+@end
+
+#endif

+ 58 - 0
Pods/FDFullscreenPopGesture/FDFullscreenPopGesture/UINavigationController+FDFullscreenPopGesture.h

@@ -0,0 +1,58 @@
+// The MIT License (MIT)
+//
+// Copyright (c) 2015-2016 forkingdog ( https://github.com/forkingdog )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in all
+// copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+// SOFTWARE.
+
+#import <UIKit/UIKit.h>
+
+/// "UINavigation+FDFullscreenPopGesture" extends UINavigationController's swipe-
+/// to-pop behavior in iOS 7+ by supporting fullscreen pan gesture. Instead of
+/// screen edge, you can now swipe from any place on the screen and the onboard
+/// interactive pop transition works seamlessly.
+///
+/// Adding the implementation file of this category to your target will
+/// automatically patch UINavigationController with this feature.
+@interface UINavigationController (FDFullscreenPopGesture)
+
+/// The gesture recognizer that actually handles interactive pop.
+@property (nonatomic, strong, readonly) UIPanGestureRecognizer *fd_fullscreenPopGestureRecognizer;
+
+/// A view controller is able to control navigation bar's appearance by itself,
+/// rather than a global way, checking "fd_prefersNavigationBarHidden" property.
+/// Default to YES, disable it if you don't want so.
+@property (nonatomic, assign) BOOL fd_viewControllerBasedNavigationBarAppearanceEnabled;
+
+@end
+
+/// Allows any view controller to disable interactive pop gesture, which might
+/// be necessary when the view controller itself handles pan gesture in some
+/// cases.
+@interface UIViewController (FDFullscreenPopGesture)
+
+/// Whether the interactive pop gesture is disabled when contained in a navigation
+/// stack.
+@property (nonatomic, assign) BOOL fd_interactivePopDisabled;
+
+/// Indicate this view controller prefers its navigation bar hidden or not,
+/// checked when view controller based navigation bar's appearance is enabled.
+/// Default to NO, bars are more likely to show.
+@property (nonatomic, assign) BOOL fd_prefersNavigationBarHidden;
+
+@end

+ 227 - 0
Pods/FDFullscreenPopGesture/FDFullscreenPopGesture/UINavigationController+FDFullscreenPopGesture.m

@@ -0,0 +1,227 @@
+// The MIT License (MIT)
+//
+// Copyright (c) 2015-2016 forkingdog ( https://github.com/forkingdog )
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in all
+// copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+// SOFTWARE.
+
+#import "UINavigationController+FDFullscreenPopGesture.h"
+#import <objc/runtime.h>
+
+@interface _FDFullscreenPopGestureRecognizerDelegate : NSObject <UIGestureRecognizerDelegate>
+
+@property (nonatomic, weak) UINavigationController *navigationController;
+
+@end
+
+@implementation _FDFullscreenPopGestureRecognizerDelegate
+
+- (BOOL)gestureRecognizerShouldBegin:(UIPanGestureRecognizer *)gestureRecognizer
+{
+    // Ignore when no view controller is pushed into the navigation stack.
+    if (self.navigationController.viewControllers.count <= 1) {
+        return NO;
+    }
+    
+    // Disable when the active view controller doesn't allow interactive pop.
+    UIViewController *topViewController = self.navigationController.viewControllers.lastObject;
+    if (topViewController.fd_interactivePopDisabled) {
+        return NO;
+    }
+
+    // Ignore pan gesture when the navigation controller is currently in transition.
+    if ([[self.navigationController valueForKey:@"_isTransitioning"] boolValue]) {
+        return NO;
+    }
+    
+    // Prevent calling the handler when the gesture begins in an opposite direction.
+    CGPoint translation = [gestureRecognizer translationInView:gestureRecognizer.view];
+    if (translation.x <= 0) {
+        return NO;
+    }
+    
+    return YES;
+}
+
+@end
+
+typedef void (^_FDViewControllerWillAppearInjectBlock)(UIViewController *viewController, BOOL animated);
+
+@interface UIViewController (FDFullscreenPopGesturePrivate)
+
+@property (nonatomic, copy) _FDViewControllerWillAppearInjectBlock fd_willAppearInjectBlock;
+
+@end
+
+@implementation UIViewController (FDFullscreenPopGesturePrivate)
+
++ (void)load
+{
+    Method originalMethod = class_getInstanceMethod(self, @selector(viewWillAppear:));
+    Method swizzledMethod = class_getInstanceMethod(self, @selector(fd_viewWillAppear:));
+    method_exchangeImplementations(originalMethod, swizzledMethod);
+}
+
+- (void)fd_viewWillAppear:(BOOL)animated
+{
+    // Forward to primary implementation.
+    [self fd_viewWillAppear:animated];
+    
+    if (self.fd_willAppearInjectBlock) {
+        self.fd_willAppearInjectBlock(self, animated);
+    }
+}
+
+- (_FDViewControllerWillAppearInjectBlock)fd_willAppearInjectBlock
+{
+    return objc_getAssociatedObject(self, _cmd);
+}
+
+- (void)setFd_willAppearInjectBlock:(_FDViewControllerWillAppearInjectBlock)block
+{
+    objc_setAssociatedObject(self, @selector(fd_willAppearInjectBlock), block, OBJC_ASSOCIATION_COPY_NONATOMIC);
+}
+
+@end
+
+@implementation UINavigationController (FDFullscreenPopGesture)
+
++ (void)load
+{
+    // Inject "-pushViewController:animated:"
+    Method originalMethod = class_getInstanceMethod(self, @selector(pushViewController:animated:));
+    Method swizzledMethod = class_getInstanceMethod(self, @selector(fd_pushViewController:animated:));
+    method_exchangeImplementations(originalMethod, swizzledMethod);
+}
+
+- (void)fd_pushViewController:(UIViewController *)viewController animated:(BOOL)animated
+{
+    if (![self.interactivePopGestureRecognizer.view.gestureRecognizers containsObject:self.fd_fullscreenPopGestureRecognizer]) {
+        
+        // Add our own gesture recognizer to where the onboard screen edge pan gesture recognizer is attached to.
+        [self.interactivePopGestureRecognizer.view addGestureRecognizer:self.fd_fullscreenPopGestureRecognizer];
+
+        // Forward the gesture events to the private handler of the onboard gesture recognizer.
+        NSArray *internalTargets = [self.interactivePopGestureRecognizer valueForKey:@"targets"];
+        id internalTarget = [internalTargets.firstObject valueForKey:@"target"];
+        SEL internalAction = NSSelectorFromString(@"handleNavigationTransition:");
+        self.fd_fullscreenPopGestureRecognizer.delegate = self.fd_popGestureRecognizerDelegate;
+        [self.fd_fullscreenPopGestureRecognizer addTarget:internalTarget action:internalAction];
+
+        // Disable the onboard gesture recognizer.
+        self.interactivePopGestureRecognizer.enabled = NO;
+    }
+    
+    // Handle perferred navigation bar appearance.
+    [self fd_setupViewControllerBasedNavigationBarAppearanceIfNeeded:viewController];
+    
+    // Forward to primary implementation.
+    [self fd_pushViewController:viewController animated:animated];
+}
+
+- (void)fd_setupViewControllerBasedNavigationBarAppearanceIfNeeded:(UIViewController *)appearingViewController
+{
+    if (!self.fd_viewControllerBasedNavigationBarAppearanceEnabled) {
+        return;
+    }
+    
+    __weak typeof(self) weakSelf = self;
+    _FDViewControllerWillAppearInjectBlock block = ^(UIViewController *viewController, BOOL animated) {
+        __strong typeof(weakSelf) strongSelf = weakSelf;
+        if (strongSelf) {
+            [strongSelf setNavigationBarHidden:viewController.fd_prefersNavigationBarHidden animated:animated];
+        }
+    };
+    
+    // Setup will appear inject block to appearing view controller.
+    // Setup disappearing view controller as well, because not every view controller is added into
+    // stack by pushing, maybe by "-setViewControllers:".
+    appearingViewController.fd_willAppearInjectBlock = block;
+    UIViewController *disappearingViewController = self.viewControllers.lastObject;
+    if (disappearingViewController && !disappearingViewController.fd_willAppearInjectBlock) {
+        disappearingViewController.fd_willAppearInjectBlock = block;
+    }
+}
+
+- (_FDFullscreenPopGestureRecognizerDelegate *)fd_popGestureRecognizerDelegate
+{
+    _FDFullscreenPopGestureRecognizerDelegate *delegate = objc_getAssociatedObject(self, _cmd);
+
+    if (!delegate) {
+        delegate = [[_FDFullscreenPopGestureRecognizerDelegate alloc] init];
+        delegate.navigationController = self;
+        
+        objc_setAssociatedObject(self, _cmd, delegate, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+    }
+    return delegate;
+}
+
+- (UIPanGestureRecognizer *)fd_fullscreenPopGestureRecognizer
+{
+    UIPanGestureRecognizer *panGestureRecognizer = objc_getAssociatedObject(self, _cmd);
+
+    if (!panGestureRecognizer) {
+        panGestureRecognizer = [[UIPanGestureRecognizer alloc] init];
+        panGestureRecognizer.maximumNumberOfTouches = 1;
+        
+        objc_setAssociatedObject(self, _cmd, panGestureRecognizer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+    }
+    return panGestureRecognizer;
+}
+
+- (BOOL)fd_viewControllerBasedNavigationBarAppearanceEnabled
+{
+    NSNumber *number = objc_getAssociatedObject(self, _cmd);
+    if (number) {
+        return number.boolValue;
+    }
+    self.fd_viewControllerBasedNavigationBarAppearanceEnabled = YES;
+    return YES;
+}
+
+- (void)setFd_viewControllerBasedNavigationBarAppearanceEnabled:(BOOL)enabled
+{
+    SEL key = @selector(fd_viewControllerBasedNavigationBarAppearanceEnabled);
+    objc_setAssociatedObject(self, key, @(enabled), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+}
+
+@end
+
+@implementation UIViewController (FDFullscreenPopGesture)
+
+- (BOOL)fd_interactivePopDisabled
+{
+    return [objc_getAssociatedObject(self, _cmd) boolValue];
+}
+
+- (void)setFd_interactivePopDisabled:(BOOL)disabled
+{
+    objc_setAssociatedObject(self, @selector(fd_interactivePopDisabled), @(disabled), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+}
+
+- (BOOL)fd_prefersNavigationBarHidden
+{
+    return [objc_getAssociatedObject(self, _cmd) boolValue];
+}
+
+- (void)setFd_prefersNavigationBarHidden:(BOOL)hidden
+{
+    objc_setAssociatedObject(self, @selector(fd_prefersNavigationBarHidden), @(hidden), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+}
+
+@end

+ 22 - 0
Pods/FDFullscreenPopGesture/LICENSE

@@ -0,0 +1,22 @@
+The MIT License (MIT)
+
+Copyright (c) 2015 
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+

+ 62 - 0
Pods/FDFullscreenPopGesture/README.md

@@ -0,0 +1,62 @@
+# FDFullscreenPopGesture
+An UINavigationController's category to enable fullscreen pop gesture in an iOS7+ system style with AOP.
+
+# Overview
+
+![snapshot](https://raw.githubusercontent.com/forkingdog/FDFullscreenPopGesture/master/Snapshots/snapshot0.gif)
+
+这个扩展来自 @J_雨 同学的这个很天才的思路,他的文章地址:[http://www.jianshu.com/p/d39f7d22db6c](http://www.jianshu.com/p/d39f7d22db6c)
+
+# Usage
+
+**AOP**, just add 2 files and **no need** for any setups, all navigation controllers will be able to use fullscreen pop gesture automatically.  
+
+To disable this pop gesture of a navigation controller:  
+
+``` objc
+navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;
+```
+
+To disable this pop gesture of a view controller:  
+
+``` objc
+viewController.fd_interactivePopDisabled = YES;
+```
+
+Require at least iOS **7.0**.
+
+# View Controller Based Navigation Bar Appearance
+
+It handles navigation bar transition properly when using fullscreen gesture to push or pop a view controller:  
+
+- with bar -> without bar
+- without bar -> with bar
+- without bar -> without bar
+
+![snapshot with bar states](https://raw.githubusercontent.com/forkingdog/FDFullscreenPopGesture/master/Snapshots/snapshot1.gif)
+
+This opmiziation is enabled by default, from now on you don't need to call **UINavigationController**'s `-setNavigationBarHidden:animated:` method, instead, use view controller's specific API to hide its bar:  
+
+``` objc
+- (void)viewDidLoad {
+    [super viewDidLoad];
+    self.fd_prefersNavigationBarHidden = NO;
+}
+```
+
+And this property is **YES** by default.
+
+# Installation
+
+Use cocoapods  
+
+``` ruby
+pod 'FDFullscreenPopGesture', '1.1'
+```
+# Release Notes
+
+**1.1** - View controller based navigation bar appearance and transition.  
+**1.0** - Fullscreen pop gesture.  
+
+# License  
+MIT

+ 28 - 0
Pods/FMDB/LICENSE.txt

@@ -0,0 +1,28 @@
+If you are using FMDB in your project, I'd love to hear about it.  Let Gus know
+by sending an email to gus@flyingmeat.com.
+
+And if you happen to come across either Gus Mueller or Rob Ryan in a bar, you
+might consider purchasing a drink of their choosing if FMDB has been useful to
+you.
+
+Finally, and shortly, this is the MIT License.
+
+Copyright (c) 2008-2014 Flying Meat Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.

+ 533 - 0
Pods/FMDB/README.markdown

@@ -0,0 +1,533 @@
+# FMDB v2.7
+<!--[![Platform](https://img.shields.io/cocoapods/p/FMDB.svg?style=flat)](http://cocoadocs.org/docsets/Alamofire)-->
+[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/FMDB.svg)](https://img.shields.io/cocoapods/v/FMDB.svg)
+[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)
+
+This is an Objective-C wrapper around SQLite: http://sqlite.org/
+
+## The FMDB Mailing List:
+http://groups.google.com/group/fmdb
+
+## Read the SQLite FAQ:
+http://www.sqlite.org/faq.html
+
+Since FMDB is built on top of SQLite, you're going to want to read this page top to bottom at least once.  And while you're there, make sure to bookmark the SQLite Documentation page: http://www.sqlite.org/docs.html
+
+## Contributing
+Do you have an awesome idea that deserves to be in FMDB?  You might consider pinging ccgus first to make sure he hasn't already ruled it out for some reason.  Otherwise pull requests are great, and make sure you stick to the local coding conventions.  However, please be patient and if you haven't heard anything from ccgus for a week or more, you might want to send a note asking what's up.
+
+## Installing
+
+### CocoaPods
+
+[![Dependency Status](https://www.versioneye.com/objective-c/fmdb/2.3/badge.svg?style=flat)](https://www.versioneye.com/objective-c/fmdb/2.3)
+[![Reference Status](https://www.versioneye.com/objective-c/fmdb/reference_badge.svg?style=flat)](https://www.versioneye.com/objective-c/fmdb/references)
+
+FMDB can be installed using [CocoaPods](https://cocoapods.org/).
+
+If you haven't done so already, you might want to initialize the project, to have it produce a `Podfile` template for you:
+
+```
+$ pod init
+```
+
+Then, edit the `Podfile`, adding `FMDB`:
+
+```ruby
+# Uncomment the next line to define a global platform for your project
+# platform :ios, '9.0'
+
+target 'MyApp' do
+    # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
+    use_frameworks!
+
+    # Pods for MyApp2
+
+    pod 'FMDB'
+    # pod 'FMDB/FTS'   # FMDB with FTS
+    # pod 'FMDB/standalone'   # FMDB with latest SQLite amalgamation source
+    # pod 'FMDB/standalone/FTS'   # FMDB with latest SQLite amalgamation source and FTS
+    # pod 'FMDB/SQLCipher'   # FMDB with SQLCipher
+end
+```
+
+Then install the pods:
+
+```
+$ pod install
+```
+
+Then open the `.xcworkspace` rather than the `.xcodeproj`.
+
+For more information on Cocoapods visit https://cocoapods.org.
+
+**If using FMDB with [SQLCipher](https://www.zetetic.net/sqlcipher/) you must use the FMDB/SQLCipher subspec. The FMDB/SQLCipher subspec declares SQLCipher as a dependency, allowing FMDB to be compiled with the `-DSQLITE_HAS_CODEC` flag.**
+
+### Carthage
+
+Once you make sure you have [the latest version of Carthage](https://github.com/Carthage/Carthage/releases), you can open up a command line terminal, navigate to your project's main directory, and then do the following commands:
+
+```
+$ echo ' github "ccgus/fmdb" ' > ./Cartfile
+$ carthage update
+```
+
+You can then configure your project as outlined in Carthage's [Getting Started](https://github.com/Carthage/Carthage#getting-started) (i.e. for iOS, adding the framework to the "Link Binary with Libraries" in your target and adding the `copy-frameworks` script; in macOS, adding the framework to the list of "Embedded Binaries").
+
+## FMDB Class Reference:
+http://ccgus.github.io/fmdb/html/index.html
+
+## Automatic Reference Counting (ARC) or Manual Memory Management?
+You can use either style in your Cocoa project.  FMDB will figure out which you are using at compile time and do the right thing.
+
+## What's New in FMDB 2.7
+
+FMDB 2.7 attempts to support a more natural interface. This represents a fairly significant change for Swift developers (audited for nullability; shifted to properties in external interfaces where possible rather than methods; etc.). For Objective-C developers, this should be a fairly seamless transition (unless you were using the ivars that were previously exposed in the public interface, which you shouldn't have been doing, anyway!). 
+
+### Nullability and Swift Optionals
+
+FMDB 2.7 is largely the same as prior versions, but has been audited for nullability. For Objective-C users, this simply means that if you perform a static analysis of your FMDB-based project, you may receive more meaningful warnings as you review your project, but there are likely to be few, if any, changes necessary in your code.
+
+For Swift users, this nullability audit results in changes that are not entirely backward compatible with FMDB 2.6, but is a little more Swifty. Before FMDB was audited for nullability, Swift was forced to defensively assume that variables were optional, but the library now more accurately knows which properties and method parameters are optional, and which are not.
+
+This means, though, that Swift code written for FMDB 2.7 may require changes. For example, consider the following Swift 3/Swift 4 code for FMDB 2.6:
+
+```swift
+queue.inTransaction { db, rollback in
+    do {
+        guard let db == db else {
+            // handle error here
+            return
+        }
+
+        try db.executeUpdate("INSERT INTO foo (bar) VALUES (?)", values: [1])
+        try db.executeUpdate("INSERT INTO foo (bar) VALUES (?)", values: [2])
+    } catch {
+        rollback?.pointee = true
+    }
+}
+```
+
+Because FMDB 2.6 was not audited for nullability, Swift inferred that `db` and `rollback` were optionals. But, now, in FMDB 2.7, Swift now knows that, for example, neither `db` nor `rollback` above can be `nil`, so they are no longer optionals. Thus it becomes:
+
+```swift
+queue.inTransaction { db, rollback in
+    do {
+        try db.executeUpdate("INSERT INTO foo (bar) VALUES (?)", values: [1])
+        try db.executeUpdate("INSERT INTO foo (bar) VALUES (?)", values: [2])
+    } catch {
+        rollback.pointee = true
+    }
+}
+```
+
+### Custom Functions
+
+In the past, when writing custom functions, you would have to generally include your own `@autoreleasepool` block to avoid problems when writing functions that scanned through a large table. Now, FMDB will automatically wrap it in an autorelease pool, so you don't have to.
+
+Also, in the past, when retrieving the values passed to the function, you had to drop down to the SQLite C API and include your own `sqlite3_value_XXX` calls. There are now `FMDatabase` methods, `valueInt`, `valueString`, etc., so you can stay within Swift and/or Objective-C, without needing to call the C functions yourself. Likewise, when specifying the return values, you no longer need to call `sqlite3_result_XXX` C API, but rather you can use `FMDatabase` methods, `resultInt`, `resultString`, etc. There is a new `enum` for `valueType` called `SqliteValueType`, which can be used for checking the type of parameter passed to the custom function.
+
+Thus, you can do something like (as of Swift 3):
+
+```swift
+db.makeFunctionNamed("RemoveDiacritics", arguments: 1) { context, argc, argv in
+    guard db.valueType(argv[0]) == .text || db.valueType(argv[0]) == .null else {
+        db.resultError("Expected string parameter", context: context)
+        return
+    }
+
+    if let string = db.valueString(argv[0])?.folding(options: .diacriticInsensitive, locale: nil) {
+        db.resultString(string, context: context)
+    } else {
+        db.resultNull(context: context)
+    }
+}
+```
+
+And you can then use that function in your SQL (in this case, matching both "Jose" and "José"):
+
+```sql
+SELECT * FROM employees WHERE RemoveDiacritics(first_name) LIKE 'jose'
+```
+
+Note, the method `makeFunctionNamed:maximumArguments:withBlock:` has been renamed to `makeFunctionNamed:arguments:block:`, to more accurately reflect the functional intent of the second parameter.
+
+### API Changes
+
+In addition to the `makeFunctionNamed` noted above, there are a few other API changes. Specifically, 
+
+ - To become consistent with the rest of the API, the methods `objectForColumnName` and `UTF8StringForColumnName` have been renamed to `objectForColumn` and `UTF8StringForColumn`.
+
+ - Note, the `objectForColumn` (and the associted subscript operator) now returns `nil` if an invalid column name/index is passed to it. It used to return `NSNull`.
+
+ - To avoid confusion with `FMDatabaseQueue` method `inTransaction`, which performs transactions, the `FMDatabase` method to determine whether you are in a transaction or not, `inTransaction`, has been replaced with a read-only property, `isInTransaction`. 
+
+ - Several functions have been converted to properties, namely, `databasePath`, `maxBusyRetryTimeInterval`, `shouldCacheStatements`, `sqliteHandle`, `hasOpenResultSets`, `lastInsertRowId`, `changes`, `goodConnection`, `columnCount`, `resultDictionary`, `applicationID`, `applicationIDString`, `userVersion`, `countOfCheckedInDatabases`, `countOfCheckedOutDatabases`, and `countOfOpenDatabases`. For Objective-C users, this has little material impact, but for Swift users, it results in a slightly more natural interface. Note: For Objective-C developers, previously versions of FMDB exposed many ivars (but we hope you weren't using them directly, anyway!), but the implmentation details for these are no longer exposed.
+
+### URL Methods
+
+In keeping with Apple's shift from paths to URLs, there are now `NSURL` renditions of the various `init` methods, previously only accepting paths. 
+
+## Usage
+There are three main classes in FMDB:
+
+1. `FMDatabase` - Represents a single SQLite database.  Used for executing SQL statements.
+2. `FMResultSet` - Represents the results of executing a query on an `FMDatabase`.
+3. `FMDatabaseQueue` - If you're wanting to perform queries and updates on multiple threads, you'll want to use this class.  It's described in the "Thread Safety" section below.
+
+### Database Creation
+An `FMDatabase` is created with a path to a SQLite database file.  This path can be one of these three:
+
+1. A file system path.  The file does not have to exist on disk.  If it does not exist, it is created for you.
+2. An empty string (`@""`).  An empty database is created at a temporary location.  This database is deleted when the `FMDatabase` connection is closed.
+3. `NULL`.  An in-memory database is created.  This database will be destroyed when the `FMDatabase` connection is closed.
+
+(For more information on temporary and in-memory databases, read the sqlite documentation on the subject: http://www.sqlite.org/inmemorydb.html)
+
+```objc
+NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"tmp.db"];
+FMDatabase *db = [FMDatabase databaseWithPath:path];
+```
+
+### Opening
+
+Before you can interact with the database, it must be opened.  Opening fails if there are insufficient resources or permissions to open and/or create the database.
+
+```objc
+if (![db open]) {
+    // [db release];   // uncomment this line in manual referencing code; in ARC, this is not necessary/permitted
+    db = nil;
+    return;
+}
+```
+
+### Executing Updates
+
+Any sort of SQL statement which is not a `SELECT` statement qualifies as an update.  This includes `CREATE`, `UPDATE`, `INSERT`, `ALTER`, `COMMIT`, `BEGIN`, `DETACH`, `DELETE`, `DROP`, `END`, `EXPLAIN`, `VACUUM`, and `REPLACE` statements (plus many more).  Basically, if your SQL statement does not begin with `SELECT`, it is an update statement.
+
+Executing updates returns a single value, a `BOOL`.  A return value of `YES` means the update was successfully executed, and a return value of `NO` means that some error was encountered.  You may invoke the `-lastErrorMessage` and `-lastErrorCode` methods to retrieve more information.
+
+### Executing Queries
+
+A `SELECT` statement is a query and is executed via one of the `-executeQuery...` methods.
+
+Executing queries returns an `FMResultSet` object if successful, and `nil` upon failure.  You should use the `-lastErrorMessage` and `-lastErrorCode` methods to determine why a query failed.
+
+In order to iterate through the results of your query, you use a `while()` loop.  You also need to "step" from one record to the other.  With FMDB, the easiest way to do that is like this:
+
+```objc
+FMResultSet *s = [db executeQuery:@"SELECT * FROM myTable"];
+while ([s next]) {
+    //retrieve values for each record
+}
+```
+
+You must always invoke `-[FMResultSet next]` before attempting to access the values returned in a query, even if you're only expecting one:
+
+```objc
+FMResultSet *s = [db executeQuery:@"SELECT COUNT(*) FROM myTable"];
+if ([s next]) {
+    int totalCount = [s intForColumnIndex:0];
+}
+```
+
+`FMResultSet` has many methods to retrieve data in an appropriate format:
+
+- `intForColumn:`
+- `longForColumn:`
+- `longLongIntForColumn:`
+- `boolForColumn:`
+- `doubleForColumn:`
+- `stringForColumn:`
+- `dateForColumn:`
+- `dataForColumn:`
+- `dataNoCopyForColumn:`
+- `UTF8StringForColumn:`
+- `objectForColumn:`
+
+Each of these methods also has a `{type}ForColumnIndex:` variant that is used to retrieve the data based on the position of the column in the results, as opposed to the column's name.
+
+Typically, there's no need to `-close` an `FMResultSet` yourself, since that happens when either the result set is deallocated, or the parent database is closed.
+
+### Closing
+
+When you have finished executing queries and updates on the database, you should `-close` the `FMDatabase` connection so that SQLite will relinquish any resources it has acquired during the course of its operation.
+
+```objc
+[db close];
+```
+
+### Transactions
+
+`FMDatabase` can begin and commit a transaction by invoking one of the appropriate methods or executing a begin/end transaction statement.
+
+### Multiple Statements and Batch Stuff
+
+You can use `FMDatabase`'s executeStatements:withResultBlock: to do multiple statements in a string:
+
+```objc
+NSString *sql = @"create table bulktest1 (id integer primary key autoincrement, x text);"
+                 "create table bulktest2 (id integer primary key autoincrement, y text);"
+                 "create table bulktest3 (id integer primary key autoincrement, z text);"
+                 "insert into bulktest1 (x) values ('XXX');"
+                 "insert into bulktest2 (y) values ('YYY');"
+                 "insert into bulktest3 (z) values ('ZZZ');";
+
+success = [db executeStatements:sql];
+
+sql = @"select count(*) as count from bulktest1;"
+       "select count(*) as count from bulktest2;"
+       "select count(*) as count from bulktest3;";
+
+success = [self.db executeStatements:sql withResultBlock:^int(NSDictionary *dictionary) {
+    NSInteger count = [dictionary[@"count"] integerValue];
+    XCTAssertEqual(count, 1, @"expected one record for dictionary %@", dictionary);
+    return 0;
+}];
+```
+
+### Data Sanitization
+
+When providing a SQL statement to FMDB, you should not attempt to "sanitize" any values before insertion.  Instead, you should use the standard SQLite binding syntax:
+
+```sql
+INSERT INTO myTable VALUES (?, ?, ?, ?)
+```
+
+The `?` character is recognized by SQLite as a placeholder for a value to be inserted.  The execution methods all accept a variable number of arguments (or a representation of those arguments, such as an `NSArray`, `NSDictionary`, or a `va_list`), which are properly escaped for you.
+
+And, to use that SQL with the `?` placeholders from Objective-C:
+
+```objc
+NSInteger identifier = 42;
+NSString *name = @"Liam O'Flaherty (\"the famous Irish author\")";
+NSDate *date = [NSDate date];
+NSString *comment = nil;
+
+BOOL success = [db executeUpdate:@"INSERT INTO authors (identifier, name, date, comment) VALUES (?, ?, ?, ?)", @(identifier), name, date, comment ?: [NSNull null]];
+if (!success) {
+    NSLog(@"error = %@", [db lastErrorMessage]);
+}
+```
+
+> **Note:** Fundamental data types, like the `NSInteger` variable `identifier`, should be as a `NSNumber` objects, achieved by using the `@` syntax, shown above. Or you can use the `[NSNumber numberWithInt:identifier]` syntax, too.
+>
+> Likewise, SQL `NULL` values should be inserted as `[NSNull null]`. For example, in the case of `comment` which might be `nil` (and is in this example), you can use the `comment ?: [NSNull null]` syntax, which will insert the string if `comment` is not `nil`, but will insert `[NSNull null]` if it is `nil`.
+
+In Swift, you would use `executeUpdate(values:)`, which not only is a concise Swift syntax, but also `throws` errors for proper error handling:
+
+```swift
+do {
+    let identifier = 42
+    let name = "Liam O'Flaherty (\"the famous Irish author\")"
+    let date = Date()
+    let comment: String? = nil
+
+    try db.executeUpdate("INSERT INTO authors (identifier, name, date, comment) VALUES (?, ?, ?, ?)", values: [identifier, name, date, comment ?? NSNull()])
+} catch {
+    print("error = \(error)")
+}
+```
+
+> **Note:** In Swift, you don't have to wrap fundamental numeric types like you do in Objective-C. But if you are going to insert an optional string, you would probably use the `comment ?? NSNull()` syntax (i.e., if it is `nil`, use `NSNull`, otherwise use the string).
+
+Alternatively, you may use named parameters syntax:
+
+```sql
+INSERT INTO authors (identifier, name, date, comment) VALUES (:identifier, :name, :date, :comment)
+```
+
+The parameters *must* start with a colon. SQLite itself supports other characters, but internally the dictionary keys are prefixed with a colon, do **not** include the colon in your dictionary keys.
+
+```objc
+NSDictionary *arguments = @{@"identifier": @(identifier), @"name": name, @"date": date, @"comment": comment ?: [NSNull null]};
+BOOL success = [db executeUpdate:@"INSERT INTO authors (identifier, name, date, comment) VALUES (:identifier, :name, :date, :comment)" withParameterDictionary:arguments];
+if (!success) {
+    NSLog(@"error = %@", [db lastErrorMessage]);
+}
+```
+
+The key point is that one should not use `NSString` method `stringWithFormat` to manually insert values into the SQL statement, itself. Nor should one Swift string interpolation to insert values into the SQL. Use `?` placeholders for values to be inserted into the database (or used in `WHERE` clauses in `SELECT` statements).
+
+<h2 id="threads">Using FMDatabaseQueue and Thread Safety.</h2>
+
+Using a single instance of `FMDatabase` from multiple threads at once is a bad idea.  It has always been OK to make a `FMDatabase` object *per thread*.  Just don't share a single instance across threads, and definitely not across multiple threads at the same time.  Bad things will eventually happen and you'll eventually get something to crash, or maybe get an exception, or maybe meteorites will fall out of the sky and hit your Mac Pro.  *This would suck*.
+
+**So don't instantiate a single `FMDatabase` object and use it across multiple threads.**
+
+Instead, use `FMDatabaseQueue`. Instantiate a single `FMDatabaseQueue` and use it across multiple threads. The `FMDatabaseQueue` object will synchronize and coordinate access across the multiple threads. Here's how to use it:
+
+First, make your queue.
+
+```objc
+FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath];
+```
+
+Then use it like so:
+
+
+```objc
+[queue inDatabase:^(FMDatabase *db) {
+    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @1];
+    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @2];
+    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @3];
+
+    FMResultSet *rs = [db executeQuery:@"select * from foo"];
+    while ([rs next]) {
+        …
+    }
+}];
+```
+
+An easy way to wrap things up in a transaction can be done like this:
+
+```objc
+[queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
+    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @1];
+    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @2];
+    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @3];
+
+    if (whoopsSomethingWrongHappened) {
+        *rollback = YES;
+        return;
+    }
+
+    // etc ...
+}];
+```
+
+The Swift equivalent would be:
+
+```swift
+queue.inTransaction { db, rollback in
+    do {
+        try db.executeUpdate("INSERT INTO myTable VALUES (?)", values: [1])
+        try db.executeUpdate("INSERT INTO myTable VALUES (?)", values: [2])
+        try db.executeUpdate("INSERT INTO myTable VALUES (?)", values: [3])
+
+        if whoopsSomethingWrongHappened {
+            rollback.pointee = true
+            return
+        }
+
+        // etc ...
+    } catch {
+        rollback.pointee = true
+        print(error)
+    }
+}
+```
+
+(Note, as of Swift 3, use `pointee`. But in Swift 2.3, use `memory` rather than `pointee`.)
+
+`FMDatabaseQueue` will run the blocks on a serialized queue (hence the name of the class).  So if you call `FMDatabaseQueue`'s methods from multiple threads at the same time, they will be executed in the order they are received.  This way queries and updates won't step on each other's toes, and every one is happy.
+
+**Note:** The calls to `FMDatabaseQueue`'s methods are blocking.  So even though you are passing along blocks, they will **not** be run on another thread.
+
+## Making custom sqlite functions, based on blocks.
+
+You can do this!  For an example, look for `-makeFunctionNamed:` in main.m
+
+## Swift
+
+You can use FMDB in Swift projects too.
+
+To do this, you must:
+
+1. Copy the relevant `.m` and `.h` files from the FMDB `src` folder into your project.
+
+ You can copy all of them (which is easiest), or only the ones you need. Likely you will need [`FMDatabase`](http://ccgus.github.io/fmdb/html/Classes/FMDatabase.html) and [`FMResultSet`](http://ccgus.github.io/fmdb/html/Classes/FMResultSet.html) at a minimum. [`FMDatabaseAdditions`](http://ccgus.github.io/fmdb/html/Categories/FMDatabase+FMDatabaseAdditions.html) provides some very useful convenience methods, so you will likely want that, too. If you are doing multithreaded access to a database, [`FMDatabaseQueue`](http://ccgus.github.io/fmdb/html/Classes/FMDatabaseQueue.html) is quite useful, too. If you choose to not copy all of the files from the `src` directory, though, you may want to update `FMDB.h` to only reference the files that you included in your project.
+
+ Note, if you're copying all of the files from the `src` folder into to your project (which is recommended), you may want to drag the individual files into your project, not the folder, itself, because if you drag the folder, you won't be prompted to add the bridging header (see next point).
+
+2. If prompted to create a "bridging header", you should do so. If not prompted and if you don't already have a bridging header, add one.
+
+ For more information on bridging headers, see [Swift and Objective-C in the Same Project](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-XID_76).
+
+3. In your bridging header, add a line that says:
+    ```objc
+    #import "FMDB.h"
+    ```
+
+4. Use the variations of `executeQuery` and `executeUpdate` with the `sql` and `values` parameters with `try` pattern, as shown below. These renditions of `executeQuery` and `executeUpdate` both `throw` errors in true Swift fashion.
+
+If you do the above, you can then write Swift code that uses `FMDatabase`. For example, as of Swift 3:
+
+```swift
+let fileURL = try! FileManager.default
+    .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
+    .appendingPathComponent("test.sqlite")
+
+let database = FMDatabase(url: fileURL)
+
+guard database.open() else {
+    print("Unable to open database")
+    return
+}
+
+do {
+    try database.executeUpdate("create table test(x text, y text, z text)", values: nil)
+    try database.executeUpdate("insert into test (x, y, z) values (?, ?, ?)", values: ["a", "b", "c"])
+    try database.executeUpdate("insert into test (x, y, z) values (?, ?, ?)", values: ["e", "f", "g"])
+
+    let rs = try database.executeQuery("select x, y, z from test", values: nil)
+    while rs.next() {
+        if let x = rs.string(forColumn: "x"), let y = rs.string(forColumn: "y"), let z = rs.string(forColumn: "z") {
+            print("x = \(x); y = \(y); z = \(z)")
+        }
+    }
+} catch {
+    print("failed: \(error.localizedDescription)")
+}
+
+database.close()
+```
+
+## History
+
+The history and changes are availbe on its [GitHub page](https://github.com/ccgus/fmdb) and are summarized in the "CHANGES_AND_TODO_LIST.txt" file.
+
+## Contributors
+
+The contributors to FMDB are contained in the "Contributors.txt" file.
+
+## Additional projects using FMDB, which might be interesting to the discerning developer.
+
+ * FMDBMigrationManager, A SQLite schema migration management system for FMDB: https://github.com/layerhq/FMDBMigrationManager
+ * FCModel, An alternative to Core Data for people who like having direct SQL access: https://github.com/marcoarment/FCModel
+
+## Quick notes on FMDB's coding style
+
+Spaces, not tabs.  Square brackets, not dot notation.  Look at what FMDB already does with curly brackets and such, and stick to that style.
+
+## Reporting bugs
+
+Reduce your bug down to the smallest amount of code possible.  You want to make it super easy for the developers to see and reproduce your bug.  If it helps, pretend that the person who can fix your bug is active on shipping 3 major products, works on a handful of open source projects, has a newborn baby, and is generally very very busy.
+
+And we've even added a template function to main.m (FMDBReportABugFunction) in the FMDB distribution to help you out:
+
+* Open up fmdb project in Xcode.
+* Open up main.m and modify the FMDBReportABugFunction to reproduce your bug.
+    * Setup your table(s) in the code.
+    * Make your query or update(s).
+    * Add some assertions which demonstrate the bug.
+
+Then you can bring it up on the FMDB mailing list by showing your nice and compact FMDBReportABugFunction, or you can report the bug via the github FMDB bug reporter.
+
+**Optional:**
+
+Figure out where the bug is, fix it, and send a patch in or bring that up on the mailing list.  Make sure all the other tests run after your modifications.
+
+## Support
+
+The support channels for FMDB are the mailing list (see above), filing a bug here, or maybe on Stack Overflow.  So that is to say, support is provided by the community and on a voluntary basis.
+
+FMDB development is overseen by Gus Mueller of Flying Meat.  If FMDB been helpful to you, consider purchasing an app from FM or telling all your friends about it.
+
+## License
+
+The license for FMDB is contained in the "License.txt" file.
+
+If you happen to come across either Gus Mueller or Rob Ryan in a bar, you might consider purchasing a drink of their choosing if FMDB has been useful to you.
+
+(The drink is for them of course, shame on you for trying to keep it.)

+ 10 - 0
Pods/FMDB/src/fmdb/FMDB.h

@@ -0,0 +1,10 @@
+#import <Foundation/Foundation.h>
+
+FOUNDATION_EXPORT double FMDBVersionNumber;
+FOUNDATION_EXPORT const unsigned char FMDBVersionString[];
+
+#import "FMDatabase.h"
+#import "FMResultSet.h"
+#import "FMDatabaseAdditions.h"
+#import "FMDatabaseQueue.h"
+#import "FMDatabasePool.h"

+ 1436 - 0
Pods/FMDB/src/fmdb/FMDatabase.h

@@ -0,0 +1,1436 @@
+#import <Foundation/Foundation.h>
+#import "FMResultSet.h"
+#import "FMDatabasePool.h"
+
+NS_ASSUME_NONNULL_BEGIN
+
+#if ! __has_feature(objc_arc)
+    #define FMDBAutorelease(__v) ([__v autorelease]);
+    #define FMDBReturnAutoreleased FMDBAutorelease
+
+    #define FMDBRetain(__v) ([__v retain]);
+    #define FMDBReturnRetained FMDBRetain
+
+    #define FMDBRelease(__v) ([__v release]);
+
+    #define FMDBDispatchQueueRelease(__v) (dispatch_release(__v));
+#else
+    // -fobjc-arc
+    #define FMDBAutorelease(__v)
+    #define FMDBReturnAutoreleased(__v) (__v)
+
+    #define FMDBRetain(__v)
+    #define FMDBReturnRetained(__v) (__v)
+
+    #define FMDBRelease(__v)
+
+// If OS_OBJECT_USE_OBJC=1, then the dispatch objects will be treated like ObjC objects
+// and will participate in ARC.
+// See the section on "Dispatch Queues and Automatic Reference Counting" in "Grand Central Dispatch (GCD) Reference" for details. 
+    #if OS_OBJECT_USE_OBJC
+        #define FMDBDispatchQueueRelease(__v)
+    #else
+        #define FMDBDispatchQueueRelease(__v) (dispatch_release(__v));
+    #endif
+#endif
+
+#if !__has_feature(objc_instancetype)
+    #define instancetype id
+#endif
+
+
+typedef int(^FMDBExecuteStatementsCallbackBlock)(NSDictionary *resultsDictionary);
+
+typedef NS_ENUM(int, FMDBCheckpointMode) {
+    FMDBCheckpointModePassive  = 0, // SQLITE_CHECKPOINT_PASSIVE,
+    FMDBCheckpointModeFull     = 1, // SQLITE_CHECKPOINT_FULL,
+    FMDBCheckpointModeRestart  = 2, // SQLITE_CHECKPOINT_RESTART,
+    FMDBCheckpointModeTruncate = 3  // SQLITE_CHECKPOINT_TRUNCATE
+};
+
+/** A SQLite ([http://sqlite.org/](http://sqlite.org/)) Objective-C wrapper.
+ 
+ ### Usage
+ The three main classes in FMDB are:
+
+ - `FMDatabase` - Represents a single SQLite database.  Used for executing SQL statements.
+ - `<FMResultSet>` - Represents the results of executing a query on an `FMDatabase`.
+ - `<FMDatabaseQueue>` - If you want to perform queries and updates on multiple threads, you'll want to use this class.
+
+ ### See also
+ 
+ - `<FMDatabasePool>` - A pool of `FMDatabase` objects.
+ - `<FMStatement>` - A wrapper for `sqlite_stmt`.
+ 
+ ### External links
+ 
+ - [FMDB on GitHub](https://github.com/ccgus/fmdb) including introductory documentation
+ - [SQLite web site](http://sqlite.org/)
+ - [FMDB mailing list](http://groups.google.com/group/fmdb)
+ - [SQLite FAQ](http://www.sqlite.org/faq.html)
+ 
+ @warning Do not instantiate a single `FMDatabase` object and use it across multiple threads. Instead, use `<FMDatabaseQueue>`.
+
+ */
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wobjc-interface-ivars"
+
+
+@interface FMDatabase : NSObject
+
+///-----------------
+/// @name Properties
+///-----------------
+
+/** Whether should trace execution */
+
+@property (atomic, assign) BOOL traceExecution;
+
+/** Whether checked out or not */
+
+@property (atomic, assign) BOOL checkedOut;
+
+/** Crash on errors */
+
+@property (atomic, assign) BOOL crashOnErrors;
+
+/** Logs errors */
+
+@property (atomic, assign) BOOL logsErrors;
+
+/** Dictionary of cached statements */
+
+@property (atomic, retain, nullable) NSMutableDictionary *cachedStatements;
+
+///---------------------
+/// @name Initialization
+///---------------------
+
+/** Create a `FMDatabase` object.
+ 
+ An `FMDatabase` is created with a path to a SQLite database file.  This path can be one of these three:
+
+ 1. A file system path.  The file does not have to exist on disk.  If it does not exist, it is created for you.
+ 2. An empty string (`@""`).  An empty database is created at a temporary location.  This database is deleted with the `FMDatabase` connection is closed.
+ 3. `nil`.  An in-memory database is created.  This database will be destroyed with the `FMDatabase` connection is closed.
+
+ For example, to create/open a database in your Mac OS X `tmp` folder:
+
+    FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"];
+
+ Or, in iOS, you might open a database in the app's `Documents` directory:
+
+    NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
+    NSString *dbPath   = [docsPath stringByAppendingPathComponent:@"test.db"];
+    FMDatabase *db     = [FMDatabase databaseWithPath:dbPath];
+
+ (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [http://www.sqlite.org/inmemorydb.html](http://www.sqlite.org/inmemorydb.html))
+
+ @param inPath Path of database file
+
+ @return `FMDatabase` object if successful; `nil` if failure.
+
+ */
+
++ (instancetype)databaseWithPath:(NSString * _Nullable)inPath;
+
+/** Create a `FMDatabase` object.
+ 
+ An `FMDatabase` is created with a path to a SQLite database file.  This path can be one of these three:
+ 
+ 1. A file system URL.  The file does not have to exist on disk.  If it does not exist, it is created for you.
+ 2. `nil`.  An in-memory database is created.  This database will be destroyed with the `FMDatabase` connection is closed.
+ 
+ For example, to create/open a database in your Mac OS X `tmp` folder:
+ 
+    FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"];
+ 
+ Or, in iOS, you might open a database in the app's `Documents` directory:
+ 
+    NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
+    NSString *dbPath   = [docsPath stringByAppendingPathComponent:@"test.db"];
+    FMDatabase *db     = [FMDatabase databaseWithPath:dbPath];
+ 
+ (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [http://www.sqlite.org/inmemorydb.html](http://www.sqlite.org/inmemorydb.html))
+ 
+ @param url The local file URL (not remote URL) of database file
+ 
+ @return `FMDatabase` object if successful; `nil` if failure.
+ 
+ */
+
++ (instancetype)databaseWithURL:(NSURL * _Nullable)url;
+
+/** Initialize a `FMDatabase` object.
+ 
+ An `FMDatabase` is created with a path to a SQLite database file.  This path can be one of these three:
+
+ 1. A file system path.  The file does not have to exist on disk.  If it does not exist, it is created for you.
+ 2. An empty string (`@""`).  An empty database is created at a temporary location.  This database is deleted with the `FMDatabase` connection is closed.
+ 3. `nil`.  An in-memory database is created.  This database will be destroyed with the `FMDatabase` connection is closed.
+
+ For example, to create/open a database in your Mac OS X `tmp` folder:
+
+    FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"];
+
+ Or, in iOS, you might open a database in the app's `Documents` directory:
+
+    NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
+    NSString *dbPath   = [docsPath stringByAppendingPathComponent:@"test.db"];
+    FMDatabase *db     = [FMDatabase databaseWithPath:dbPath];
+
+ (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [http://www.sqlite.org/inmemorydb.html](http://www.sqlite.org/inmemorydb.html))
+
+ @param path Path of database file.
+ 
+ @return `FMDatabase` object if successful; `nil` if failure.
+
+ */
+
+- (instancetype)initWithPath:(NSString * _Nullable)path;
+
+/** Initialize a `FMDatabase` object.
+ 
+ An `FMDatabase` is created with a local file URL to a SQLite database file.  This path can be one of these three:
+ 
+ 1. A file system URL.  The file does not have to exist on disk.  If it does not exist, it is created for you.
+ 2. `nil`.  An in-memory database is created.  This database will be destroyed with the `FMDatabase` connection is closed.
+ 
+ For example, to create/open a database in your Mac OS X `tmp` folder:
+ 
+ FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"];
+ 
+ Or, in iOS, you might open a database in the app's `Documents` directory:
+ 
+ NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
+ NSString *dbPath   = [docsPath stringByAppendingPathComponent:@"test.db"];
+ FMDatabase *db     = [FMDatabase databaseWithPath:dbPath];
+ 
+ (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [http://www.sqlite.org/inmemorydb.html](http://www.sqlite.org/inmemorydb.html))
+ 
+ @param url The file `NSURL` of database file.
+ 
+ @return `FMDatabase` object if successful; `nil` if failure.
+ 
+ */
+
+- (instancetype)initWithURL:(NSURL * _Nullable)url;
+
+///-----------------------------------
+/// @name Opening and closing database
+///-----------------------------------
+
+/// Is the database open or not?
+
+@property (nonatomic) BOOL isOpen;
+
+/** Opening a new database connection
+ 
+ The database is opened for reading and writing, and is created if it does not already exist.
+
+ @return `YES` if successful, `NO` on error.
+
+ @see [sqlite3_open()](http://sqlite.org/c3ref/open.html)
+ @see openWithFlags:
+ @see close
+ */
+
+- (BOOL)open;
+
+/** Opening a new database connection with flags and an optional virtual file system (VFS)
+
+ @param flags one of the following three values, optionally combined with the `SQLITE_OPEN_NOMUTEX`, `SQLITE_OPEN_FULLMUTEX`, `SQLITE_OPEN_SHAREDCACHE`, `SQLITE_OPEN_PRIVATECACHE`, and/or `SQLITE_OPEN_URI` flags:
+
+ `SQLITE_OPEN_READONLY`
+
+ The database is opened in read-only mode. If the database does not already exist, an error is returned.
+ 
+ `SQLITE_OPEN_READWRITE`
+ 
+ The database is opened for reading and writing if possible, or reading only if the file is write protected by the operating system. In either case the database must already exist, otherwise an error is returned.
+ 
+ `SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE`
+ 
+ The database is opened for reading and writing, and is created if it does not already exist. This is the behavior that is always used for `open` method.
+  
+ @return `YES` if successful, `NO` on error.
+
+ @see [sqlite3_open_v2()](http://sqlite.org/c3ref/open.html)
+ @see open
+ @see close
+ */
+
+- (BOOL)openWithFlags:(int)flags;
+
+/** Opening a new database connection with flags and an optional virtual file system (VFS)
+ 
+ @param flags one of the following three values, optionally combined with the `SQLITE_OPEN_NOMUTEX`, `SQLITE_OPEN_FULLMUTEX`, `SQLITE_OPEN_SHAREDCACHE`, `SQLITE_OPEN_PRIVATECACHE`, and/or `SQLITE_OPEN_URI` flags:
+ 
+ `SQLITE_OPEN_READONLY`
+ 
+ The database is opened in read-only mode. If the database does not already exist, an error is returned.
+ 
+ `SQLITE_OPEN_READWRITE`
+ 
+ The database is opened for reading and writing if possible, or reading only if the file is write protected by the operating system. In either case the database must already exist, otherwise an error is returned.
+ 
+ `SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE`
+ 
+ The database is opened for reading and writing, and is created if it does not already exist. This is the behavior that is always used for `open` method.
+ 
+ @param vfsName   If vfs is given the value is passed to the vfs parameter of sqlite3_open_v2.
+ 
+ @return `YES` if successful, `NO` on error.
+ 
+ @see [sqlite3_open_v2()](http://sqlite.org/c3ref/open.html)
+ @see open
+ @see close
+ */
+
+- (BOOL)openWithFlags:(int)flags vfs:(NSString * _Nullable)vfsName;
+
+/** Closing a database connection
+ 
+ @return `YES` if success, `NO` on error.
+ 
+ @see [sqlite3_close()](http://sqlite.org/c3ref/close.html)
+ @see open
+ @see openWithFlags:
+ */
+
+- (BOOL)close;
+
+/** Test to see if we have a good connection to the database.
+ 
+ This will confirm whether:
+ 
+ - is database open
+ - if open, it will try a simple SELECT statement and confirm that it succeeds.
+
+ @return `YES` if everything succeeds, `NO` on failure.
+ */
+
+@property (nonatomic, readonly) BOOL goodConnection;
+
+
+///----------------------
+/// @name Perform updates
+///----------------------
+
+/** Execute single update statement
+ 
+ This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html), [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) to bind values to `?` placeholders in the SQL with the optional list of parameters, and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update.
+
+ The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method.
+
+ @param sql The SQL to be performed, with optional `?` placeholders.
+ 
+ @param outErr A reference to the `NSError` pointer to be updated with an auto released `NSError` object if an error if an error occurs. If `nil`, no `NSError` object will be returned.
+ 
+ @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.).
+
+ @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
+
+ @see lastError
+ @see lastErrorCode
+ @see lastErrorMessage
+ @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html)
+ */
+
+- (BOOL)executeUpdate:(NSString*)sql withErrorAndBindings:(NSError * _Nullable *)outErr, ...;
+
+/** Execute single update statement
+ 
+ @see executeUpdate:withErrorAndBindings:
+ 
+ @warning **Deprecated**: Please use `<executeUpdate:withErrorAndBindings>` instead.
+ */
+
+- (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError * _Nullable*)outErr, ...  __deprecated_msg("Use executeUpdate:withErrorAndBindings: instead");;
+
+/** Execute single update statement
+
+ This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html), [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) to bind values to `?` placeholders in the SQL with the optional list of parameters, and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update.
+
+ The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method.
+ 
+ @param sql The SQL to be performed, with optional `?` placeholders.
+
+ @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.).
+
+ @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
+ 
+ @see lastError
+ @see lastErrorCode
+ @see lastErrorMessage
+ @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html)
+ 
+ @note This technique supports the use of `?` placeholders in the SQL, automatically binding any supplied value parameters to those placeholders. This approach is more robust than techniques that entail using `stringWithFormat` to manually build SQL statements, which can be problematic if the values happened to include any characters that needed to be quoted.
+ 
+ @note You cannot use this method from Swift due to incompatibilities between Swift and Objective-C variadic implementations. Consider using `<executeUpdate:values:>` instead.
+ */
+
+- (BOOL)executeUpdate:(NSString*)sql, ...;
+
+/** Execute single update statement
+
+ This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. Do not use `?` placeholders in the SQL if you use this method.
+
+ @param format The SQL to be performed, with `printf`-style escape sequences.
+
+ @param ... Optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement.
+
+ @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
+
+ @see executeUpdate:
+ @see lastError
+ @see lastErrorCode
+ @see lastErrorMessage
+ 
+ @note This method does not technically perform a traditional printf-style replacement. What this method actually does is replace the printf-style percent sequences with a SQLite `?` placeholder, and then bind values to that placeholder. Thus the following command
+
+    [db executeUpdateWithFormat:@"INSERT INTO test (name) VALUES (%@)", @"Gus"];
+
+ is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `<executeUpdate:>`
+
+    [db executeUpdate:@"INSERT INTO test (name) VALUES (?)", @"Gus"];
+
+ There are two reasons why this distinction is important. First, the printf-style escape sequences can only be used where it is permissible to use a SQLite `?` placeholder. You can use it only for values in SQL statements, but not for table names or column names or any other non-value context. This method also cannot be used in conjunction with `pragma` statements and the like. Second, note the lack of quotation marks in the SQL. The `VALUES` clause was _not_ `VALUES ('%@')` (like you might have to do if you built a SQL statement using `NSString` method `stringWithFormat`), but rather simply `VALUES (%@)`.
+ */
+
+- (BOOL)executeUpdateWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
+
+/** Execute single update statement
+ 
+ This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) binding any `?` placeholders in the SQL with the optional list of parameters.
+ 
+ The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method.
+ 
+ @param sql The SQL to be performed, with optional `?` placeholders.
+ 
+ @param arguments A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement.
+ 
+ @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
+ 
+ @see executeUpdate:values:error:
+ @see lastError
+ @see lastErrorCode
+ @see lastErrorMessage
+ */
+
+- (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments;
+
+/** Execute single update statement
+ 
+ This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) binding any `?` placeholders in the SQL with the optional list of parameters.
+ 
+ The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method.
+ 
+ This is similar to `<executeUpdate:withArgumentsInArray:>`, except that this also accepts a pointer to a `NSError` pointer, so that errors can be returned.
+
+ In Swift, this throws errors, as if it were defined as follows:
+ 
+ `func executeUpdate(sql: String, values: [Any]?) throws -> Bool`
+ 
+ @param sql The SQL to be performed, with optional `?` placeholders.
+ 
+ @param values A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement.
+
+ @param error A `NSError` object to receive any error object (if any).
+
+ @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
+ 
+ @see lastError
+ @see lastErrorCode
+ @see lastErrorMessage
+ 
+ */
+
+- (BOOL)executeUpdate:(NSString*)sql values:(NSArray * _Nullable)values error:(NSError * _Nullable __autoreleasing *)error;
+
+/** Execute single update statement
+
+ This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL.
+
+ The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method.
+
+ @param sql The SQL to be performed, with optional `?` placeholders.
+
+ @param arguments A `NSDictionary` of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement.
+
+ @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
+
+ @see lastError
+ @see lastErrorCode
+ @see lastErrorMessage
+*/
+
+- (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments;
+
+
+/** Execute single update statement
+
+ This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL.
+
+ The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method.
+
+ @param sql The SQL to be performed, with optional `?` placeholders.
+
+ @param args A `va_list` of arguments.
+
+ @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
+
+ @see lastError
+ @see lastErrorCode
+ @see lastErrorMessage
+ */
+
+- (BOOL)executeUpdate:(NSString*)sql withVAList: (va_list)args;
+
+/** Execute multiple SQL statements
+ 
+ This executes a series of SQL statements that are combined in a single string (e.g. the SQL generated by the `sqlite3` command line `.dump` command). This accepts no value parameters, but rather simply expects a single string with multiple SQL statements, each terminated with a semicolon. This uses `sqlite3_exec`. 
+
+ @param  sql  The SQL to be performed
+ 
+ @return      `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
+
+ @see executeStatements:withResultBlock:
+ @see [sqlite3_exec()](http://sqlite.org/c3ref/exec.html)
+
+ */
+
+- (BOOL)executeStatements:(NSString *)sql;
+
+/** Execute multiple SQL statements with callback handler
+ 
+ This executes a series of SQL statements that are combined in a single string (e.g. the SQL generated by the `sqlite3` command line `.dump` command). This accepts no value parameters, but rather simply expects a single string with multiple SQL statements, each terminated with a semicolon. This uses `sqlite3_exec`.
+
+ @param sql       The SQL to be performed.
+ @param block     A block that will be called for any result sets returned by any SQL statements. 
+                  Note, if you supply this block, it must return integer value, zero upon success (this would be a good opportunity to use SQLITE_OK),
+                  non-zero value upon failure (which will stop the bulk execution of the SQL).  If a statement returns values, the block will be called with the results from the query in NSDictionary *resultsDictionary.
+                  This may be `nil` if you don't care to receive any results.
+
+ @return          `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`,
+                  `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
+ 
+ @see executeStatements:
+ @see [sqlite3_exec()](http://sqlite.org/c3ref/exec.html)
+
+ */
+
+- (BOOL)executeStatements:(NSString *)sql withResultBlock:(__attribute__((noescape)) FMDBExecuteStatementsCallbackBlock _Nullable)block;
+
+/** Last insert rowid
+ 
+ Each entry in an SQLite table has a unique 64-bit signed integer key called the "rowid". The rowid is always available as an undeclared column named `ROWID`, `OID`, or `_ROWID_` as long as those names are not also used by explicitly declared columns. If the table has a column of type `INTEGER PRIMARY KEY` then that column is another alias for the rowid.
+ 
+ This routine returns the rowid of the most recent successful `INSERT` into the database from the database connection in the first argument. As of SQLite version 3.7.7, this routines records the last insert rowid of both ordinary tables and virtual tables. If no successful `INSERT`s have ever occurred on that database connection, zero is returned.
+ 
+ @return The rowid of the last inserted row.
+ 
+ @see [sqlite3_last_insert_rowid()](http://sqlite.org/c3ref/last_insert_rowid.html)
+
+ */
+
+@property (nonatomic, readonly) int64_t lastInsertRowId;
+
+/** The number of rows changed by prior SQL statement.
+ 
+ This function returns the number of database rows that were changed or inserted or deleted by the most recently completed SQL statement on the database connection specified by the first parameter. Only changes that are directly specified by the INSERT, UPDATE, or DELETE statement are counted.
+ 
+ @return The number of rows changed by prior SQL statement.
+ 
+ @see [sqlite3_changes()](http://sqlite.org/c3ref/changes.html)
+ 
+ */
+
+@property (nonatomic, readonly) int changes;
+
+
+///-------------------------
+/// @name Retrieving results
+///-------------------------
+
+/** Execute select statement
+
+ Executing queries returns an `<FMResultSet>` object if successful, and `nil` upon failure.  Like executing updates, there is a variant that accepts an `NSError **` parameter.  Otherwise you should use the `<lastErrorMessage>` and `<lastErrorMessage>` methods to determine why a query failed.
+ 
+ In order to iterate through the results of your query, you use a `while()` loop.  You also need to "step" (via `<[FMResultSet next]>`) from one record to the other.
+ 
+ This method employs [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) for any optional value parameters. This  properly escapes any characters that need escape sequences (e.g. quotation marks), which eliminates simple SQL errors as well as protects against SQL injection attacks. This method natively handles `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects. All other object types will be interpreted as text values using the object's `description` method.
+
+ @param sql The SELECT statement to be performed, with optional `?` placeholders.
+
+ @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.).
+
+ @return A `<FMResultSet>` for the result set upon success; `nil` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
+ 
+ @see FMResultSet
+ @see [`FMResultSet next`](<[FMResultSet next]>)
+ @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html)
+ 
+ @note You cannot use this method from Swift due to incompatibilities between Swift and Objective-C variadic implementations. Consider using `<executeQuery:values:>` instead.
+ */
+
+- (FMResultSet * _Nullable)executeQuery:(NSString*)sql, ...;
+
+/** Execute select statement
+
+ Executing queries returns an `<FMResultSet>` object if successful, and `nil` upon failure.  Like executing updates, there is a variant that accepts an `NSError **` parameter.  Otherwise you should use the `<lastErrorMessage>` and `<lastErrorMessage>` methods to determine why a query failed.
+ 
+ In order to iterate through the results of your query, you use a `while()` loop.  You also need to "step" (via `<[FMResultSet next]>`) from one record to the other.
+ 
+ @param format The SQL to be performed, with `printf`-style escape sequences.
+
+ @param ... Optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement.
+
+ @return A `<FMResultSet>` for the result set upon success; `nil` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
+
+ @see executeQuery:
+ @see FMResultSet
+ @see [`FMResultSet next`](<[FMResultSet next]>)
+
+ @note This method does not technically perform a traditional printf-style replacement. What this method actually does is replace the printf-style percent sequences with a SQLite `?` placeholder, and then bind values to that placeholder. Thus the following command
+ 
+    [db executeQueryWithFormat:@"SELECT * FROM test WHERE name=%@", @"Gus"];
+ 
+ is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `<executeQuery:>`
+ 
+    [db executeQuery:@"SELECT * FROM test WHERE name=?", @"Gus"];
+ 
+ There are two reasons why this distinction is important. First, the printf-style escape sequences can only be used where it is permissible to use a SQLite `?` placeholder. You can use it only for values in SQL statements, but not for table names or column names or any other non-value context. This method also cannot be used in conjunction with `pragma` statements and the like. Second, note the lack of quotation marks in the SQL. The `WHERE` clause was _not_ `WHERE name='%@'` (like you might have to do if you built a SQL statement using `NSString` method `stringWithFormat`), but rather simply `WHERE name=%@`.
+ 
+ */
+
+- (FMResultSet * _Nullable)executeQueryWithFormat:(NSString*)format, ... NS_FORMAT_FUNCTION(1,2);
+
+/** Execute select statement
+
+ Executing queries returns an `<FMResultSet>` object if successful, and `nil` upon failure.  Like executing updates, there is a variant that accepts an `NSError **` parameter.  Otherwise you should use the `<lastErrorMessage>` and `<lastErrorMessage>` methods to determine why a query failed.
+ 
+ In order to iterate through the results of your query, you use a `while()` loop.  You also need to "step" (via `<[FMResultSet next]>`) from one record to the other.
+ 
+ @param sql The SELECT statement to be performed, with optional `?` placeholders.
+
+ @param arguments A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement.
+
+ @return A `<FMResultSet>` for the result set upon success; `nil` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
+
+ @see -executeQuery:values:error:
+ @see FMResultSet
+ @see [`FMResultSet next`](<[FMResultSet next]>)
+ */
+
+- (FMResultSet * _Nullable)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments;
+
+/** Execute select statement
+ 
+ Executing queries returns an `<FMResultSet>` object if successful, and `nil` upon failure.  Like executing updates, there is a variant that accepts an `NSError **` parameter.  Otherwise you should use the `<lastErrorMessage>` and `<lastErrorMessage>` methods to determine why a query failed.
+ 
+ In order to iterate through the results of your query, you use a `while()` loop.  You also need to "step" (via `<[FMResultSet next]>`) from one record to the other.
+ 
+ This is similar to `<executeQuery:withArgumentsInArray:>`, except that this also accepts a pointer to a `NSError` pointer, so that errors can be returned.
+ 
+ In Swift, this throws errors, as if it were defined as follows:
+ 
+ `func executeQuery(sql: String, values: [Any]?) throws  -> FMResultSet!`
+
+ @param sql The SELECT statement to be performed, with optional `?` placeholders.
+ 
+ @param values A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement.
+
+ @param error A `NSError` object to receive any error object (if any).
+
+ @return A `<FMResultSet>` for the result set upon success; `nil` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
+ 
+ @see FMResultSet
+ @see [`FMResultSet next`](<[FMResultSet next]>)
+ 
+ @note When called from Swift, only use the first two parameters, `sql` and `values`. This but throws the error.
+
+ */
+
+- (FMResultSet * _Nullable)executeQuery:(NSString *)sql values:(NSArray * _Nullable)values error:(NSError * _Nullable __autoreleasing *)error;
+
+/** Execute select statement
+
+ Executing queries returns an `<FMResultSet>` object if successful, and `nil` upon failure.  Like executing updates, there is a variant that accepts an `NSError **` parameter.  Otherwise you should use the `<lastErrorMessage>` and `<lastErrorMessage>` methods to determine why a query failed.
+ 
+ In order to iterate through the results of your query, you use a `while()` loop.  You also need to "step" (via `<[FMResultSet next]>`) from one record to the other.
+ 
+ @param sql The SELECT statement to be performed, with optional `?` placeholders.
+
+ @param arguments A `NSDictionary` of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement.
+
+ @return A `<FMResultSet>` for the result set upon success; `nil` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
+
+ @see FMResultSet
+ @see [`FMResultSet next`](<[FMResultSet next]>)
+ */
+
+- (FMResultSet * _Nullable)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary * _Nullable)arguments;
+
+
+// Documentation forthcoming.
+- (FMResultSet * _Nullable)executeQuery:(NSString *)sql withVAList:(va_list)args;
+
+///-------------------
+/// @name Transactions
+///-------------------
+
+/** Begin a transaction
+ 
+ @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
+ 
+ @see commit
+ @see rollback
+ @see beginDeferredTransaction
+ @see isInTransaction
+ 
+ @warning    Unlike SQLite's `BEGIN TRANSACTION`, this method currently performs
+             an exclusive transaction, not a deferred transaction. This behavior
+             is likely to change in future versions of FMDB, whereby this method
+             will likely eventually adopt standard SQLite behavior and perform
+             deferred transactions. If you really need exclusive tranaction, it is
+             recommended that you use `beginExclusiveTransaction`, instead, not
+             only to make your intent explicit, but also to future-proof your code.
+
+ */
+
+- (BOOL)beginTransaction;
+
+/** Begin a deferred transaction
+ 
+ @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
+ 
+ @see commit
+ @see rollback
+ @see beginTransaction
+ @see isInTransaction
+ */
+
+- (BOOL)beginDeferredTransaction;
+
+/** Begin an immediate transaction
+ 
+ @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
+ 
+ @see commit
+ @see rollback
+ @see beginTransaction
+ @see isInTransaction
+ */
+
+- (BOOL)beginImmediateTransaction;
+
+/** Begin an exclusive transaction
+ 
+ @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
+ 
+ @see commit
+ @see rollback
+ @see beginTransaction
+ @see isInTransaction
+ */
+
+- (BOOL)beginExclusiveTransaction;
+
+/** Commit a transaction
+
+ Commit a transaction that was initiated with either `<beginTransaction>` or with `<beginDeferredTransaction>`.
+ 
+ @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
+ 
+ @see beginTransaction
+ @see beginDeferredTransaction
+ @see rollback
+ @see isInTransaction
+ */
+
+- (BOOL)commit;
+
+/** Rollback a transaction
+
+ Rollback a transaction that was initiated with either `<beginTransaction>` or with `<beginDeferredTransaction>`.
+
+ @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
+ 
+ @see beginTransaction
+ @see beginDeferredTransaction
+ @see commit
+ @see isInTransaction
+ */
+
+- (BOOL)rollback;
+
+/** Identify whether currently in a transaction or not
+  
+ @see beginTransaction
+ @see beginDeferredTransaction
+ @see commit
+ @see rollback
+ */
+
+@property (nonatomic, readonly) BOOL isInTransaction;
+
+- (BOOL)inTransaction __deprecated_msg("Use isInTransaction property instead");
+
+
+///----------------------------------------
+/// @name Cached statements and result sets
+///----------------------------------------
+
+/** Clear cached statements */
+
+- (void)clearCachedStatements;
+
+/** Close all open result sets */
+
+- (void)closeOpenResultSets;
+
+/** Whether database has any open result sets
+ 
+ @return `YES` if there are open result sets; `NO` if not.
+ */
+
+@property (nonatomic, readonly) BOOL hasOpenResultSets;
+
+/** Whether should cache statements or not
+  */
+
+@property (nonatomic) BOOL shouldCacheStatements;
+
+/** Interupt pending database operation
+ 
+ This method causes any pending database operation to abort and return at its earliest opportunity
+ 
+ @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
+ 
+ */
+
+- (BOOL)interrupt;
+
+///-------------------------
+/// @name Encryption methods
+///-------------------------
+
+/** Set encryption key.
+ 
+ @param key The key to be used.
+
+ @return `YES` if success, `NO` on error.
+
+ @see https://www.zetetic.net/sqlcipher/
+ 
+ @warning You need to have purchased the sqlite encryption extensions for this method to work.
+ */
+
+- (BOOL)setKey:(NSString*)key;
+
+/** Reset encryption key
+
+ @param key The key to be used.
+
+ @return `YES` if success, `NO` on error.
+
+ @see https://www.zetetic.net/sqlcipher/
+
+ @warning You need to have purchased the sqlite encryption extensions for this method to work.
+ */
+
+- (BOOL)rekey:(NSString*)key;
+
+/** Set encryption key using `keyData`.
+ 
+ @param keyData The `NSData` to be used.
+
+ @return `YES` if success, `NO` on error.
+
+ @see https://www.zetetic.net/sqlcipher/
+ 
+ @warning You need to have purchased the sqlite encryption extensions for this method to work.
+ */
+
+- (BOOL)setKeyWithData:(NSData *)keyData;
+
+/** Reset encryption key using `keyData`.
+
+ @param keyData The `NSData` to be used.
+
+ @return `YES` if success, `NO` on error.
+
+ @see https://www.zetetic.net/sqlcipher/
+
+ @warning You need to have purchased the sqlite encryption extensions for this method to work.
+ */
+
+- (BOOL)rekeyWithData:(NSData *)keyData;
+
+
+///------------------------------
+/// @name General inquiry methods
+///------------------------------
+
+/** The path of the database file
+ */
+
+@property (nonatomic, readonly, nullable) NSString *databasePath;
+
+/** The file URL of the database file.
+ */
+
+@property (nonatomic, readonly, nullable) NSURL *databaseURL;
+
+/** The underlying SQLite handle 
+ 
+ @return The `sqlite3` pointer.
+ 
+ */
+
+@property (nonatomic, readonly) void *sqliteHandle;
+
+
+///-----------------------------
+/// @name Retrieving error codes
+///-----------------------------
+
+/** Last error message
+ 
+ Returns the English-language text that describes the most recent failed SQLite API call associated with a database connection. If a prior API call failed but the most recent API call succeeded, this return value is undefined.
+
+ @return `NSString` of the last error message.
+ 
+ @see [sqlite3_errmsg()](http://sqlite.org/c3ref/errcode.html)
+ @see lastErrorCode
+ @see lastError
+ 
+ */
+
+- (NSString*)lastErrorMessage;
+
+/** Last error code
+ 
+ Returns the numeric result code or extended result code for the most recent failed SQLite API call associated with a database connection. If a prior API call failed but the most recent API call succeeded, this return value is undefined.
+ 
+ @return Integer value of the last error code.
+ 
+ @see [sqlite3_errcode()](http://sqlite.org/c3ref/errcode.html)
+ @see lastErrorMessage
+ @see lastError
+ 
+ */
+
+- (int)lastErrorCode;
+
+/** Last extended error code
+ 
+ Returns the numeric extended result code for the most recent failed SQLite API call associated with a database connection. If a prior API call failed but the most recent API call succeeded, this return value is undefined.
+ 
+ @return Integer value of the last extended error code.
+ 
+ @see [sqlite3_errcode()](http://sqlite.org/c3ref/errcode.html)
+ @see [2. Primary Result Codes versus Extended Result Codes](http://sqlite.org/rescode.html#primary_result_codes_versus_extended_result_codes)
+ @see [5. Extended Result Code List](http://sqlite.org/rescode.html#extrc)
+ @see lastErrorMessage
+ @see lastError
+ 
+ */
+
+- (int)lastExtendedErrorCode;
+
+/** Had error
+
+ @return `YES` if there was an error, `NO` if no error.
+ 
+ @see lastError
+ @see lastErrorCode
+ @see lastErrorMessage
+ 
+ */
+
+- (BOOL)hadError;
+
+/** Last error
+
+ @return `NSError` representing the last error.
+ 
+ @see lastErrorCode
+ @see lastErrorMessage
+ 
+ */
+
+- (NSError *)lastError;
+
+
+// description forthcoming
+@property (nonatomic) NSTimeInterval maxBusyRetryTimeInterval;
+
+
+///------------------
+/// @name Save points
+///------------------
+
+/** Start save point
+ 
+ @param name Name of save point.
+ 
+ @param outErr A `NSError` object to receive any error object (if any).
+ 
+ @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
+ 
+ @see releaseSavePointWithName:error:
+ @see rollbackToSavePointWithName:error:
+ */
+
+- (BOOL)startSavePointWithName:(NSString*)name error:(NSError * _Nullable *)outErr;
+
+/** Release save point
+
+ @param name Name of save point.
+ 
+ @param outErr A `NSError` object to receive any error object (if any).
+ 
+ @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
+
+ @see startSavePointWithName:error:
+ @see rollbackToSavePointWithName:error:
+ 
+ */
+
+- (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError * _Nullable *)outErr;
+
+/** Roll back to save point
+
+ @param name Name of save point.
+ @param outErr A `NSError` object to receive any error object (if any).
+ 
+ @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
+ 
+ @see startSavePointWithName:error:
+ @see releaseSavePointWithName:error:
+ 
+ */
+
+- (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError * _Nullable *)outErr;
+
+/** Start save point
+
+ @param block Block of code to perform from within save point.
+ 
+ @return The NSError corresponding to the error, if any. If no error, returns `nil`.
+
+ @see startSavePointWithName:error:
+ @see releaseSavePointWithName:error:
+ @see rollbackToSavePointWithName:error:
+ 
+ */
+
+- (NSError * _Nullable)inSavePoint:(__attribute__((noescape)) void (^)(BOOL *rollback))block;
+
+
+///-----------------
+/// @name Checkpoint
+///-----------------
+
+/** Performs a WAL checkpoint
+ 
+ @param checkpointMode The checkpoint mode for sqlite3_wal_checkpoint_v2
+ @param error The NSError corresponding to the error, if any.
+ @return YES on success, otherwise NO.
+ */
+- (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode error:(NSError * _Nullable *)error;
+
+/** Performs a WAL checkpoint
+ 
+ @param checkpointMode The checkpoint mode for sqlite3_wal_checkpoint_v2
+ @param name The db name for sqlite3_wal_checkpoint_v2
+ @param error The NSError corresponding to the error, if any.
+ @return YES on success, otherwise NO.
+ */
+- (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode name:(NSString * _Nullable)name error:(NSError * _Nullable *)error;
+
+/** Performs a WAL checkpoint
+ 
+ @param checkpointMode The checkpoint mode for sqlite3_wal_checkpoint_v2
+ @param name The db name for sqlite3_wal_checkpoint_v2
+ @param error The NSError corresponding to the error, if any.
+ @param logFrameCount If not NULL, then this is set to the total number of frames in the log file or to -1 if the checkpoint could not run because of an error or because the database is not in WAL mode.
+ @param checkpointCount If not NULL, then this is set to the total number of checkpointed frames in the log file (including any that were already checkpointed before the function was called) or to -1 if the checkpoint could not run due to an error or because the database is not in WAL mode.
+ @return YES on success, otherwise NO.
+ */
+- (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode name:(NSString * _Nullable)name logFrameCount:(int * _Nullable)logFrameCount checkpointCount:(int * _Nullable)checkpointCount error:(NSError * _Nullable *)error;
+
+///----------------------------
+/// @name SQLite library status
+///----------------------------
+
+/** Test to see if the library is threadsafe
+
+ @return `NO` if and only if SQLite was compiled with mutexing code omitted due to the SQLITE_THREADSAFE compile-time option being set to 0.
+
+ @see [sqlite3_threadsafe()](http://sqlite.org/c3ref/threadsafe.html)
+ */
+
++ (BOOL)isSQLiteThreadSafe;
+
+/** Run-time library version numbers
+ 
+ @return The sqlite library version string.
+ 
+ @see [sqlite3_libversion()](http://sqlite.org/c3ref/libversion.html)
+ */
+
++ (NSString*)sqliteLibVersion;
+
+
++ (NSString*)FMDBUserVersion;
+
++ (SInt32)FMDBVersion;
+
+
+///------------------------
+/// @name Make SQL function
+///------------------------
+
+/** Adds SQL functions or aggregates or to redefine the behavior of existing SQL functions or aggregates.
+ 
+ For example:
+ 
+    [db makeFunctionNamed:@"RemoveDiacritics" arguments:1 block:^(void *context, int argc, void **argv) {
+        SqliteValueType type = [self.db valueType:argv[0]];
+        if (type == SqliteValueTypeNull) {
+            [self.db resultNullInContext:context];
+             return;
+        }
+        if (type != SqliteValueTypeText) {
+            [self.db resultError:@"Expected text" context:context];
+            return;
+        }
+        NSString *string = [self.db valueString:argv[0]];
+        NSString *result = [string stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:nil];
+        [self.db resultString:result context:context];
+    }];
+
+    FMResultSet *rs = [db executeQuery:@"SELECT * FROM employees WHERE RemoveDiacritics(first_name) LIKE 'jose'"];
+    NSAssert(rs, @"Error %@", [db lastErrorMessage]);
+ 
+ @param name Name of function.
+
+ @param arguments Maximum number of parameters.
+
+ @param block The block of code for the function.
+
+ @see [sqlite3_create_function()](http://sqlite.org/c3ref/create_function.html)
+ */
+
+- (void)makeFunctionNamed:(NSString *)name arguments:(int)arguments block:(void (^)(void *context, int argc, void * _Nonnull * _Nonnull argv))block;
+
+- (void)makeFunctionNamed:(NSString *)name maximumArguments:(int)count withBlock:(void (^)(void *context, int argc, void * _Nonnull * _Nonnull argv))block __deprecated_msg("Use makeFunctionNamed:arguments:block:");
+
+typedef NS_ENUM(int, SqliteValueType) {
+    SqliteValueTypeInteger = 1,
+    SqliteValueTypeFloat   = 2,
+    SqliteValueTypeText    = 3,
+    SqliteValueTypeBlob    = 4,
+    SqliteValueTypeNull    = 5
+};
+
+- (SqliteValueType)valueType:(void *)argv;
+
+/**
+ Get integer value of parameter in custom function.
+ 
+ @param value The argument whose value to return.
+ @return The integer value.
+ 
+ @see makeFunctionNamed:arguments:block:
+ */
+- (int)valueInt:(void *)value;
+
+/**
+ Get long value of parameter in custom function.
+ 
+ @param value The argument whose value to return.
+ @return The long value.
+ 
+ @see makeFunctionNamed:arguments:block:
+ */
+- (long long)valueLong:(void *)value;
+
+/**
+ Get double value of parameter in custom function.
+ 
+ @param value The argument whose value to return.
+ @return The double value.
+ 
+ @see makeFunctionNamed:arguments:block:
+ */
+- (double)valueDouble:(void *)value;
+
+/**
+ Get `NSData` value of parameter in custom function.
+ 
+ @param value The argument whose value to return.
+ @return The data object.
+ 
+ @see makeFunctionNamed:arguments:block:
+ */
+- (NSData * _Nullable)valueData:(void *)value;
+
+/**
+ Get string value of parameter in custom function.
+ 
+ @param value The argument whose value to return.
+ @return The string value.
+ 
+ @see makeFunctionNamed:arguments:block:
+ */
+- (NSString * _Nullable)valueString:(void *)value;
+
+/**
+ Return null value from custom function.
+ 
+ @param context The context to which the null value will be returned.
+ 
+ @see makeFunctionNamed:arguments:block:
+ */
+- (void)resultNullInContext:(void *)context NS_SWIFT_NAME(resultNull(context:));
+
+/**
+ Return integer value from custom function.
+ 
+ @param value The integer value to be returned.
+ @param context The context to which the value will be returned.
+ 
+ @see makeFunctionNamed:arguments:block:
+ */
+- (void)resultInt:(int) value context:(void *)context;
+
+/**
+ Return long value from custom function.
+ 
+ @param value The long value to be returned.
+ @param context The context to which the value will be returned.
+ 
+ @see makeFunctionNamed:arguments:block:
+ */
+- (void)resultLong:(long long)value context:(void *)context;
+
+/**
+ Return double value from custom function.
+ 
+ @param value The double value to be returned.
+ @param context The context to which the value will be returned.
+ 
+ @see makeFunctionNamed:arguments:block:
+ */
+- (void)resultDouble:(double)value context:(void *)context;
+
+/**
+ Return `NSData` object from custom function.
+ 
+ @param data The `NSData` object to be returned.
+ @param context The context to which the value will be returned.
+ 
+ @see makeFunctionNamed:arguments:block:
+ */
+- (void)resultData:(NSData *)data context:(void *)context;
+
+/**
+ Return string value from custom function.
+ 
+ @param value The string value to be returned.
+ @param context The context to which the value will be returned.
+ 
+ @see makeFunctionNamed:arguments:block:
+ */
+- (void)resultString:(NSString *)value context:(void *)context;
+
+/**
+ Return error string from custom function.
+ 
+ @param error The error string to be returned.
+ @param context The context to which the error will be returned.
+ 
+ @see makeFunctionNamed:arguments:block:
+ */
+- (void)resultError:(NSString *)error context:(void *)context;
+
+/**
+ Return error code from custom function.
+ 
+ @param errorCode The integer error code to be returned.
+ @param context The context to which the error will be returned.
+ 
+ @see makeFunctionNamed:arguments:block:
+ */
+- (void)resultErrorCode:(int)errorCode context:(void *)context;
+
+/**
+ Report memory error in custom function.
+ 
+ @param context The context to which the error will be returned.
+ 
+ @see makeFunctionNamed:arguments:block:
+ */
+- (void)resultErrorNoMemoryInContext:(void *)context NS_SWIFT_NAME(resultErrorNoMemory(context:));
+
+/**
+ Report that string or BLOB is too long to represent in custom function.
+ 
+ @param context The context to which the error will be returned.
+ 
+ @see makeFunctionNamed:arguments:block:
+ */
+- (void)resultErrorTooBigInContext:(void *)context NS_SWIFT_NAME(resultErrorTooBig(context:));
+
+///---------------------
+/// @name Date formatter
+///---------------------
+
+/** Generate an `NSDateFormatter` that won't be broken by permutations of timezones or locales.
+ 
+ Use this method to generate values to set the dateFormat property.
+ 
+ Example:
+
+    myDB.dateFormat = [FMDatabase storeableDateFormat:@"yyyy-MM-dd HH:mm:ss"];
+
+ @param format A valid NSDateFormatter format string.
+ 
+ @return A `NSDateFormatter` that can be used for converting dates to strings and vice versa.
+ 
+ @see hasDateFormatter
+ @see setDateFormat:
+ @see dateFromString:
+ @see stringFromDate:
+ @see storeableDateFormat:
+
+ @warning Note that `NSDateFormatter` is not thread-safe, so the formatter generated by this method should be assigned to only one FMDB instance and should not be used for other purposes.
+
+ */
+
++ (NSDateFormatter *)storeableDateFormat:(NSString *)format;
+
+/** Test whether the database has a date formatter assigned.
+ 
+ @return `YES` if there is a date formatter; `NO` if not.
+ 
+ @see hasDateFormatter
+ @see setDateFormat:
+ @see dateFromString:
+ @see stringFromDate:
+ @see storeableDateFormat:
+ */
+
+- (BOOL)hasDateFormatter;
+
+/** Set to a date formatter to use string dates with sqlite instead of the default UNIX timestamps.
+ 
+ @param format Set to nil to use UNIX timestamps. Defaults to nil. Should be set using a formatter generated using FMDatabase::storeableDateFormat.
+ 
+ @see hasDateFormatter
+ @see setDateFormat:
+ @see dateFromString:
+ @see stringFromDate:
+ @see storeableDateFormat:
+ 
+ @warning Note there is no direct getter for the `NSDateFormatter`, and you should not use the formatter you pass to FMDB for other purposes, as `NSDateFormatter` is not thread-safe.
+ */
+
+- (void)setDateFormat:(NSDateFormatter * _Nullable)format;
+
+/** Convert the supplied NSString to NSDate, using the current database formatter.
+ 
+ @param s `NSString` to convert to `NSDate`.
+ 
+ @return The `NSDate` object; or `nil` if no formatter is set.
+ 
+ @see hasDateFormatter
+ @see setDateFormat:
+ @see dateFromString:
+ @see stringFromDate:
+ @see storeableDateFormat:
+ */
+
+- (NSDate * _Nullable)dateFromString:(NSString *)s;
+
+/** Convert the supplied NSDate to NSString, using the current database formatter.
+ 
+ @param date `NSDate` of date to convert to `NSString`.
+
+ @return The `NSString` representation of the date; `nil` if no formatter is set.
+ 
+ @see hasDateFormatter
+ @see setDateFormat:
+ @see dateFromString:
+ @see stringFromDate:
+ @see storeableDateFormat:
+ */
+
+- (NSString * _Nullable)stringFromDate:(NSDate *)date;
+
+@end
+
+
+/** Objective-C wrapper for `sqlite3_stmt`
+ 
+ This is a wrapper for a SQLite `sqlite3_stmt`. Generally when using FMDB you will not need to interact directly with `FMStatement`, but rather with `<FMDatabase>` and `<FMResultSet>` only.
+ 
+ ### See also
+ 
+ - `<FMDatabase>`
+ - `<FMResultSet>`
+ - [`sqlite3_stmt`](http://www.sqlite.org/c3ref/stmt.html)
+ */
+
+@interface FMStatement : NSObject {
+    void *_statement;
+    NSString *_query;
+    long _useCount;
+    BOOL _inUse;
+}
+
+///-----------------
+/// @name Properties
+///-----------------
+
+/** Usage count */
+
+@property (atomic, assign) long useCount;
+
+/** SQL statement */
+
+@property (atomic, retain) NSString *query;
+
+/** SQLite sqlite3_stmt
+ 
+ @see [`sqlite3_stmt`](http://www.sqlite.org/c3ref/stmt.html)
+ */
+
+@property (atomic, assign) void *statement;
+
+/** Indication of whether the statement is in use */
+
+@property (atomic, assign) BOOL inUse;
+
+///----------------------------
+/// @name Closing and Resetting
+///----------------------------
+
+/** Close statement */
+
+- (void)close;
+
+/** Reset statement */
+
+- (void)reset;
+
+@end
+
+#pragma clang diagnostic pop
+
+NS_ASSUME_NONNULL_END

+ 1675 - 0
Pods/FMDB/src/fmdb/FMDatabase.m

@@ -0,0 +1,1675 @@
+#import "FMDatabase.h"
+#import <unistd.h>
+#import <objc/runtime.h>
+
+#if FMDB_SQLITE_STANDALONE
+#import <sqlite3/sqlite3.h>
+#else
+#import <sqlite3.h>
+#endif
+
+@interface FMDatabase () {
+    void*               _db;
+    BOOL                _isExecutingStatement;
+    NSTimeInterval      _startBusyRetryTime;
+    
+    NSMutableSet        *_openResultSets;
+    NSMutableSet        *_openFunctions;
+    
+    NSDateFormatter     *_dateFormat;
+}
+
+NS_ASSUME_NONNULL_BEGIN
+
+- (FMResultSet * _Nullable)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray * _Nullable)arrayArgs orDictionary:(NSDictionary * _Nullable)dictionaryArgs orVAList:(va_list)args;
+- (BOOL)executeUpdate:(NSString *)sql error:(NSError * _Nullable *)outErr withArgumentsInArray:(NSArray * _Nullable)arrayArgs orDictionary:(NSDictionary * _Nullable)dictionaryArgs orVAList:(va_list)args;
+
+NS_ASSUME_NONNULL_END
+
+@end
+
+@implementation FMDatabase
+
+// Because these two properties have all of their accessor methods implemented,
+// we have to synthesize them to get the corresponding ivars. The rest of the
+// properties have their ivars synthesized automatically for us.
+
+@synthesize shouldCacheStatements = _shouldCacheStatements;
+@synthesize maxBusyRetryTimeInterval = _maxBusyRetryTimeInterval;
+
+#pragma mark FMDatabase instantiation and deallocation
+
++ (instancetype)databaseWithPath:(NSString *)aPath {
+    return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath]);
+}
+
++ (instancetype)databaseWithURL:(NSURL *)url {
+    return FMDBReturnAutoreleased([[self alloc] initWithURL:url]);
+}
+
+- (instancetype)init {
+    return [self initWithPath:nil];
+}
+
+- (instancetype)initWithURL:(NSURL *)url {
+    return [self initWithPath:url.path];
+}
+
+- (instancetype)initWithPath:(NSString *)path {
+    
+    assert(sqlite3_threadsafe()); // whoa there big boy- gotta make sure sqlite it happy with what we're going to do.
+    
+    self = [super init];
+    
+    if (self) {
+        _databasePath               = [path copy];
+        _openResultSets             = [[NSMutableSet alloc] init];
+        _db                         = nil;
+        _logsErrors                 = YES;
+        _crashOnErrors              = NO;
+        _maxBusyRetryTimeInterval   = 2;
+        _isOpen                     = NO;
+    }
+    
+    return self;
+}
+
+#if ! __has_feature(objc_arc)
+- (void)finalize {
+    [self close];
+    [super finalize];
+}
+#endif
+
+- (void)dealloc {
+    [self close];
+    FMDBRelease(_openResultSets);
+    FMDBRelease(_cachedStatements);
+    FMDBRelease(_dateFormat);
+    FMDBRelease(_databasePath);
+    FMDBRelease(_openFunctions);
+    
+#if ! __has_feature(objc_arc)
+    [super dealloc];
+#endif
+}
+
+- (NSURL *)databaseURL {
+    return _databasePath ? [NSURL fileURLWithPath:_databasePath] : nil;
+}
+
++ (NSString*)FMDBUserVersion {
+    return @"2.7.5";
+}
+
+// returns 0x0240 for version 2.4.  This makes it super easy to do things like:
+// /* need to make sure to do X with FMDB version 2.4 or later */
+// if ([FMDatabase FMDBVersion] >= 0x0240) { … }
+
++ (SInt32)FMDBVersion {
+    
+    // we go through these hoops so that we only have to change the version number in a single spot.
+    static dispatch_once_t once;
+    static SInt32 FMDBVersionVal = 0;
+    
+    dispatch_once(&once, ^{
+        NSString *prodVersion = [self FMDBUserVersion];
+        
+        if ([[prodVersion componentsSeparatedByString:@"."] count] < 3) {
+            prodVersion = [prodVersion stringByAppendingString:@".0"];
+        }
+        
+        NSString *junk = [prodVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
+        
+        char *e = nil;
+        FMDBVersionVal = (int) strtoul([junk UTF8String], &e, 16);
+        
+    });
+    
+    return FMDBVersionVal;
+}
+
+#pragma mark SQLite information
+
++ (NSString*)sqliteLibVersion {
+    return [NSString stringWithFormat:@"%s", sqlite3_libversion()];
+}
+
++ (BOOL)isSQLiteThreadSafe {
+    // make sure to read the sqlite headers on this guy!
+    return sqlite3_threadsafe() != 0;
+}
+
+- (void*)sqliteHandle {
+    return _db;
+}
+
+- (const char*)sqlitePath {
+    
+    if (!_databasePath) {
+        return ":memory:";
+    }
+    
+    if ([_databasePath length] == 0) {
+        return ""; // this creates a temporary database (it's an sqlite thing).
+    }
+    
+    return [_databasePath fileSystemRepresentation];
+    
+}
+
+#pragma mark Open and close database
+
+- (BOOL)open {
+    if (_isOpen) {
+        return YES;
+    }
+    
+    // if we previously tried to open and it failed, make sure to close it before we try again
+    
+    if (_db) {
+        [self close];
+    }
+    
+    // now open database
+
+    int err = sqlite3_open([self sqlitePath], (sqlite3**)&_db );
+    if(err != SQLITE_OK) {
+        NSLog(@"error opening!: %d", err);
+        return NO;
+    }
+    
+    if (_maxBusyRetryTimeInterval > 0.0) {
+        // set the handler
+        [self setMaxBusyRetryTimeInterval:_maxBusyRetryTimeInterval];
+    }
+    
+    _isOpen = YES;
+    
+    return YES;
+}
+
+- (BOOL)openWithFlags:(int)flags {
+    return [self openWithFlags:flags vfs:nil];
+}
+
+- (BOOL)openWithFlags:(int)flags vfs:(NSString *)vfsName {
+#if SQLITE_VERSION_NUMBER >= 3005000
+    if (_isOpen) {
+        return YES;
+    }
+    
+    // if we previously tried to open and it failed, make sure to close it before we try again
+    
+    if (_db) {
+        [self close];
+    }
+    
+    // now open database
+    
+    int err = sqlite3_open_v2([self sqlitePath], (sqlite3**)&_db, flags, [vfsName UTF8String]);
+    if(err != SQLITE_OK) {
+        NSLog(@"error opening!: %d", err);
+        return NO;
+    }
+    
+    if (_maxBusyRetryTimeInterval > 0.0) {
+        // set the handler
+        [self setMaxBusyRetryTimeInterval:_maxBusyRetryTimeInterval];
+    }
+    
+    _isOpen = YES;
+    
+    return YES;
+#else
+    NSLog(@"openWithFlags requires SQLite 3.5");
+    return NO;
+#endif
+}
+
+- (BOOL)close {
+    
+    [self clearCachedStatements];
+    [self closeOpenResultSets];
+    
+    if (!_db) {
+        return YES;
+    }
+    
+    int  rc;
+    BOOL retry;
+    BOOL triedFinalizingOpenStatements = NO;
+    
+    do {
+        retry   = NO;
+        rc      = sqlite3_close(_db);
+        if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) {
+            if (!triedFinalizingOpenStatements) {
+                triedFinalizingOpenStatements = YES;
+                sqlite3_stmt *pStmt;
+                while ((pStmt = sqlite3_next_stmt(_db, nil)) !=0) {
+                    NSLog(@"Closing leaked statement");
+                    sqlite3_finalize(pStmt);
+                    retry = YES;
+                }
+            }
+        }
+        else if (SQLITE_OK != rc) {
+            NSLog(@"error closing!: %d", rc);
+        }
+    }
+    while (retry);
+    
+    _db = nil;
+    _isOpen = false;
+    
+    return YES;
+}
+
+#pragma mark Busy handler routines
+
+// NOTE: appledoc seems to choke on this function for some reason;
+//       so when generating documentation, you might want to ignore the
+//       .m files so that it only documents the public interfaces outlined
+//       in the .h files.
+//
+//       This is a known appledoc bug that it has problems with C functions
+//       within a class implementation, but for some reason, only this
+//       C function causes problems; the rest don't. Anyway, ignoring the .m
+//       files with appledoc will prevent this problem from occurring.
+
+static int FMDBDatabaseBusyHandler(void *f, int count) {
+    FMDatabase *self = (__bridge FMDatabase*)f;
+    
+    if (count == 0) {
+        self->_startBusyRetryTime = [NSDate timeIntervalSinceReferenceDate];
+        return 1;
+    }
+    
+    NSTimeInterval delta = [NSDate timeIntervalSinceReferenceDate] - (self->_startBusyRetryTime);
+    
+    if (delta < [self maxBusyRetryTimeInterval]) {
+        int requestedSleepInMillseconds = (int) arc4random_uniform(50) + 50;
+        int actualSleepInMilliseconds = sqlite3_sleep(requestedSleepInMillseconds);
+        if (actualSleepInMilliseconds != requestedSleepInMillseconds) {
+            NSLog(@"WARNING: Requested sleep of %i milliseconds, but SQLite returned %i. Maybe SQLite wasn't built with HAVE_USLEEP=1?", requestedSleepInMillseconds, actualSleepInMilliseconds);
+        }
+        return 1;
+    }
+    
+    return 0;
+}
+
+- (void)setMaxBusyRetryTimeInterval:(NSTimeInterval)timeout {
+    
+    _maxBusyRetryTimeInterval = timeout;
+    
+    if (!_db) {
+        return;
+    }
+    
+    if (timeout > 0) {
+        sqlite3_busy_handler(_db, &FMDBDatabaseBusyHandler, (__bridge void *)(self));
+    }
+    else {
+        // turn it off otherwise
+        sqlite3_busy_handler(_db, nil, nil);
+    }
+}
+
+- (NSTimeInterval)maxBusyRetryTimeInterval {
+    return _maxBusyRetryTimeInterval;
+}
+
+
+// we no longer make busyRetryTimeout public
+// but for folks who don't bother noticing that the interface to FMDatabase changed,
+// we'll still implement the method so they don't get suprise crashes
+- (int)busyRetryTimeout {
+    NSLog(@"%s:%d", __FUNCTION__, __LINE__);
+    NSLog(@"FMDB: busyRetryTimeout no longer works, please use maxBusyRetryTimeInterval");
+    return -1;
+}
+
+- (void)setBusyRetryTimeout:(int)i {
+#pragma unused(i)
+    NSLog(@"%s:%d", __FUNCTION__, __LINE__);
+    NSLog(@"FMDB: setBusyRetryTimeout does nothing, please use setMaxBusyRetryTimeInterval:");
+}
+
+#pragma mark Result set functions
+
+- (BOOL)hasOpenResultSets {
+    return [_openResultSets count] > 0;
+}
+
+- (void)closeOpenResultSets {
+    
+    //Copy the set so we don't get mutation errors
+    NSSet *openSetCopy = FMDBReturnAutoreleased([_openResultSets copy]);
+    for (NSValue *rsInWrappedInATastyValueMeal in openSetCopy) {
+        FMResultSet *rs = (FMResultSet *)[rsInWrappedInATastyValueMeal pointerValue];
+        
+        [rs setParentDB:nil];
+        [rs close];
+        
+        [_openResultSets removeObject:rsInWrappedInATastyValueMeal];
+    }
+}
+
+- (void)resultSetDidClose:(FMResultSet *)resultSet {
+    NSValue *setValue = [NSValue valueWithNonretainedObject:resultSet];
+    
+    [_openResultSets removeObject:setValue];
+}
+
+#pragma mark Cached statements
+
+- (void)clearCachedStatements {
+    
+    for (NSMutableSet *statements in [_cachedStatements objectEnumerator]) {
+        for (FMStatement *statement in [statements allObjects]) {
+            [statement close];
+        }
+    }
+    
+    [_cachedStatements removeAllObjects];
+}
+
+- (FMStatement*)cachedStatementForQuery:(NSString*)query {
+    
+    NSMutableSet* statements = [_cachedStatements objectForKey:query];
+    
+    return [[statements objectsPassingTest:^BOOL(FMStatement* statement, BOOL *stop) {
+        
+        *stop = ![statement inUse];
+        return *stop;
+        
+    }] anyObject];
+}
+
+
+- (void)setCachedStatement:(FMStatement*)statement forQuery:(NSString*)query {
+    NSParameterAssert(query);
+    if (!query) {
+        NSLog(@"API misuse, -[FMDatabase setCachedStatement:forQuery:] query must not be nil");
+        return;
+    }
+    
+    query = [query copy]; // in case we got handed in a mutable string...
+    [statement setQuery:query];
+    
+    NSMutableSet* statements = [_cachedStatements objectForKey:query];
+    if (!statements) {
+        statements = [NSMutableSet set];
+    }
+    
+    [statements addObject:statement];
+    
+    [_cachedStatements setObject:statements forKey:query];
+    
+    FMDBRelease(query);
+}
+
+#pragma mark Key routines
+
+- (BOOL)rekey:(NSString*)key {
+    NSData *keyData = [NSData dataWithBytes:(void *)[key UTF8String] length:(NSUInteger)strlen([key UTF8String])];
+    
+    return [self rekeyWithData:keyData];
+}
+
+- (BOOL)rekeyWithData:(NSData *)keyData {
+#ifdef SQLITE_HAS_CODEC
+    if (!keyData) {
+        return NO;
+    }
+    
+    int rc = sqlite3_rekey(_db, [keyData bytes], (int)[keyData length]);
+    
+    if (rc != SQLITE_OK) {
+        NSLog(@"error on rekey: %d", rc);
+        NSLog(@"%@", [self lastErrorMessage]);
+    }
+    
+    return (rc == SQLITE_OK);
+#else
+#pragma unused(keyData)
+    return NO;
+#endif
+}
+
+- (BOOL)setKey:(NSString*)key {
+    NSData *keyData = [NSData dataWithBytes:[key UTF8String] length:(NSUInteger)strlen([key UTF8String])];
+    
+    return [self setKeyWithData:keyData];
+}
+
+- (BOOL)setKeyWithData:(NSData *)keyData {
+#ifdef SQLITE_HAS_CODEC
+    if (!keyData) {
+        return NO;
+    }
+    
+    int rc = sqlite3_key(_db, [keyData bytes], (int)[keyData length]);
+    
+    return (rc == SQLITE_OK);
+#else
+#pragma unused(keyData)
+    return NO;
+#endif
+}
+
+#pragma mark Date routines
+
++ (NSDateFormatter *)storeableDateFormat:(NSString *)format {
+    
+    NSDateFormatter *result = FMDBReturnAutoreleased([[NSDateFormatter alloc] init]);
+    result.dateFormat = format;
+    result.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
+    result.locale = FMDBReturnAutoreleased([[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]);
+    return result;
+}
+
+
+- (BOOL)hasDateFormatter {
+    return _dateFormat != nil;
+}
+
+- (void)setDateFormat:(NSDateFormatter *)format {
+    FMDBAutorelease(_dateFormat);
+    _dateFormat = FMDBReturnRetained(format);
+}
+
+- (NSDate *)dateFromString:(NSString *)s {
+    return [_dateFormat dateFromString:s];
+}
+
+- (NSString *)stringFromDate:(NSDate *)date {
+    return [_dateFormat stringFromDate:date];
+}
+
+#pragma mark State of database
+
+- (BOOL)goodConnection {
+    
+    if (!_isOpen) {
+        return NO;
+    }
+    
+    FMResultSet *rs = [self executeQuery:@"select name from sqlite_master where type='table'"];
+    
+    if (rs) {
+        [rs close];
+        return YES;
+    }
+    
+    return NO;
+}
+
+- (void)warnInUse {
+    NSLog(@"The FMDatabase %@ is currently in use.", self);
+    
+#ifndef NS_BLOCK_ASSERTIONS
+    if (_crashOnErrors) {
+        NSAssert(false, @"The FMDatabase %@ is currently in use.", self);
+        abort();
+    }
+#endif
+}
+
+- (BOOL)databaseExists {
+    
+    if (!_isOpen) {
+        
+        NSLog(@"The FMDatabase %@ is not open.", self);
+        
+#ifndef NS_BLOCK_ASSERTIONS
+        if (_crashOnErrors) {
+            NSAssert(false, @"The FMDatabase %@ is not open.", self);
+            abort();
+        }
+#endif
+        
+        return NO;
+    }
+    
+    return YES;
+}
+
+#pragma mark Error routines
+
+- (NSString *)lastErrorMessage {
+    return [NSString stringWithUTF8String:sqlite3_errmsg(_db)];
+}
+
+- (BOOL)hadError {
+    int lastErrCode = [self lastErrorCode];
+    
+    return (lastErrCode > SQLITE_OK && lastErrCode < SQLITE_ROW);
+}
+
+- (int)lastErrorCode {
+    return sqlite3_errcode(_db);
+}
+
+- (int)lastExtendedErrorCode {
+    return sqlite3_extended_errcode(_db);
+}
+
+- (NSError*)errorWithMessage:(NSString *)message {
+    NSDictionary* errorMessage = [NSDictionary dictionaryWithObject:message forKey:NSLocalizedDescriptionKey];
+    
+    return [NSError errorWithDomain:@"FMDatabase" code:sqlite3_errcode(_db) userInfo:errorMessage];
+}
+
+- (NSError*)lastError {
+    return [self errorWithMessage:[self lastErrorMessage]];
+}
+
+#pragma mark Update information routines
+
+- (sqlite_int64)lastInsertRowId {
+    
+    if (_isExecutingStatement) {
+        [self warnInUse];
+        return NO;
+    }
+    
+    _isExecutingStatement = YES;
+    
+    sqlite_int64 ret = sqlite3_last_insert_rowid(_db);
+    
+    _isExecutingStatement = NO;
+    
+    return ret;
+}
+
+- (int)changes {
+    if (_isExecutingStatement) {
+        [self warnInUse];
+        return 0;
+    }
+    
+    _isExecutingStatement = YES;
+    
+    int ret = sqlite3_changes(_db);
+    
+    _isExecutingStatement = NO;
+    
+    return ret;
+}
+
+#pragma mark SQL manipulation
+
+- (void)bindObject:(id)obj toColumn:(int)idx inStatement:(sqlite3_stmt*)pStmt {
+    
+    if ((!obj) || ((NSNull *)obj == [NSNull null])) {
+        sqlite3_bind_null(pStmt, idx);
+    }
+    
+    // FIXME - someday check the return codes on these binds.
+    else if ([obj isKindOfClass:[NSData class]]) {
+        const void *bytes = [obj bytes];
+        if (!bytes) {
+            // it's an empty NSData object, aka [NSData data].
+            // Don't pass a NULL pointer, or sqlite will bind a SQL null instead of a blob.
+            bytes = "";
+        }
+        sqlite3_bind_blob(pStmt, idx, bytes, (int)[obj length], SQLITE_STATIC);
+    }
+    else if ([obj isKindOfClass:[NSDate class]]) {
+        if (self.hasDateFormatter)
+            sqlite3_bind_text(pStmt, idx, [[self stringFromDate:obj] UTF8String], -1, SQLITE_STATIC);
+        else
+            sqlite3_bind_double(pStmt, idx, [obj timeIntervalSince1970]);
+    }
+    else if ([obj isKindOfClass:[NSNumber class]]) {
+        
+        if (strcmp([obj objCType], @encode(char)) == 0) {
+            sqlite3_bind_int(pStmt, idx, [obj charValue]);
+        }
+        else if (strcmp([obj objCType], @encode(unsigned char)) == 0) {
+            sqlite3_bind_int(pStmt, idx, [obj unsignedCharValue]);
+        }
+        else if (strcmp([obj objCType], @encode(short)) == 0) {
+            sqlite3_bind_int(pStmt, idx, [obj shortValue]);
+        }
+        else if (strcmp([obj objCType], @encode(unsigned short)) == 0) {
+            sqlite3_bind_int(pStmt, idx, [obj unsignedShortValue]);
+        }
+        else if (strcmp([obj objCType], @encode(int)) == 0) {
+            sqlite3_bind_int(pStmt, idx, [obj intValue]);
+        }
+        else if (strcmp([obj objCType], @encode(unsigned int)) == 0) {
+            sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedIntValue]);
+        }
+        else if (strcmp([obj objCType], @encode(long)) == 0) {
+            sqlite3_bind_int64(pStmt, idx, [obj longValue]);
+        }
+        else if (strcmp([obj objCType], @encode(unsigned long)) == 0) {
+            sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedLongValue]);
+        }
+        else if (strcmp([obj objCType], @encode(long long)) == 0) {
+            sqlite3_bind_int64(pStmt, idx, [obj longLongValue]);
+        }
+        else if (strcmp([obj objCType], @encode(unsigned long long)) == 0) {
+            sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedLongLongValue]);
+        }
+        else if (strcmp([obj objCType], @encode(float)) == 0) {
+            sqlite3_bind_double(pStmt, idx, [obj floatValue]);
+        }
+        else if (strcmp([obj objCType], @encode(double)) == 0) {
+            sqlite3_bind_double(pStmt, idx, [obj doubleValue]);
+        }
+        else if (strcmp([obj objCType], @encode(BOOL)) == 0) {
+            sqlite3_bind_int(pStmt, idx, ([obj boolValue] ? 1 : 0));
+        }
+        else {
+            sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC);
+        }
+    }
+    else {
+        sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC);
+    }
+}
+
+- (void)extractSQL:(NSString *)sql argumentsList:(va_list)args intoString:(NSMutableString *)cleanedSQL arguments:(NSMutableArray *)arguments {
+    
+    NSUInteger length = [sql length];
+    unichar last = '\0';
+    for (NSUInteger i = 0; i < length; ++i) {
+        id arg = nil;
+        unichar current = [sql characterAtIndex:i];
+        unichar add = current;
+        if (last == '%') {
+            switch (current) {
+                case '@':
+                    arg = va_arg(args, id);
+                    break;
+                case 'c':
+                    // warning: second argument to 'va_arg' is of promotable type 'char'; this va_arg has undefined behavior because arguments will be promoted to 'int'
+                    arg = [NSString stringWithFormat:@"%c", va_arg(args, int)];
+                    break;
+                case 's':
+                    arg = [NSString stringWithUTF8String:va_arg(args, char*)];
+                    break;
+                case 'd':
+                case 'D':
+                case 'i':
+                    arg = [NSNumber numberWithInt:va_arg(args, int)];
+                    break;
+                case 'u':
+                case 'U':
+                    arg = [NSNumber numberWithUnsignedInt:va_arg(args, unsigned int)];
+                    break;
+                case 'h':
+                    i++;
+                    if (i < length && [sql characterAtIndex:i] == 'i') {
+                        //  warning: second argument to 'va_arg' is of promotable type 'short'; this va_arg has undefined behavior because arguments will be promoted to 'int'
+                        arg = [NSNumber numberWithShort:(short)(va_arg(args, int))];
+                    }
+                    else if (i < length && [sql characterAtIndex:i] == 'u') {
+                        // warning: second argument to 'va_arg' is of promotable type 'unsigned short'; this va_arg has undefined behavior because arguments will be promoted to 'int'
+                        arg = [NSNumber numberWithUnsignedShort:(unsigned short)(va_arg(args, uint))];
+                    }
+                    else {
+                        i--;
+                    }
+                    break;
+                case 'q':
+                    i++;
+                    if (i < length && [sql characterAtIndex:i] == 'i') {
+                        arg = [NSNumber numberWithLongLong:va_arg(args, long long)];
+                    }
+                    else if (i < length && [sql characterAtIndex:i] == 'u') {
+                        arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)];
+                    }
+                    else {
+                        i--;
+                    }
+                    break;
+                case 'f':
+                    arg = [NSNumber numberWithDouble:va_arg(args, double)];
+                    break;
+                case 'g':
+                    // warning: second argument to 'va_arg' is of promotable type 'float'; this va_arg has undefined behavior because arguments will be promoted to 'double'
+                    arg = [NSNumber numberWithFloat:(float)(va_arg(args, double))];
+                    break;
+                case 'l':
+                    i++;
+                    if (i < length) {
+                        unichar next = [sql characterAtIndex:i];
+                        if (next == 'l') {
+                            i++;
+                            if (i < length && [sql characterAtIndex:i] == 'd') {
+                                //%lld
+                                arg = [NSNumber numberWithLongLong:va_arg(args, long long)];
+                            }
+                            else if (i < length && [sql characterAtIndex:i] == 'u') {
+                                //%llu
+                                arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)];
+                            }
+                            else {
+                                i--;
+                            }
+                        }
+                        else if (next == 'd') {
+                            //%ld
+                            arg = [NSNumber numberWithLong:va_arg(args, long)];
+                        }
+                        else if (next == 'u') {
+                            //%lu
+                            arg = [NSNumber numberWithUnsignedLong:va_arg(args, unsigned long)];
+                        }
+                        else {
+                            i--;
+                        }
+                    }
+                    else {
+                        i--;
+                    }
+                    break;
+                default:
+                    // something else that we can't interpret. just pass it on through like normal
+                    break;
+            }
+        }
+        else if (current == '%') {
+            // percent sign; skip this character
+            add = '\0';
+        }
+        
+        if (arg != nil) {
+            [cleanedSQL appendString:@"?"];
+            [arguments addObject:arg];
+        }
+        else if (add == (unichar)'@' && last == (unichar) '%') {
+            [cleanedSQL appendFormat:@"NULL"];
+        }
+        else if (add != '\0') {
+            [cleanedSQL appendFormat:@"%C", add];
+        }
+        last = current;
+    }
+}
+
+#pragma mark Execute queries
+
+- (FMResultSet *)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary *)arguments {
+    return [self executeQuery:sql withArgumentsInArray:nil orDictionary:arguments orVAList:nil];
+}
+
+- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args {
+    
+    if (![self databaseExists]) {
+        return 0x00;
+    }
+    
+    if (_isExecutingStatement) {
+        [self warnInUse];
+        return 0x00;
+    }
+    
+    _isExecutingStatement = YES;
+    
+    int rc                  = 0x00;
+    sqlite3_stmt *pStmt     = 0x00;
+    FMStatement *statement  = 0x00;
+    FMResultSet *rs         = 0x00;
+    
+    if (_traceExecution && sql) {
+        NSLog(@"%@ executeQuery: %@", self, sql);
+    }
+    
+    if (_shouldCacheStatements) {
+        statement = [self cachedStatementForQuery:sql];
+        pStmt = statement ? [statement statement] : 0x00;
+        [statement reset];
+    }
+    
+    if (!pStmt) {
+        
+        rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0);
+        
+        if (SQLITE_OK != rc) {
+            if (_logsErrors) {
+                NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
+                NSLog(@"DB Query: %@", sql);
+                NSLog(@"DB Path: %@", _databasePath);
+            }
+            
+            if (_crashOnErrors) {
+                NSAssert(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
+                abort();
+            }
+            
+            sqlite3_finalize(pStmt);
+            _isExecutingStatement = NO;
+            return nil;
+        }
+    }
+    
+    id obj;
+    int idx = 0;
+    int queryCount = sqlite3_bind_parameter_count(pStmt); // pointed out by Dominic Yu (thanks!)
+    
+    // If dictionaryArgs is passed in, that means we are using sqlite's named parameter support
+    if (dictionaryArgs) {
+        
+        for (NSString *dictionaryKey in [dictionaryArgs allKeys]) {
+            
+            // Prefix the key with a colon.
+            NSString *parameterName = [[NSString alloc] initWithFormat:@":%@", dictionaryKey];
+            
+            if (_traceExecution) {
+                NSLog(@"%@ = %@", parameterName, [dictionaryArgs objectForKey:dictionaryKey]);
+            }
+            
+            // Get the index for the parameter name.
+            int namedIdx = sqlite3_bind_parameter_index(pStmt, [parameterName UTF8String]);
+            
+            FMDBRelease(parameterName);
+            
+            if (namedIdx > 0) {
+                // Standard binding from here.
+                [self bindObject:[dictionaryArgs objectForKey:dictionaryKey] toColumn:namedIdx inStatement:pStmt];
+                // increment the binding count, so our check below works out
+                idx++;
+            }
+            else {
+                NSLog(@"Could not find index for %@", dictionaryKey);
+            }
+        }
+    }
+    else {
+        
+        while (idx < queryCount) {
+            
+            if (arrayArgs && idx < (int)[arrayArgs count]) {
+                obj = [arrayArgs objectAtIndex:(NSUInteger)idx];
+            }
+            else if (args) {
+                obj = va_arg(args, id);
+            }
+            else {
+                //We ran out of arguments
+                break;
+            }
+            
+            if (_traceExecution) {
+                if ([obj isKindOfClass:[NSData class]]) {
+                    NSLog(@"data: %ld bytes", (unsigned long)[(NSData*)obj length]);
+                }
+                else {
+                    NSLog(@"obj: %@", obj);
+                }
+            }
+            
+            idx++;
+            
+            [self bindObject:obj toColumn:idx inStatement:pStmt];
+        }
+    }
+    
+    if (idx != queryCount) {
+        NSLog(@"Error: the bind count is not correct for the # of variables (executeQuery)");
+        sqlite3_finalize(pStmt);
+        _isExecutingStatement = NO;
+        return nil;
+    }
+    
+    FMDBRetain(statement); // to balance the release below
+    
+    if (!statement) {
+        statement = [[FMStatement alloc] init];
+        [statement setStatement:pStmt];
+        
+        if (_shouldCacheStatements && sql) {
+            [self setCachedStatement:statement forQuery:sql];
+        }
+    }
+    
+    // the statement gets closed in rs's dealloc or [rs close];
+    rs = [FMResultSet resultSetWithStatement:statement usingParentDatabase:self];
+    [rs setQuery:sql];
+    
+    NSValue *openResultSet = [NSValue valueWithNonretainedObject:rs];
+    [_openResultSets addObject:openResultSet];
+    
+    [statement setUseCount:[statement useCount] + 1];
+    
+    FMDBRelease(statement);
+    
+    _isExecutingStatement = NO;
+    
+    return rs;
+}
+
+- (FMResultSet *)executeQuery:(NSString*)sql, ... {
+    va_list args;
+    va_start(args, sql);
+    
+    id result = [self executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:args];
+    
+    va_end(args);
+    return result;
+}
+
+- (FMResultSet *)executeQueryWithFormat:(NSString*)format, ... {
+    va_list args;
+    va_start(args, format);
+    
+    NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]];
+    NSMutableArray *arguments = [NSMutableArray array];
+    [self extractSQL:format argumentsList:args intoString:sql arguments:arguments];
+    
+    va_end(args);
+    
+    return [self executeQuery:sql withArgumentsInArray:arguments];
+}
+
+- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments {
+    return [self executeQuery:sql withArgumentsInArray:arguments orDictionary:nil orVAList:nil];
+}
+
+- (FMResultSet *)executeQuery:(NSString *)sql values:(NSArray *)values error:(NSError * __autoreleasing *)error {
+    FMResultSet *rs = [self executeQuery:sql withArgumentsInArray:values orDictionary:nil orVAList:nil];
+    if (!rs && error) {
+        *error = [self lastError];
+    }
+    return rs;
+}
+
+- (FMResultSet *)executeQuery:(NSString*)sql withVAList:(va_list)args {
+    return [self executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:args];
+}
+
+#pragma mark Execute updates
+
+- (BOOL)executeUpdate:(NSString*)sql error:(NSError**)outErr withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args {
+    
+    if (![self databaseExists]) {
+        return NO;
+    }
+    
+    if (_isExecutingStatement) {
+        [self warnInUse];
+        return NO;
+    }
+    
+    _isExecutingStatement = YES;
+    
+    int rc                   = 0x00;
+    sqlite3_stmt *pStmt      = 0x00;
+    FMStatement *cachedStmt  = 0x00;
+    
+    if (_traceExecution && sql) {
+        NSLog(@"%@ executeUpdate: %@", self, sql);
+    }
+    
+    if (_shouldCacheStatements) {
+        cachedStmt = [self cachedStatementForQuery:sql];
+        pStmt = cachedStmt ? [cachedStmt statement] : 0x00;
+        [cachedStmt reset];
+    }
+    
+    if (!pStmt) {
+        rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0);
+        
+        if (SQLITE_OK != rc) {
+            if (_logsErrors) {
+                NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
+                NSLog(@"DB Query: %@", sql);
+                NSLog(@"DB Path: %@", _databasePath);
+            }
+            
+            if (_crashOnErrors) {
+                NSAssert(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
+                abort();
+            }
+            
+            if (outErr) {
+                *outErr = [self errorWithMessage:[NSString stringWithUTF8String:sqlite3_errmsg(_db)]];
+            }
+            
+            sqlite3_finalize(pStmt);
+            
+            _isExecutingStatement = NO;
+            return NO;
+        }
+    }
+    
+    id obj;
+    int idx = 0;
+    int queryCount = sqlite3_bind_parameter_count(pStmt);
+    
+    // If dictionaryArgs is passed in, that means we are using sqlite's named parameter support
+    if (dictionaryArgs) {
+        
+        for (NSString *dictionaryKey in [dictionaryArgs allKeys]) {
+            
+            // Prefix the key with a colon.
+            NSString *parameterName = [[NSString alloc] initWithFormat:@":%@", dictionaryKey];
+            
+            if (_traceExecution) {
+                NSLog(@"%@ = %@", parameterName, [dictionaryArgs objectForKey:dictionaryKey]);
+            }
+            // Get the index for the parameter name.
+            int namedIdx = sqlite3_bind_parameter_index(pStmt, [parameterName UTF8String]);
+            
+            FMDBRelease(parameterName);
+            
+            if (namedIdx > 0) {
+                // Standard binding from here.
+                [self bindObject:[dictionaryArgs objectForKey:dictionaryKey] toColumn:namedIdx inStatement:pStmt];
+                
+                // increment the binding count, so our check below works out
+                idx++;
+            }
+            else {
+                NSString *message = [NSString stringWithFormat:@"Could not find index for %@", dictionaryKey];
+                
+                if (_logsErrors) {
+                    NSLog(@"%@", message);
+                }
+                if (outErr) {
+                    *outErr = [self errorWithMessage:message];
+                }
+            }
+        }
+    }
+    else {
+        
+        while (idx < queryCount) {
+            
+            if (arrayArgs && idx < (int)[arrayArgs count]) {
+                obj = [arrayArgs objectAtIndex:(NSUInteger)idx];
+            }
+            else if (args) {
+                obj = va_arg(args, id);
+            }
+            else {
+                //We ran out of arguments
+                break;
+            }
+            
+            if (_traceExecution) {
+                if ([obj isKindOfClass:[NSData class]]) {
+                    NSLog(@"data: %ld bytes", (unsigned long)[(NSData*)obj length]);
+                }
+                else {
+                    NSLog(@"obj: %@", obj);
+                }
+            }
+            
+            idx++;
+            
+            [self bindObject:obj toColumn:idx inStatement:pStmt];
+        }
+    }
+    
+    
+    if (idx != queryCount) {
+        NSString *message = [NSString stringWithFormat:@"Error: the bind count (%d) is not correct for the # of variables in the query (%d) (%@) (executeUpdate)", idx, queryCount, sql];
+        if (_logsErrors) {
+            NSLog(@"%@", message);
+        }
+        if (outErr) {
+            *outErr = [self errorWithMessage:message];
+        }
+        
+        sqlite3_finalize(pStmt);
+        _isExecutingStatement = NO;
+        return NO;
+    }
+    
+    /* Call sqlite3_step() to run the virtual machine. Since the SQL being
+     ** executed is not a SELECT statement, we assume no data will be returned.
+     */
+    
+    rc      = sqlite3_step(pStmt);
+    
+    if (SQLITE_DONE == rc) {
+        // all is well, let's return.
+    }
+    else if (SQLITE_INTERRUPT == rc) {
+        if (_logsErrors) {
+            NSLog(@"Error calling sqlite3_step. Query was interrupted (%d: %s) SQLITE_INTERRUPT", rc, sqlite3_errmsg(_db));
+            NSLog(@"DB Query: %@", sql);
+        }
+    }
+    else if (rc == SQLITE_ROW) {
+        NSString *message = [NSString stringWithFormat:@"A executeUpdate is being called with a query string '%@'", sql];
+        if (_logsErrors) {
+            NSLog(@"%@", message);
+            NSLog(@"DB Query: %@", sql);
+        }
+        if (outErr) {
+            *outErr = [self errorWithMessage:message];
+        }
+    }
+    else {
+        if (outErr) {
+            *outErr = [self errorWithMessage:[NSString stringWithUTF8String:sqlite3_errmsg(_db)]];
+        }
+        
+        if (SQLITE_ERROR == rc) {
+            if (_logsErrors) {
+                NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_ERROR", rc, sqlite3_errmsg(_db));
+                NSLog(@"DB Query: %@", sql);
+            }
+        }
+        else if (SQLITE_MISUSE == rc) {
+            // uh oh.
+            if (_logsErrors) {
+                NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_MISUSE", rc, sqlite3_errmsg(_db));
+                NSLog(@"DB Query: %@", sql);
+            }
+        }
+        else {
+            // wtf?
+            if (_logsErrors) {
+                NSLog(@"Unknown error calling sqlite3_step (%d: %s) eu", rc, sqlite3_errmsg(_db));
+                NSLog(@"DB Query: %@", sql);
+            }
+        }
+    }
+    
+    if (_shouldCacheStatements && !cachedStmt) {
+        cachedStmt = [[FMStatement alloc] init];
+        
+        [cachedStmt setStatement:pStmt];
+        
+        [self setCachedStatement:cachedStmt forQuery:sql];
+        
+        FMDBRelease(cachedStmt);
+    }
+    
+    int closeErrorCode;
+    
+    if (cachedStmt) {
+        [cachedStmt setUseCount:[cachedStmt useCount] + 1];
+        closeErrorCode = sqlite3_reset(pStmt);
+    }
+    else {
+        /* Finalize the virtual machine. This releases all memory and other
+         ** resources allocated by the sqlite3_prepare() call above.
+         */
+        closeErrorCode = sqlite3_finalize(pStmt);
+    }
+    
+    if (closeErrorCode != SQLITE_OK) {
+        if (_logsErrors) {
+            NSLog(@"Unknown error finalizing or resetting statement (%d: %s)", closeErrorCode, sqlite3_errmsg(_db));
+            NSLog(@"DB Query: %@", sql);
+        }
+    }
+    
+    _isExecutingStatement = NO;
+    return (rc == SQLITE_DONE || rc == SQLITE_OK);
+}
+
+
+- (BOOL)executeUpdate:(NSString*)sql, ... {
+    va_list args;
+    va_start(args, sql);
+    
+    BOOL result = [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:nil orVAList:args];
+    
+    va_end(args);
+    return result;
+}
+
+- (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments {
+    return [self executeUpdate:sql error:nil withArgumentsInArray:arguments orDictionary:nil orVAList:nil];
+}
+
+- (BOOL)executeUpdate:(NSString*)sql values:(NSArray *)values error:(NSError * __autoreleasing *)error {
+    return [self executeUpdate:sql error:error withArgumentsInArray:values orDictionary:nil orVAList:nil];
+}
+
+- (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments {
+    return [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:arguments orVAList:nil];
+}
+
+- (BOOL)executeUpdate:(NSString*)sql withVAList:(va_list)args {
+    return [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:nil orVAList:args];
+}
+
+- (BOOL)executeUpdateWithFormat:(NSString*)format, ... {
+    va_list args;
+    va_start(args, format);
+    
+    NSMutableString *sql      = [NSMutableString stringWithCapacity:[format length]];
+    NSMutableArray *arguments = [NSMutableArray array];
+    
+    [self extractSQL:format argumentsList:args intoString:sql arguments:arguments];
+    
+    va_end(args);
+    
+    return [self executeUpdate:sql withArgumentsInArray:arguments];
+}
+
+
+int FMDBExecuteBulkSQLCallback(void *theBlockAsVoid, int columns, char **values, char **names); // shhh clang.
+int FMDBExecuteBulkSQLCallback(void *theBlockAsVoid, int columns, char **values, char **names) {
+    
+    if (!theBlockAsVoid) {
+        return SQLITE_OK;
+    }
+    
+    int (^execCallbackBlock)(NSDictionary *resultsDictionary) = (__bridge int (^)(NSDictionary *__strong))(theBlockAsVoid);
+    
+    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:(NSUInteger)columns];
+    
+    for (NSInteger i = 0; i < columns; i++) {
+        NSString *key = [NSString stringWithUTF8String:names[i]];
+        id value = values[i] ? [NSString stringWithUTF8String:values[i]] : [NSNull null];
+        value = value ? value : [NSNull null];
+        [dictionary setObject:value forKey:key];
+    }
+    
+    return execCallbackBlock(dictionary);
+}
+
+- (BOOL)executeStatements:(NSString *)sql {
+    return [self executeStatements:sql withResultBlock:nil];
+}
+
+- (BOOL)executeStatements:(NSString *)sql withResultBlock:(__attribute__((noescape)) FMDBExecuteStatementsCallbackBlock)block {
+    
+    int rc;
+    char *errmsg = nil;
+    
+    rc = sqlite3_exec([self sqliteHandle], [sql UTF8String], block ? FMDBExecuteBulkSQLCallback : nil, (__bridge void *)(block), &errmsg);
+    
+    if (errmsg && [self logsErrors]) {
+        NSLog(@"Error inserting batch: %s", errmsg);
+        sqlite3_free(errmsg);
+    }
+    
+    return (rc == SQLITE_OK);
+}
+
+- (BOOL)executeUpdate:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... {
+    
+    va_list args;
+    va_start(args, outErr);
+    
+    BOOL result = [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:args];
+    
+    va_end(args);
+    return result;
+}
+
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-implementations"
+- (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... {
+    va_list args;
+    va_start(args, outErr);
+    
+    BOOL result = [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:args];
+    
+    va_end(args);
+    return result;
+}
+
+#pragma clang diagnostic pop
+
+#pragma mark Transactions
+
+- (BOOL)rollback {
+    BOOL b = [self executeUpdate:@"rollback transaction"];
+    
+    if (b) {
+        _isInTransaction = NO;
+    }
+    
+    return b;
+}
+
+- (BOOL)commit {
+    BOOL b =  [self executeUpdate:@"commit transaction"];
+    
+    if (b) {
+        _isInTransaction = NO;
+    }
+    
+    return b;
+}
+
+- (BOOL)beginTransaction {
+    
+    BOOL b = [self executeUpdate:@"begin exclusive transaction"];
+    if (b) {
+        _isInTransaction = YES;
+    }
+    
+    return b;
+}
+
+- (BOOL)beginDeferredTransaction {
+    
+    BOOL b = [self executeUpdate:@"begin deferred transaction"];
+    if (b) {
+        _isInTransaction = YES;
+    }
+    
+    return b;
+}
+
+- (BOOL)beginImmediateTransaction {
+    
+    BOOL b = [self executeUpdate:@"begin immediate transaction"];
+    if (b) {
+        _isInTransaction = YES;
+    }
+    
+    return b;
+}
+
+- (BOOL)beginExclusiveTransaction {
+    
+    BOOL b = [self executeUpdate:@"begin exclusive transaction"];
+    if (b) {
+        _isInTransaction = YES;
+    }
+    
+    return b;
+}
+
+- (BOOL)inTransaction {
+    return _isInTransaction;
+}
+
+- (BOOL)interrupt
+{
+    if (_db) {
+        sqlite3_interrupt([self sqliteHandle]);
+        return YES;
+    }
+    return NO;
+}
+
+static NSString *FMDBEscapeSavePointName(NSString *savepointName) {
+    return [savepointName stringByReplacingOccurrencesOfString:@"'" withString:@"''"];
+}
+
+- (BOOL)startSavePointWithName:(NSString*)name error:(NSError**)outErr {
+#if SQLITE_VERSION_NUMBER >= 3007000
+    NSParameterAssert(name);
+    
+    NSString *sql = [NSString stringWithFormat:@"savepoint '%@';", FMDBEscapeSavePointName(name)];
+    
+    return [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:nil];
+#else
+    NSString *errorMessage = NSLocalizedStringFromTable(@"Save point functions require SQLite 3.7", @"FMDB", nil);
+    if (self.logsErrors) NSLog(@"%@", errorMessage);
+    return NO;
+#endif
+}
+
+- (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError**)outErr {
+#if SQLITE_VERSION_NUMBER >= 3007000
+    NSParameterAssert(name);
+    
+    NSString *sql = [NSString stringWithFormat:@"release savepoint '%@';", FMDBEscapeSavePointName(name)];
+
+    return [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:nil];
+#else
+    NSString *errorMessage = NSLocalizedStringFromTable(@"Save point functions require SQLite 3.7", @"FMDB", nil);
+    if (self.logsErrors) NSLog(@"%@", errorMessage);
+    return NO;
+#endif
+}
+
+- (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError**)outErr {
+#if SQLITE_VERSION_NUMBER >= 3007000
+    NSParameterAssert(name);
+    
+    NSString *sql = [NSString stringWithFormat:@"rollback transaction to savepoint '%@';", FMDBEscapeSavePointName(name)];
+
+    return [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:nil];
+#else
+    NSString *errorMessage = NSLocalizedStringFromTable(@"Save point functions require SQLite 3.7", @"FMDB", nil);
+    if (self.logsErrors) NSLog(@"%@", errorMessage);
+    return NO;
+#endif
+}
+
+- (NSError*)inSavePoint:(__attribute__((noescape)) void (^)(BOOL *rollback))block {
+#if SQLITE_VERSION_NUMBER >= 3007000
+    static unsigned long savePointIdx = 0;
+    
+    NSString *name = [NSString stringWithFormat:@"dbSavePoint%ld", savePointIdx++];
+    
+    BOOL shouldRollback = NO;
+    
+    NSError *err = 0x00;
+    
+    if (![self startSavePointWithName:name error:&err]) {
+        return err;
+    }
+    
+    if (block) {
+        block(&shouldRollback);
+    }
+    
+    if (shouldRollback) {
+        // We need to rollback and release this savepoint to remove it
+        [self rollbackToSavePointWithName:name error:&err];
+    }
+    [self releaseSavePointWithName:name error:&err];
+    
+    return err;
+#else
+    NSString *errorMessage = NSLocalizedStringFromTable(@"Save point functions require SQLite 3.7", @"FMDB", nil);
+    if (self.logsErrors) NSLog(@"%@", errorMessage);
+    return [NSError errorWithDomain:@"FMDatabase" code:0 userInfo:@{NSLocalizedDescriptionKey : errorMessage}];
+#endif
+}
+
+- (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode error:(NSError * __autoreleasing *)error {
+    return [self checkpoint:checkpointMode name:nil logFrameCount:NULL checkpointCount:NULL error:error];
+}
+
+- (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode name:(NSString *)name error:(NSError * __autoreleasing *)error {
+    return [self checkpoint:checkpointMode name:name logFrameCount:NULL checkpointCount:NULL error:error];
+}
+
+- (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode name:(NSString *)name logFrameCount:(int *)logFrameCount checkpointCount:(int *)checkpointCount error:(NSError * __autoreleasing *)error
+{
+    const char* dbName = [name UTF8String];
+#if SQLITE_VERSION_NUMBER >= 3007006
+    int err = sqlite3_wal_checkpoint_v2(_db, dbName, checkpointMode, logFrameCount, checkpointCount);
+#else
+    NSLog(@"sqlite3_wal_checkpoint_v2 unavailable before sqlite 3.7.6. Ignoring checkpoint mode: %d", mode);
+    int err = sqlite3_wal_checkpoint(_db, dbName);
+#endif
+    if(err != SQLITE_OK) {
+        if (error) {
+            *error = [self lastError];
+        }
+        if (self.logsErrors) NSLog(@"%@", [self lastErrorMessage]);
+        if (self.crashOnErrors) {
+            NSAssert(false, @"%@", [self lastErrorMessage]);
+            abort();
+        }
+        return NO;
+    } else {
+        return YES;
+    }
+}
+
+#pragma mark Cache statements
+
+- (BOOL)shouldCacheStatements {
+    return _shouldCacheStatements;
+}
+
+- (void)setShouldCacheStatements:(BOOL)value {
+    
+    _shouldCacheStatements = value;
+    
+    if (_shouldCacheStatements && !_cachedStatements) {
+        [self setCachedStatements:[NSMutableDictionary dictionary]];
+    }
+    
+    if (!_shouldCacheStatements) {
+        [self setCachedStatements:nil];
+    }
+}
+
+#pragma mark Callback function
+
+void FMDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv); // -Wmissing-prototypes
+void FMDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv) {
+#if ! __has_feature(objc_arc)
+    void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (id)sqlite3_user_data(context);
+#else
+    void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (__bridge id)sqlite3_user_data(context);
+#endif
+    if (block) {
+        @autoreleasepool {
+            block(context, argc, argv);
+        }
+    }
+}
+
+// deprecated because "arguments" parameter is not maximum argument count, but actual argument count.
+
+- (void)makeFunctionNamed:(NSString *)name maximumArguments:(int)arguments withBlock:(void (^)(void *context, int argc, void **argv))block {
+    [self makeFunctionNamed:name arguments:arguments block:block];
+}
+
+- (void)makeFunctionNamed:(NSString *)name arguments:(int)arguments block:(void (^)(void *context, int argc, void **argv))block {
+    
+    if (!_openFunctions) {
+        _openFunctions = [NSMutableSet new];
+    }
+    
+    id b = FMDBReturnAutoreleased([block copy]);
+    
+    [_openFunctions addObject:b];
+    
+    /* I tried adding custom functions to release the block when the connection is destroyed- but they seemed to never be called, so we use _openFunctions to store the values instead. */
+#if ! __has_feature(objc_arc)
+    sqlite3_create_function([self sqliteHandle], [name UTF8String], arguments, SQLITE_UTF8, (void*)b, &FMDBBlockSQLiteCallBackFunction, 0x00, 0x00);
+#else
+    sqlite3_create_function([self sqliteHandle], [name UTF8String], arguments, SQLITE_UTF8, (__bridge void*)b, &FMDBBlockSQLiteCallBackFunction, 0x00, 0x00);
+#endif
+}
+
+- (SqliteValueType)valueType:(void *)value {
+    return sqlite3_value_type(value);
+}
+
+- (int)valueInt:(void *)value {
+    return sqlite3_value_int(value);
+}
+
+- (long long)valueLong:(void *)value {
+    return sqlite3_value_int64(value);
+}
+
+- (double)valueDouble:(void *)value {
+    return sqlite3_value_double(value);
+}
+
+- (NSData *)valueData:(void *)value {
+    const void *bytes = sqlite3_value_blob(value);
+    int length = sqlite3_value_bytes(value);
+    return bytes ? [NSData dataWithBytes:bytes length:(NSUInteger)length] : nil;
+}
+
+- (NSString *)valueString:(void *)value {
+    const char *cString = (const char *)sqlite3_value_text(value);
+    return cString ? [NSString stringWithUTF8String:cString] : nil;
+}
+
+- (void)resultNullInContext:(void *)context {
+    sqlite3_result_null(context);
+}
+
+- (void)resultInt:(int) value context:(void *)context {
+    sqlite3_result_int(context, value);
+}
+
+- (void)resultLong:(long long)value context:(void *)context {
+    sqlite3_result_int64(context, value);
+}
+
+- (void)resultDouble:(double)value context:(void *)context {
+    sqlite3_result_double(context, value);
+}
+
+- (void)resultData:(NSData *)data context:(void *)context {
+    sqlite3_result_blob(context, data.bytes, (int)data.length, SQLITE_TRANSIENT);
+}
+
+- (void)resultString:(NSString *)value context:(void *)context {
+    sqlite3_result_text(context, [value UTF8String], -1, SQLITE_TRANSIENT);
+}
+
+- (void)resultError:(NSString *)error context:(void *)context {
+    sqlite3_result_error(context, [error UTF8String], -1);
+}
+
+- (void)resultErrorCode:(int)errorCode context:(void *)context {
+    sqlite3_result_error_code(context, errorCode);
+}
+
+- (void)resultErrorNoMemoryInContext:(void *)context {
+    sqlite3_result_error_nomem(context);
+}
+
+- (void)resultErrorTooBigInContext:(void *)context {
+    sqlite3_result_error_toobig(context);
+}
+
+@end
+
+
+
+@implementation FMStatement
+
+#if ! __has_feature(objc_arc)
+- (void)finalize {
+    [self close];
+    [super finalize];
+}
+#endif
+
+- (void)dealloc {
+    [self close];
+    FMDBRelease(_query);
+#if ! __has_feature(objc_arc)
+    [super dealloc];
+#endif
+}
+
+- (void)close {
+    if (_statement) {
+        sqlite3_finalize(_statement);
+        _statement = 0x00;
+    }
+    
+    _inUse = NO;
+}
+
+- (void)reset {
+    if (_statement) {
+        sqlite3_reset(_statement);
+    }
+    
+    _inUse = NO;
+}
+
+- (NSString*)description {
+    return [NSString stringWithFormat:@"%@ %ld hit(s) for query %@", [super description], _useCount, _query];
+}
+
+@end
+

+ 250 - 0
Pods/FMDB/src/fmdb/FMDatabaseAdditions.h

@@ -0,0 +1,250 @@
+//
+//  FMDatabaseAdditions.h
+//  fmdb
+//
+//  Created by August Mueller on 10/30/05.
+//  Copyright 2005 Flying Meat Inc.. All rights reserved.
+//
+
+#import <Foundation/Foundation.h>
+#import "FMDatabase.h"
+
+NS_ASSUME_NONNULL_BEGIN
+
+/** Category of additions for `<FMDatabase>` class.
+ 
+ ### See also
+
+ - `<FMDatabase>`
+ */
+
+@interface FMDatabase (FMDatabaseAdditions)
+
+///----------------------------------------
+/// @name Return results of SQL to variable
+///----------------------------------------
+
+/** Return `int` value for query
+ 
+ @param query The SQL query to be performed. 
+ @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query.
+
+ @return `int` value.
+ 
+ @note This is not available from Swift.
+ */
+
+- (int)intForQuery:(NSString*)query, ...;
+
+/** Return `long` value for query
+
+ @param query The SQL query to be performed.
+ @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query.
+
+ @return `long` value.
+ 
+ @note This is not available from Swift.
+ */
+
+- (long)longForQuery:(NSString*)query, ...;
+
+/** Return `BOOL` value for query
+
+ @param query The SQL query to be performed.
+ @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query.
+
+ @return `BOOL` value.
+ 
+ @note This is not available from Swift.
+ */
+
+- (BOOL)boolForQuery:(NSString*)query, ...;
+
+/** Return `double` value for query
+
+ @param query The SQL query to be performed.
+ @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query.
+
+ @return `double` value.
+ 
+ @note This is not available from Swift.
+ */
+
+- (double)doubleForQuery:(NSString*)query, ...;
+
+/** Return `NSString` value for query
+
+ @param query The SQL query to be performed.
+ @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query.
+
+ @return `NSString` value.
+ 
+ @note This is not available from Swift.
+ */
+
+- (NSString * _Nullable)stringForQuery:(NSString*)query, ...;
+
+/** Return `NSData` value for query
+
+ @param query The SQL query to be performed.
+ @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query.
+
+ @return `NSData` value.
+ 
+ @note This is not available from Swift.
+ */
+
+- (NSData * _Nullable)dataForQuery:(NSString*)query, ...;
+
+/** Return `NSDate` value for query
+
+ @param query The SQL query to be performed.
+ @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query.
+
+ @return `NSDate` value.
+ 
+ @note This is not available from Swift.
+ */
+
+- (NSDate * _Nullable)dateForQuery:(NSString*)query, ...;
+
+
+// Notice that there's no dataNoCopyForQuery:.
+// That would be a bad idea, because we close out the result set, and then what
+// happens to the data that we just didn't copy?  Who knows, not I.
+
+
+///--------------------------------
+/// @name Schema related operations
+///--------------------------------
+
+/** Does table exist in database?
+
+ @param tableName The name of the table being looked for.
+
+ @return `YES` if table found; `NO` if not found.
+ */
+
+- (BOOL)tableExists:(NSString*)tableName;
+
+/** The schema of the database.
+ 
+ This will be the schema for the entire database. For each entity, each row of the result set will include the following fields:
+ 
+ - `type` - The type of entity (e.g. table, index, view, or trigger)
+ - `name` - The name of the object
+ - `tbl_name` - The name of the table to which the object references
+ - `rootpage` - The page number of the root b-tree page for tables and indices
+ - `sql` - The SQL that created the entity
+
+ @return `FMResultSet` of schema; `nil` on error.
+ 
+ @see [SQLite File Format](http://www.sqlite.org/fileformat.html)
+ */
+
+- (FMResultSet * _Nullable)getSchema;
+
+/** The schema of the database.
+
+ This will be the schema for a particular table as report by SQLite `PRAGMA`, for example:
+ 
+    PRAGMA table_info('employees')
+ 
+ This will report:
+ 
+ - `cid` - The column ID number
+ - `name` - The name of the column
+ - `type` - The data type specified for the column
+ - `notnull` - whether the field is defined as NOT NULL (i.e. values required)
+ - `dflt_value` - The default value for the column
+ - `pk` - Whether the field is part of the primary key of the table
+
+ @param tableName The name of the table for whom the schema will be returned.
+ 
+ @return `FMResultSet` of schema; `nil` on error.
+ 
+ @see [table_info](http://www.sqlite.org/pragma.html#pragma_table_info)
+ */
+
+- (FMResultSet * _Nullable)getTableSchema:(NSString*)tableName;
+
+/** Test to see if particular column exists for particular table in database
+ 
+ @param columnName The name of the column.
+ 
+ @param tableName The name of the table.
+ 
+ @return `YES` if column exists in table in question; `NO` otherwise.
+ */
+
+- (BOOL)columnExists:(NSString*)columnName inTableWithName:(NSString*)tableName;
+
+/** Test to see if particular column exists for particular table in database
+
+ @param columnName The name of the column.
+
+ @param tableName The name of the table.
+
+ @return `YES` if column exists in table in question; `NO` otherwise.
+ 
+ @see columnExists:inTableWithName:
+ 
+ @warning Deprecated - use `<columnExists:inTableWithName:>` instead.
+ */
+
+- (BOOL)columnExists:(NSString*)tableName columnName:(NSString*)columnName __deprecated_msg("Use columnExists:inTableWithName: instead");
+
+
+/** Validate SQL statement
+ 
+ This validates SQL statement by performing `sqlite3_prepare_v2`, but not returning the results, but instead immediately calling `sqlite3_finalize`.
+ 
+ @param sql The SQL statement being validated.
+ 
+ @param error This is a pointer to a `NSError` object that will receive the autoreleased `NSError` object if there was any error. If this is `nil`, no `NSError` result will be returned.
+ 
+ @return `YES` if validation succeeded without incident; `NO` otherwise.
+ 
+ */
+
+- (BOOL)validateSQL:(NSString*)sql error:(NSError * _Nullable *)error;
+
+
+///-----------------------------------
+/// @name Application identifier tasks
+///-----------------------------------
+
+/** Retrieve application ID
+ 
+ @return The `uint32_t` numeric value of the application ID.
+ 
+ @see setApplicationID:
+ */
+
+@property (nonatomic) uint32_t applicationID;
+
+#if TARGET_OS_MAC && !TARGET_OS_IPHONE
+
+/** Retrieve application ID string
+
+ @see setApplicationIDString:
+ */
+
+@property (nonatomic, retain) NSString *applicationIDString;
+
+#endif
+
+///-----------------------------------
+/// @name user version identifier tasks
+///-----------------------------------
+
+/** Retrieve user version
+ 
+ @see setUserVersion:
+ */
+
+@property (nonatomic) uint32_t userVersion;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 245 - 0
Pods/FMDB/src/fmdb/FMDatabaseAdditions.m

@@ -0,0 +1,245 @@
+//
+//  FMDatabaseAdditions.m
+//  fmdb
+//
+//  Created by August Mueller on 10/30/05.
+//  Copyright 2005 Flying Meat Inc.. All rights reserved.
+//
+
+#import "FMDatabase.h"
+#import "FMDatabaseAdditions.h"
+#import "TargetConditionals.h"
+
+#if FMDB_SQLITE_STANDALONE
+#import <sqlite3/sqlite3.h>
+#else
+#import <sqlite3.h>
+#endif
+
+@interface FMDatabase (PrivateStuff)
+- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray * _Nullable)arrayArgs orDictionary:(NSDictionary * _Nullable)dictionaryArgs orVAList:(va_list)args;
+@end
+
+@implementation FMDatabase (FMDatabaseAdditions)
+
+#define RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(type, sel)             \
+va_list args;                                                        \
+va_start(args, query);                                               \
+FMResultSet *resultSet = [self executeQuery:query withArgumentsInArray:0x00 orDictionary:0x00 orVAList:args];   \
+va_end(args);                                                        \
+if (![resultSet next]) { return (type)0; }                           \
+type ret = [resultSet sel:0];                                        \
+[resultSet close];                                                   \
+[resultSet setParentDB:nil];                                         \
+return ret;
+
+
+- (NSString *)stringForQuery:(NSString*)query, ... {
+    RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSString *, stringForColumnIndex);
+}
+
+- (int)intForQuery:(NSString*)query, ... {
+    RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(int, intForColumnIndex);
+}
+
+- (long)longForQuery:(NSString*)query, ... {
+    RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(long, longForColumnIndex);
+}
+
+- (BOOL)boolForQuery:(NSString*)query, ... {
+    RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(BOOL, boolForColumnIndex);
+}
+
+- (double)doubleForQuery:(NSString*)query, ... {
+    RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(double, doubleForColumnIndex);
+}
+
+- (NSData*)dataForQuery:(NSString*)query, ... {
+    RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSData *, dataForColumnIndex);
+}
+
+- (NSDate*)dateForQuery:(NSString*)query, ... {
+    RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSDate *, dateForColumnIndex);
+}
+
+
+- (BOOL)tableExists:(NSString*)tableName {
+    
+    tableName = [tableName lowercaseString];
+    
+    FMResultSet *rs = [self executeQuery:@"select [sql] from sqlite_master where [type] = 'table' and lower(name) = ?", tableName];
+    
+    //if at least one next exists, table exists
+    BOOL returnBool = [rs next];
+    
+    //close and free object
+    [rs close];
+    
+    return returnBool;
+}
+
+/*
+ get table with list of tables: result colums: type[STRING], name[STRING],tbl_name[STRING],rootpage[INTEGER],sql[STRING]
+ check if table exist in database  (patch from OZLB)
+*/
+- (FMResultSet * _Nullable)getSchema {
+    
+    //result colums: type[STRING], name[STRING],tbl_name[STRING],rootpage[INTEGER],sql[STRING]
+    FMResultSet *rs = [self executeQuery:@"SELECT type, name, tbl_name, rootpage, sql FROM (SELECT * FROM sqlite_master UNION ALL SELECT * FROM sqlite_temp_master) WHERE type != 'meta' AND name NOT LIKE 'sqlite_%' ORDER BY tbl_name, type DESC, name"];
+    
+    return rs;
+}
+
+/* 
+ get table schema: result colums: cid[INTEGER], name,type [STRING], notnull[INTEGER], dflt_value[],pk[INTEGER]
+*/
+- (FMResultSet * _Nullable)getTableSchema:(NSString*)tableName {
+    
+    //result colums: cid[INTEGER], name,type [STRING], notnull[INTEGER], dflt_value[],pk[INTEGER]
+    FMResultSet *rs = [self executeQuery:[NSString stringWithFormat: @"pragma table_info('%@')", tableName]];
+    
+    return rs;
+}
+
+- (BOOL)columnExists:(NSString*)columnName inTableWithName:(NSString*)tableName {
+    
+    BOOL returnBool = NO;
+    
+    tableName  = [tableName lowercaseString];
+    columnName = [columnName lowercaseString];
+    
+    FMResultSet *rs = [self getTableSchema:tableName];
+    
+    //check if column is present in table schema
+    while ([rs next]) {
+        if ([[[rs stringForColumn:@"name"] lowercaseString] isEqualToString:columnName]) {
+            returnBool = YES;
+            break;
+        }
+    }
+    
+    //If this is not done FMDatabase instance stays out of pool
+    [rs close];
+    
+    return returnBool;
+}
+
+
+
+- (uint32_t)applicationID {
+#if SQLITE_VERSION_NUMBER >= 3007017
+    uint32_t r = 0;
+    
+    FMResultSet *rs = [self executeQuery:@"pragma application_id"];
+    
+    if ([rs next]) {
+        r = (uint32_t)[rs longLongIntForColumnIndex:0];
+    }
+    
+    [rs close];
+    
+    return r;
+#else
+    NSString *errorMessage = NSLocalizedStringFromTable(@"Application ID functions require SQLite 3.7.17", @"FMDB", nil);
+    if (self.logsErrors) NSLog(@"%@", errorMessage);
+    return 0;
+#endif
+}
+
+- (void)setApplicationID:(uint32_t)appID {
+#if SQLITE_VERSION_NUMBER >= 3007017
+    NSString *query = [NSString stringWithFormat:@"pragma application_id=%d", appID];
+    FMResultSet *rs = [self executeQuery:query];
+    [rs next];
+    [rs close];
+#else
+    NSString *errorMessage = NSLocalizedStringFromTable(@"Application ID functions require SQLite 3.7.17", @"FMDB", nil);
+    if (self.logsErrors) NSLog(@"%@", errorMessage);
+#endif
+}
+
+
+#if TARGET_OS_MAC && !TARGET_OS_IPHONE
+
+- (NSString*)applicationIDString {
+#if SQLITE_VERSION_NUMBER >= 3007017
+    NSString *s = NSFileTypeForHFSTypeCode([self applicationID]);
+    
+    assert([s length] == 6);
+    
+    s = [s substringWithRange:NSMakeRange(1, 4)];
+    
+    
+    return s;
+#else
+    NSString *errorMessage = NSLocalizedStringFromTable(@"Application ID functions require SQLite 3.7.17", @"FMDB", nil);
+    if (self.logsErrors) NSLog(@"%@", errorMessage);
+    return nil;
+#endif
+}
+
+- (void)setApplicationIDString:(NSString*)s {
+#if SQLITE_VERSION_NUMBER >= 3007017
+    if ([s length] != 4) {
+        NSLog(@"setApplicationIDString: string passed is not exactly 4 chars long. (was %ld)", [s length]);
+    }
+    
+    [self setApplicationID:NSHFSTypeCodeFromFileType([NSString stringWithFormat:@"'%@'", s])];
+#else
+    NSString *errorMessage = NSLocalizedStringFromTable(@"Application ID functions require SQLite 3.7.17", @"FMDB", nil);
+    if (self.logsErrors) NSLog(@"%@", errorMessage);
+#endif
+}
+
+#endif
+
+- (uint32_t)userVersion {
+    uint32_t r = 0;
+    
+    FMResultSet *rs = [self executeQuery:@"pragma user_version"];
+    
+    if ([rs next]) {
+        r = (uint32_t)[rs longLongIntForColumnIndex:0];
+    }
+    
+    [rs close];
+    return r;
+}
+
+- (void)setUserVersion:(uint32_t)version {
+    NSString *query = [NSString stringWithFormat:@"pragma user_version = %d", version];
+    FMResultSet *rs = [self executeQuery:query];
+    [rs next];
+    [rs close];
+}
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-implementations"
+
+- (BOOL)columnExists:(NSString*)tableName columnName:(NSString*)columnName __attribute__ ((deprecated)) {
+    return [self columnExists:columnName inTableWithName:tableName];
+}
+
+#pragma clang diagnostic pop
+
+- (BOOL)validateSQL:(NSString*)sql error:(NSError**)error {
+    sqlite3_stmt *pStmt = NULL;
+    BOOL validationSucceeded = YES;
+    
+    int rc = sqlite3_prepare_v2([self sqliteHandle], [sql UTF8String], -1, &pStmt, 0);
+    if (rc != SQLITE_OK) {
+        validationSucceeded = NO;
+        if (error) {
+            *error = [NSError errorWithDomain:NSCocoaErrorDomain
+                                         code:[self lastErrorCode]
+                                     userInfo:[NSDictionary dictionaryWithObject:[self lastErrorMessage]
+                                                                          forKey:NSLocalizedDescriptionKey]];
+        }
+    }
+    
+    sqlite3_finalize(pStmt);
+    
+    return validationSucceeded;
+}
+
+@end

+ 280 - 0
Pods/FMDB/src/fmdb/FMDatabasePool.h

@@ -0,0 +1,280 @@
+//
+//  FMDatabasePool.h
+//  fmdb
+//
+//  Created by August Mueller on 6/22/11.
+//  Copyright 2011 Flying Meat Inc. All rights reserved.
+//
+
+#import <Foundation/Foundation.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+@class FMDatabase;
+
+/** Pool of `<FMDatabase>` objects.
+
+ ### See also
+ 
+ - `<FMDatabaseQueue>`
+ - `<FMDatabase>`
+
+ @warning Before using `FMDatabasePool`, please consider using `<FMDatabaseQueue>` instead.
+
+ If you really really really know what you're doing and `FMDatabasePool` is what
+ you really really need (ie, you're using a read only database), OK you can use
+ it.  But just be careful not to deadlock!
+
+ For an example on deadlocking, search for:
+ `ONLY_USE_THE_POOL_IF_YOU_ARE_DOING_READS_OTHERWISE_YOULL_DEADLOCK_USE_FMDATABASEQUEUE_INSTEAD`
+ in the main.m file.
+ */
+
+@interface FMDatabasePool : NSObject
+
+/** Database path */
+
+@property (atomic, copy, nullable) NSString *path;
+
+/** Delegate object */
+
+@property (atomic, assign, nullable) id delegate;
+
+/** Maximum number of databases to create */
+
+@property (atomic, assign) NSUInteger maximumNumberOfDatabasesToCreate;
+
+/** Open flags */
+
+@property (atomic, readonly) int openFlags;
+
+/**  Custom virtual file system name */
+
+@property (atomic, copy, nullable) NSString *vfsName;
+
+
+///---------------------
+/// @name Initialization
+///---------------------
+
+/** Create pool using path.
+ 
+ @param aPath The file path of the database.
+ 
+ @return The `FMDatabasePool` object. `nil` on error.
+ */
+
++ (instancetype)databasePoolWithPath:(NSString * _Nullable)aPath;
+
+/** Create pool using file URL.
+ 
+ @param url The file `NSURL` of the database.
+ 
+ @return The `FMDatabasePool` object. `nil` on error.
+ */
+
++ (instancetype)databasePoolWithURL:(NSURL * _Nullable)url;
+
+/** Create pool using path and specified flags
+ 
+ @param aPath The file path of the database.
+ @param openFlags Flags passed to the openWithFlags method of the database.
+ 
+ @return The `FMDatabasePool` object. `nil` on error.
+ */
+
++ (instancetype)databasePoolWithPath:(NSString * _Nullable)aPath flags:(int)openFlags;
+
+/** Create pool using file URL and specified flags
+ 
+ @param url The file `NSURL` of the database.
+ @param openFlags Flags passed to the openWithFlags method of the database.
+ 
+ @return The `FMDatabasePool` object. `nil` on error.
+ */
+
++ (instancetype)databasePoolWithURL:(NSURL * _Nullable)url flags:(int)openFlags;
+
+/** Create pool using path.
+ 
+ @param aPath The file path of the database.
+ 
+ @return The `FMDatabasePool` object. `nil` on error.
+ */
+
+- (instancetype)initWithPath:(NSString * _Nullable)aPath;
+
+/** Create pool using file URL.
+ 
+ @param url The file `NSURL of the database.
+ 
+ @return The `FMDatabasePool` object. `nil` on error.
+ */
+
+- (instancetype)initWithURL:(NSURL * _Nullable)url;
+
+/** Create pool using path and specified flags.
+ 
+ @param aPath The file path of the database.
+ @param openFlags Flags passed to the openWithFlags method of the database
+ 
+ @return The `FMDatabasePool` object. `nil` on error.
+ */
+
+- (instancetype)initWithPath:(NSString * _Nullable)aPath flags:(int)openFlags;
+
+/** Create pool using file URL and specified flags.
+ 
+ @param url The file `NSURL` of the database.
+ @param openFlags Flags passed to the openWithFlags method of the database
+ 
+ @return The `FMDatabasePool` object. `nil` on error.
+ */
+
+- (instancetype)initWithURL:(NSURL * _Nullable)url flags:(int)openFlags;
+
+/** Create pool using path and specified flags.
+ 
+ @param aPath The file path of the database.
+ @param openFlags Flags passed to the openWithFlags method of the database
+ @param vfsName The name of a custom virtual file system
+ 
+ @return The `FMDatabasePool` object. `nil` on error.
+ */
+
+- (instancetype)initWithPath:(NSString * _Nullable)aPath flags:(int)openFlags vfs:(NSString * _Nullable)vfsName;
+
+/** Create pool using file URL and specified flags.
+ 
+ @param url The file `NSURL` of the database.
+ @param openFlags Flags passed to the openWithFlags method of the database
+ @param vfsName The name of a custom virtual file system
+ 
+ @return The `FMDatabasePool` object. `nil` on error.
+ */
+
+- (instancetype)initWithURL:(NSURL * _Nullable)url flags:(int)openFlags vfs:(NSString * _Nullable)vfsName;
+
+/** Returns the Class of 'FMDatabase' subclass, that will be used to instantiate database object.
+
+ Subclasses can override this method to return specified Class of 'FMDatabase' subclass.
+
+ @return The Class of 'FMDatabase' subclass, that will be used to instantiate database object.
+ */
+
++ (Class)databaseClass;
+
+///------------------------------------------------
+/// @name Keeping track of checked in/out databases
+///------------------------------------------------
+
+/** Number of checked-in databases in pool
+ */
+
+@property (nonatomic, readonly) NSUInteger countOfCheckedInDatabases;
+
+/** Number of checked-out databases in pool
+ */
+
+@property (nonatomic, readonly) NSUInteger countOfCheckedOutDatabases;
+
+/** Total number of databases in pool
+ */
+
+@property (nonatomic, readonly) NSUInteger countOfOpenDatabases;
+
+/** Release all databases in pool */
+
+- (void)releaseAllDatabases;
+
+///------------------------------------------
+/// @name Perform database operations in pool
+///------------------------------------------
+
+/** Synchronously perform database operations in pool.
+
+ @param block The code to be run on the `FMDatabasePool` pool.
+ */
+
+- (void)inDatabase:(__attribute__((noescape)) void (^)(FMDatabase *db))block;
+
+/** Synchronously perform database operations in pool using transaction.
+ 
+ @param block The code to be run on the `FMDatabasePool` pool.
+ 
+ @warning   Unlike SQLite's `BEGIN TRANSACTION`, this method currently performs
+            an exclusive transaction, not a deferred transaction. This behavior
+            is likely to change in future versions of FMDB, whereby this method
+            will likely eventually adopt standard SQLite behavior and perform
+            deferred transactions. If you really need exclusive tranaction, it is
+            recommended that you use `inExclusiveTransaction`, instead, not only
+            to make your intent explicit, but also to future-proof your code.
+  */
+
+- (void)inTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block;
+
+/** Synchronously perform database operations in pool using exclusive transaction.
+ 
+ @param block The code to be run on the `FMDatabasePool` pool.
+ */
+
+- (void)inExclusiveTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block;
+
+/** Synchronously perform database operations in pool using deferred transaction.
+
+ @param block The code to be run on the `FMDatabasePool` pool.
+ */
+
+- (void)inDeferredTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block;
+
+/** Synchronously perform database operations on queue, using immediate transactions.
+
+ @param block The code to be run on the queue of `FMDatabaseQueue`
+ */
+
+- (void)inImmediateTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block;
+
+/** Synchronously perform database operations in pool using save point.
+
+ @param block The code to be run on the `FMDatabasePool` pool.
+ 
+ @return `NSError` object if error; `nil` if successful.
+
+ @warning You can not nest these, since calling it will pull another database out of the pool and you'll get a deadlock. If you need to nest, use `<[FMDatabase startSavePointWithName:error:]>` instead.
+*/
+
+- (NSError * _Nullable)inSavePoint:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block;
+
+@end
+
+
+/** FMDatabasePool delegate category
+ 
+ This is a category that defines the protocol for the FMDatabasePool delegate
+ */
+
+@interface NSObject (FMDatabasePoolDelegate)
+
+/** Asks the delegate whether database should be added to the pool. 
+ 
+ @param pool     The `FMDatabasePool` object.
+ @param database The `FMDatabase` object.
+ 
+ @return `YES` if it should add database to pool; `NO` if not.
+ 
+ */
+
+- (BOOL)databasePool:(FMDatabasePool*)pool shouldAddDatabaseToPool:(FMDatabase*)database;
+
+/** Tells the delegate that database was added to the pool.
+ 
+ @param pool     The `FMDatabasePool` object.
+ @param database The `FMDatabase` object.
+
+ */
+
+- (void)databasePool:(FMDatabasePool*)pool didAddDatabase:(FMDatabase*)database;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 335 - 0
Pods/FMDB/src/fmdb/FMDatabasePool.m

@@ -0,0 +1,335 @@
+//
+//  FMDatabasePool.m
+//  fmdb
+//
+//  Created by August Mueller on 6/22/11.
+//  Copyright 2011 Flying Meat Inc. All rights reserved.
+//
+
+#if FMDB_SQLITE_STANDALONE
+#import <sqlite3/sqlite3.h>
+#else
+#import <sqlite3.h>
+#endif
+
+#import "FMDatabasePool.h"
+#import "FMDatabase.h"
+
+typedef NS_ENUM(NSInteger, FMDBTransaction) {
+    FMDBTransactionExclusive,
+    FMDBTransactionDeferred,
+    FMDBTransactionImmediate,
+};
+
+@interface FMDatabasePool () {
+    dispatch_queue_t    _lockQueue;
+    
+    NSMutableArray      *_databaseInPool;
+    NSMutableArray      *_databaseOutPool;
+}
+
+- (void)pushDatabaseBackInPool:(FMDatabase*)db;
+- (FMDatabase*)db;
+
+@end
+
+
+@implementation FMDatabasePool
+@synthesize path=_path;
+@synthesize delegate=_delegate;
+@synthesize maximumNumberOfDatabasesToCreate=_maximumNumberOfDatabasesToCreate;
+@synthesize openFlags=_openFlags;
+
+
++ (instancetype)databasePoolWithPath:(NSString *)aPath {
+    return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath]);
+}
+
++ (instancetype)databasePoolWithURL:(NSURL *)url {
+    return FMDBReturnAutoreleased([[self alloc] initWithPath:url.path]);
+}
+
++ (instancetype)databasePoolWithPath:(NSString *)aPath flags:(int)openFlags {
+    return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath flags:openFlags]);
+}
+
++ (instancetype)databasePoolWithURL:(NSURL *)url flags:(int)openFlags {
+    return FMDBReturnAutoreleased([[self alloc] initWithPath:url.path flags:openFlags]);
+}
+
+- (instancetype)initWithURL:(NSURL *)url flags:(int)openFlags vfs:(NSString *)vfsName {
+    return [self initWithPath:url.path flags:openFlags vfs:vfsName];
+}
+
+- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags vfs:(NSString *)vfsName {
+    
+    self = [super init];
+    
+    if (self != nil) {
+        _path               = [aPath copy];
+        _lockQueue          = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL);
+        _databaseInPool     = FMDBReturnRetained([NSMutableArray array]);
+        _databaseOutPool    = FMDBReturnRetained([NSMutableArray array]);
+        _openFlags          = openFlags;
+        _vfsName            = [vfsName copy];
+    }
+    
+    return self;
+}
+
+- (instancetype)initWithPath:(NSString *)aPath flags:(int)openFlags {
+    return [self initWithPath:aPath flags:openFlags vfs:nil];
+}
+
+- (instancetype)initWithURL:(NSURL *)url flags:(int)openFlags {
+    return [self initWithPath:url.path flags:openFlags vfs:nil];
+}
+
+- (instancetype)initWithPath:(NSString*)aPath {
+    // default flags for sqlite3_open
+    return [self initWithPath:aPath flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE];
+}
+
+- (instancetype)initWithURL:(NSURL *)url {
+    return [self initWithPath:url.path];
+}
+
+- (instancetype)init {
+    return [self initWithPath:nil];
+}
+
++ (Class)databaseClass {
+    return [FMDatabase class];
+}
+
+- (void)dealloc {
+    
+    _delegate = 0x00;
+    FMDBRelease(_path);
+    FMDBRelease(_databaseInPool);
+    FMDBRelease(_databaseOutPool);
+    FMDBRelease(_vfsName);
+    
+    if (_lockQueue) {
+        FMDBDispatchQueueRelease(_lockQueue);
+        _lockQueue = 0x00;
+    }
+#if ! __has_feature(objc_arc)
+    [super dealloc];
+#endif
+}
+
+
+- (void)executeLocked:(void (^)(void))aBlock {
+    dispatch_sync(_lockQueue, aBlock);
+}
+
+- (void)pushDatabaseBackInPool:(FMDatabase*)db {
+    
+    if (!db) { // db can be null if we set an upper bound on the # of databases to create.
+        return;
+    }
+    
+    [self executeLocked:^() {
+        
+        if ([self->_databaseInPool containsObject:db]) {
+            [[NSException exceptionWithName:@"Database already in pool" reason:@"The FMDatabase being put back into the pool is already present in the pool" userInfo:nil] raise];
+        }
+        
+        [self->_databaseInPool addObject:db];
+        [self->_databaseOutPool removeObject:db];
+        
+    }];
+}
+
+- (FMDatabase*)db {
+    
+    __block FMDatabase *db;
+    
+    
+    [self executeLocked:^() {
+        db = [self->_databaseInPool lastObject];
+        
+        BOOL shouldNotifyDelegate = NO;
+        
+        if (db) {
+            [self->_databaseOutPool addObject:db];
+            [self->_databaseInPool removeLastObject];
+        }
+        else {
+            
+            if (self->_maximumNumberOfDatabasesToCreate) {
+                NSUInteger currentCount = [self->_databaseOutPool count] + [self->_databaseInPool count];
+                
+                if (currentCount >= self->_maximumNumberOfDatabasesToCreate) {
+                    NSLog(@"Maximum number of databases (%ld) has already been reached!", (long)currentCount);
+                    return;
+                }
+            }
+            
+            db = [[[self class] databaseClass] databaseWithPath:self->_path];
+            shouldNotifyDelegate = YES;
+        }
+        
+        //This ensures that the db is opened before returning
+#if SQLITE_VERSION_NUMBER >= 3005000
+        BOOL success = [db openWithFlags:self->_openFlags vfs:self->_vfsName];
+#else
+        BOOL success = [db open];
+#endif
+        if (success) {
+            if ([self->_delegate respondsToSelector:@selector(databasePool:shouldAddDatabaseToPool:)] && ![self->_delegate databasePool:self shouldAddDatabaseToPool:db]) {
+                [db close];
+                db = 0x00;
+            }
+            else {
+                //It should not get added in the pool twice if lastObject was found
+                if (![self->_databaseOutPool containsObject:db]) {
+                    [self->_databaseOutPool addObject:db];
+                    
+                    if (shouldNotifyDelegate && [self->_delegate respondsToSelector:@selector(databasePool:didAddDatabase:)]) {
+                        [self->_delegate databasePool:self didAddDatabase:db];
+                    }
+                }
+            }
+        }
+        else {
+            NSLog(@"Could not open up the database at path %@", self->_path);
+            db = 0x00;
+        }
+    }];
+    
+    return db;
+}
+
+- (NSUInteger)countOfCheckedInDatabases {
+    
+    __block NSUInteger count;
+    
+    [self executeLocked:^() {
+        count = [self->_databaseInPool count];
+    }];
+    
+    return count;
+}
+
+- (NSUInteger)countOfCheckedOutDatabases {
+    
+    __block NSUInteger count;
+    
+    [self executeLocked:^() {
+        count = [self->_databaseOutPool count];
+    }];
+    
+    return count;
+}
+
+- (NSUInteger)countOfOpenDatabases {
+    __block NSUInteger count;
+    
+    [self executeLocked:^() {
+        count = [self->_databaseOutPool count] + [self->_databaseInPool count];
+    }];
+    
+    return count;
+}
+
+- (void)releaseAllDatabases {
+    [self executeLocked:^() {
+        [self->_databaseOutPool removeAllObjects];
+        [self->_databaseInPool removeAllObjects];
+    }];
+}
+
+- (void)inDatabase:(__attribute__((noescape)) void (^)(FMDatabase *db))block {
+    
+    FMDatabase *db = [self db];
+    
+    block(db);
+    
+    [self pushDatabaseBackInPool:db];
+}
+
+- (void)beginTransaction:(FMDBTransaction)transaction withBlock:(void (^)(FMDatabase *db, BOOL *rollback))block {
+    
+    BOOL shouldRollback = NO;
+    
+    FMDatabase *db = [self db];
+    
+    switch (transaction) {
+        case FMDBTransactionExclusive:
+            [db beginTransaction];
+            break;
+        case FMDBTransactionDeferred:
+            [db beginDeferredTransaction];
+            break;
+        case FMDBTransactionImmediate:
+            [db beginImmediateTransaction];
+            break;
+    }
+    
+    
+    block(db, &shouldRollback);
+    
+    if (shouldRollback) {
+        [db rollback];
+    }
+    else {
+        [db commit];
+    }
+    
+    [self pushDatabaseBackInPool:db];
+}
+
+- (void)inTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block {
+    [self beginTransaction:FMDBTransactionExclusive withBlock:block];
+}
+
+- (void)inDeferredTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block {
+    [self beginTransaction:FMDBTransactionDeferred withBlock:block];
+}
+
+- (void)inExclusiveTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block {
+    [self beginTransaction:FMDBTransactionExclusive withBlock:block];
+}
+
+- (void)inImmediateTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block {
+    [self beginTransaction:FMDBTransactionImmediate withBlock:block];
+}
+
+- (NSError*)inSavePoint:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block {
+#if SQLITE_VERSION_NUMBER >= 3007000
+    static unsigned long savePointIdx = 0;
+    
+    NSString *name = [NSString stringWithFormat:@"savePoint%ld", savePointIdx++];
+    
+    BOOL shouldRollback = NO;
+    
+    FMDatabase *db = [self db];
+    
+    NSError *err = 0x00;
+    
+    if (![db startSavePointWithName:name error:&err]) {
+        [self pushDatabaseBackInPool:db];
+        return err;
+    }
+    
+    block(db, &shouldRollback);
+    
+    if (shouldRollback) {
+        // We need to rollback and release this savepoint to remove it
+        [db rollbackToSavePointWithName:name error:&err];
+    }
+    [db releaseSavePointWithName:name error:&err];
+    
+    [self pushDatabaseBackInPool:db];
+    
+    return err;
+#else
+    NSString *errorMessage = NSLocalizedStringFromTable(@"Save point functions require SQLite 3.7", @"FMDB", nil);
+    if (self.logsErrors) NSLog(@"%@", errorMessage);
+    return [NSError errorWithDomain:@"FMDatabase" code:0 userInfo:@{NSLocalizedDescriptionKey : errorMessage}];
+#endif
+}
+
+@end

+ 289 - 0
Pods/FMDB/src/fmdb/FMDatabaseQueue.h

@@ -0,0 +1,289 @@
+//
+//  FMDatabaseQueue.h
+//  fmdb
+//
+//  Created by August Mueller on 6/22/11.
+//  Copyright 2011 Flying Meat Inc. All rights reserved.
+//
+
+#import <Foundation/Foundation.h>
+#import "FMDatabase.h"
+
+NS_ASSUME_NONNULL_BEGIN
+
+/** To perform queries and updates on multiple threads, you'll want to use `FMDatabaseQueue`.
+
+ Using a single instance of `<FMDatabase>` from multiple threads at once is a bad idea.  It has always been OK to make a `<FMDatabase>` object *per thread*.  Just don't share a single instance across threads, and definitely not across multiple threads at the same time.
+
+ Instead, use `FMDatabaseQueue`. Here's how to use it:
+
+ First, make your queue.
+
+    FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath];
+
+ Then use it like so:
+
+    [queue inDatabase:^(FMDatabase *db) {
+        [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]];
+        [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]];
+        [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]];
+
+        FMResultSet *rs = [db executeQuery:@"select * from foo"];
+        while ([rs next]) {
+            //…
+        }
+    }];
+
+ An easy way to wrap things up in a transaction can be done like this:
+
+    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
+        [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]];
+        [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]];
+        [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]];
+
+        if (whoopsSomethingWrongHappened) {
+            *rollback = YES;
+            return;
+        }
+        // etc…
+        [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:4]];
+    }];
+
+ `FMDatabaseQueue` will run the blocks on a serialized queue (hence the name of the class).  So if you call `FMDatabaseQueue`'s methods from multiple threads at the same time, they will be executed in the order they are received.  This way queries and updates won't step on each other's toes, and every one is happy.
+
+ ### See also
+
+ - `<FMDatabase>`
+
+ @warning Do not instantiate a single `<FMDatabase>` object and use it across multiple threads. Use `FMDatabaseQueue` instead.
+ 
+ @warning The calls to `FMDatabaseQueue`'s methods are blocking.  So even though you are passing along blocks, they will **not** be run on another thread.
+
+ */
+
+@interface FMDatabaseQueue : NSObject
+/** Path of database */
+
+@property (atomic, retain, nullable) NSString *path;
+
+/** Open flags */
+
+@property (atomic, readonly) int openFlags;
+
+/**  Custom virtual file system name */
+
+@property (atomic, copy, nullable) NSString *vfsName;
+
+///----------------------------------------------------
+/// @name Initialization, opening, and closing of queue
+///----------------------------------------------------
+
+/** Create queue using path.
+ 
+ @param aPath The file path of the database.
+ 
+ @return The `FMDatabaseQueue` object. `nil` on error.
+ */
+
++ (nullable instancetype)databaseQueueWithPath:(NSString * _Nullable)aPath;
+
+/** Create queue using file URL.
+ 
+ @param url The file `NSURL` of the database.
+ 
+ @return The `FMDatabaseQueue` object. `nil` on error.
+ */
+
++ (nullable instancetype)databaseQueueWithURL:(NSURL * _Nullable)url;
+
+/** Create queue using path and specified flags.
+ 
+ @param aPath The file path of the database.
+ @param openFlags Flags passed to the openWithFlags method of the database.
+ 
+ @return The `FMDatabaseQueue` object. `nil` on error.
+ */
++ (nullable instancetype)databaseQueueWithPath:(NSString * _Nullable)aPath flags:(int)openFlags;
+
+/** Create queue using file URL and specified flags.
+ 
+ @param url The file `NSURL` of the database.
+ @param openFlags Flags passed to the openWithFlags method of the database.
+ 
+ @return The `FMDatabaseQueue` object. `nil` on error.
+ */
++ (nullable instancetype)databaseQueueWithURL:(NSURL * _Nullable)url flags:(int)openFlags;
+
+/** Create queue using path.
+ 
+ @param aPath The file path of the database.
+ 
+ @return The `FMDatabaseQueue` object. `nil` on error.
+ */
+
+- (nullable instancetype)initWithPath:(NSString * _Nullable)aPath;
+
+/** Create queue using file URL.
+ 
+ @param url The file `NSURL of the database.
+ 
+ @return The `FMDatabaseQueue` object. `nil` on error.
+ */
+
+- (nullable instancetype)initWithURL:(NSURL * _Nullable)url;
+
+/** Create queue using path and specified flags.
+ 
+ @param aPath The file path of the database.
+ @param openFlags Flags passed to the openWithFlags method of the database.
+ 
+ @return The `FMDatabaseQueue` object. `nil` on error.
+ */
+
+- (nullable instancetype)initWithPath:(NSString * _Nullable)aPath flags:(int)openFlags;
+
+/** Create queue using file URL and specified flags.
+ 
+ @param url The file path of the database.
+ @param openFlags Flags passed to the openWithFlags method of the database.
+ 
+ @return The `FMDatabaseQueue` object. `nil` on error.
+ */
+
+- (nullable instancetype)initWithURL:(NSURL * _Nullable)url flags:(int)openFlags;
+
+/** Create queue using path and specified flags.
+ 
+ @param aPath The file path of the database.
+ @param openFlags Flags passed to the openWithFlags method of the database
+ @param vfsName The name of a custom virtual file system
+ 
+ @return The `FMDatabaseQueue` object. `nil` on error.
+ */
+
+- (nullable instancetype)initWithPath:(NSString * _Nullable)aPath flags:(int)openFlags vfs:(NSString * _Nullable)vfsName;
+
+/** Create queue using file URL and specified flags.
+ 
+ @param url The file `NSURL of the database.
+ @param openFlags Flags passed to the openWithFlags method of the database
+ @param vfsName The name of a custom virtual file system
+ 
+ @return The `FMDatabaseQueue` object. `nil` on error.
+ */
+
+- (nullable instancetype)initWithURL:(NSURL * _Nullable)url flags:(int)openFlags vfs:(NSString * _Nullable)vfsName;
+
+/** Returns the Class of 'FMDatabase' subclass, that will be used to instantiate database object.
+ 
+ Subclasses can override this method to return specified Class of 'FMDatabase' subclass.
+ 
+ @return The Class of 'FMDatabase' subclass, that will be used to instantiate database object.
+ */
+
++ (Class)databaseClass;
+
+/** Close database used by queue. */
+
+- (void)close;
+
+/** Interupt pending database operation. */
+
+- (void)interrupt;
+
+///-----------------------------------------------
+/// @name Dispatching database operations to queue
+///-----------------------------------------------
+
+/** Synchronously perform database operations on queue.
+ 
+ @param block The code to be run on the queue of `FMDatabaseQueue`
+ */
+
+- (void)inDatabase:(__attribute__((noescape)) void (^)(FMDatabase *db))block;
+
+/** Synchronously perform database operations on queue, using transactions.
+
+ @param block The code to be run on the queue of `FMDatabaseQueue`
+ 
+ @warning    Unlike SQLite's `BEGIN TRANSACTION`, this method currently performs
+             an exclusive transaction, not a deferred transaction. This behavior
+             is likely to change in future versions of FMDB, whereby this method
+             will likely eventually adopt standard SQLite behavior and perform
+             deferred transactions. If you really need exclusive tranaction, it is
+             recommended that you use `inExclusiveTransaction`, instead, not only
+             to make your intent explicit, but also to future-proof your code.
+
+ */
+
+- (void)inTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block;
+
+/** Synchronously perform database operations on queue, using deferred transactions.
+ 
+ @param block The code to be run on the queue of `FMDatabaseQueue`
+ */
+
+- (void)inDeferredTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block;
+
+/** Synchronously perform database operations on queue, using exclusive transactions.
+ 
+ @param block The code to be run on the queue of `FMDatabaseQueue`
+ */
+
+- (void)inExclusiveTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block;
+
+/** Synchronously perform database operations on queue, using immediate transactions.
+
+ @param block The code to be run on the queue of `FMDatabaseQueue`
+ */
+
+- (void)inImmediateTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block;
+
+///-----------------------------------------------
+/// @name Dispatching database operations to queue
+///-----------------------------------------------
+
+/** Synchronously perform database operations using save point.
+
+ @param block The code to be run on the queue of `FMDatabaseQueue`
+ */
+
+// NOTE: you can not nest these, since calling it will pull another database out of the pool and you'll get a deadlock.
+// If you need to nest, use FMDatabase's startSavePointWithName:error: instead.
+- (NSError * _Nullable)inSavePoint:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block;
+
+///-----------------
+/// @name Checkpoint
+///-----------------
+
+/** Performs a WAL checkpoint
+ 
+ @param checkpointMode The checkpoint mode for sqlite3_wal_checkpoint_v2
+ @param error The NSError corresponding to the error, if any.
+ @return YES on success, otherwise NO.
+ */
+- (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode error:(NSError * _Nullable *)error;
+
+/** Performs a WAL checkpoint
+ 
+ @param checkpointMode The checkpoint mode for sqlite3_wal_checkpoint_v2
+ @param name The db name for sqlite3_wal_checkpoint_v2
+ @param error The NSError corresponding to the error, if any.
+ @return YES on success, otherwise NO.
+ */
+- (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode name:(NSString * _Nullable)name error:(NSError * _Nullable *)error;
+
+/** Performs a WAL checkpoint
+ 
+ @param checkpointMode The checkpoint mode for sqlite3_wal_checkpoint_v2
+ @param name The db name for sqlite3_wal_checkpoint_v2
+ @param error The NSError corresponding to the error, if any.
+ @param logFrameCount If not NULL, then this is set to the total number of frames in the log file or to -1 if the checkpoint could not run because of an error or because the database is not in WAL mode.
+ @param checkpointCount If not NULL, then this is set to the total number of checkpointed frames in the log file (including any that were already checkpointed before the function was called) or to -1 if the checkpoint could not run due to an error or because the database is not in WAL mode.
+ @return YES on success, otherwise NO.
+ */
+- (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode name:(NSString * _Nullable)name logFrameCount:(int * _Nullable)logFrameCount checkpointCount:(int * _Nullable)checkpointCount error:(NSError * _Nullable *)error;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 318 - 0
Pods/FMDB/src/fmdb/FMDatabaseQueue.m

@@ -0,0 +1,318 @@
+//
+//  FMDatabaseQueue.m
+//  fmdb
+//
+//  Created by August Mueller on 6/22/11.
+//  Copyright 2011 Flying Meat Inc. All rights reserved.
+//
+
+#import "FMDatabaseQueue.h"
+#import "FMDatabase.h"
+
+#if FMDB_SQLITE_STANDALONE
+#import <sqlite3/sqlite3.h>
+#else
+#import <sqlite3.h>
+#endif
+
+typedef NS_ENUM(NSInteger, FMDBTransaction) {
+    FMDBTransactionExclusive,
+    FMDBTransactionDeferred,
+    FMDBTransactionImmediate,
+};
+
+/*
+ 
+ Note: we call [self retain]; before using dispatch_sync, just incase 
+ FMDatabaseQueue is released on another thread and we're in the middle of doing
+ something in dispatch_sync
+ 
+ */
+
+/*
+ * A key used to associate the FMDatabaseQueue object with the dispatch_queue_t it uses.
+ * This in turn is used for deadlock detection by seeing if inDatabase: is called on
+ * the queue's dispatch queue, which should not happen and causes a deadlock.
+ */
+static const void * const kDispatchQueueSpecificKey = &kDispatchQueueSpecificKey;
+
+@interface FMDatabaseQueue () {
+    dispatch_queue_t    _queue;
+    FMDatabase          *_db;
+}
+@end
+
+@implementation FMDatabaseQueue
+
++ (instancetype)databaseQueueWithPath:(NSString *)aPath {
+    FMDatabaseQueue *q = [[self alloc] initWithPath:aPath];
+    
+    FMDBAutorelease(q);
+    
+    return q;
+}
+
++ (instancetype)databaseQueueWithURL:(NSURL *)url {
+    return [self databaseQueueWithPath:url.path];
+}
+
++ (instancetype)databaseQueueWithPath:(NSString *)aPath flags:(int)openFlags {
+    FMDatabaseQueue *q = [[self alloc] initWithPath:aPath flags:openFlags];
+    
+    FMDBAutorelease(q);
+    
+    return q;
+}
+
++ (instancetype)databaseQueueWithURL:(NSURL *)url flags:(int)openFlags {
+    return [self databaseQueueWithPath:url.path flags:openFlags];
+}
+
++ (Class)databaseClass {
+    return [FMDatabase class];
+}
+
+- (instancetype)initWithURL:(NSURL *)url flags:(int)openFlags vfs:(NSString *)vfsName {
+    return [self initWithPath:url.path flags:openFlags vfs:vfsName];
+}
+
+- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags vfs:(NSString *)vfsName {
+    self = [super init];
+    
+    if (self != nil) {
+        
+        _db = [[[self class] databaseClass] databaseWithPath:aPath];
+        FMDBRetain(_db);
+        
+#if SQLITE_VERSION_NUMBER >= 3005000
+        BOOL success = [_db openWithFlags:openFlags vfs:vfsName];
+#else
+        BOOL success = [_db open];
+#endif
+        if (!success) {
+            NSLog(@"Could not create database queue for path %@", aPath);
+            FMDBRelease(self);
+            return 0x00;
+        }
+        
+        _path = FMDBReturnRetained(aPath);
+        
+        _queue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL);
+        dispatch_queue_set_specific(_queue, kDispatchQueueSpecificKey, (__bridge void *)self, NULL);
+        _openFlags = openFlags;
+        _vfsName = [vfsName copy];
+    }
+    
+    return self;
+}
+
+- (instancetype)initWithPath:(NSString *)aPath flags:(int)openFlags {
+    return [self initWithPath:aPath flags:openFlags vfs:nil];
+}
+
+- (instancetype)initWithURL:(NSURL *)url flags:(int)openFlags {
+    return [self initWithPath:url.path flags:openFlags vfs:nil];
+}
+
+- (instancetype)initWithURL:(NSURL *)url {
+    return [self initWithPath:url.path];
+}
+
+- (instancetype)initWithPath:(NSString *)aPath {
+    // default flags for sqlite3_open
+    return [self initWithPath:aPath flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE vfs:nil];
+}
+
+- (instancetype)init {
+    return [self initWithPath:nil];
+}
+
+- (void)dealloc {
+    FMDBRelease(_db);
+    FMDBRelease(_path);
+    FMDBRelease(_vfsName);
+    
+    if (_queue) {
+        FMDBDispatchQueueRelease(_queue);
+        _queue = 0x00;
+    }
+#if ! __has_feature(objc_arc)
+    [super dealloc];
+#endif
+}
+
+- (void)close {
+    FMDBRetain(self);
+    dispatch_sync(_queue, ^() {
+        [self->_db close];
+        FMDBRelease(_db);
+        self->_db = 0x00;
+    });
+    FMDBRelease(self);
+}
+
+- (void)interrupt {
+    [[self database] interrupt];
+}
+
+- (FMDatabase*)database {
+    if (![_db isOpen]) {
+        if (!_db) {
+           _db = FMDBReturnRetained([[[self class] databaseClass] databaseWithPath:_path]);
+        }
+        
+#if SQLITE_VERSION_NUMBER >= 3005000
+        BOOL success = [_db openWithFlags:_openFlags vfs:_vfsName];
+#else
+        BOOL success = [_db open];
+#endif
+        if (!success) {
+            NSLog(@"FMDatabaseQueue could not reopen database for path %@", _path);
+            FMDBRelease(_db);
+            _db  = 0x00;
+            return 0x00;
+        }
+    }
+    
+    return _db;
+}
+
+- (void)inDatabase:(__attribute__((noescape)) void (^)(FMDatabase *db))block {
+#ifndef NDEBUG
+    /* Get the currently executing queue (which should probably be nil, but in theory could be another DB queue
+     * and then check it against self to make sure we're not about to deadlock. */
+    FMDatabaseQueue *currentSyncQueue = (__bridge id)dispatch_get_specific(kDispatchQueueSpecificKey);
+    assert(currentSyncQueue != self && "inDatabase: was called reentrantly on the same queue, which would lead to a deadlock");
+#endif
+    
+    FMDBRetain(self);
+    
+    dispatch_sync(_queue, ^() {
+        
+        FMDatabase *db = [self database];
+        
+        block(db);
+        
+        if ([db hasOpenResultSets]) {
+            NSLog(@"Warning: there is at least one open result set around after performing [FMDatabaseQueue inDatabase:]");
+            
+#if defined(DEBUG) && DEBUG
+            NSSet *openSetCopy = FMDBReturnAutoreleased([[db valueForKey:@"_openResultSets"] copy]);
+            for (NSValue *rsInWrappedInATastyValueMeal in openSetCopy) {
+                FMResultSet *rs = (FMResultSet *)[rsInWrappedInATastyValueMeal pointerValue];
+                NSLog(@"query: '%@'", [rs query]);
+            }
+#endif
+        }
+    });
+    
+    FMDBRelease(self);
+}
+
+- (void)beginTransaction:(FMDBTransaction)transaction withBlock:(void (^)(FMDatabase *db, BOOL *rollback))block {
+    FMDBRetain(self);
+    dispatch_sync(_queue, ^() { 
+        
+        BOOL shouldRollback = NO;
+
+        switch (transaction) {
+            case FMDBTransactionExclusive:
+                [[self database] beginTransaction];
+                break;
+            case FMDBTransactionDeferred:
+                [[self database] beginDeferredTransaction];
+                break;
+            case FMDBTransactionImmediate:
+                [[self database] beginImmediateTransaction];
+                break;
+        }
+        
+        block([self database], &shouldRollback);
+        
+        if (shouldRollback) {
+            [[self database] rollback];
+        }
+        else {
+            [[self database] commit];
+        }
+    });
+    
+    FMDBRelease(self);
+}
+
+- (void)inTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block {
+    [self beginTransaction:FMDBTransactionExclusive withBlock:block];
+}
+
+- (void)inDeferredTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block {
+    [self beginTransaction:FMDBTransactionDeferred withBlock:block];
+}
+
+- (void)inExclusiveTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block {
+    [self beginTransaction:FMDBTransactionExclusive withBlock:block];
+}
+
+- (void)inImmediateTransaction:(__attribute__((noescape)) void (^)(FMDatabase * _Nonnull, BOOL * _Nonnull))block {
+    [self beginTransaction:FMDBTransactionImmediate withBlock:block];
+}
+
+- (NSError*)inSavePoint:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block {
+#if SQLITE_VERSION_NUMBER >= 3007000
+    static unsigned long savePointIdx = 0;
+    __block NSError *err = 0x00;
+    FMDBRetain(self);
+    dispatch_sync(_queue, ^() { 
+        
+        NSString *name = [NSString stringWithFormat:@"savePoint%ld", savePointIdx++];
+        
+        BOOL shouldRollback = NO;
+        
+        if ([[self database] startSavePointWithName:name error:&err]) {
+            
+            block([self database], &shouldRollback);
+            
+            if (shouldRollback) {
+                // We need to rollback and release this savepoint to remove it
+                [[self database] rollbackToSavePointWithName:name error:&err];
+            }
+            [[self database] releaseSavePointWithName:name error:&err];
+            
+        }
+    });
+    FMDBRelease(self);
+    return err;
+#else
+    NSString *errorMessage = NSLocalizedStringFromTable(@"Save point functions require SQLite 3.7", @"FMDB", nil);
+    if (_db.logsErrors) NSLog(@"%@", errorMessage);
+    return [NSError errorWithDomain:@"FMDatabase" code:0 userInfo:@{NSLocalizedDescriptionKey : errorMessage}];
+#endif
+}
+
+- (BOOL)checkpoint:(FMDBCheckpointMode)mode error:(NSError * __autoreleasing *)error
+{
+    return [self checkpoint:mode name:nil logFrameCount:NULL checkpointCount:NULL error:error];
+}
+
+- (BOOL)checkpoint:(FMDBCheckpointMode)mode name:(NSString *)name error:(NSError * __autoreleasing *)error
+{
+    return [self checkpoint:mode name:name logFrameCount:NULL checkpointCount:NULL error:error];
+}
+
+- (BOOL)checkpoint:(FMDBCheckpointMode)mode name:(NSString *)name logFrameCount:(int * _Nullable)logFrameCount checkpointCount:(int * _Nullable)checkpointCount error:(NSError * __autoreleasing _Nullable * _Nullable)error
+{
+    __block BOOL result;
+    __block NSError *blockError;
+    
+    FMDBRetain(self);
+    dispatch_sync(_queue, ^() {
+        result = [self.database checkpoint:mode name:name logFrameCount:NULL checkpointCount:NULL error:&blockError];
+    });
+    FMDBRelease(self);
+    
+    if (error) {
+        *error = blockError;
+    }
+    return result;
+}
+
+@end

+ 467 - 0
Pods/FMDB/src/fmdb/FMResultSet.h

@@ -0,0 +1,467 @@
+#import <Foundation/Foundation.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+#ifndef __has_feature      // Optional.
+#define __has_feature(x) 0 // Compatibility with non-clang compilers.
+#endif
+
+#ifndef NS_RETURNS_NOT_RETAINED
+#if __has_feature(attribute_ns_returns_not_retained)
+#define NS_RETURNS_NOT_RETAINED __attribute__((ns_returns_not_retained))
+#else
+#define NS_RETURNS_NOT_RETAINED
+#endif
+#endif
+
+@class FMDatabase;
+@class FMStatement;
+
+/** Represents the results of executing a query on an `<FMDatabase>`.
+ 
+ ### See also
+ 
+ - `<FMDatabase>`
+ */
+
+@interface FMResultSet : NSObject
+
+@property (nonatomic, retain, nullable) FMDatabase *parentDB;
+
+///-----------------
+/// @name Properties
+///-----------------
+
+/** Executed query */
+
+@property (atomic, retain, nullable) NSString *query;
+
+/** `NSMutableDictionary` mapping column names to numeric index */
+
+@property (readonly) NSMutableDictionary *columnNameToIndexMap;
+
+/** `FMStatement` used by result set. */
+
+@property (atomic, retain, nullable) FMStatement *statement;
+
+///------------------------------------
+/// @name Creating and closing a result set
+///------------------------------------
+
+/** Create result set from `<FMStatement>`
+ 
+ @param statement A `<FMStatement>` to be performed
+ 
+ @param aDB A `<FMDatabase>` to be used
+ 
+ @return A `FMResultSet` on success; `nil` on failure
+ */
+
++ (instancetype)resultSetWithStatement:(FMStatement *)statement usingParentDatabase:(FMDatabase*)aDB;
+
+/** Close result set */
+
+- (void)close;
+
+///---------------------------------------
+/// @name Iterating through the result set
+///---------------------------------------
+
+/** Retrieve next row for result set.
+ 
+ You must always invoke `next` or `nextWithError` before attempting to access the values returned in a query, even if you're only expecting one.
+
+ @return `YES` if row successfully retrieved; `NO` if end of result set reached
+ 
+ @see hasAnotherRow
+ */
+
+- (BOOL)next;
+
+/** Retrieve next row for result set.
+ 
+  You must always invoke `next` or `nextWithError` before attempting to access the values returned in a query, even if you're only expecting one.
+ 
+ @param outErr A 'NSError' object to receive any error object (if any).
+ 
+ @return 'YES' if row successfully retrieved; 'NO' if end of result set reached
+ 
+ @see hasAnotherRow
+ */
+
+- (BOOL)nextWithError:(NSError * _Nullable *)outErr;
+
+/** Did the last call to `<next>` succeed in retrieving another row?
+
+ @return `YES` if the last call to `<next>` succeeded in retrieving another record; `NO` if not.
+ 
+ @see next
+ 
+ @warning The `hasAnotherRow` method must follow a call to `<next>`. If the previous database interaction was something other than a call to `next`, then this method may return `NO`, whether there is another row of data or not.
+ */
+
+- (BOOL)hasAnotherRow;
+
+///---------------------------------------------
+/// @name Retrieving information from result set
+///---------------------------------------------
+
+/** How many columns in result set
+ 
+ @return Integer value of the number of columns.
+ */
+
+@property (nonatomic, readonly) int columnCount;
+
+/** Column index for column name
+
+ @param columnName `NSString` value of the name of the column.
+
+ @return Zero-based index for column.
+ */
+
+- (int)columnIndexForName:(NSString*)columnName;
+
+/** Column name for column index
+
+ @param columnIdx Zero-based index for column.
+
+ @return columnName `NSString` value of the name of the column.
+ */
+
+- (NSString * _Nullable)columnNameForIndex:(int)columnIdx;
+
+/** Result set integer value for column.
+
+ @param columnName `NSString` value of the name of the column.
+
+ @return `int` value of the result set's column.
+ */
+
+- (int)intForColumn:(NSString*)columnName;
+
+/** Result set integer value for column.
+
+ @param columnIdx Zero-based index for column.
+
+ @return `int` value of the result set's column.
+ */
+
+- (int)intForColumnIndex:(int)columnIdx;
+
+/** Result set `long` value for column.
+
+ @param columnName `NSString` value of the name of the column.
+
+ @return `long` value of the result set's column.
+ */
+
+- (long)longForColumn:(NSString*)columnName;
+
+/** Result set long value for column.
+
+ @param columnIdx Zero-based index for column.
+
+ @return `long` value of the result set's column.
+ */
+
+- (long)longForColumnIndex:(int)columnIdx;
+
+/** Result set `long long int` value for column.
+
+ @param columnName `NSString` value of the name of the column.
+
+ @return `long long int` value of the result set's column.
+ */
+
+- (long long int)longLongIntForColumn:(NSString*)columnName;
+
+/** Result set `long long int` value for column.
+
+ @param columnIdx Zero-based index for column.
+
+ @return `long long int` value of the result set's column.
+ */
+
+- (long long int)longLongIntForColumnIndex:(int)columnIdx;
+
+/** Result set `unsigned long long int` value for column.
+
+ @param columnName `NSString` value of the name of the column.
+
+ @return `unsigned long long int` value of the result set's column.
+ */
+
+- (unsigned long long int)unsignedLongLongIntForColumn:(NSString*)columnName;
+
+/** Result set `unsigned long long int` value for column.
+
+ @param columnIdx Zero-based index for column.
+
+ @return `unsigned long long int` value of the result set's column.
+ */
+
+- (unsigned long long int)unsignedLongLongIntForColumnIndex:(int)columnIdx;
+
+/** Result set `BOOL` value for column.
+
+ @param columnName `NSString` value of the name of the column.
+
+ @return `BOOL` value of the result set's column.
+ */
+
+- (BOOL)boolForColumn:(NSString*)columnName;
+
+/** Result set `BOOL` value for column.
+
+ @param columnIdx Zero-based index for column.
+
+ @return `BOOL` value of the result set's column.
+ */
+
+- (BOOL)boolForColumnIndex:(int)columnIdx;
+
+/** Result set `double` value for column.
+
+ @param columnName `NSString` value of the name of the column.
+
+ @return `double` value of the result set's column.
+ 
+ */
+
+- (double)doubleForColumn:(NSString*)columnName;
+
+/** Result set `double` value for column.
+
+ @param columnIdx Zero-based index for column.
+
+ @return `double` value of the result set's column.
+ 
+ */
+
+- (double)doubleForColumnIndex:(int)columnIdx;
+
+/** Result set `NSString` value for column.
+
+ @param columnName `NSString` value of the name of the column.
+
+ @return String value of the result set's column.
+ 
+ */
+
+- (NSString * _Nullable)stringForColumn:(NSString*)columnName;
+
+/** Result set `NSString` value for column.
+
+ @param columnIdx Zero-based index for column.
+
+ @return String value of the result set's column.
+ */
+
+- (NSString * _Nullable)stringForColumnIndex:(int)columnIdx;
+
+/** Result set `NSDate` value for column.
+
+ @param columnName `NSString` value of the name of the column.
+
+ @return Date value of the result set's column.
+ */
+
+- (NSDate * _Nullable)dateForColumn:(NSString*)columnName;
+
+/** Result set `NSDate` value for column.
+
+ @param columnIdx Zero-based index for column.
+
+ @return Date value of the result set's column.
+ 
+ */
+
+- (NSDate * _Nullable)dateForColumnIndex:(int)columnIdx;
+
+/** Result set `NSData` value for column.
+ 
+ This is useful when storing binary data in table (such as image or the like).
+
+ @param columnName `NSString` value of the name of the column.
+
+ @return Data value of the result set's column.
+ 
+ */
+
+- (NSData * _Nullable)dataForColumn:(NSString*)columnName;
+
+/** Result set `NSData` value for column.
+
+ @param columnIdx Zero-based index for column.
+
+ @return Data value of the result set's column.
+ */
+
+- (NSData * _Nullable)dataForColumnIndex:(int)columnIdx;
+
+/** Result set `(const unsigned char *)` value for column.
+
+ @param columnName `NSString` value of the name of the column.
+
+ @return `(const unsigned char *)` value of the result set's column.
+ */
+
+- (const unsigned char * _Nullable)UTF8StringForColumn:(NSString*)columnName;
+
+- (const unsigned char * _Nullable)UTF8StringForColumnName:(NSString*)columnName __deprecated_msg("Use UTF8StringForColumn instead");
+
+/** Result set `(const unsigned char *)` value for column.
+
+ @param columnIdx Zero-based index for column.
+
+ @return `(const unsigned char *)` value of the result set's column.
+ */
+
+- (const unsigned char * _Nullable)UTF8StringForColumnIndex:(int)columnIdx;
+
+/** Result set object for column.
+
+ @param columnName Name of the column.
+
+ @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object.
+
+ @see objectForKeyedSubscript:
+ */
+
+- (id _Nullable)objectForColumn:(NSString*)columnName;
+
+- (id _Nullable)objectForColumnName:(NSString*)columnName __deprecated_msg("Use objectForColumn instead");
+
+/** Result set object for column.
+
+ @param columnIdx Zero-based index for column.
+
+ @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object.
+
+ @see objectAtIndexedSubscript:
+ */
+
+- (id _Nullable)objectForColumnIndex:(int)columnIdx;
+
+/** Result set object for column.
+ 
+ This method allows the use of the "boxed" syntax supported in Modern Objective-C. For example, by defining this method, the following syntax is now supported:
+ 
+    id result = rs[@"employee_name"];
+ 
+ This simplified syntax is equivalent to calling:
+ 
+    id result = [rs objectForKeyedSubscript:@"employee_name"];
+ 
+ which is, it turns out, equivalent to calling:
+ 
+    id result = [rs objectForColumnName:@"employee_name"];
+
+ @param columnName `NSString` value of the name of the column.
+
+ @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object.
+ */
+
+- (id _Nullable)objectForKeyedSubscript:(NSString *)columnName;
+
+/** Result set object for column.
+
+ This method allows the use of the "boxed" syntax supported in Modern Objective-C. For example, by defining this method, the following syntax is now supported:
+
+    id result = rs[0];
+
+ This simplified syntax is equivalent to calling:
+
+    id result = [rs objectForKeyedSubscript:0];
+
+ which is, it turns out, equivalent to calling:
+
+    id result = [rs objectForColumnName:0];
+
+ @param columnIdx Zero-based index for column.
+
+ @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object.
+ */
+
+- (id _Nullable)objectAtIndexedSubscript:(int)columnIdx;
+
+/** Result set `NSData` value for column.
+
+ @param columnName `NSString` value of the name of the column.
+
+ @return Data value of the result set's column.
+
+ @warning If you are going to use this data after you iterate over the next row, or after you close the
+result set, make sure to make a copy of the data first (or just use `<dataForColumn:>`/`<dataForColumnIndex:>`)
+If you don't, you're going to be in a world of hurt when you try and use the data.
+ 
+ */
+
+- (NSData * _Nullable)dataNoCopyForColumn:(NSString *)columnName NS_RETURNS_NOT_RETAINED;
+
+/** Result set `NSData` value for column.
+
+ @param columnIdx Zero-based index for column.
+
+ @return Data value of the result set's column.
+
+ @warning If you are going to use this data after you iterate over the next row, or after you close the
+ result set, make sure to make a copy of the data first (or just use `<dataForColumn:>`/`<dataForColumnIndex:>`)
+ If you don't, you're going to be in a world of hurt when you try and use the data.
+
+ */
+
+- (NSData * _Nullable)dataNoCopyForColumnIndex:(int)columnIdx NS_RETURNS_NOT_RETAINED;
+
+/** Is the column `NULL`?
+ 
+ @param columnIdx Zero-based index for column.
+
+ @return `YES` if column is `NULL`; `NO` if not `NULL`.
+ */
+
+- (BOOL)columnIndexIsNull:(int)columnIdx;
+
+/** Is the column `NULL`?
+
+ @param columnName `NSString` value of the name of the column.
+
+ @return `YES` if column is `NULL`; `NO` if not `NULL`.
+ */
+
+- (BOOL)columnIsNull:(NSString*)columnName;
+
+
+/** Returns a dictionary of the row results mapped to case sensitive keys of the column names. 
+ 
+ @warning The keys to the dictionary are case sensitive of the column names.
+ */
+
+@property (nonatomic, readonly, nullable) NSDictionary *resultDictionary;
+ 
+/** Returns a dictionary of the row results
+ 
+ @see resultDictionary
+ 
+ @warning **Deprecated**: Please use `<resultDictionary>` instead.  Also, beware that `<resultDictionary>` is case sensitive! 
+ */
+
+- (NSDictionary * _Nullable)resultDict __deprecated_msg("Use resultDictionary instead");
+
+///-----------------------------
+/// @name Key value coding magic
+///-----------------------------
+
+/** Performs `setValue` to yield support for key value observing.
+ 
+ @param object The object for which the values will be set. This is the key-value-coding compliant object that you might, for example, observe.
+
+ */
+
+- (void)kvcMagic:(id)object;
+
+ 
+@end
+
+NS_ASSUME_NONNULL_END

+ 432 - 0
Pods/FMDB/src/fmdb/FMResultSet.m

@@ -0,0 +1,432 @@
+#import "FMResultSet.h"
+#import "FMDatabase.h"
+#import <unistd.h>
+
+#if FMDB_SQLITE_STANDALONE
+#import <sqlite3/sqlite3.h>
+#else
+#import <sqlite3.h>
+#endif
+
+@interface FMDatabase ()
+- (void)resultSetDidClose:(FMResultSet *)resultSet;
+@end
+
+@interface FMResultSet () {
+    NSMutableDictionary *_columnNameToIndexMap;
+}
+@end
+
+@implementation FMResultSet
+
++ (instancetype)resultSetWithStatement:(FMStatement *)statement usingParentDatabase:(FMDatabase*)aDB {
+    
+    FMResultSet *rs = [[FMResultSet alloc] init];
+    
+    [rs setStatement:statement];
+    [rs setParentDB:aDB];
+    
+    NSParameterAssert(![statement inUse]);
+    [statement setInUse:YES]; // weak reference
+    
+    return FMDBReturnAutoreleased(rs);
+}
+
+#if ! __has_feature(objc_arc)
+- (void)finalize {
+    [self close];
+    [super finalize];
+}
+#endif
+
+- (void)dealloc {
+    [self close];
+    
+    FMDBRelease(_query);
+    _query = nil;
+    
+    FMDBRelease(_columnNameToIndexMap);
+    _columnNameToIndexMap = nil;
+    
+#if ! __has_feature(objc_arc)
+    [super dealloc];
+#endif
+}
+
+- (void)close {
+    [_statement reset];
+    FMDBRelease(_statement);
+    _statement = nil;
+    
+    // we don't need this anymore... (i think)
+    //[_parentDB setInUse:NO];
+    [_parentDB resultSetDidClose:self];
+    [self setParentDB:nil];
+}
+
+- (int)columnCount {
+    return sqlite3_column_count([_statement statement]);
+}
+
+- (NSMutableDictionary *)columnNameToIndexMap {
+    if (!_columnNameToIndexMap) {
+        int columnCount = sqlite3_column_count([_statement statement]);
+        _columnNameToIndexMap = [[NSMutableDictionary alloc] initWithCapacity:(NSUInteger)columnCount];
+        int columnIdx = 0;
+        for (columnIdx = 0; columnIdx < columnCount; columnIdx++) {
+            [_columnNameToIndexMap setObject:[NSNumber numberWithInt:columnIdx]
+                                      forKey:[[NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)] lowercaseString]];
+        }
+    }
+    return _columnNameToIndexMap;
+}
+
+- (void)kvcMagic:(id)object {
+    
+    int columnCount = sqlite3_column_count([_statement statement]);
+    
+    int columnIdx = 0;
+    for (columnIdx = 0; columnIdx < columnCount; columnIdx++) {
+        
+        const char *c = (const char *)sqlite3_column_text([_statement statement], columnIdx);
+        
+        // check for a null row
+        if (c) {
+            NSString *s = [NSString stringWithUTF8String:c];
+            
+            [object setValue:s forKey:[NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)]];
+        }
+    }
+}
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-implementations"
+
+- (NSDictionary *)resultDict {
+    
+    NSUInteger num_cols = (NSUInteger)sqlite3_data_count([_statement statement]);
+    
+    if (num_cols > 0) {
+        NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:num_cols];
+        
+        NSEnumerator *columnNames = [[self columnNameToIndexMap] keyEnumerator];
+        NSString *columnName = nil;
+        while ((columnName = [columnNames nextObject])) {
+            id objectValue = [self objectForColumnName:columnName];
+            [dict setObject:objectValue forKey:columnName];
+        }
+        
+        return FMDBReturnAutoreleased([dict copy]);
+    }
+    else {
+        NSLog(@"Warning: There seem to be no columns in this set.");
+    }
+    
+    return nil;
+}
+
+#pragma clang diagnostic pop
+
+- (NSDictionary*)resultDictionary {
+    
+    NSUInteger num_cols = (NSUInteger)sqlite3_data_count([_statement statement]);
+    
+    if (num_cols > 0) {
+        NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:num_cols];
+        
+        int columnCount = sqlite3_column_count([_statement statement]);
+        
+        int columnIdx = 0;
+        for (columnIdx = 0; columnIdx < columnCount; columnIdx++) {
+            
+            NSString *columnName = [NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)];
+            id objectValue = [self objectForColumnIndex:columnIdx];
+            [dict setObject:objectValue forKey:columnName];
+        }
+        
+        return dict;
+    }
+    else {
+        NSLog(@"Warning: There seem to be no columns in this set.");
+    }
+    
+    return nil;
+}
+
+
+
+
+- (BOOL)next {
+    return [self nextWithError:nil];
+}
+
+- (BOOL)nextWithError:(NSError **)outErr {
+    
+    int rc = sqlite3_step([_statement statement]);
+    
+    if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) {
+        NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [_parentDB databasePath]);
+        NSLog(@"Database busy");
+        if (outErr) {
+            *outErr = [_parentDB lastError];
+        }
+    }
+    else if (SQLITE_DONE == rc || SQLITE_ROW == rc) {
+        // all is well, let's return.
+    }
+    else if (SQLITE_ERROR == rc) {
+        NSLog(@"Error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle]));
+        if (outErr) {
+            *outErr = [_parentDB lastError];
+        }
+    }
+    else if (SQLITE_MISUSE == rc) {
+        // uh oh.
+        NSLog(@"Error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle]));
+        if (outErr) {
+            if (_parentDB) {
+                *outErr = [_parentDB lastError];
+            }
+            else {
+                // If 'next' or 'nextWithError' is called after the result set is closed,
+                // we need to return the appropriate error.
+                NSDictionary* errorMessage = [NSDictionary dictionaryWithObject:@"parentDB does not exist" forKey:NSLocalizedDescriptionKey];
+                *outErr = [NSError errorWithDomain:@"FMDatabase" code:SQLITE_MISUSE userInfo:errorMessage];
+            }
+            
+        }
+    }
+    else {
+        // wtf?
+        NSLog(@"Unknown error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle]));
+        if (outErr) {
+            *outErr = [_parentDB lastError];
+        }
+    }
+    
+    
+    if (rc != SQLITE_ROW) {
+        [self close];
+    }
+    
+    return (rc == SQLITE_ROW);
+}
+
+- (BOOL)hasAnotherRow {
+    return sqlite3_errcode([_parentDB sqliteHandle]) == SQLITE_ROW;
+}
+
+- (int)columnIndexForName:(NSString*)columnName {
+    columnName = [columnName lowercaseString];
+    
+    NSNumber *n = [[self columnNameToIndexMap] objectForKey:columnName];
+    
+    if (n != nil) {
+        return [n intValue];
+    }
+    
+    NSLog(@"Warning: I could not find the column named '%@'.", columnName);
+    
+    return -1;
+}
+
+- (int)intForColumn:(NSString*)columnName {
+    return [self intForColumnIndex:[self columnIndexForName:columnName]];
+}
+
+- (int)intForColumnIndex:(int)columnIdx {
+    return sqlite3_column_int([_statement statement], columnIdx);
+}
+
+- (long)longForColumn:(NSString*)columnName {
+    return [self longForColumnIndex:[self columnIndexForName:columnName]];
+}
+
+- (long)longForColumnIndex:(int)columnIdx {
+    return (long)sqlite3_column_int64([_statement statement], columnIdx);
+}
+
+- (long long int)longLongIntForColumn:(NSString*)columnName {
+    return [self longLongIntForColumnIndex:[self columnIndexForName:columnName]];
+}
+
+- (long long int)longLongIntForColumnIndex:(int)columnIdx {
+    return sqlite3_column_int64([_statement statement], columnIdx);
+}
+
+- (unsigned long long int)unsignedLongLongIntForColumn:(NSString*)columnName {
+    return [self unsignedLongLongIntForColumnIndex:[self columnIndexForName:columnName]];
+}
+
+- (unsigned long long int)unsignedLongLongIntForColumnIndex:(int)columnIdx {
+    return (unsigned long long int)[self longLongIntForColumnIndex:columnIdx];
+}
+
+- (BOOL)boolForColumn:(NSString*)columnName {
+    return [self boolForColumnIndex:[self columnIndexForName:columnName]];
+}
+
+- (BOOL)boolForColumnIndex:(int)columnIdx {
+    return ([self intForColumnIndex:columnIdx] != 0);
+}
+
+- (double)doubleForColumn:(NSString*)columnName {
+    return [self doubleForColumnIndex:[self columnIndexForName:columnName]];
+}
+
+- (double)doubleForColumnIndex:(int)columnIdx {
+    return sqlite3_column_double([_statement statement], columnIdx);
+}
+
+- (NSString *)stringForColumnIndex:(int)columnIdx {
+    
+    if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) {
+        return nil;
+    }
+    
+    const char *c = (const char *)sqlite3_column_text([_statement statement], columnIdx);
+    
+    if (!c) {
+        // null row.
+        return nil;
+    }
+    
+    return [NSString stringWithUTF8String:c];
+}
+
+- (NSString*)stringForColumn:(NSString*)columnName {
+    return [self stringForColumnIndex:[self columnIndexForName:columnName]];
+}
+
+- (NSDate*)dateForColumn:(NSString*)columnName {
+    return [self dateForColumnIndex:[self columnIndexForName:columnName]];
+}
+
+- (NSDate*)dateForColumnIndex:(int)columnIdx {
+    
+    if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) {
+        return nil;
+    }
+    
+    return [_parentDB hasDateFormatter] ? [_parentDB dateFromString:[self stringForColumnIndex:columnIdx]] : [NSDate dateWithTimeIntervalSince1970:[self doubleForColumnIndex:columnIdx]];
+}
+
+
+- (NSData*)dataForColumn:(NSString*)columnName {
+    return [self dataForColumnIndex:[self columnIndexForName:columnName]];
+}
+
+- (NSData*)dataForColumnIndex:(int)columnIdx {
+    
+    if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) {
+        return nil;
+    }
+    
+    const char *dataBuffer = sqlite3_column_blob([_statement statement], columnIdx);
+    int dataSize = sqlite3_column_bytes([_statement statement], columnIdx);
+
+    if (dataBuffer == NULL) {
+        return nil;
+    }
+    
+    return [NSData dataWithBytes:(const void *)dataBuffer length:(NSUInteger)dataSize];
+}
+
+
+- (NSData*)dataNoCopyForColumn:(NSString*)columnName {
+    return [self dataNoCopyForColumnIndex:[self columnIndexForName:columnName]];
+}
+
+- (NSData*)dataNoCopyForColumnIndex:(int)columnIdx {
+    
+    if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) {
+        return nil;
+    }
+  
+    const char *dataBuffer = sqlite3_column_blob([_statement statement], columnIdx);
+    int dataSize = sqlite3_column_bytes([_statement statement], columnIdx);
+    
+    NSData *data = [NSData dataWithBytesNoCopy:(void *)dataBuffer length:(NSUInteger)dataSize freeWhenDone:NO];
+    
+    return data;
+}
+
+
+- (BOOL)columnIndexIsNull:(int)columnIdx {
+    return sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL;
+}
+
+- (BOOL)columnIsNull:(NSString*)columnName {
+    return [self columnIndexIsNull:[self columnIndexForName:columnName]];
+}
+
+- (const unsigned char *)UTF8StringForColumnIndex:(int)columnIdx {
+    
+    if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) {
+        return nil;
+    }
+    
+    return sqlite3_column_text([_statement statement], columnIdx);
+}
+
+- (const unsigned char *)UTF8StringForColumn:(NSString*)columnName {
+    return [self UTF8StringForColumnIndex:[self columnIndexForName:columnName]];
+}
+
+- (const unsigned char *)UTF8StringForColumnName:(NSString*)columnName {
+    return [self UTF8StringForColumn:columnName];
+}
+
+- (id)objectForColumnIndex:(int)columnIdx {
+    if (columnIdx < 0 || columnIdx >= sqlite3_column_count([_statement statement])) {
+        return nil;
+    }
+    
+    int columnType = sqlite3_column_type([_statement statement], columnIdx);
+    
+    id returnValue = nil;
+    
+    if (columnType == SQLITE_INTEGER) {
+        returnValue = [NSNumber numberWithLongLong:[self longLongIntForColumnIndex:columnIdx]];
+    }
+    else if (columnType == SQLITE_FLOAT) {
+        returnValue = [NSNumber numberWithDouble:[self doubleForColumnIndex:columnIdx]];
+    }
+    else if (columnType == SQLITE_BLOB) {
+        returnValue = [self dataForColumnIndex:columnIdx];
+    }
+    else {
+        //default to a string for everything else
+        returnValue = [self stringForColumnIndex:columnIdx];
+    }
+    
+    if (returnValue == nil) {
+        returnValue = [NSNull null];
+    }
+    
+    return returnValue;
+}
+
+- (id)objectForColumnName:(NSString*)columnName {
+    return [self objectForColumn:columnName];
+}
+
+- (id)objectForColumn:(NSString*)columnName {
+    return [self objectForColumnIndex:[self columnIndexForName:columnName]];
+}
+
+// returns autoreleased NSString containing the name of the column in the result set
+- (NSString*)columnNameForIndex:(int)columnIdx {
+    return [NSString stringWithUTF8String: sqlite3_column_name([_statement statement], columnIdx)];
+}
+
+- (id)objectAtIndexedSubscript:(int)columnIdx {
+    return [self objectForColumnIndex:columnIdx];
+}
+
+- (id)objectForKeyedSubscript:(NSString *)columnName {
+    return [self objectForColumn:columnName];
+}
+
+
+@end

+ 19 - 0
Pods/MJExtension/LICENSE

@@ -0,0 +1,19 @@
+Copyright (c) 2013-2019 MJExtension (https://github.com/CoderMJLee/MJExtension)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.

+ 27 - 0
Pods/MJExtension/MJExtension/MJExtension.h

@@ -0,0 +1,27 @@
+//
+//  MJExtension.h
+//  MJExtension
+//
+//  Created by mj on 14-1-15.
+//  Copyright (c) 2014年 小码哥. All rights reserved.
+//
+
+#import <Foundation/Foundation.h>
+#import "NSObject+MJCoding.h"
+#import "NSObject+MJProperty.h"
+#import "NSObject+MJClass.h"
+#import "NSObject+MJKeyValue.h"
+#import "NSString+MJExtension.h"
+#import "MJExtensionConst.h"
+
+#import "MJFoundation.h"
+
+//! Project version number for MJExtension.
+FOUNDATION_EXPORT double MJExtensionVersionNumber;
+
+//! Project version string for MJExtension.
+FOUNDATION_EXPORT const unsigned char MJExtensionVersionString[];
+
+// In this header, you should import all the public headers of your framework using statements like #import <MJExtension/PublicHeader.h>
+
+

+ 111 - 0
Pods/MJExtension/MJExtension/MJExtensionConst.h

@@ -0,0 +1,111 @@
+
+#ifndef __MJExtensionConst__H__
+#define __MJExtensionConst__H__
+
+#import <Foundation/Foundation.h>
+
+#ifndef MJ_LOCK
+#define MJ_LOCK(lock) dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER);
+#endif
+
+#ifndef MJ_UNLOCK
+#define MJ_UNLOCK(lock) dispatch_semaphore_signal(lock);
+#endif
+
+// 信号量
+#define MJExtensionSemaphoreCreate \
+extern dispatch_semaphore_t mje_signalSemaphore; \
+extern dispatch_once_t mje_onceTokenSemaphore; \
+dispatch_once(&mje_onceTokenSemaphore, ^{ \
+    mje_signalSemaphore = dispatch_semaphore_create(1); \
+});
+
+// 过期
+#define MJExtensionDeprecated(instead) NS_DEPRECATED(2_0, 2_0, 2_0, 2_0, instead)
+
+// 构建错误
+#define MJExtensionBuildError(clazz, msg) \
+NSError *error = [NSError errorWithDomain:msg code:250 userInfo:nil]; \
+[clazz setMj_error:error];
+
+// 日志输出
+#ifdef DEBUG
+#define MJExtensionLog(...) NSLog(__VA_ARGS__)
+#else
+#define MJExtensionLog(...)
+#endif
+
+/**
+ * 断言
+ * @param condition   条件
+ * @param returnValue 返回值
+ */
+#define MJExtensionAssertError(condition, returnValue, clazz, msg) \
+[clazz setMj_error:nil]; \
+if ((condition) == NO) { \
+    MJExtensionBuildError(clazz, msg); \
+    return returnValue;\
+}
+
+#define MJExtensionAssert2(condition, returnValue) \
+if ((condition) == NO) return returnValue;
+
+/**
+ * 断言
+ * @param condition   条件
+ */
+#define MJExtensionAssert(condition) MJExtensionAssert2(condition, )
+
+/**
+ * 断言
+ * @param param         参数
+ * @param returnValue   返回值
+ */
+#define MJExtensionAssertParamNotNil2(param, returnValue) \
+MJExtensionAssert2((param) != nil, returnValue)
+
+/**
+ * 断言
+ * @param param   参数
+ */
+#define MJExtensionAssertParamNotNil(param) MJExtensionAssertParamNotNil2(param, )
+
+/**
+ * 打印所有的属性
+ */
+#define MJLogAllIvars \
+- (NSString *)description \
+{ \
+    return [self mj_keyValues].description; \
+}
+#define MJExtensionLogAllProperties MJLogAllIvars
+
+/** 仅在 Debugger 展示所有的属性 */
+#define MJImplementDebugDescription \
+- (NSString *)debugDescription \
+{ \
+return [self mj_keyValues].debugDescription; \
+}
+
+/**
+ *  类型(属性类型)
+ */
+FOUNDATION_EXPORT NSString *const MJPropertyTypeInt;
+FOUNDATION_EXPORT NSString *const MJPropertyTypeShort;
+FOUNDATION_EXPORT NSString *const MJPropertyTypeFloat;
+FOUNDATION_EXPORT NSString *const MJPropertyTypeDouble;
+FOUNDATION_EXPORT NSString *const MJPropertyTypeLong;
+FOUNDATION_EXPORT NSString *const MJPropertyTypeLongLong;
+FOUNDATION_EXPORT NSString *const MJPropertyTypeChar;
+FOUNDATION_EXPORT NSString *const MJPropertyTypeBOOL1;
+FOUNDATION_EXPORT NSString *const MJPropertyTypeBOOL2;
+FOUNDATION_EXPORT NSString *const MJPropertyTypePointer;
+
+FOUNDATION_EXPORT NSString *const MJPropertyTypeIvar;
+FOUNDATION_EXPORT NSString *const MJPropertyTypeMethod;
+FOUNDATION_EXPORT NSString *const MJPropertyTypeBlock;
+FOUNDATION_EXPORT NSString *const MJPropertyTypeClass;
+FOUNDATION_EXPORT NSString *const MJPropertyTypeSEL;
+FOUNDATION_EXPORT NSString *const MJPropertyTypeId;
+
+#endif

+ 27 - 0
Pods/MJExtension/MJExtension/MJExtensionConst.m

@@ -0,0 +1,27 @@
+#ifndef __MJExtensionConst__M__
+#define __MJExtensionConst__M__
+
+#import <Foundation/Foundation.h>
+
+/**
+ *  成员变量类型(属性类型)
+ */
+NSString *const MJPropertyTypeInt = @"i";
+NSString *const MJPropertyTypeShort = @"s";
+NSString *const MJPropertyTypeFloat = @"f";
+NSString *const MJPropertyTypeDouble = @"d";
+NSString *const MJPropertyTypeLong = @"l";
+NSString *const MJPropertyTypeLongLong = @"q";
+NSString *const MJPropertyTypeChar = @"c";
+NSString *const MJPropertyTypeBOOL1 = @"c";
+NSString *const MJPropertyTypeBOOL2 = @"b";
+NSString *const MJPropertyTypePointer = @"*";
+
+NSString *const MJPropertyTypeIvar = @"^{objc_ivar=}";
+NSString *const MJPropertyTypeMethod = @"^{objc_method=}";
+NSString *const MJPropertyTypeBlock = @"@?";
+NSString *const MJPropertyTypeClass = @"#";
+NSString *const MJPropertyTypeSEL = @":";
+NSString *const MJPropertyTypeId = @"@";
+
+#endif

+ 16 - 0
Pods/MJExtension/MJExtension/MJFoundation.h

@@ -0,0 +1,16 @@
+//
+//  MJFoundation.h
+//  MJExtensionExample
+//
+//  Created by MJ Lee on 14/7/16.
+//  Copyright (c) 2014年 小码哥. All rights reserved.
+//
+
+#import <Foundation/Foundation.h>
+
+@interface MJFoundation : NSObject
+
++ (BOOL)isClassFromFoundation:(Class)c;
++ (BOOL)isFromNSObjectProtocolProperty:(NSString *)propertyName;
+
+@end

+ 70 - 0
Pods/MJExtension/MJExtension/MJFoundation.m

@@ -0,0 +1,70 @@
+//
+//  MJFoundation.m
+//  MJExtensionExample
+//
+//  Created by MJ Lee on 14/7/16.
+//  Copyright (c) 2014年 小码哥. All rights reserved.
+//
+
+#import "MJFoundation.h"
+#import "MJExtensionConst.h"
+#import <CoreData/CoreData.h>
+#import "objc/runtime.h"
+
+@implementation MJFoundation
+
++ (BOOL)isClassFromFoundation:(Class)c
+{
+    if (c == [NSObject class] || c == [NSManagedObject class]) return YES;
+    
+    static NSSet *foundationClasses;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        // 集合中没有NSObject,因为几乎所有的类都是继承自NSObject,具体是不是NSObject需要特殊判断
+        foundationClasses = [NSSet setWithObjects:
+                             [NSURL class],
+                             [NSDate class],
+                             [NSValue class],
+                             [NSData class],
+                             [NSError class],
+                             [NSArray class],
+                             [NSDictionary class],
+                             [NSString class],
+                             [NSAttributedString class], nil];
+    });
+    
+    __block BOOL result = NO;
+    [foundationClasses enumerateObjectsUsingBlock:^(Class foundationClass, BOOL *stop) {
+        if ([c isSubclassOfClass:foundationClass]) {
+            result = YES;
+            *stop = YES;
+        }
+    }];
+    return result;
+}
+
++ (BOOL)isFromNSObjectProtocolProperty:(NSString *)propertyName
+{
+    if (!propertyName) return NO;
+    
+    static NSSet<NSString *> *objectProtocolPropertyNames;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        unsigned int count = 0;
+        objc_property_t *propertyList = protocol_copyPropertyList(@protocol(NSObject), &count);
+        NSMutableSet *propertyNames = [NSMutableSet setWithCapacity:count];
+        for (int i = 0; i < count; i++) {
+            objc_property_t property = propertyList[i];
+            NSString *propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
+            if (propertyName) {
+                [propertyNames addObject:propertyName];
+            }
+        }
+        objectProtocolPropertyNames = [propertyNames copy];
+        free(propertyList);
+    });
+    
+    return [objectProtocolPropertyNames containsObject:propertyName];
+}
+
+@end

+ 53 - 0
Pods/MJExtension/MJExtension/MJProperty.h

@@ -0,0 +1,53 @@
+//
+//  MJProperty.h
+//  MJExtensionExample
+//
+//  Created by MJ Lee on 15/4/17.
+//  Copyright (c) 2015年 小码哥. All rights reserved.
+//  包装一个成员属性
+
+#import <Foundation/Foundation.h>
+#import <objc/runtime.h>
+#import "MJPropertyType.h"
+#import "MJPropertyKey.h"
+
+/**
+ *  包装一个成员
+ */
+@interface MJProperty : NSObject
+/** 成员属性 */
+@property (nonatomic, assign) objc_property_t property;
+/** 成员属性的名字 */
+@property (nonatomic, readonly) NSString *name;
+
+/** 成员属性的类型 */
+@property (nonatomic, readonly) MJPropertyType *type;
+/** 成员属性来源于哪个类(可能是父类) */
+@property (nonatomic, assign) Class srcClass;
+
+/**** 同一个成员属性 - 父类和子类的行为可能不一致(originKey、propertyKeys、objectClassInArray) ****/
+/** 设置最原始的key */
+- (void)setOriginKey:(id)originKey forClass:(Class)c;
+/** 对应着字典中的多级key(里面存放的数组,数组里面都是MJPropertyKey对象) */
+- (NSArray *)propertyKeysForClass:(Class)c;
+
+/** 模型数组中的模型类型 */
+- (void)setObjectClassInArray:(Class)objectClass forClass:(Class)c;
+- (Class)objectClassInArrayForClass:(Class)c;
+/**** 同一个成员变量 - 父类和子类的行为可能不一致(key、keys、objectClassInArray) ****/
+
+/**
+ * 设置object的成员变量值
+ */
+- (void)setValue:(id)value forObject:(id)object;
+/**
+ * 得到object的成员属性值
+ */
+- (id)valueForObject:(id)object;
+
+/**
+ *  初始化
+ */
++ (instancetype)cachedPropertyWithProperty:(objc_property_t)property;
+
+@end

+ 211 - 0
Pods/MJExtension/MJExtension/MJProperty.m

@@ -0,0 +1,211 @@
+//
+//  MJProperty.m
+//  MJExtensionExample
+//
+//  Created by MJ Lee on 15/4/17.
+//  Copyright (c) 2015年 小码哥. All rights reserved.
+//
+
+#import "MJProperty.h"
+#import "MJFoundation.h"
+#import "MJExtensionConst.h"
+#import <objc/message.h>
+#include "TargetConditionals.h"
+
+@interface MJProperty()
+@property (strong, nonatomic) NSMutableDictionary *propertyKeysDict;
+@property (strong, nonatomic) NSMutableDictionary *objectClassInArrayDict;
+@property (strong, nonatomic) dispatch_semaphore_t propertyKeysLock;
+@property (strong, nonatomic) dispatch_semaphore_t objectClassInArrayLock;
+@end
+
+@implementation MJProperty
+
+#pragma mark - 初始化
+- (instancetype)init
+{
+    if (self = [super init]) {
+        _propertyKeysDict = [NSMutableDictionary dictionary];
+        _objectClassInArrayDict = [NSMutableDictionary dictionary];
+        _propertyKeysLock = dispatch_semaphore_create(1);
+        _objectClassInArrayLock = dispatch_semaphore_create(1);
+    }
+    return self;
+}
+
+#pragma mark - 缓存
++ (instancetype)cachedPropertyWithProperty:(objc_property_t)property
+{
+    MJProperty *propertyObj = objc_getAssociatedObject(self, property);
+    if (propertyObj == nil) {
+        propertyObj = [[self alloc] init];
+        propertyObj.property = property;
+        objc_setAssociatedObject(self, property, propertyObj, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+    }
+    return propertyObj;
+}
+
+#pragma mark - 公共方法
+- (void)setProperty:(objc_property_t)property
+{
+    _property = property;
+    
+    MJExtensionAssertParamNotNil(property);
+    
+    // 1.属性名
+    _name = @(property_getName(property));
+    
+    // 2.成员类型
+    NSString *attrs = @(property_getAttributes(property));
+    NSUInteger dotLoc = [attrs rangeOfString:@","].location;
+    NSString *code = nil;
+    NSUInteger loc = 1;
+    if (dotLoc == NSNotFound) { // 没有,
+        code = [attrs substringFromIndex:loc];
+    } else {
+        code = [attrs substringWithRange:NSMakeRange(loc, dotLoc - loc)];
+    }
+    _type = [MJPropertyType cachedTypeWithCode:code];
+}
+
+/**
+ *  获得成员变量的值
+ */
+- (id)valueForObject:(id)object
+{
+    if (self.type.KVCDisabled) return [NSNull null];
+    
+    id value = [object valueForKey:self.name];
+    
+    // 32位BOOL类型转换json后成Int类型
+    /** https://github.com/CoderMJLee/MJExtension/issues/545 */
+    // 32 bit device OR 32 bit Simulator
+#if defined(__arm__) || (TARGET_OS_SIMULATOR && !__LP64__)
+    if (self.type.isBoolType) {
+        value = @([(NSNumber *)value boolValue]);
+    }
+#endif
+    
+    return value;
+}
+
+/**
+ *  设置成员变量的值
+ */
+- (void)setValue:(id)value forObject:(id)object
+{
+    if (self.type.KVCDisabled || value == nil) return;
+    [object setValue:value forKey:self.name];
+}
+
+/**
+ *  通过字符串key创建对应的keys
+ */
+- (NSArray *)propertyKeysWithStringKey:(NSString *)stringKey
+{
+    if (stringKey.length == 0) return nil;
+    
+    NSMutableArray *propertyKeys = [NSMutableArray array];
+    // 如果有多级映射
+    NSArray *oldKeys = [stringKey componentsSeparatedByString:@"."];
+    
+    for (NSString *oldKey in oldKeys) {
+        NSUInteger start = [oldKey rangeOfString:@"["].location;
+        if (start != NSNotFound) { // 有索引的key
+            NSString *prefixKey = [oldKey substringToIndex:start];
+            NSString *indexKey = prefixKey;
+            if (prefixKey.length) {
+                MJPropertyKey *propertyKey = [[MJPropertyKey alloc] init];
+                propertyKey.name = prefixKey;
+                [propertyKeys addObject:propertyKey];
+                
+                indexKey = [oldKey stringByReplacingOccurrencesOfString:prefixKey withString:@""];
+            }
+            
+            /** 解析索引 **/
+            // 元素
+            NSArray *cmps = [[indexKey stringByReplacingOccurrencesOfString:@"[" withString:@""] componentsSeparatedByString:@"]"];
+            for (NSInteger i = 0; i<cmps.count - 1; i++) {
+                MJPropertyKey *subPropertyKey = [[MJPropertyKey alloc] init];
+                subPropertyKey.type = MJPropertyKeyTypeArray;
+                subPropertyKey.name = cmps[i];
+                [propertyKeys addObject:subPropertyKey];
+            }
+        } else { // 没有索引的key
+            MJPropertyKey *propertyKey = [[MJPropertyKey alloc] init];
+            propertyKey.name = oldKey;
+            [propertyKeys addObject:propertyKey];
+        }
+    }
+    
+    return propertyKeys;
+}
+
+/** 对应着字典中的key */
+- (void)setOriginKey:(id)originKey forClass:(Class)c
+{
+    if ([originKey isKindOfClass:[NSString class]]) { // 字符串类型的key
+        NSArray *propertyKeys = [self propertyKeysWithStringKey:originKey];
+        if (propertyKeys.count) {
+            [self setPropertyKeys:@[propertyKeys] forClass:c];
+        }
+    } else if ([originKey isKindOfClass:[NSArray class]]) {
+        NSMutableArray *keyses = [NSMutableArray array];
+        for (NSString *stringKey in originKey) {
+            NSArray *propertyKeys = [self propertyKeysWithStringKey:stringKey];
+            if (propertyKeys.count) {
+                [keyses addObject:propertyKeys];
+            }
+        }
+        if (keyses.count) {
+            [self setPropertyKeys:keyses forClass:c];
+        }
+    }
+}
+
+/** 对应着字典中的多级key */
+- (void)setPropertyKeys:(NSArray *)propertyKeys forClass:(Class)c
+{
+    if (propertyKeys.count == 0) return;
+    NSString *key = NSStringFromClass(c);
+    if (!key) return;
+    
+    MJ_LOCK(self.propertyKeysLock);
+    self.propertyKeysDict[key] = propertyKeys;
+    MJ_UNLOCK(self.propertyKeysLock);
+}
+
+- (NSArray *)propertyKeysForClass:(Class)c
+{
+    NSString *key = NSStringFromClass(c);
+    if (!key) return nil;
+    
+    MJ_LOCK(self.propertyKeysLock);
+    NSArray *propertyKeys = self.propertyKeysDict[key];
+    MJ_UNLOCK(self.propertyKeysLock);
+    return propertyKeys;
+}
+
+/** 模型数组中的模型类型 */
+- (void)setObjectClassInArray:(Class)objectClass forClass:(Class)c
+{
+    if (!objectClass) return;
+    NSString *key = NSStringFromClass(c);
+    if (!key) return;
+    
+    MJ_LOCK(self.objectClassInArrayLock);
+    self.objectClassInArrayDict[key] = objectClass;
+    MJ_UNLOCK(self.objectClassInArrayLock);
+}
+
+- (Class)objectClassInArrayForClass:(Class)c
+{
+    NSString *key = NSStringFromClass(c);
+    if (!key) return nil;
+    
+    MJ_LOCK(self.objectClassInArrayLock);
+    Class objectClass = self.objectClassInArrayDict[key];
+    MJ_UNLOCK(self.objectClassInArrayLock);
+    return objectClass;
+}
+@end

+ 30 - 0
Pods/MJExtension/MJExtension/MJPropertyKey.h

@@ -0,0 +1,30 @@
+//
+//  MJPropertyKey.h
+//  MJExtensionExample
+//
+//  Created by MJ Lee on 15/8/11.
+//  Copyright (c) 2015年 小码哥. All rights reserved.
+//
+
+#import <Foundation/Foundation.h>
+
+typedef enum {
+    MJPropertyKeyTypeDictionary = 0, // 字典的key
+    MJPropertyKeyTypeArray // 数组的key
+} MJPropertyKeyType;
+
+/**
+ *  属性的key
+ */
+@interface MJPropertyKey : NSObject
+/** key的名字 */
+@property (copy,   nonatomic) NSString *name;
+/** key的种类,可能是@"10",可能是@"age" */
+@property (assign, nonatomic) MJPropertyKeyType type;
+
+/**
+ *  根据当前的key,也就是name,从object(字典或者数组)中取值
+ */
+- (id)valueInObject:(id)object;
+
+@end

+ 25 - 0
Pods/MJExtension/MJExtension/MJPropertyKey.m

@@ -0,0 +1,25 @@
+//
+//  MJPropertyKey.m
+//  MJExtensionExample
+//
+//  Created by MJ Lee on 15/8/11.
+//  Copyright (c) 2015年 小码哥. All rights reserved.
+//
+
+#import "MJPropertyKey.h"
+
+@implementation MJPropertyKey
+
+- (id)valueInObject:(id)object
+{
+    if ([object isKindOfClass:[NSDictionary class]] && self.type == MJPropertyKeyTypeDictionary) {
+        return object[self.name];
+    } else if ([object isKindOfClass:[NSArray class]] && self.type == MJPropertyKeyTypeArray) {
+        NSArray *array = object;
+        NSUInteger index = self.name.intValue;
+        if (index < array.count) return array[index];
+        return nil;
+    }
+    return nil;
+}
+@end

+ 39 - 0
Pods/MJExtension/MJExtension/MJPropertyType.h

@@ -0,0 +1,39 @@
+//
+//  MJPropertyType.h
+//  MJExtension
+//
+//  Created by mj on 14-1-15.
+//  Copyright (c) 2014年 小码哥. All rights reserved.
+//  包装一种类型
+
+#import <Foundation/Foundation.h>
+
+/**
+ *  包装一种类型
+ */
+@interface MJPropertyType : NSObject
+/** 类型标识符 */
+@property (nonatomic, copy) NSString *code;
+
+/** 是否为id类型 */
+@property (nonatomic, readonly, getter=isIdType) BOOL idType;
+
+/** 是否为基本数字类型:int、float等 */
+@property (nonatomic, readonly, getter=isNumberType) BOOL numberType;
+
+/** 是否为BOOL类型 */
+@property (nonatomic, readonly, getter=isBoolType) BOOL boolType;
+
+/** 对象类型(如果是基本数据类型,此值为nil) */
+@property (nonatomic, readonly) Class typeClass;
+
+/** 类型是否来自于Foundation框架,比如NSString、NSArray */
+@property (nonatomic, readonly, getter = isFromFoundation) BOOL fromFoundation;
+/** 类型是否不支持KVC */
+@property (nonatomic, readonly, getter = isKVCDisabled) BOOL KVCDisabled;
+
+/**
+ *  获得缓存的类型对象
+ */
++ (instancetype)cachedTypeWithCode:(NSString *)code;
+@end

+ 71 - 0
Pods/MJExtension/MJExtension/MJPropertyType.m

@@ -0,0 +1,71 @@
+//
+//  MJPropertyType.m
+//  MJExtension
+//
+//  Created by mj on 14-1-15.
+//  Copyright (c) 2014年 小码哥. All rights reserved.
+//
+
+#import "MJPropertyType.h"
+#import "MJExtension.h"
+#import "MJFoundation.h"
+#import "MJExtensionConst.h"
+
+@implementation MJPropertyType
+
++ (instancetype)cachedTypeWithCode:(NSString *)code
+{
+    MJExtensionAssertParamNotNil2(code, nil);
+    
+    static NSMutableDictionary *types;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        types = [NSMutableDictionary dictionary];
+    });
+    
+    MJPropertyType *type = types[code];
+    if (type == nil) {
+        type = [[self alloc] init];
+        type.code = code;
+        types[code] = type;
+    }
+    return type;
+}
+
+#pragma mark - 公共方法
+- (void)setCode:(NSString *)code
+{
+    _code = code;
+    
+    MJExtensionAssertParamNotNil(code);
+    
+    if ([code isEqualToString:MJPropertyTypeId]) {
+        _idType = YES;
+    } else if (code.length == 0) {
+        _KVCDisabled = YES;
+    } else if (code.length > 3 && [code hasPrefix:@"@\""]) {
+        // 去掉@"和",截取中间的类型名称
+        _code = [code substringWithRange:NSMakeRange(2, code.length - 3)];
+        _typeClass = NSClassFromString(_code);
+        _fromFoundation = [MJFoundation isClassFromFoundation:_typeClass];
+        _numberType = [_typeClass isSubclassOfClass:[NSNumber class]];
+        
+    } else if ([code isEqualToString:MJPropertyTypeSEL] ||
+               [code isEqualToString:MJPropertyTypeIvar] ||
+               [code isEqualToString:MJPropertyTypeMethod]) {
+        _KVCDisabled = YES;
+    }
+    
+    // 是否为数字类型
+    NSString *lowerCode = _code.lowercaseString;
+    NSArray *numberTypes = @[MJPropertyTypeInt, MJPropertyTypeShort, MJPropertyTypeBOOL1, MJPropertyTypeBOOL2, MJPropertyTypeFloat, MJPropertyTypeDouble, MJPropertyTypeLong, MJPropertyTypeLongLong, MJPropertyTypeChar];
+    if ([numberTypes containsObject:lowerCode]) {
+        _numberType = YES;
+        
+        if ([lowerCode isEqualToString:MJPropertyTypeBOOL1]
+            || [lowerCode isEqualToString:MJPropertyTypeBOOL2]) {
+            _boolType = YES;
+        }
+    }
+}
+@end

+ 90 - 0
Pods/MJExtension/MJExtension/NSObject+MJClass.h

@@ -0,0 +1,90 @@
+//
+//  NSObject+MJClass.h
+//  MJExtensionExample
+//
+//  Created by MJ Lee on 15/8/11.
+//  Copyright (c) 2015年 小码哥. All rights reserved.
+//
+
+#import <Foundation/Foundation.h>
+
+/**
+ *  遍历所有类的block(父类)
+ */
+typedef void (^MJClassesEnumeration)(Class c, BOOL *stop);
+
+/** 这个数组中的属性名才会进行字典和模型的转换 */
+typedef NSArray * (^MJAllowedPropertyNames)(void);
+/** 这个数组中的属性名才会进行归档 */
+typedef NSArray * (^MJAllowedCodingPropertyNames)(void);
+
+/** 这个数组中的属性名将会被忽略:不进行字典和模型的转换 */
+typedef NSArray * (^MJIgnoredPropertyNames)(void);
+/** 这个数组中的属性名将会被忽略:不进行归档 */
+typedef NSArray * (^MJIgnoredCodingPropertyNames)(void);
+
+/**
+ * 类相关的扩展
+ */
+@interface NSObject (MJClass)
+/**
+ *  遍历所有的类
+ */
++ (void)mj_enumerateClasses:(MJClassesEnumeration)enumeration;
++ (void)mj_enumerateAllClasses:(MJClassesEnumeration)enumeration;
+
+#pragma mark - 属性白名单配置
+/**
+ *  这个数组中的属性名才会进行字典和模型的转换
+ *
+ *  @param allowedPropertyNames          这个数组中的属性名才会进行字典和模型的转换
+ */
++ (void)mj_setupAllowedPropertyNames:(MJAllowedPropertyNames)allowedPropertyNames;
+
+/**
+ *  这个数组中的属性名才会进行字典和模型的转换
+ */
++ (NSMutableArray *)mj_totalAllowedPropertyNames;
+
+#pragma mark - 属性黑名单配置
+/**
+ *  这个数组中的属性名将会被忽略:不进行字典和模型的转换
+ *
+ *  @param ignoredPropertyNames          这个数组中的属性名将会被忽略:不进行字典和模型的转换
+ */
++ (void)mj_setupIgnoredPropertyNames:(MJIgnoredPropertyNames)ignoredPropertyNames;
+
+/**
+ *  这个数组中的属性名将会被忽略:不进行字典和模型的转换
+ */
++ (NSMutableArray *)mj_totalIgnoredPropertyNames;
+
+#pragma mark - 归档属性白名单配置
+/**
+ *  这个数组中的属性名才会进行归档
+ *
+ *  @param allowedCodingPropertyNames          这个数组中的属性名才会进行归档
+ */
++ (void)mj_setupAllowedCodingPropertyNames:(MJAllowedCodingPropertyNames)allowedCodingPropertyNames;
+
+/**
+ *  这个数组中的属性名才会进行字典和模型的转换
+ */
++ (NSMutableArray *)mj_totalAllowedCodingPropertyNames;
+
+#pragma mark - 归档属性黑名单配置
+/**
+ *  这个数组中的属性名将会被忽略:不进行归档
+ *
+ *  @param ignoredCodingPropertyNames          这个数组中的属性名将会被忽略:不进行归档
+ */
++ (void)mj_setupIgnoredCodingPropertyNames:(MJIgnoredCodingPropertyNames)ignoredCodingPropertyNames;
+
+/**
+ *  这个数组中的属性名将会被忽略:不进行归档
+ */
++ (NSMutableArray *)mj_totalIgnoredCodingPropertyNames;
+
+#pragma mark - 内部使用
++ (void)mj_setupBlockReturnValue:(id (^)(void))block key:(const char *)key;
+@end

+ 174 - 0
Pods/MJExtension/MJExtension/NSObject+MJClass.m

@@ -0,0 +1,174 @@
+//
+//  NSObject+MJClass.m
+//  MJExtensionExample
+//
+//  Created by MJ Lee on 15/8/11.
+//  Copyright (c) 2015年 小码哥. All rights reserved.
+//
+
+#import "NSObject+MJClass.h"
+#import "NSObject+MJCoding.h"
+#import "NSObject+MJKeyValue.h"
+#import "MJFoundation.h"
+#import <objc/runtime.h>
+
+static const char MJAllowedPropertyNamesKey = '\0';
+static const char MJIgnoredPropertyNamesKey = '\0';
+static const char MJAllowedCodingPropertyNamesKey = '\0';
+static const char MJIgnoredCodingPropertyNamesKey = '\0';
+
+@implementation NSObject (MJClass)
+
++ (NSMutableDictionary *)mj_classDictForKey:(const void *)key
+{
+    static NSMutableDictionary *allowedPropertyNamesDict;
+    static NSMutableDictionary *ignoredPropertyNamesDict;
+    static NSMutableDictionary *allowedCodingPropertyNamesDict;
+    static NSMutableDictionary *ignoredCodingPropertyNamesDict;
+    
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        allowedPropertyNamesDict = [NSMutableDictionary dictionary];
+        ignoredPropertyNamesDict = [NSMutableDictionary dictionary];
+        allowedCodingPropertyNamesDict = [NSMutableDictionary dictionary];
+        ignoredCodingPropertyNamesDict = [NSMutableDictionary dictionary];
+    });
+    
+    if (key == &MJAllowedPropertyNamesKey) return allowedPropertyNamesDict;
+    if (key == &MJIgnoredPropertyNamesKey) return ignoredPropertyNamesDict;
+    if (key == &MJAllowedCodingPropertyNamesKey) return allowedCodingPropertyNamesDict;
+    if (key == &MJIgnoredCodingPropertyNamesKey) return ignoredCodingPropertyNamesDict;
+    return nil;
+}
+
++ (void)mj_enumerateClasses:(MJClassesEnumeration)enumeration
+{
+    // 1.没有block就直接返回
+    if (enumeration == nil) return;
+    
+    // 2.停止遍历的标记
+    BOOL stop = NO;
+    
+    // 3.当前正在遍历的类
+    Class c = self;
+    
+    // 4.开始遍历每一个类
+    while (c && !stop) {
+        // 4.1.执行操作
+        enumeration(c, &stop);
+        
+        // 4.2.获得父类
+        c = class_getSuperclass(c);
+        
+        if ([MJFoundation isClassFromFoundation:c]) break;
+    }
+}
+
++ (void)mj_enumerateAllClasses:(MJClassesEnumeration)enumeration
+{
+    // 1.没有block就直接返回
+    if (enumeration == nil) return;
+    
+    // 2.停止遍历的标记
+    BOOL stop = NO;
+    
+    // 3.当前正在遍历的类
+    Class c = self;
+    
+    // 4.开始遍历每一个类
+    while (c && !stop) {
+        // 4.1.执行操作
+        enumeration(c, &stop);
+        
+        // 4.2.获得父类
+        c = class_getSuperclass(c);
+    }
+}
+
+#pragma mark - 属性黑名单配置
++ (void)mj_setupIgnoredPropertyNames:(MJIgnoredPropertyNames)ignoredPropertyNames
+{
+    [self mj_setupBlockReturnValue:ignoredPropertyNames key:&MJIgnoredPropertyNamesKey];
+}
+
++ (NSMutableArray *)mj_totalIgnoredPropertyNames
+{
+    return [self mj_totalObjectsWithSelector:@selector(mj_ignoredPropertyNames) key:&MJIgnoredPropertyNamesKey];
+}
+
+#pragma mark - 归档属性黑名单配置
++ (void)mj_setupIgnoredCodingPropertyNames:(MJIgnoredCodingPropertyNames)ignoredCodingPropertyNames
+{
+    [self mj_setupBlockReturnValue:ignoredCodingPropertyNames key:&MJIgnoredCodingPropertyNamesKey];
+}
+
++ (NSMutableArray *)mj_totalIgnoredCodingPropertyNames
+{
+    return [self mj_totalObjectsWithSelector:@selector(mj_ignoredCodingPropertyNames) key:&MJIgnoredCodingPropertyNamesKey];
+}
+
+#pragma mark - 属性白名单配置
++ (void)mj_setupAllowedPropertyNames:(MJAllowedPropertyNames)allowedPropertyNames;
+{
+    [self mj_setupBlockReturnValue:allowedPropertyNames key:&MJAllowedPropertyNamesKey];
+}
+
++ (NSMutableArray *)mj_totalAllowedPropertyNames
+{
+    return [self mj_totalObjectsWithSelector:@selector(mj_allowedPropertyNames) key:&MJAllowedPropertyNamesKey];
+}
+
+#pragma mark - 归档属性白名单配置
++ (void)mj_setupAllowedCodingPropertyNames:(MJAllowedCodingPropertyNames)allowedCodingPropertyNames
+{
+    [self mj_setupBlockReturnValue:allowedCodingPropertyNames key:&MJAllowedCodingPropertyNamesKey];
+}
+
++ (NSMutableArray *)mj_totalAllowedCodingPropertyNames
+{
+    return [self mj_totalObjectsWithSelector:@selector(mj_allowedCodingPropertyNames) key:&MJAllowedCodingPropertyNamesKey];
+}
+
+#pragma mark - block和方法处理:存储block的返回值
++ (void)mj_setupBlockReturnValue:(id (^)(void))block key:(const char *)key {
+    MJExtensionSemaphoreCreate
+    MJ_LOCK(mje_signalSemaphore);
+    if (block) {
+        objc_setAssociatedObject(self, key, block(), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+    } else {
+        objc_setAssociatedObject(self, key, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+    }
+    
+    // 清空数据
+    [[self mj_classDictForKey:key] removeAllObjects];
+    MJ_UNLOCK(mje_signalSemaphore);
+}
+
++ (NSMutableArray *)mj_totalObjectsWithSelector:(SEL)selector key:(const char *)key
+{
+    MJExtensionSemaphoreCreate
+    MJ_LOCK(mje_signalSemaphore);
+    NSMutableArray *array = [self mj_classDictForKey:key][NSStringFromClass(self)];
+    if (array == nil) {
+        // 创建、存储
+        [self mj_classDictForKey:key][NSStringFromClass(self)] = array = [NSMutableArray array];
+        
+        if ([self respondsToSelector:selector]) {
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
+            NSArray *subArray = [self performSelector:selector];
+#pragma clang diagnostic pop
+            if (subArray) {
+                [array addObjectsFromArray:subArray];
+            }
+        }
+        
+        [self mj_enumerateAllClasses:^(__unsafe_unretained Class c, BOOL *stop) {
+            NSArray *subArray = objc_getAssociatedObject(c, key);
+            [array addObjectsFromArray:subArray];
+        }];
+    }
+    MJ_UNLOCK(mje_signalSemaphore);
+    return array;
+}
+@end

+ 66 - 0
Pods/MJExtension/MJExtension/NSObject+MJCoding.h

@@ -0,0 +1,66 @@
+//
+//  NSObject+MJCoding.h
+//  MJExtension
+//
+//  Created by mj on 14-1-15.
+//  Copyright (c) 2014年 小码哥. All rights reserved.
+//
+
+#import <Foundation/Foundation.h>
+#import "MJExtensionConst.h"
+
+/**
+ *  Codeing协议
+ */
+@protocol MJCoding <NSObject>
+@optional
+/**
+ *  这个数组中的属性名才会进行归档
+ */
++ (NSArray *)mj_allowedCodingPropertyNames;
+/**
+ *  这个数组中的属性名将会被忽略:不进行归档
+ */
++ (NSArray *)mj_ignoredCodingPropertyNames;
+@end
+
+@interface NSObject (MJCoding) <MJCoding>
+/**
+ *  解码(从文件中解析对象)
+ */
+- (void)mj_decode:(NSCoder *)decoder;
+/**
+ *  编码(将对象写入文件中)
+ */
+- (void)mj_encode:(NSCoder *)encoder;
+@end
+
+/**
+ 归档的实现
+ */
+#define MJCodingImplementation \
+- (id)initWithCoder:(NSCoder *)decoder \
+{ \
+if (self = [super init]) { \
+[self mj_decode:decoder]; \
+} \
+return self; \
+} \
+\
+- (void)encodeWithCoder:(NSCoder *)encoder \
+{ \
+[self mj_encode:encoder]; \
+}\
+
+#define MJExtensionCodingImplementation MJCodingImplementation
+
+#define MJSecureCodingImplementation(CLASS, FLAG) \
+@interface CLASS (MJSecureCoding) <NSSecureCoding> \
+@end \
+@implementation CLASS (MJSecureCoding) \
+MJCodingImplementation \
++ (BOOL)supportsSecureCoding { \
+return FLAG; \
+} \
+@end \
+

+ 59 - 0
Pods/MJExtension/MJExtension/NSObject+MJCoding.m

@@ -0,0 +1,59 @@
+//
+//  NSObject+MJCoding.m
+//  MJExtension
+//
+//  Created by mj on 14-1-15.
+//  Copyright (c) 2014年 小码哥. All rights reserved.
+//
+
+#import "NSObject+MJCoding.h"
+#import "NSObject+MJClass.h"
+#import "NSObject+MJProperty.h"
+#import "MJProperty.h"
+
+@implementation NSObject (MJCoding)
+
+- (void)mj_encode:(NSCoder *)encoder
+{
+    Class clazz = [self class];
+    
+    NSArray *allowedCodingPropertyNames = [clazz mj_totalAllowedCodingPropertyNames];
+    NSArray *ignoredCodingPropertyNames = [clazz mj_totalIgnoredCodingPropertyNames];
+    
+    [clazz mj_enumerateProperties:^(MJProperty *property, BOOL *stop) {
+        // 检测是否被忽略
+        if (allowedCodingPropertyNames.count && ![allowedCodingPropertyNames containsObject:property.name]) return;
+        if ([ignoredCodingPropertyNames containsObject:property.name]) return;
+        
+        id value = [property valueForObject:self];
+        if (value == nil) return;
+        [encoder encodeObject:value forKey:property.name];
+    }];
+}
+
+- (void)mj_decode:(NSCoder *)decoder
+{
+    Class clazz = [self class];
+    
+    NSArray *allowedCodingPropertyNames = [clazz mj_totalAllowedCodingPropertyNames];
+    NSArray *ignoredCodingPropertyNames = [clazz mj_totalIgnoredCodingPropertyNames];
+    
+    [clazz mj_enumerateProperties:^(MJProperty *property, BOOL *stop) {
+        // 检测是否被忽略
+        if (allowedCodingPropertyNames.count && ![allowedCodingPropertyNames containsObject:property.name]) return;
+        if ([ignoredCodingPropertyNames containsObject:property.name]) return;
+        
+        // fixed `-[NSKeyedUnarchiver validateAllowedClass:forKey:] allowed unarchiving safe plist type ''NSNumber'(This will be disallowed in the future.)` warning.
+        Class genericClass = [property objectClassInArrayForClass:property.srcClass];
+        // If genericClass exists, property.type.typeClass would be a collection type(Array, Set, Dictionary). This scenario([obj, nil, obj, nil]) would not happened.
+        NSSet *classes = [NSSet setWithObjects:NSNumber.class,
+                          property.type.typeClass, genericClass, nil];
+        id value = [decoder decodeObjectOfClasses:classes forKey:property.name];
+        if (value == nil) { // 兼容以前的MJExtension版本
+            value = [decoder decodeObjectForKey:[@"_" stringByAppendingString:property.name]];
+        }
+        if (value == nil) return;
+        [property setValue:value forObject:self];
+    }];
+}
+@end

+ 194 - 0
Pods/MJExtension/MJExtension/NSObject+MJKeyValue.h

@@ -0,0 +1,194 @@
+//
+//  NSObject+MJKeyValue.h
+//  MJExtension
+//
+//  Created by mj on 13-8-24.
+//  Copyright (c) 2013年 小码哥. All rights reserved.
+//
+
+#import <Foundation/Foundation.h>
+#import "MJExtensionConst.h"
+#import <CoreData/CoreData.h>
+#import "MJProperty.h"
+
+/**
+ *  KeyValue协议
+ */
+@protocol MJKeyValue <NSObject>
+@optional
+/**
+ *  只有这个数组中的属性名才允许进行字典和模型的转换
+ */
++ (NSArray *)mj_allowedPropertyNames;
+
+/**
+ *  这个数组中的属性名将会被忽略:不进行字典和模型的转换
+ */
++ (NSArray *)mj_ignoredPropertyNames;
+
+/**
+ *  将属性名换为其他key去字典中取值
+ *
+ *  @return 字典中的key是属性名,value是从字典中取值用的key
+ */
++ (NSDictionary *)mj_replacedKeyFromPropertyName;
+
+/**
+ *  将属性名换为其他key去字典中取值
+ *
+ *  @return 从字典中取值用的key
+ */
++ (id)mj_replacedKeyFromPropertyName121:(NSString *)propertyName;
+
+/**
+ *  数组中需要转换的模型类
+ *
+ *  @return 字典中的key是数组属性名,value是数组中存放模型的Class(Class类型或者NSString类型)
+ */
++ (NSDictionary *)mj_objectClassInArray;
+
+
+/** 特殊地区在字符串格式化数字时使用 */
++ (NSLocale *)mj_numberLocale;
+
+/**
+ *  旧值换新值,用于过滤字典中的值
+ *
+ *  @param oldValue 旧值
+ *
+ *  @return 新值
+ */
+- (id)mj_newValueFromOldValue:(id)oldValue property:(MJProperty *)property;
+
+/**
+ *  当字典转模型完毕时调用
+ */
+- (void)mj_keyValuesDidFinishConvertingToObject MJExtensionDeprecated("请使用`mj_didConvertToObjectWithKeyValues:`替代");
+- (void)mj_keyValuesDidFinishConvertingToObject:(NSDictionary *)keyValues MJExtensionDeprecated("请使用`mj_didConvertToObjectWithKeyValues:`替代");
+- (void)mj_didConvertToObjectWithKeyValues:(NSDictionary *)keyValues;
+
+/**
+ *  当模型转字典完毕时调用
+ */
+- (void)mj_objectDidFinishConvertingToKeyValues MJExtensionDeprecated("请使用`mj_objectDidConvertToKeyValues:`替代");
+- (void)mj_objectDidConvertToKeyValues:(NSMutableDictionary *)keyValues;
+
+@end
+
+@interface NSObject (MJKeyValue) <MJKeyValue>
+#pragma mark - 类方法
+/**
+ * 字典转模型过程中遇到的错误
+ */
++ (NSError *)mj_error;
+
+/**
+ *  模型转字典时,字典的key是否参考replacedKeyFromPropertyName等方法(父类设置了,子类也会继承下来)
+ */
++ (void)mj_referenceReplacedKeyWhenCreatingKeyValues:(BOOL)reference;
+
+#pragma mark - 对象方法
+/**
+ *  将字典的键值对转成模型属性
+ *  @param keyValues 字典(可以是NSDictionary、NSData、NSString)
+ */
+- (instancetype)mj_setKeyValues:(id)keyValues;
+
+/**
+ *  将字典的键值对转成模型属性
+ *  @param keyValues 字典(可以是NSDictionary、NSData、NSString)
+ *  @param context   CoreData上下文
+ */
+- (instancetype)mj_setKeyValues:(id)keyValues context:(NSManagedObjectContext *)context;
+
+/**
+ *  将模型转成字典
+ *  @return 字典
+ */
+- (NSMutableDictionary *)mj_keyValues;
+- (NSMutableDictionary *)mj_keyValuesWithKeys:(NSArray *)keys;
+- (NSMutableDictionary *)mj_keyValuesWithIgnoredKeys:(NSArray *)ignoredKeys;
+
+/**
+ *  通过模型数组来创建一个字典数组
+ *  @param objectArray 模型数组
+ *  @return 字典数组
+ */
++ (NSMutableArray *)mj_keyValuesArrayWithObjectArray:(NSArray *)objectArray;
++ (NSMutableArray *)mj_keyValuesArrayWithObjectArray:(NSArray *)objectArray keys:(NSArray *)keys;
++ (NSMutableArray *)mj_keyValuesArrayWithObjectArray:(NSArray *)objectArray ignoredKeys:(NSArray *)ignoredKeys;
+
+#pragma mark - 字典转模型
+/**
+ *  通过字典来创建一个模型
+ *  @param keyValues 字典(可以是NSDictionary、NSData、NSString)
+ *  @return 新建的对象
+ */
++ (instancetype)mj_objectWithKeyValues:(id)keyValues;
+
+/**
+ *  通过字典来创建一个CoreData模型
+ *  @param keyValues 字典(可以是NSDictionary、NSData、NSString)
+ *  @param context   CoreData上下文
+ *  @return 新建的对象
+ */
++ (instancetype)mj_objectWithKeyValues:(id)keyValues context:(NSManagedObjectContext *)context;
+
+/**
+ *  通过plist来创建一个模型
+ *  @param filename 文件名(仅限于mainBundle中的文件)
+ *  @return 新建的对象
+ */
++ (instancetype)mj_objectWithFilename:(NSString *)filename;
+
+/**
+ *  通过plist来创建一个模型
+ *  @param file 文件全路径
+ *  @return 新建的对象
+ */
++ (instancetype)mj_objectWithFile:(NSString *)file;
+
+#pragma mark - 字典数组转模型数组
+/**
+ *  通过字典数组来创建一个模型数组
+ *  @param keyValuesArray 字典数组(可以是NSDictionary、NSData、NSString)
+ *  @return 模型数组
+ */
++ (NSMutableArray *)mj_objectArrayWithKeyValuesArray:(id)keyValuesArray;
+
+/**
+ *  通过字典数组来创建一个模型数组
+ *  @param keyValuesArray 字典数组(可以是NSDictionary、NSData、NSString)
+ *  @param context        CoreData上下文
+ *  @return 模型数组
+ */
++ (NSMutableArray *)mj_objectArrayWithKeyValuesArray:(id)keyValuesArray context:(NSManagedObjectContext *)context;
+
+/**
+ *  通过plist来创建一个模型数组
+ *  @param filename 文件名(仅限于mainBundle中的文件)
+ *  @return 模型数组
+ */
++ (NSMutableArray *)mj_objectArrayWithFilename:(NSString *)filename;
+
+/**
+ *  通过plist来创建一个模型数组
+ *  @param file 文件全路径
+ *  @return 模型数组
+ */
++ (NSMutableArray *)mj_objectArrayWithFile:(NSString *)file;
+
+#pragma mark - 转换为JSON
+/**
+ *  转换为JSON Data
+ */
+- (NSData *)mj_JSONData;
+/**
+ *  转换为字典或者数组
+ */
+- (id)mj_JSONObject;
+/**
+ *  转换为JSON 字符串
+ */
+- (NSString *)mj_JSONString;
+@end

+ 524 - 0
Pods/MJExtension/MJExtension/NSObject+MJKeyValue.m

@@ -0,0 +1,524 @@
+//
+//  NSObject+MJKeyValue.m
+//  MJExtension
+//
+//  Created by mj on 13-8-24.
+//  Copyright (c) 2013年 小码哥. All rights reserved.
+//
+
+#import "NSObject+MJKeyValue.h"
+#import "NSObject+MJProperty.h"
+#import "NSString+MJExtension.h"
+#import "MJProperty.h"
+#import "MJPropertyType.h"
+#import "MJExtensionConst.h"
+#import "MJFoundation.h"
+#import "NSString+MJExtension.h"
+#import "NSObject+MJClass.h"
+
+@implementation NSDecimalNumber(MJKeyValue)
+
+- (id)mj_standardValueWithTypeCode:(NSString *)typeCode {
+    // 由于这里涉及到编译器问题, 暂时保留 Long, 实际上在 64 位系统上, 这 2 个精度范围相同,
+    // 32 位略有不同, 其余都可使用 Double 进行强转不丢失精度
+    if ([typeCode isEqualToString:MJPropertyTypeLongLong]) {
+        return @(self.longLongValue);
+    } else if ([typeCode isEqualToString:MJPropertyTypeLongLong.uppercaseString]) {
+        return @(self.unsignedLongLongValue);
+    } else if ([typeCode isEqualToString:MJPropertyTypeLong]) {
+        return @(self.longValue);
+    } else if ([typeCode isEqualToString:MJPropertyTypeLong.uppercaseString]) {
+        return @(self.unsignedLongValue);
+    } else {
+        return @(self.doubleValue);
+    }
+}
+
+@end
+
+@implementation NSObject (MJKeyValue)
+
+#pragma mark - 错误
+static const char MJErrorKey = '\0';
++ (NSError *)mj_error
+{
+    return objc_getAssociatedObject(self, &MJErrorKey);
+}
+
++ (void)setMj_error:(NSError *)error
+{
+    objc_setAssociatedObject(self, &MJErrorKey, error, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+}
+
+#pragma mark - 模型 -> 字典时的参考
+/** 模型转字典时,字典的key是否参考replacedKeyFromPropertyName等方法(父类设置了,子类也会继承下来) */
+static const char MJReferenceReplacedKeyWhenCreatingKeyValuesKey = '\0';
+
++ (void)mj_referenceReplacedKeyWhenCreatingKeyValues:(BOOL)reference
+{
+    objc_setAssociatedObject(self, &MJReferenceReplacedKeyWhenCreatingKeyValuesKey, @(reference), OBJC_ASSOCIATION_ASSIGN);
+}
+
++ (BOOL)mj_isReferenceReplacedKeyWhenCreatingKeyValues
+{
+    __block id value = objc_getAssociatedObject(self, &MJReferenceReplacedKeyWhenCreatingKeyValuesKey);
+    if (!value) {
+        [self mj_enumerateAllClasses:^(__unsafe_unretained Class c, BOOL *stop) {
+            value = objc_getAssociatedObject(c, &MJReferenceReplacedKeyWhenCreatingKeyValuesKey);
+            
+            if (value) *stop = YES;
+        }];
+    }
+    return [value boolValue];
+}
+
+#pragma mark - --常用的对象--
++ (void)load
+{
+    // 默认设置
+    [self mj_referenceReplacedKeyWhenCreatingKeyValues:YES];
+}
+
+#pragma mark - --公共方法--
+#pragma mark - 字典 -> 模型
+- (instancetype)mj_setKeyValues:(id)keyValues
+{
+    return [self mj_setKeyValues:keyValues context:nil];
+}
+
+/**
+ 核心代码:
+ */
+- (instancetype)mj_setKeyValues:(id)keyValues context:(NSManagedObjectContext *)context
+{
+    // 获得JSON对象
+    keyValues = [keyValues mj_JSONObject];
+    
+    MJExtensionAssertError([keyValues isKindOfClass:[NSDictionary class]], self, [self class], @"keyValues参数不是一个字典");
+    
+    Class clazz = [self class];
+    NSArray *allowedPropertyNames = [clazz mj_totalAllowedPropertyNames];
+    NSArray *ignoredPropertyNames = [clazz mj_totalIgnoredPropertyNames];
+    
+    NSLocale *numberLocale = nil;
+    if ([self.class respondsToSelector:@selector(mj_numberLocale)]) {
+        numberLocale = self.class.mj_numberLocale;
+    }
+    
+    //通过封装的方法回调一个通过运行时编写的,用于返回属性列表的方法。
+    [clazz mj_enumerateProperties:^(MJProperty *property, BOOL *stop) {
+        @try {
+            // 0.检测是否被忽略
+            if (allowedPropertyNames.count && ![allowedPropertyNames containsObject:property.name]) return;
+            if ([ignoredPropertyNames containsObject:property.name]) return;
+            
+            // 1.取出属性值
+            id value;
+            NSArray *propertyKeyses = [property propertyKeysForClass:clazz];
+            for (NSArray *propertyKeys in propertyKeyses) {
+                value = keyValues;
+                for (MJPropertyKey *propertyKey in propertyKeys) {
+                    value = [propertyKey valueInObject:value];
+                }
+                if (value) break;
+            }
+            
+            // 值的过滤
+            id newValue = [clazz mj_getNewValueFromObject:self oldValue:value property:property];
+            if (newValue != value) { // 有过滤后的新值
+                [property setValue:newValue forObject:self];
+                return;
+            }
+            
+            // 如果没有值,就直接返回
+            if (!value || value == [NSNull null]) return;
+            
+            // 2.复杂处理
+            MJPropertyType *type = property.type;
+            Class propertyClass = type.typeClass;
+            Class objectClass = [property objectClassInArrayForClass:[self class]];
+            
+            // 不可变 -> 可变处理
+            if (propertyClass == [NSMutableArray class] && [value isKindOfClass:[NSArray class]]) {
+                value = [NSMutableArray arrayWithArray:value];
+            } else if (propertyClass == [NSMutableDictionary class] && [value isKindOfClass:[NSDictionary class]]) {
+                value = [NSMutableDictionary dictionaryWithDictionary:value];
+            } else if (propertyClass == [NSMutableString class] && [value isKindOfClass:[NSString class]]) {
+                value = [NSMutableString stringWithString:value];
+            } else if (propertyClass == [NSMutableData class] && [value isKindOfClass:[NSData class]]) {
+                value = [NSMutableData dataWithData:value];
+            }
+            
+            if (!type.isFromFoundation && propertyClass) { // 模型属性
+                value = [propertyClass mj_objectWithKeyValues:value context:context];
+            } else if (objectClass) {
+                if (objectClass == [NSURL class] && [value isKindOfClass:[NSArray class]]) {
+                    // string array -> url array
+                    NSMutableArray *urlArray = [NSMutableArray array];
+                    for (NSString *string in value) {
+                        if (![string isKindOfClass:[NSString class]]) continue;
+                        [urlArray addObject:string.mj_url];
+                    }
+                    value = urlArray;
+                } else { // 字典数组-->模型数组
+                    value = [objectClass mj_objectArrayWithKeyValuesArray:value context:context];
+                }
+            } else if (propertyClass == [NSString class]) {
+                if ([value isKindOfClass:[NSNumber class]]) {
+                    // NSNumber -> NSString
+                    value = [value description];
+                } else if ([value isKindOfClass:[NSURL class]]) {
+                    // NSURL -> NSString
+                    value = [value absoluteString];
+                }
+            } else if ([value isKindOfClass:[NSString class]]) {
+                if (propertyClass == [NSURL class]) {
+                    // NSString -> NSURL
+                    // 字符串转码
+                    value = [value mj_url];
+                } else if (type.isNumberType) {
+                    NSString *oldValue = value;
+                    
+                    // NSString -> NSDecimalNumber, 使用 DecimalNumber 来转换数字, 避免丢失精度以及溢出
+                    NSDecimalNumber *decimalValue = [NSDecimalNumber decimalNumberWithString:oldValue
+                                                                                      locale:numberLocale];
+                    
+                    // 检查特殊情况
+                    if (decimalValue == NSDecimalNumber.notANumber) {
+                        value = @(0);
+                    }else if (propertyClass != [NSDecimalNumber class]) {
+                        value = [decimalValue mj_standardValueWithTypeCode:type.code];
+                    } else {
+                        value = decimalValue;
+                    }
+                    
+                    // 如果是BOOL
+                    if (type.isBoolType) {
+                        // 字符串转BOOL(字符串没有charValue方法)
+                        // 系统会调用字符串的charValue转为BOOL类型
+                        NSString *lower = [oldValue lowercaseString];
+                        if ([lower isEqualToString:@"yes"] || [lower isEqualToString:@"true"]) {
+                            value = @YES;
+                        } else if ([lower isEqualToString:@"no"] || [lower isEqualToString:@"false"]) {
+                            value = @NO;
+                        }
+                    }
+                }
+            } else if ([value isKindOfClass:[NSNumber class]] && propertyClass == [NSDecimalNumber class]){
+                // 过滤 NSDecimalNumber类型
+                if (![value isKindOfClass:[NSDecimalNumber class]]) {
+                    value = [NSDecimalNumber decimalNumberWithDecimal:[((NSNumber *)value) decimalValue]];
+                }
+            }
+            
+            // 经过转换后, 最终检查 value 与 property 是否匹配
+            if (propertyClass && ![value isKindOfClass:propertyClass]) {
+                value = nil;
+            }
+            
+            // 3.赋值
+            [property setValue:value forObject:self];
+        } @catch (NSException *exception) {
+            MJExtensionBuildError([self class], exception.reason);
+            MJExtensionLog(@"%@", exception);
+#ifdef DEBUG
+            [exception raise];
+#endif
+        }
+    }];
+    
+    // 转换完毕
+    if ([self respondsToSelector:@selector(mj_didConvertToObjectWithKeyValues:)]) {
+        [self mj_didConvertToObjectWithKeyValues:keyValues];
+    }
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored"-Wdeprecated-declarations"
+    if ([self respondsToSelector:@selector(mj_keyValuesDidFinishConvertingToObject)]) {
+        [self mj_keyValuesDidFinishConvertingToObject];
+    }
+    if ([self respondsToSelector:@selector(mj_keyValuesDidFinishConvertingToObject:)]) {
+        [self mj_keyValuesDidFinishConvertingToObject:keyValues];
+    }
+#pragma clang diagnostic pop
+    return self;
+}
+
++ (instancetype)mj_objectWithKeyValues:(id)keyValues
+{
+    return [self mj_objectWithKeyValues:keyValues context:nil];
+}
+
++ (instancetype)mj_objectWithKeyValues:(id)keyValues context:(NSManagedObjectContext *)context
+{
+    // 获得JSON对象
+    keyValues = [keyValues mj_JSONObject];
+    MJExtensionAssertError([keyValues isKindOfClass:[NSDictionary class]], nil, [self class], @"keyValues参数不是一个字典");
+    
+    if ([self isSubclassOfClass:[NSManagedObject class]] && context) {
+        NSString *entityName = [(NSManagedObject *)self entity].name;
+        return [[NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:context] mj_setKeyValues:keyValues context:context];
+    }
+    return [[[self alloc] init] mj_setKeyValues:keyValues];
+}
+
++ (instancetype)mj_objectWithFilename:(NSString *)filename
+{
+    MJExtensionAssertError(filename != nil, nil, [self class], @"filename参数为nil");
+    
+    return [self mj_objectWithFile:[[NSBundle mainBundle] pathForResource:filename ofType:nil]];
+}
+
++ (instancetype)mj_objectWithFile:(NSString *)file
+{
+    MJExtensionAssertError(file != nil, nil, [self class], @"file参数为nil");
+    
+    return [self mj_objectWithKeyValues:[NSDictionary dictionaryWithContentsOfFile:file]];
+}
+
+#pragma mark - 字典数组 -> 模型数组
++ (NSMutableArray *)mj_objectArrayWithKeyValuesArray:(NSArray *)keyValuesArray
+{
+    return [self mj_objectArrayWithKeyValuesArray:keyValuesArray context:nil];
+}
+
++ (NSMutableArray *)mj_objectArrayWithKeyValuesArray:(id)keyValuesArray context:(NSManagedObjectContext *)context
+{
+    // 如果是JSON字符串
+    keyValuesArray = [keyValuesArray mj_JSONObject];
+    
+    // 1.判断真实性
+    MJExtensionAssertError([keyValuesArray isKindOfClass:[NSArray class]], nil, [self class], @"keyValuesArray参数不是一个数组");
+    
+    // 如果数组里面放的是NSString、NSNumber等数据
+    if ([MJFoundation isClassFromFoundation:self]) return [NSMutableArray arrayWithArray:keyValuesArray];
+    
+
+    // 2.创建数组
+    NSMutableArray *modelArray = [NSMutableArray array];
+    
+    // 3.遍历
+    for (NSDictionary *keyValues in keyValuesArray) {
+        if ([keyValues isKindOfClass:[NSArray class]]){
+            [modelArray addObject:[self mj_objectArrayWithKeyValuesArray:keyValues context:context]];
+        } else {
+            id model = [self mj_objectWithKeyValues:keyValues context:context];
+            if (model) [modelArray addObject:model];
+        }
+    }
+    
+    return modelArray;
+}
+
++ (NSMutableArray *)mj_objectArrayWithFilename:(NSString *)filename
+{
+    MJExtensionAssertError(filename != nil, nil, [self class], @"filename参数为nil");
+    
+    return [self mj_objectArrayWithFile:[[NSBundle mainBundle] pathForResource:filename ofType:nil]];
+}
+
++ (NSMutableArray *)mj_objectArrayWithFile:(NSString *)file
+{
+    MJExtensionAssertError(file != nil, nil, [self class], @"file参数为nil");
+    
+    return [self mj_objectArrayWithKeyValuesArray:[NSArray arrayWithContentsOfFile:file]];
+}
+
+#pragma mark - 模型 -> 字典
+- (NSMutableDictionary *)mj_keyValues
+{
+    return [self mj_keyValuesWithKeys:nil ignoredKeys:nil];
+}
+
+- (NSMutableDictionary *)mj_keyValuesWithKeys:(NSArray *)keys
+{
+    return [self mj_keyValuesWithKeys:keys ignoredKeys:nil];
+}
+
+- (NSMutableDictionary *)mj_keyValuesWithIgnoredKeys:(NSArray *)ignoredKeys
+{
+    return [self mj_keyValuesWithKeys:nil ignoredKeys:ignoredKeys];
+}
+
+- (NSMutableDictionary *)mj_keyValuesWithKeys:(NSArray *)keys ignoredKeys:(NSArray *)ignoredKeys
+{
+    // 如果自己不是模型类, 那就返回自己
+    // 模型类过滤掉 NSNull
+    // 唯一一个不返回自己的
+    if ([self isMemberOfClass:NSNull.class]) { return nil; }
+    // 这里虽然返回了自己, 但是其实是有报错信息的.
+    // TODO: 报错机制不好, 需要重做
+    MJExtensionAssertError(![MJFoundation isClassFromFoundation:[self class]], (NSMutableDictionary *)self, [self class], @"不是自定义的模型类")
+    
+    id keyValues = [NSMutableDictionary dictionary];
+    
+    Class clazz = [self class];
+    NSArray *allowedPropertyNames = [clazz mj_totalAllowedPropertyNames];
+    NSArray *ignoredPropertyNames = [clazz mj_totalIgnoredPropertyNames];
+    
+    [clazz mj_enumerateProperties:^(MJProperty *property, BOOL *stop) {
+        @try {
+            // 0.检测是否被忽略
+            if (allowedPropertyNames.count && ![allowedPropertyNames containsObject:property.name]) return;
+            if ([ignoredPropertyNames containsObject:property.name]) return;
+            if (keys.count && ![keys containsObject:property.name]) return;
+            if ([ignoredKeys containsObject:property.name]) return;
+            
+            // 1.取出属性值
+            id value = [property valueForObject:self];
+            if (!value) return;
+            
+            // 2.如果是模型属性
+            MJPropertyType *type = property.type;
+            Class propertyClass = type.typeClass;
+            if (!type.isFromFoundation && propertyClass) {
+                value = [value mj_keyValues];
+            } else if ([value isKindOfClass:[NSArray class]]) {
+                // 3.处理数组里面有模型的情况
+                value = [NSObject mj_keyValuesArrayWithObjectArray:value];
+            } else if (propertyClass == [NSURL class]) {
+                value = [value absoluteString];
+            }
+            
+            // 4.赋值
+            if ([clazz mj_isReferenceReplacedKeyWhenCreatingKeyValues]) {
+                NSArray *propertyKeys = [[property propertyKeysForClass:clazz] firstObject];
+                NSUInteger keyCount = propertyKeys.count;
+                // 创建字典
+                __block id innerContainer = keyValues;
+                [propertyKeys enumerateObjectsUsingBlock:^(MJPropertyKey *propertyKey, NSUInteger idx, BOOL *stop) {
+                    // 下一个属性
+                    MJPropertyKey *nextPropertyKey = nil;
+                    if (idx != keyCount - 1) {
+                        nextPropertyKey = propertyKeys[idx + 1];
+                    }
+                    
+                    if (nextPropertyKey) { // 不是最后一个key
+                        // 当前propertyKey对应的字典或者数组
+                        id tempInnerContainer = [propertyKey valueInObject:innerContainer];
+                        if (tempInnerContainer == nil || [tempInnerContainer isKindOfClass:[NSNull class]]) {
+                            if (nextPropertyKey.type == MJPropertyKeyTypeDictionary) {
+                                tempInnerContainer = [NSMutableDictionary dictionary];
+                            } else {
+                                tempInnerContainer = [NSMutableArray array];
+                            }
+                            if (propertyKey.type == MJPropertyKeyTypeDictionary) {
+                                innerContainer[propertyKey.name] = tempInnerContainer;
+                            } else {
+                                innerContainer[propertyKey.name.intValue] = tempInnerContainer;
+                            }
+                        }
+                        
+                        if ([tempInnerContainer isKindOfClass:[NSMutableArray class]]) {
+                            NSMutableArray *tempInnerContainerArray = tempInnerContainer;
+                            int index = nextPropertyKey.name.intValue;
+                            while (tempInnerContainerArray.count < index + 1) {
+                                [tempInnerContainerArray addObject:[NSNull null]];
+                            }
+                        }
+                        
+                        innerContainer = tempInnerContainer;
+                    } else { // 最后一个key
+                        if (propertyKey.type == MJPropertyKeyTypeDictionary) {
+                            innerContainer[propertyKey.name] = value;
+                        } else {
+                            innerContainer[propertyKey.name.intValue] = value;
+                        }
+                    }
+                }];
+            } else {
+                keyValues[property.name] = value;
+            }
+        } @catch (NSException *exception) {
+            MJExtensionBuildError([self class], exception.reason);
+            MJExtensionLog(@"%@", exception);
+#ifdef DEBUG
+            [exception raise];
+#endif
+        }
+    }];
+    
+    // 转换完毕
+    if ([self respondsToSelector:@selector(mj_objectDidConvertToKeyValues:)]) {
+        [self mj_objectDidConvertToKeyValues:keyValues];
+    }
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored"-Wdeprecated-declarations"
+    if ([self respondsToSelector:@selector(mj_objectDidFinishConvertingToKeyValues)]) {
+        [self mj_objectDidFinishConvertingToKeyValues];
+    }
+#pragma clang diagnostic pop
+    
+    return keyValues;
+}
+#pragma mark - 模型数组 -> 字典数组
++ (NSMutableArray *)mj_keyValuesArrayWithObjectArray:(NSArray *)objectArray
+{
+    return [self mj_keyValuesArrayWithObjectArray:objectArray keys:nil ignoredKeys:nil];
+}
+
++ (NSMutableArray *)mj_keyValuesArrayWithObjectArray:(NSArray *)objectArray keys:(NSArray *)keys
+{
+    return [self mj_keyValuesArrayWithObjectArray:objectArray keys:keys ignoredKeys:nil];
+}
+
++ (NSMutableArray *)mj_keyValuesArrayWithObjectArray:(NSArray *)objectArray ignoredKeys:(NSArray *)ignoredKeys
+{
+    return [self mj_keyValuesArrayWithObjectArray:objectArray keys:nil ignoredKeys:ignoredKeys];
+}
+
++ (NSMutableArray *)mj_keyValuesArrayWithObjectArray:(NSArray *)objectArray keys:(NSArray *)keys ignoredKeys:(NSArray *)ignoredKeys
+{
+    // 0.判断真实性
+    MJExtensionAssertError([objectArray isKindOfClass:[NSArray class]], nil, [self class], @"objectArray参数不是一个数组");
+    
+    // 1.创建数组
+    NSMutableArray *keyValuesArray = [NSMutableArray array];
+    for (id object in objectArray) {
+        if (keys) {
+            id convertedObj = [object mj_keyValuesWithKeys:keys];
+            if (!convertedObj) { continue; }
+            [keyValuesArray addObject:convertedObj];
+        } else {
+            id convertedObj = [object mj_keyValuesWithIgnoredKeys:ignoredKeys];
+            if (!convertedObj) { continue; }
+            [keyValuesArray addObject:convertedObj];
+        }
+    }
+    return keyValuesArray;
+}
+
+#pragma mark - 转换为JSON
+- (NSData *)mj_JSONData
+{
+    if ([self isKindOfClass:[NSString class]]) {
+        return [((NSString *)self) dataUsingEncoding:NSUTF8StringEncoding];
+    } else if ([self isKindOfClass:[NSData class]]) {
+        return (NSData *)self;
+    }
+    
+    return [NSJSONSerialization dataWithJSONObject:[self mj_JSONObject] options:kNilOptions error:nil];
+}
+
+- (id)mj_JSONObject
+{
+    if ([self isKindOfClass:[NSString class]]) {
+        return [NSJSONSerialization JSONObjectWithData:[((NSString *)self) dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
+    } else if ([self isKindOfClass:[NSData class]]) {
+        return [NSJSONSerialization JSONObjectWithData:(NSData *)self options:kNilOptions error:nil];
+    }
+    
+    return self.mj_keyValues;
+}
+
+- (NSString *)mj_JSONString
+{
+    if ([self isKindOfClass:[NSString class]]) {
+        return (NSString *)self;
+    } else if ([self isKindOfClass:[NSData class]]) {
+        return [[NSString alloc] initWithData:(NSData *)self encoding:NSUTF8StringEncoding];
+    }
+    
+    return [[NSString alloc] initWithData:[self mj_JSONData] encoding:NSUTF8StringEncoding];
+}
+
+@end

+ 70 - 0
Pods/MJExtension/MJExtension/NSObject+MJProperty.h

@@ -0,0 +1,70 @@
+//
+//  NSObject+MJProperty.h
+//  MJExtensionExample
+//
+//  Created by MJ Lee on 15/4/17.
+//  Copyright (c) 2015年 小码哥. All rights reserved.
+//
+
+#import <Foundation/Foundation.h>
+#import "MJExtensionConst.h"
+
+@class MJProperty;
+
+/**
+ *  遍历成员变量用的block
+ *
+ *  @param property 成员的包装对象
+ *  @param stop   YES代表停止遍历,NO代表继续遍历
+ */
+typedef void (^MJPropertiesEnumeration)(MJProperty *property, BOOL *stop);
+
+/** 将属性名换为其他key去字典中取值 */
+typedef NSDictionary * (^MJReplacedKeyFromPropertyName)(void);
+typedef id (^MJReplacedKeyFromPropertyName121)(NSString *propertyName);
+/** 数组中需要转换的模型类 */
+typedef NSDictionary * (^MJObjectClassInArray)(void);
+/** 用于过滤字典中的值 */
+typedef id (^MJNewValueFromOldValue)(id object, id oldValue, MJProperty *property);
+
+/**
+ * 成员属性相关的扩展
+ */
+@interface NSObject (MJProperty)
+#pragma mark - 遍历
+/**
+ *  遍历所有的成员
+ */
++ (void)mj_enumerateProperties:(MJPropertiesEnumeration)enumeration;
+
+#pragma mark - 新值配置
+/**
+ *  用于过滤字典中的值
+ *
+ *  @param newValueFormOldValue 用于过滤字典中的值
+ */
++ (void)mj_setupNewValueFromOldValue:(MJNewValueFromOldValue)newValueFormOldValue;
++ (id)mj_getNewValueFromObject:(__unsafe_unretained id)object oldValue:(__unsafe_unretained id)oldValue property:(__unsafe_unretained MJProperty *)property;
+
+#pragma mark - key配置
+/**
+ *  将属性名换为其他key去字典中取值
+ *
+ *  @param replacedKeyFromPropertyName 将属性名换为其他key去字典中取值
+ */
++ (void)mj_setupReplacedKeyFromPropertyName:(MJReplacedKeyFromPropertyName)replacedKeyFromPropertyName;
+/**
+ *  将属性名换为其他key去字典中取值
+ *
+ *  @param replacedKeyFromPropertyName121 将属性名换为其他key去字典中取值
+ */
++ (void)mj_setupReplacedKeyFromPropertyName121:(MJReplacedKeyFromPropertyName121)replacedKeyFromPropertyName121;
+
+#pragma mark - array model class配置
+/**
+ *  数组中需要转换的模型类
+ *
+ *  @param objectClassInArray          数组中需要转换的模型类
+ */
++ (void)mj_setupObjectClassInArray:(MJObjectClassInArray)objectClassInArray;
+@end

+ 240 - 0
Pods/MJExtension/MJExtension/NSObject+MJProperty.m

@@ -0,0 +1,240 @@
+//
+//  NSObject+MJProperty.m
+//  MJExtensionExample
+//
+//  Created by MJ Lee on 15/4/17.
+//  Copyright (c) 2015年 小码哥. All rights reserved.
+//
+
+#import "NSObject+MJProperty.h"
+#import "NSObject+MJKeyValue.h"
+#import "NSObject+MJCoding.h"
+#import "NSObject+MJClass.h"
+#import "MJProperty.h"
+#import "MJFoundation.h"
+#import <objc/runtime.h>
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wundeclared-selector"
+#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
+
+static const char MJReplacedKeyFromPropertyNameKey = '\0';
+static const char MJReplacedKeyFromPropertyName121Key = '\0';
+static const char MJNewValueFromOldValueKey = '\0';
+static const char MJObjectClassInArrayKey = '\0';
+
+static const char MJCachedPropertiesKey = '\0';
+
+dispatch_semaphore_t mje_signalSemaphore;
+dispatch_once_t mje_onceTokenSemaphore;
+
+@implementation NSObject (Property)
+
++ (NSMutableDictionary *)mj_propertyDictForKey:(const void *)key
+{
+    static NSMutableDictionary *replacedKeyFromPropertyNameDict;
+    static NSMutableDictionary *replacedKeyFromPropertyName121Dict;
+    static NSMutableDictionary *newValueFromOldValueDict;
+    static NSMutableDictionary *objectClassInArrayDict;
+    static NSMutableDictionary *cachedPropertiesDict;
+    
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        replacedKeyFromPropertyNameDict = [NSMutableDictionary dictionary];
+        replacedKeyFromPropertyName121Dict = [NSMutableDictionary dictionary];
+        newValueFromOldValueDict = [NSMutableDictionary dictionary];
+        objectClassInArrayDict = [NSMutableDictionary dictionary];
+        cachedPropertiesDict = [NSMutableDictionary dictionary];
+    });
+    
+    if (key == &MJReplacedKeyFromPropertyNameKey) return replacedKeyFromPropertyNameDict;
+    if (key == &MJReplacedKeyFromPropertyName121Key) return replacedKeyFromPropertyName121Dict;
+    if (key == &MJNewValueFromOldValueKey) return newValueFromOldValueDict;
+    if (key == &MJObjectClassInArrayKey) return objectClassInArrayDict;
+    if (key == &MJCachedPropertiesKey) return cachedPropertiesDict;
+    return nil;
+}
+
+#pragma mark - --私有方法--
++ (id)mj_propertyKey:(NSString *)propertyName
+{
+    MJExtensionAssertParamNotNil2(propertyName, nil);
+    
+    __block id key = nil;
+    // 查看有没有需要替换的key
+    if ([self respondsToSelector:@selector(mj_replacedKeyFromPropertyName121:)]) {
+        key = [self mj_replacedKeyFromPropertyName121:propertyName];
+    }
+    
+    // 调用block
+    if (!key) {
+        [self mj_enumerateAllClasses:^(__unsafe_unretained Class c, BOOL *stop) {
+            MJReplacedKeyFromPropertyName121 block = objc_getAssociatedObject(c, &MJReplacedKeyFromPropertyName121Key);
+            if (block) {
+                key = block(propertyName);
+            }
+            if (key) *stop = YES;
+        }];
+    }
+    
+    // 查看有没有需要替换的key
+    if ((!key || [key isEqual:propertyName]) && [self respondsToSelector:@selector(mj_replacedKeyFromPropertyName)]) {
+        key = [self mj_replacedKeyFromPropertyName][propertyName];
+    }
+    
+    if (!key || [key isEqual:propertyName]) {
+        [self mj_enumerateAllClasses:^(__unsafe_unretained Class c, BOOL *stop) {
+            NSDictionary *dict = objc_getAssociatedObject(c, &MJReplacedKeyFromPropertyNameKey);
+            if (dict) {
+                key = dict[propertyName];
+            }
+            if (key && ![key isEqual:propertyName]) *stop = YES;
+        }];
+    }
+    
+    // 2.用属性名作为key
+    if (!key) key = propertyName;
+    
+    return key;
+}
+
++ (Class)mj_propertyObjectClassInArray:(NSString *)propertyName
+{
+    __block id clazz = nil;
+    if ([self respondsToSelector:@selector(mj_objectClassInArray)]) {
+        clazz = [self mj_objectClassInArray][propertyName];
+    }
+    
+    if (!clazz) {
+        [self mj_enumerateAllClasses:^(__unsafe_unretained Class c, BOOL *stop) {
+            NSDictionary *dict = objc_getAssociatedObject(c, &MJObjectClassInArrayKey);
+            if (dict) {
+                clazz = dict[propertyName];
+            }
+            if (clazz) *stop = YES;
+        }];
+    }
+    
+    // 如果是NSString类型
+    if ([clazz isKindOfClass:[NSString class]]) {
+        clazz = NSClassFromString(clazz);
+    }
+    return clazz;
+}
+
+#pragma mark - --公共方法--
++ (void)mj_enumerateProperties:(MJPropertiesEnumeration)enumeration
+{
+    // 获得成员变量
+    NSArray *cachedProperties = [self mj_properties];
+    // 遍历成员变量
+    BOOL stop = NO;
+    for (MJProperty *property in cachedProperties) {
+        enumeration(property, &stop);
+        if (stop) break;
+    }
+}
+
+#pragma mark - 公共方法
++ (NSArray *)mj_properties
+{
+    MJExtensionSemaphoreCreate
+    MJ_LOCK(mje_signalSemaphore);
+    NSMutableDictionary *cachedInfo = [self mj_propertyDictForKey:&MJCachedPropertiesKey];
+    NSMutableArray *cachedProperties = cachedInfo[NSStringFromClass(self)];
+    if (cachedProperties == nil) {
+        cachedProperties = [NSMutableArray array];
+        
+        [self mj_enumerateClasses:^(__unsafe_unretained Class c, BOOL *stop) {
+            // 1.获得所有的成员变量
+            unsigned int outCount = 0;
+            objc_property_t *properties = class_copyPropertyList(c, &outCount);
+            
+            // 2.遍历每一个成员变量
+            for (unsigned int i = 0; i<outCount; i++) {
+                MJProperty *property = [MJProperty cachedPropertyWithProperty:properties[i]];
+                // 过滤掉Foundation框架类里面的属性
+                if ([MJFoundation isClassFromFoundation:property.srcClass]) continue;
+                // 过滤掉`hash`, `superclass`, `description`, `debugDescription`
+                if ([MJFoundation isFromNSObjectProtocolProperty:property.name]) continue;
+                
+                property.srcClass = c;
+                [property setOriginKey:[self mj_propertyKey:property.name] forClass:self];
+                [property setObjectClassInArray:[self mj_propertyObjectClassInArray:property.name] forClass:self];
+                [cachedProperties addObject:property];
+            }
+            
+            // 3.释放内存
+            free(properties);
+        }];
+        
+        cachedInfo[NSStringFromClass(self)] = cachedProperties;
+    }
+    NSArray *properties = [cachedProperties copy];
+    MJ_UNLOCK(mje_signalSemaphore);
+    
+    return properties;
+}
+
+#pragma mark - 新值配置
++ (void)mj_setupNewValueFromOldValue:(MJNewValueFromOldValue)newValueFormOldValue {
+    MJExtensionSemaphoreCreate
+    MJ_LOCK(mje_signalSemaphore);
+    objc_setAssociatedObject(self, &MJNewValueFromOldValueKey, newValueFormOldValue, OBJC_ASSOCIATION_COPY_NONATOMIC);
+    MJ_UNLOCK(mje_signalSemaphore);
+}
+
++ (id)mj_getNewValueFromObject:(__unsafe_unretained id)object oldValue:(__unsafe_unretained id)oldValue property:(MJProperty *__unsafe_unretained)property{
+    // 如果有实现方法
+    if ([object respondsToSelector:@selector(mj_newValueFromOldValue:property:)]) {
+        return [object mj_newValueFromOldValue:oldValue property:property];
+    }
+    
+    MJExtensionSemaphoreCreate
+    MJ_LOCK(mje_signalSemaphore);
+    // 查看静态设置
+    __block id newValue = oldValue;
+    [self mj_enumerateAllClasses:^(__unsafe_unretained Class c, BOOL *stop) {
+        MJNewValueFromOldValue block = objc_getAssociatedObject(c, &MJNewValueFromOldValueKey);
+        if (block) {
+            newValue = block(object, oldValue, property);
+            *stop = YES;
+        }
+    }];
+    MJ_UNLOCK(mje_signalSemaphore);
+    return newValue;
+}
+
++ (void)mj_removeCachedProperties {
+    MJExtensionSemaphoreCreate
+    MJ_LOCK(mje_signalSemaphore);
+    [[self mj_propertyDictForKey:&MJCachedPropertiesKey] removeAllObjects];
+    MJ_UNLOCK(mje_signalSemaphore);
+}
+
+#pragma mark - array model class配置
++ (void)mj_setupObjectClassInArray:(MJObjectClassInArray)objectClassInArray
+{
+    [self mj_setupBlockReturnValue:objectClassInArray key:&MJObjectClassInArrayKey];
+    
+    [self mj_removeCachedProperties];
+}
+
+#pragma mark - key配置
+
++ (void)mj_setupReplacedKeyFromPropertyName:(MJReplacedKeyFromPropertyName)replacedKeyFromPropertyName {
+    [self mj_setupBlockReturnValue:replacedKeyFromPropertyName key:&MJReplacedKeyFromPropertyNameKey];
+    
+    [self mj_removeCachedProperties];
+}
+
++ (void)mj_setupReplacedKeyFromPropertyName121:(MJReplacedKeyFromPropertyName121)replacedKeyFromPropertyName121 {
+    MJExtensionSemaphoreCreate
+    MJ_LOCK(mje_signalSemaphore);
+    objc_setAssociatedObject(self, &MJReplacedKeyFromPropertyName121Key, replacedKeyFromPropertyName121, OBJC_ASSOCIATION_COPY_NONATOMIC);
+    
+    [[self mj_propertyDictForKey:&MJCachedPropertiesKey] removeAllObjects];
+    MJ_UNLOCK(mje_signalSemaphore);
+}
+@end
+#pragma clang diagnostic pop

+ 33 - 0
Pods/MJExtension/MJExtension/NSString+MJExtension.h

@@ -0,0 +1,33 @@
+//
+//  NSString+MJExtension.h
+//  MJExtensionExample
+//
+//  Created by MJ Lee on 15/6/7.
+//  Copyright (c) 2015年 小码哥. All rights reserved.
+//
+
+#import <Foundation/Foundation.h>
+#import "MJExtensionConst.h"
+
+@interface NSString (MJExtension)
+/**
+ *  驼峰转下划线(loveYou -> love_you)
+ */
+- (NSString *)mj_underlineFromCamel;
+/**
+ *  下划线转驼峰(love_you -> loveYou)
+ */
+- (NSString *)mj_camelFromUnderline;
+/**
+ * 首字母变大写
+ */
+- (NSString *)mj_firstCharUpper;
+/**
+ * 首字母变小写
+ */
+- (NSString *)mj_firstCharLower;
+
+- (BOOL)mj_isPureInt;
+
+- (NSURL *)mj_url;
+@end

+ 80 - 0
Pods/MJExtension/MJExtension/NSString+MJExtension.m

@@ -0,0 +1,80 @@
+//
+//  NSString+MJExtension.m
+//  MJExtensionExample
+//
+//  Created by MJ Lee on 15/6/7.
+//  Copyright (c) 2015年 小码哥. All rights reserved.
+//
+
+#import "NSString+MJExtension.h"
+
+@implementation NSString (MJExtension)
+- (NSString *)mj_underlineFromCamel
+{
+    if (self.length == 0) return self;
+    NSMutableString *string = [NSMutableString string];
+    for (NSUInteger i = 0; i<self.length; i++) {
+        unichar c = [self characterAtIndex:i];
+        NSString *cString = [NSString stringWithFormat:@"%c", c];
+        NSString *cStringLower = [cString lowercaseString];
+        if ([cString isEqualToString:cStringLower]) {
+            [string appendString:cStringLower];
+        } else {
+            [string appendString:@"_"];
+            [string appendString:cStringLower];
+        }
+    }
+    return string;
+}
+
+- (NSString *)mj_camelFromUnderline
+{
+    if (self.length == 0) return self;
+    NSMutableString *string = [NSMutableString string];
+    NSArray *cmps = [self componentsSeparatedByString:@"_"];
+    for (NSUInteger i = 0; i<cmps.count; i++) {
+        NSString *cmp = cmps[i];
+        if (i && cmp.length) {
+            [string appendString:[NSString stringWithFormat:@"%c", [cmp characterAtIndex:0]].uppercaseString];
+            if (cmp.length >= 2) [string appendString:[cmp substringFromIndex:1]];
+        } else {
+            [string appendString:cmp];
+        }
+    }
+    return string;
+}
+
+- (NSString *)mj_firstCharLower
+{
+    if (self.length == 0) return self;
+    NSMutableString *string = [NSMutableString string];
+    [string appendString:[NSString stringWithFormat:@"%c", [self characterAtIndex:0]].lowercaseString];
+    if (self.length >= 2) [string appendString:[self substringFromIndex:1]];
+    return string;
+}
+
+- (NSString *)mj_firstCharUpper
+{
+    if (self.length == 0) return self;
+    NSMutableString *string = [NSMutableString string];
+    [string appendString:[NSString stringWithFormat:@"%c", [self characterAtIndex:0]].uppercaseString];
+    if (self.length >= 2) [string appendString:[self substringFromIndex:1]];
+    return string;
+}
+
+- (BOOL)mj_isPureInt
+{
+    NSScanner *scan = [NSScanner scannerWithString:self];
+    int val;
+    return [scan scanInt:&val] && [scan isAtEnd];
+}
+
+- (NSURL *)mj_url
+{
+//    [self stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"!$&'()*+,-./:;=?@_~%#[]"]];
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored"-Wdeprecated-declarations"
+    return [NSURL URLWithString:(NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]", NULL,kCFStringEncodingUTF8))];
+#pragma clang diagnostic pop
+}
+@end

+ 637 - 0
Pods/MJExtension/README.md

@@ -0,0 +1,637 @@
+MJExtension
+===
+[![SPM supported](https://img.shields.io/badge/SPM-supported-4BC51D.svg?style=flat)](https://github.com/apple/swift-package-manager)
+[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)
+[![podversion](https://img.shields.io/cocoapods/v/MJExtension.svg)](https://cocoapods.org/pods/MJExtension)
+![Platform](https://img.shields.io/cocoapods/p/MJExtension.svg?style=flat)
+
+- A fast, convenient and nonintrusive conversion framework between JSON and model.
+- 转换速度快、使用简单方便的字典转模型框架
+
+[📜✍🏻**Release Notes**: more details](https://github.com/CoderMJLee/MJExtension/releases)
+
+## Contents
+
+* [Getting Started 【开始使用】](#Getting_Started)
+	* [Features 【能做什么】](#Features)
+	* [Installation 【安装】](#Installation)
+* [Examples 【示例】](#Examples)
+  * [Usage in Swift](#usage_in_swift)
+  * [JSON -> Model](#JSON_Model)
+  * [JSONString -> Model](#JSONString_Model)
+  * [Model contains model](#Model_contains_model)
+  * [Model contains model-array](#Model_contains_model_array)
+  * [Model name - JSON key mapping](#Model_name_JSON_key_mapping)
+  * [JSON array -> model array](#JSON_array_model_array)
+  * [Model -> JSON](#Model_JSON)
+  * [Model array -> JSON array](#Model_array_JSON_array)
+  * [Core Data](#Core_Data)
+  * [Coding](#Coding)
+  * [Secure Coding](#SecureCoding)
+  * [Camel -> underline](#Camel_underline)
+  * [NSString -> NSDate, nil -> @""](#NSString_NSDate)
+  * [NSDate -> NSString](#NSDate_NSString)
+  * [More use cases](#More_use_cases)
+
+---
+
+## <a id="Getting_Started"></a> Getting Started【开始使用】
+
+### <a id="Features"></a> Features【能做什么】
+- MJExtension是一套字典和模型之间互相转换的超轻量级框架
+* `JSON` --> `Model`、`Core Data Model`
+* `JSONString` --> `Model`、`Core Data Model`
+* `Model`、`Core Data Model` --> `JSON`
+* `JSON Array` --> `Model Array`、`Core Data Model Array`
+* `JSONString` --> `Model Array`、`Core Data Model Array`
+* `Model Array`、`Core Data Model Array` --> `JSON Array`
+* Coding all properties of a model with only one line of code.
+    * 只需要一行代码,就能实现模型的所有属性进行Coding / SecureCoding(归档和解档)
+
+### <a id="Installation"></a> Installation【安装】
+
+#### CocoaPods【使用CocoaPods】
+
+```ruby
+pod 'MJExtension'
+```
+
+#### Carthage
+
+```ruby
+github "CoderMJLee/MJExtension"
+```
+
+#### Swift Package Manager
+
+Released from [`3.4.0`](https://github.com/CoderMJLee/MJExtension/releases/)
+
+#### Manually【手动导入】
+
+- Drag all source files under folder `MJExtension` to your project.【将`MJExtension`文件夹中的所有源代码拽入项目中】
+- Import the main header file:`#import "MJExtension.h"`【导入主头文件:`#import "MJExtension.h"`】
+
+## <a id="Examples"></a> Examples【示例】
+
+**Add `MJKeyValue` protocol to your model if needed【如果有需要, 请在模型中加入 `MJKeyValue` 协议】**
+
+### <a id="usage_in_swift"></a> Usage in Swift [关于在Swift中使用MJExtension] ‼️
+
+> Example: 
+>
+> - [Model - MJTester.swift](MJExtensionTests/SwiftModel/MJTester.swift)
+>
+> - [Usage - SwiftModelTests.swift](MJExtensionTests/SwiftModelTests.swift)
+
+```swift
+@objc(MJTester)
+@objcMembers
+class MJTester: NSObject {
+    // make sure to use `dynamic` attribute for basic type & must use as Non-Optional & must set initial value
+    dynamic var isSpecialAgent: Bool = false
+    dynamic var age: Int = 0
+    
+    var name: String?
+    var identifier: String?
+}
+```
+
+1.  `@objc` or `@objcMembers` attributes should be added to class or property for declaration of Objc accessibility [在 Swift4 之后, 请在属性前加 `@objc` 修饰或在类前增加 `@objcMembers`. 以保证 Swift 的属性能够暴露给 Objc 使用. ]
+2.  If you let `Bool` & `Int` as property type, make sure that using `dynamic` to attribute it. It must be `Non-Optional` type and assign `a default value`.[如果要使用 `Bool` 和 `Int` 等 Swfit 专用基本类型, 请使用 `dynamic` 关键字修饰, 类型为 `Non-Optional`, 並且给定初始值.]
+
+> 纯Swift版的JSON与Model转换框架已经开源上架
+>
+> - [KakaJSON](https://github.com/kakaopensource/KakaJSON)
+> - [中文教程](https://www.cnblogs.com/mjios/p/11352776.html)
+> - 如果你的项目是用Swift写的Model,墙裂推荐使用[KakaJSON](https://github.com/kakaopensource/KakaJSON)
+>   - 已经对各种常用的数据场景进行了大量的单元测试
+>   - 简单易用、功能丰富、转换快速
+
+### <a id="JSON_Model"></a> The most simple JSON -> Model【最简单的字典转模型】
+
+```objc
+typedef enum {
+    SexMale,
+    SexFemale
+} Sex;
+
+@interface User : NSObject
+@property (copy, nonatomic) NSString *name;
+@property (copy, nonatomic) NSString *icon;
+@property (assign, nonatomic) unsigned int age;
+@property (copy, nonatomic) NSString *height;
+@property (strong, nonatomic) NSNumber *money;
+@property (assign, nonatomic) Sex sex;
+@property (assign, nonatomic, getter=isGay) BOOL gay;
+@end
+
+/***********************************************/
+
+NSDictionary *dict = @{
+    @"name" : @"Jack",
+    @"icon" : @"lufy.png",
+    @"age" : @20,
+    @"height" : @"1.55",
+    @"money" : @100.9,
+    @"sex" : @(SexFemale),
+    @"gay" : @"true"
+//   @"gay" : @"1"
+//   @"gay" : @"NO"
+};
+
+// JSON -> User
+User *user = [User mj_objectWithKeyValues:dict];
+
+NSLog(@"name=%@, icon=%@, age=%zd, height=%@, money=%@, sex=%d, gay=%d", user.name, user.icon, user.age, user.height, user.money, user.sex, user.gay);
+// name=Jack, icon=lufy.png, age=20, height=1.550000, money=100.9, sex=1
+```
+
+### <a id="JSONString_Model"></a> JSONString -> Model【JSON字符串转模型】
+
+```objc
+// 1.Define a JSONString
+NSString *jsonString = @"{\"name\":\"Jack\", \"icon\":\"lufy.png\", \"age\":20}";
+
+// 2.JSONString -> User
+User *user = [User mj_objectWithKeyValues:jsonString];
+
+// 3.Print user's properties
+NSLog(@"name=%@, icon=%@, age=%d", user.name, user.icon, user.age);
+// name=Jack, icon=lufy.png, age=20
+```
+
+### <a id="Model_contains_model"></a> Model contains model【模型中嵌套模型】
+
+```objc
+@interface Status : NSObject
+@property (copy, nonatomic) NSString *text;
+@property (strong, nonatomic) User *user;
+@property (strong, nonatomic) Status *retweetedStatus;
+@end
+
+/***********************************************/
+
+NSDictionary *dict = @{
+    @"text" : @"Agree!Nice weather!",
+    @"user" : @{
+        @"name" : @"Jack",
+        @"icon" : @"lufy.png"
+    },
+    @"retweetedStatus" : @{
+        @"text" : @"Nice weather!",
+        @"user" : @{
+            @"name" : @"Rose",
+            @"icon" : @"nami.png"
+        }
+    }
+};
+
+// JSON -> Status
+Status *status = [Status mj_objectWithKeyValues:dict];
+
+NSString *text = status.text;
+NSString *name = status.user.name;
+NSString *icon = status.user.icon;
+NSLog(@"text=%@, name=%@, icon=%@", text, name, icon);
+// text=Agree!Nice weather!, name=Jack, icon=lufy.png
+
+NSString *text2 = status.retweetedStatus.text;
+NSString *name2 = status.retweetedStatus.user.name;
+NSString *icon2 = status.retweetedStatus.user.icon;
+NSLog(@"text2=%@, name2=%@, icon2=%@", text2, name2, icon2);
+// text2=Nice weather!, name2=Rose, icon2=nami.png
+```
+
+### <a id="Model_contains_model_array"></a> Model contains model-array【模型中有个数组属性,数组里面又要装着其他模型】
+
+```objc
+@interface Ad : NSObject
+@property (copy, nonatomic) NSString *image;
+@property (copy, nonatomic) NSString *url;
+@end
+
+@interface StatusResult : NSObject
+/** Contatins status model */
+@property (strong, nonatomic) NSMutableArray *statuses;
+/** Contatins ad model */
+@property (strong, nonatomic) NSArray *ads;
+@property (strong, nonatomic) NSNumber *totalNumber;
+@end
+
+/***********************************************/
+
+// Tell MJExtension what type of model will be contained in statuses and ads.
+[StatusResult mj_setupObjectClassInArray:^NSDictionary *{
+    return @{
+               @"statuses" : @"Status",
+               // @"statuses" : [Status class],
+               @"ads" : @"Ad"
+               // @"ads" : [Ad class]
+           };
+}];
+// Equals: StatusResult.m implements +mj_objectClassInArray method.
+
+NSDictionary *dict = @{
+    @"statuses" : @[
+                      @{
+                          @"text" : @"Nice weather!",
+                          @"user" : @{
+                              @"name" : @"Rose",
+                              @"icon" : @"nami.png"
+                          }
+                      },
+                      @{
+                          @"text" : @"Go camping tomorrow!",
+                          @"user" : @{
+                              @"name" : @"Jack",
+                              @"icon" : @"lufy.png"
+                          }
+                      }
+                  ],
+    @"ads" : @[
+                 @{
+                     @"image" : @"ad01.png",
+                     @"url" : @"http://www.ad01.com"
+                 },
+                 @{
+                     @"image" : @"ad02.png",
+                     @"url" : @"http://www.ad02.com"
+                 }
+             ],
+    @"totalNumber" : @"2014"
+};
+
+// JSON -> StatusResult
+StatusResult *result = [StatusResult mj_objectWithKeyValues:dict];
+
+NSLog(@"totalNumber=%@", result.totalNumber);
+// totalNumber=2014
+
+// Printing
+for (Status *status in result.statuses) {
+    NSString *text = status.text;
+    NSString *name = status.user.name;
+    NSString *icon = status.user.icon;
+    NSLog(@"text=%@, name=%@, icon=%@", text, name, icon);
+}
+// text=Nice weather!, name=Rose, icon=nami.png
+// text=Go camping tomorrow!, name=Jack, icon=lufy.png
+
+// Printing
+for (Ad *ad in result.ads) {
+    NSLog(@"image=%@, url=%@", ad.image, ad.url);
+}
+// image=ad01.png, url=http://www.ad01.com
+// image=ad02.png, url=http://www.ad02.com
+```
+
+### <a id="Model_name_JSON_key_mapping"></a> Model name - JSON key mapping【模型中的属性名和字典中的key不相同(或者需要多级映射)】
+
+```objc
+@interface Bag : NSObject
+@property (copy, nonatomic) NSString *name;
+@property (assign, nonatomic) double price;
+@end
+
+@interface Student : NSObject
+@property (copy, nonatomic) NSString *ID;
+@property (copy, nonatomic) NSString *desc;
+@property (copy, nonatomic) NSString *nowName;
+@property (copy, nonatomic) NSString *oldName;
+@property (copy, nonatomic) NSString *nameChangedTime;
+@property (strong, nonatomic) Bag *bag;
+@end
+
+/***********************************************/
+
+// How to map
+[Student mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
+    return @{
+               @"ID" : @"id",
+               @"desc" : @"description",
+               @"oldName" : @"name.oldName",
+               @"nowName" : @"name.newName",
+               @"nameChangedTime" : @"name.info[1].nameChangedTime",
+               @"bag" : @"other.bag"
+           };
+}];
+// Equals: Student.m implements +mj_replacedKeyFromPropertyName method.
+
+NSDictionary *dict = @{
+    @"id" : @"20",
+    @"description" : @"kids",
+    @"name" : @{
+        @"newName" : @"lufy",
+        @"oldName" : @"kitty",
+        @"info" : @[
+        		 @"test-data",
+        		 @{
+            	             @"nameChangedTime" : @"2013-08"
+                         }
+                  ]
+    },
+    @"other" : @{
+        @"bag" : @{
+            @"name" : @"a red bag",
+            @"price" : @100.7
+        }
+    }
+};
+
+// JSON -> Student
+Student *stu = [Student mj_objectWithKeyValues:dict];
+
+// Printing
+NSLog(@"ID=%@, desc=%@, oldName=%@, nowName=%@, nameChangedTime=%@",
+      stu.ID, stu.desc, stu.oldName, stu.nowName, stu.nameChangedTime);
+// ID=20, desc=kids, oldName=kitty, nowName=lufy, nameChangedTime=2013-08
+NSLog(@"bagName=%@, bagPrice=%f", stu.bag.name, stu.bag.price);
+// bagName=a red bag, bagPrice=100.700000
+```
+
+
+### <a id="JSON_array_model_array"></a> JSON array -> model array【将一个字典数组转成模型数组】
+
+```objc
+NSArray *dictArray = @[
+                         @{
+                             @"name" : @"Jack",
+                             @"icon" : @"lufy.png"
+                         },
+                         @{
+                             @"name" : @"Rose",
+                             @"icon" : @"nami.png"
+                         }
+                     ];
+
+// JSON array -> User array
+NSArray *userArray = [User mj_objectArrayWithKeyValuesArray:dictArray];
+
+// Printing
+for (User *user in userArray) {
+    NSLog(@"name=%@, icon=%@", user.name, user.icon);
+}
+// name=Jack, icon=lufy.png
+// name=Rose, icon=nami.png
+```
+
+### <a id="Model_JSON"></a> Model -> JSON【将一个模型转成字典】
+```objc
+// New model
+User *user = [[User alloc] init];
+user.name = @"Jack";
+user.icon = @"lufy.png";
+
+Status *status = [[Status alloc] init];
+status.user = user;
+status.text = @"Nice mood!";
+
+// Status -> JSON
+NSDictionary *statusDict = status.mj_keyValues;
+NSLog(@"%@", statusDict);
+/*
+ {
+ text = "Nice mood!";
+ user =     {
+ icon = "lufy.png";
+ name = Jack;
+ };
+ }
+ */
+
+// More complex situation
+Student *stu = [[Student alloc] init];
+stu.ID = @"123";
+stu.oldName = @"rose";
+stu.nowName = @"jack";
+stu.desc = @"handsome";
+stu.nameChangedTime = @"2018-09-08";
+
+Bag *bag = [[Bag alloc] init];
+bag.name = @"a red bag";
+bag.price = 205;
+stu.bag = bag;
+
+NSDictionary *stuDict = stu.mj_keyValues;
+NSLog(@"%@", stuDict);
+/*
+{
+    ID = 123;
+    bag =     {
+        name = "\U5c0f\U4e66\U5305";
+        price = 205;
+    };
+    desc = handsome;
+    nameChangedTime = "2018-09-08";
+    nowName = jack;
+    oldName = rose;
+}
+ */
+```
+
+### <a id="Model_array_JSON_array"></a> Model array -> JSON array【将一个模型数组转成字典数组】
+
+```objc
+// New model array
+User *user1 = [[User alloc] init];
+user1.name = @"Jack";
+user1.icon = @"lufy.png";
+
+User *user2 = [[User alloc] init];
+user2.name = @"Rose";
+user2.icon = @"nami.png";
+
+NSArray *userArray = @[user1, user2];
+
+// Model array -> JSON array
+NSArray *dictArray = [User mj_keyValuesArrayWithObjectArray:userArray];
+NSLog(@"%@", dictArray);
+/*
+ (
+ {
+ icon = "lufy.png";
+ name = Jack;
+ },
+ {
+ icon = "nami.png";
+ name = Rose;
+ }
+ )
+ */
+```
+
+### <a id="Core_Data"></a> Core Data
+
+```swift
+func json2CoreDataObject() {
+    context.performAndWait {
+        let object = MJCoreDataTester.mj_object(withKeyValues: Values.testJSONObject, context: context)
+        // use the object
+    }
+}
+
+func coreDataObject2JSON() {
+    context.performAndWait {        
+        let dict = coreDataObject.mj_keyValues()
+        // use dict
+    }
+}
+```
+
+### <a id="Coding"></a> Coding (Archive & Unarchive methods are deprecated in iOS 12)
+
+```objc
+#import "MJExtension.h"
+
+@implementation MJBag
+// NSCoding Implementation
+MJCodingImplementation
+@end
+
+/***********************************************/
+
+// what properties not to be coded
+[MJBag mj_setupIgnoredCodingPropertyNames:^NSArray *{
+    return @[@"name"];
+}];
+// Equals: MJBag.m implements +mj_ignoredCodingPropertyNames method.
+
+// Create model
+MJBag *bag = [[MJBag alloc] init];
+bag.name = @"Red bag";
+bag.price = 200.8;
+
+NSString *file = [NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/bag.data"];
+// Encoding by archiving
+[NSKeyedArchiver archiveRootObject:bag toFile:file];
+
+// Decoding by unarchiving
+MJBag *decodedBag = [NSKeyedUnarchiver unarchiveObjectWithFile:file];
+NSLog(@"name=%@, price=%f", decodedBag.name, decodedBag.price);
+// name=(null), price=200.800000
+```
+
+### <a id="SecureCoding"></a> Secure Coding
+
+Using `MJSecureCodingImplementation(class, isSupport)` macro.
+
+```objc
+@import MJExtension;
+
+// NSSecureCoding Implementation
+MJSecureCodingImplementation(MJBag, YES)
+
+@implementation MJBag
+@end
+
+ /***********************************************/
+
+// what properties not to be coded
+[MJBag mj_setupIgnoredCodingPropertyNames:^NSArray *{
+    return @[@"name"];
+}];
+// Equals: MJBag.m implements +mj_ignoredCodingPropertyNames method.
+
+// Create model
+MJBag *bag = [[MJBag alloc] init];
+bag.name = @"Red bag";
+bag.price = 200.8;
+bag.isBig = YES;
+bag.weight = 200;
+
+NSString *file = [NSTemporaryDirectory() stringByAppendingPathComponent:@"bag.data"];
+
+NSError *error = nil;
+// Encoding by archiving
+NSData *data = [NSKeyedArchiver archivedDataWithRootObject:bag requiringSecureCoding:YES error:&error];
+[data writeToFile:file atomically:true];
+
+// Decoding by unarchiving
+NSData *readData = [NSFileManager.defaultManager contentsAtPath:file];
+error = nil;
+MJBag *decodedBag = [NSKeyedUnarchiver unarchivedObjectOfClass:MJBag.class fromData:readData error:&error];
+MJExtensionLog(@"name=%@, price=%f", decodedBag.name, decodedBag.price);
+```
+
+### <a id="Camel_underline"></a> Camel -> underline【统一转换属性名(比如驼峰转下划线)】
+
+```objc
+// Dog
+#import "MJExtension.h"
+
+@implementation Dog
++ (NSString *)mj_replacedKeyFromPropertyName121:(NSString *)propertyName
+{
+    // nickName -> nick_name
+    return [propertyName mj_underlineFromCamel];
+}
+@end
+
+// NSDictionary
+NSDictionary *dict = @{
+                       @"nick_name" : @"旺财",
+                       @"sale_price" : @"10.5",
+                       @"run_speed" : @"100.9"
+                       };
+// NSDictionary -> Dog
+Dog *dog = [Dog mj_objectWithKeyValues:dict];
+
+// printing
+NSLog(@"nickName=%@, scalePrice=%f runSpeed=%f", dog.nickName, dog.salePrice, dog.runSpeed);
+```
+
+### <a id="NSString_NSDate"></a> NSString -> NSDate, nil -> @""【过滤字典的值(比如字符串日期处理为NSDate、字符串nil处理为@"")】
+```objc
+// Book
+#import "MJExtension.h"
+
+@implementation Book
+- (id)mj_newValueFromOldValue:(id)oldValue property:(MJProperty *)property
+{
+    if ([property.name isEqualToString:@"publisher"]) {
+        if (oldValue == nil) return @"";
+    } else if (property.type.typeClass == [NSDate class]) {
+        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
+        fmt.dateFormat = @"yyyy-MM-dd";
+        return [fmt dateFromString:oldValue];
+    }
+
+    return oldValue;
+}
+@end
+
+// NSDictionary
+NSDictionary *dict = @{
+                       @"name" : @"5分钟突破iOS开发",
+                       @"publishedTime" : @"2011-09-10"
+                       };
+// NSDictionary -> Book
+Book *book = [Book mj_objectWithKeyValues:dict];
+
+// printing
+NSLog(@"name=%@, publisher=%@, publishedTime=%@", book.name, book.publisher, book.publishedTime);
+```
+
+### <a id="NSDate_NSString"></a> NSDate -> NSString【模型转字典时, 修改 Date 类型至 String】
+
+```objc
+- (void)mj_objectDidConvertToKeyValues:(NSMutableDictionary *)keyValues {
+    // NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
+    // formatter.dateFormat = @"yyy-MM-dd";
+    // should use sharedFormatter for better performance  
+    keyValues[@"publishedTime"] = [sharedFormatter stringFromDate:self.publishedTime];
+}
+```
+
+
+
+### <a id="More_use_cases"></a> More use cases【更多用法】
+
+- Please reference to `NSObject+MJKeyValue.h` and `NSObject+MJCoding.h`
+
+
+## 期待
+* 如果在使用过程中遇到BUG,希望你能Issues我,谢谢(或者尝试下载最新的框架代码看看BUG修复没有)
+* 如果在使用过程中发现功能不够用,希望你能Issues我,我非常想为这个框架增加更多好用的功能,谢谢
+* 如果你想为MJExtension输出代码,请拼命Pull Requests我
+

+ 19 - 0
Pods/MJRefresh/LICENSE

@@ -0,0 +1,19 @@
+Copyright (c) 2013-2015 MJRefresh (https://github.com/CoderMJLee/MJRefresh)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.

+ 34 - 0
Pods/MJRefresh/MJRefresh/Base/MJRefreshAutoFooter.h

@@ -0,0 +1,34 @@
+//
+//  MJRefreshAutoFooter.h
+//  MJRefresh
+//
+//  Created by MJ Lee on 15/4/24.
+//  Copyright (c) 2015年 小码哥. All rights reserved.
+//
+
+#if __has_include(<MJRefresh/MJRefreshFooter.h>)
+#import <MJRefresh/MJRefreshFooter.h>
+#else
+#import "MJRefreshFooter.h"
+#endif
+
+NS_ASSUME_NONNULL_BEGIN
+
+@interface MJRefreshAutoFooter : MJRefreshFooter
+/** 是否自动刷新(默认为YES) */
+@property (assign, nonatomic, getter=isAutomaticallyRefresh) BOOL automaticallyRefresh;
+
+/** 当底部控件出现多少时就自动刷新(默认为1.0,也就是底部控件完全出现时,才会自动刷新) */
+@property (assign, nonatomic) CGFloat appearencePercentTriggerAutoRefresh MJRefreshDeprecated("请使用triggerAutomaticallyRefreshPercent属性");
+
+/** 当底部控件出现多少时就自动刷新(默认为1.0,也就是底部控件完全出现时,才会自动刷新) */
+@property (assign, nonatomic) CGFloat triggerAutomaticallyRefreshPercent;
+
+/** 自动触发次数, 默认为 1, 仅在拖拽 ScrollView 时才生效,
+ 
+ 如果为 -1, 则为无限触发
+ */
+@property (nonatomic) NSInteger autoTriggerTimes;
+@end
+
+NS_ASSUME_NONNULL_END

+ 216 - 0
Pods/MJRefresh/MJRefresh/Base/MJRefreshAutoFooter.m

@@ -0,0 +1,216 @@
+//
+//  MJRefreshAutoFooter.m
+//  MJRefresh
+//
+//  Created by MJ Lee on 15/4/24.
+//  Copyright (c) 2015年 小码哥. All rights reserved.
+//
+
+#import "MJRefreshAutoFooter.h"
+#import "NSBundle+MJRefresh.h"
+#import "UIView+MJExtension.h"
+#import "UIScrollView+MJExtension.h"
+#import "UIScrollView+MJRefresh.h"
+
+@interface MJRefreshAutoFooter()
+/** 一个新的拖拽 */
+@property (nonatomic) BOOL triggerByDrag;
+@property (nonatomic) NSInteger leftTriggerTimes;
+@end
+
+@implementation MJRefreshAutoFooter
+
+#pragma mark - 初始化
+- (void)willMoveToSuperview:(UIView *)newSuperview
+{
+    [super willMoveToSuperview:newSuperview];
+    
+    if (newSuperview) { // 新的父控件
+        if (self.hidden == NO) {
+            self.scrollView.mj_insetB += self.mj_h;
+        }
+        
+        // 设置位置
+        self.mj_y = _scrollView.mj_contentH;
+    } else { // 被移除了
+        if (self.hidden == NO) {
+            self.scrollView.mj_insetB -= self.mj_h;
+        }
+    }
+}
+
+#pragma mark - 过期方法
+- (void)setAppearencePercentTriggerAutoRefresh:(CGFloat)appearencePercentTriggerAutoRefresh
+{
+    self.triggerAutomaticallyRefreshPercent = appearencePercentTriggerAutoRefresh;
+}
+
+- (CGFloat)appearencePercentTriggerAutoRefresh
+{
+    return self.triggerAutomaticallyRefreshPercent;
+}
+
+#pragma mark - 实现父类的方法
+- (void)prepare
+{
+    [super prepare];
+    
+    // 默认底部控件100%出现时才会自动刷新
+    self.triggerAutomaticallyRefreshPercent = 1.0;
+    
+    // 设置为默认状态
+    self.automaticallyRefresh = YES;
+    
+    self.autoTriggerTimes = 1;
+}
+
+- (void)scrollViewContentSizeDidChange:(NSDictionary *)change
+{
+    [super scrollViewContentSizeDidChange:change];
+    
+    CGSize size = [change[NSKeyValueChangeNewKey] CGSizeValue];
+    CGFloat contentHeight = size.height == 0 ? self.scrollView.mj_contentH : size.height;
+    // 设置位置
+    CGFloat y = contentHeight + self.ignoredScrollViewContentInsetBottom;
+    if (self.mj_y != y) {
+        self.mj_y = y;
+    }
+}
+
+- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change
+{
+    [super scrollViewContentOffsetDidChange:change];
+    
+    if (self.state != MJRefreshStateIdle || !self.automaticallyRefresh || self.mj_y == 0) return;
+    
+    if (_scrollView.mj_insetT + _scrollView.mj_contentH > _scrollView.mj_h) { // 内容超过一个屏幕
+        // 这里的_scrollView.mj_contentH替换掉self.mj_y更为合理
+        if (_scrollView.mj_offsetY >= _scrollView.mj_contentH - _scrollView.mj_h + self.mj_h * self.triggerAutomaticallyRefreshPercent + _scrollView.mj_insetB - self.mj_h) {
+            // 防止手松开时连续调用
+            CGPoint old = [change[@"old"] CGPointValue];
+            CGPoint new = [change[@"new"] CGPointValue];
+            if (new.y <= old.y) return;
+            
+            if (_scrollView.isDragging) {
+                self.triggerByDrag = YES;
+            }
+            // 当底部刷新控件完全出现时,才刷新
+            [self beginRefreshing];
+        }
+    }
+}
+
+- (void)scrollViewPanStateDidChange:(NSDictionary *)change
+{
+    [super scrollViewPanStateDidChange:change];
+    
+    if (self.state != MJRefreshStateIdle) return;
+    
+    UIGestureRecognizerState panState = _scrollView.panGestureRecognizer.state;
+    
+    switch (panState) {
+        // 手松开
+        case UIGestureRecognizerStateEnded: {
+            if (_scrollView.mj_insetT + _scrollView.mj_contentH <= _scrollView.mj_h) {  // 不够一个屏幕
+                if (_scrollView.mj_offsetY >= - _scrollView.mj_insetT) { // 向上拽
+                    self.triggerByDrag = YES;
+                    [self beginRefreshing];
+                }
+            } else { // 超出一个屏幕
+                if (_scrollView.mj_offsetY >= _scrollView.mj_contentH + _scrollView.mj_insetB - _scrollView.mj_h) {
+                    self.triggerByDrag = YES;
+                    [self beginRefreshing];
+                }
+            }
+        }
+            break;
+            
+        case UIGestureRecognizerStateBegan: {
+            [self resetTriggerTimes];
+        }
+            break;
+            
+        default:
+            break;
+    }
+}
+
+- (BOOL)unlimitedTrigger {
+    return self.leftTriggerTimes == -1;
+}
+
+- (void)beginRefreshing
+{
+    if (self.triggerByDrag && self.leftTriggerTimes <= 0 && !self.unlimitedTrigger) {
+        return;
+    }
+    
+    [super beginRefreshing];
+}
+
+- (void)setState:(MJRefreshState)state
+{
+    MJRefreshCheckState
+    
+    if (state == MJRefreshStateRefreshing) {
+        [self executeRefreshingCallback];
+    } else if (state == MJRefreshStateNoMoreData || state == MJRefreshStateIdle) {
+        if (self.triggerByDrag) {
+            if (!self.unlimitedTrigger) {
+                self.leftTriggerTimes -= 1;
+            }
+            self.triggerByDrag = NO;
+        }
+        
+        if (MJRefreshStateRefreshing == oldState) {
+            if (self.scrollView.pagingEnabled) {
+                CGPoint offset = self.scrollView.contentOffset;
+                offset.y -= self.scrollView.mj_insetB;
+                [UIView animateWithDuration:self.slowAnimationDuration animations:^{
+                    self.scrollView.contentOffset = offset;
+                    
+                    if (self.endRefreshingAnimationBeginAction) {
+                        self.endRefreshingAnimationBeginAction();
+                    }
+                } completion:^(BOOL finished) {
+                    if (self.endRefreshingCompletionBlock) {
+                        self.endRefreshingCompletionBlock();
+                    }
+                }];
+                return;
+            }
+            
+            if (self.endRefreshingCompletionBlock) {
+                self.endRefreshingCompletionBlock();
+            }
+        }
+    }
+}
+
+- (void)resetTriggerTimes {
+    self.leftTriggerTimes = self.autoTriggerTimes;
+}
+
+- (void)setHidden:(BOOL)hidden
+{
+    BOOL lastHidden = self.isHidden;
+    
+    [super setHidden:hidden];
+    
+    if (!lastHidden && hidden) {
+        self.state = MJRefreshStateIdle;
+        
+        self.scrollView.mj_insetB -= self.mj_h;
+    } else if (lastHidden && !hidden) {
+        self.scrollView.mj_insetB += self.mj_h;
+        
+        // 设置位置
+        self.mj_y = _scrollView.mj_contentH;
+    }
+}
+
+- (void)setAutoTriggerTimes:(NSInteger)autoTriggerTimes {
+    _autoTriggerTimes = autoTriggerTimes;
+    self.leftTriggerTimes = autoTriggerTimes;
+}
+@end

+ 21 - 0
Pods/MJRefresh/MJRefresh/Base/MJRefreshBackFooter.h

@@ -0,0 +1,21 @@
+//
+//  MJRefreshBackFooter.h
+//  MJRefresh
+//
+//  Created by MJ Lee on 15/4/24.
+//  Copyright (c) 2015年 小码哥. All rights reserved.
+//
+
+#if __has_include(<MJRefresh/MJRefreshFooter.h>)
+#import <MJRefresh/MJRefreshFooter.h>
+#else
+#import "MJRefreshFooter.h"
+#endif
+
+NS_ASSUME_NONNULL_BEGIN
+
+@interface MJRefreshBackFooter : MJRefreshFooter
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 158 - 0
Pods/MJRefresh/MJRefresh/Base/MJRefreshBackFooter.m

@@ -0,0 +1,158 @@
+//
+//  MJRefreshBackFooter.m
+//  MJRefresh
+//
+//  Created by MJ Lee on 15/4/24.
+//  Copyright (c) 2015年 小码哥. All rights reserved.
+//
+
+#import "MJRefreshBackFooter.h"
+#import "NSBundle+MJRefresh.h"
+#import "UIView+MJExtension.h"
+#import "UIScrollView+MJExtension.h"
+#import "UIScrollView+MJRefresh.h"
+
+@interface MJRefreshBackFooter()
+@property (assign, nonatomic) NSInteger lastRefreshCount;
+@property (assign, nonatomic) CGFloat lastBottomDelta;
+@end
+
+@implementation MJRefreshBackFooter
+
+#pragma mark - 初始化
+- (void)willMoveToSuperview:(UIView *)newSuperview
+{
+    [super willMoveToSuperview:newSuperview];
+    
+    [self scrollViewContentSizeDidChange:nil];
+}
+
+#pragma mark - 实现父类的方法
+- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change
+{
+    [super scrollViewContentOffsetDidChange:change];
+    
+    // 如果正在刷新,直接返回
+    if (self.state == MJRefreshStateRefreshing) return;
+    
+    _scrollViewOriginalInset = self.scrollView.mj_inset;
+    
+    // 当前的contentOffset
+    CGFloat currentOffsetY = self.scrollView.mj_offsetY;
+    // 尾部控件刚好出现的offsetY
+    CGFloat happenOffsetY = [self happenOffsetY];
+    // 如果是向下滚动到看不见尾部控件,直接返回
+    if (currentOffsetY <= happenOffsetY) return;
+    
+    CGFloat pullingPercent = (currentOffsetY - happenOffsetY) / self.mj_h;
+    
+    // 如果已全部加载,仅设置pullingPercent,然后返回
+    if (self.state == MJRefreshStateNoMoreData) {
+        self.pullingPercent = pullingPercent;
+        return;
+    }
+    
+    if (self.scrollView.isDragging) {
+        self.pullingPercent = pullingPercent;
+        // 普通 和 即将刷新 的临界点
+        CGFloat normal2pullingOffsetY = happenOffsetY + self.mj_h;
+        
+        if (self.state == MJRefreshStateIdle && currentOffsetY > normal2pullingOffsetY) {
+            // 转为即将刷新状态
+            self.state = MJRefreshStatePulling;
+        } else if (self.state == MJRefreshStatePulling && currentOffsetY <= normal2pullingOffsetY) {
+            // 转为普通状态
+            self.state = MJRefreshStateIdle;
+        }
+    } else if (self.state == MJRefreshStatePulling) {// 即将刷新 && 手松开
+        // 开始刷新
+        [self beginRefreshing];
+    } else if (pullingPercent < 1) {
+        self.pullingPercent = pullingPercent;
+    }
+}
+
+- (void)scrollViewContentSizeDidChange:(NSDictionary *)change
+{
+    [super scrollViewContentSizeDidChange:change];
+    
+    CGSize size = [change[NSKeyValueChangeNewKey] CGSizeValue];
+    CGFloat contentHeight = size.height == 0 ? self.scrollView.mj_contentH : size.height;
+    // 内容的高度
+    contentHeight += self.ignoredScrollViewContentInsetBottom;
+    // 表格的高度
+    CGFloat scrollHeight = self.scrollView.mj_h - self.scrollViewOriginalInset.top - self.scrollViewOriginalInset.bottom + self.ignoredScrollViewContentInsetBottom;
+    // 设置位置
+    CGFloat y = MAX(contentHeight, scrollHeight);
+    if (self.mj_y != y) {
+        self.mj_y = y;
+    }
+}
+
+- (void)setState:(MJRefreshState)state
+{
+    MJRefreshCheckState
+    
+    // 根据状态来设置属性
+    if (state == MJRefreshStateNoMoreData || state == MJRefreshStateIdle) {
+        // 刷新完毕
+        if (MJRefreshStateRefreshing == oldState) {
+            [UIView animateWithDuration:self.slowAnimationDuration animations:^{
+                if (self.endRefreshingAnimationBeginAction) {
+                    self.endRefreshingAnimationBeginAction();
+                }
+                
+                self.scrollView.mj_insetB -= self.lastBottomDelta;
+                // 自动调整透明度
+                if (self.isAutomaticallyChangeAlpha) self.alpha = 0.0;
+            } completion:^(BOOL finished) {
+                self.pullingPercent = 0.0;
+                
+                if (self.endRefreshingCompletionBlock) {
+                    self.endRefreshingCompletionBlock();
+                }
+            }];
+        }
+        
+        CGFloat deltaH = [self heightForContentBreakView];
+        // 刚刷新完毕
+        if (MJRefreshStateRefreshing == oldState && deltaH > 0 && self.scrollView.mj_totalDataCount != self.lastRefreshCount) {
+            self.scrollView.mj_offsetY = self.scrollView.mj_offsetY;
+        }
+    } else if (state == MJRefreshStateRefreshing) {
+        // 记录刷新前的数量
+        self.lastRefreshCount = self.scrollView.mj_totalDataCount;
+        
+        [UIView animateWithDuration:self.fastAnimationDuration animations:^{
+            CGFloat bottom = self.mj_h + self.scrollViewOriginalInset.bottom;
+            CGFloat deltaH = [self heightForContentBreakView];
+            if (deltaH < 0) { // 如果内容高度小于view的高度
+                bottom -= deltaH;
+            }
+            self.lastBottomDelta = bottom - self.scrollView.mj_insetB;
+            self.scrollView.mj_insetB = bottom;
+            self.scrollView.mj_offsetY = [self happenOffsetY] + self.mj_h;
+        } completion:^(BOOL finished) {
+            [self executeRefreshingCallback];
+        }];
+    }
+}
+#pragma mark - 私有方法
+#pragma mark 获得scrollView的内容 超出 view 的高度
+- (CGFloat)heightForContentBreakView
+{
+    CGFloat h = self.scrollView.frame.size.height - self.scrollViewOriginalInset.bottom - self.scrollViewOriginalInset.top;
+    return self.scrollView.contentSize.height - h;
+}
+
+#pragma mark 刚好看到上拉刷新控件时的contentOffset.y
+- (CGFloat)happenOffsetY
+{
+    CGFloat deltaH = [self heightForContentBreakView];
+    if (deltaH > 0) {
+        return deltaH - self.scrollViewOriginalInset.top;
+    } else {
+        return - self.scrollViewOriginalInset.top;
+    }
+}
+@end

+ 151 - 0
Pods/MJRefresh/MJRefresh/Base/MJRefreshComponent.h

@@ -0,0 +1,151 @@
+//  代码地址: https://github.com/CoderMJLee/MJRefresh
+//  MJRefreshComponent.h
+//  MJRefresh
+//
+//  Created by MJ Lee on 15/3/4.
+//  Copyright (c) 2015年 小码哥. All rights reserved.
+//  刷新控件的基类
+
+#import <UIKit/UIKit.h>
+#if __has_include(<MJRefresh/MJRefreshConst.h>)
+#import <MJRefresh/MJRefreshConst.h>
+#else
+#import "MJRefreshConst.h"
+#endif
+
+NS_ASSUME_NONNULL_BEGIN
+
+/** 刷新控件的状态 */
+typedef NS_ENUM(NSInteger, MJRefreshState) {
+    /** 普通闲置状态 */
+    MJRefreshStateIdle = 1,
+    /** 松开就可以进行刷新的状态 */
+    MJRefreshStatePulling,
+    /** 正在刷新中的状态 */
+    MJRefreshStateRefreshing,
+    /** 即将刷新的状态 */
+    MJRefreshStateWillRefresh,
+    /** 所有数据加载完毕,没有更多的数据了 */
+    MJRefreshStateNoMoreData
+};
+
+/** 进入刷新状态的回调 */
+typedef void (^MJRefreshComponentRefreshingBlock)(void) MJRefreshDeprecated("first deprecated in 3.3.0 - Use `MJRefreshComponentAction` instead");
+/** 开始刷新后的回调(进入刷新状态后的回调) */
+typedef void (^MJRefreshComponentBeginRefreshingCompletionBlock)(void) MJRefreshDeprecated("first deprecated in 3.3.0 - Use `MJRefreshComponentAction` instead");
+/** 结束刷新后的回调 */
+typedef void (^MJRefreshComponentEndRefreshingCompletionBlock)(void) MJRefreshDeprecated("first deprecated in 3.3.0 - Use `MJRefreshComponentAction` instead");
+
+/** 刷新用到的回调类型 */
+typedef void (^MJRefreshComponentAction)(void);
+
+/** 刷新控件的基类 */
+@interface MJRefreshComponent : UIView
+{
+    /** 记录scrollView刚开始的inset */
+    UIEdgeInsets _scrollViewOriginalInset;
+    /** 父控件 */
+    __weak UIScrollView *_scrollView;
+}
+
+#pragma mark - 刷新动画时间控制
+/** 快速动画时间(一般用在刷新开始的回弹动画), 默认 0.25 */
+@property (nonatomic) NSTimeInterval fastAnimationDuration;
+/** 慢速动画时间(一般用在刷新结束后的回弹动画), 默认 0.4*/
+@property (nonatomic) NSTimeInterval slowAnimationDuration;
+/** 关闭全部默认动画效果, 可以简单粗暴地解决 CollectionView 的回弹动画 bug */
+- (instancetype)setAnimationDisabled;
+
+#pragma mark - 刷新回调
+/** 正在刷新的回调 */
+@property (copy, nonatomic, nullable) MJRefreshComponentAction refreshingBlock;
+/** 设置回调对象和回调方法 */
+- (void)setRefreshingTarget:(id)target refreshingAction:(SEL)action;
+
+/** 回调对象 */
+@property (weak, nonatomic) id refreshingTarget;
+/** 回调方法 */
+@property (assign, nonatomic) SEL refreshingAction;
+/** 触发回调(交给子类去调用) */
+- (void)executeRefreshingCallback;
+
+#pragma mark - 刷新状态控制
+/** 进入刷新状态 */
+- (void)beginRefreshing;
+- (void)beginRefreshingWithCompletionBlock:(void (^)(void))completionBlock;
+/** 开始刷新后的回调(进入刷新状态后的回调) */
+@property (copy, nonatomic, nullable) MJRefreshComponentAction beginRefreshingCompletionBlock;
+/** 带动画的结束刷新的回调 */
+@property (copy, nonatomic, nullable) MJRefreshComponentAction endRefreshingAnimateCompletionBlock MJRefreshDeprecated("first deprecated in 3.3.0 - Use `endRefreshingAnimationBeginAction` instead");
+@property (copy, nonatomic, nullable) MJRefreshComponentAction endRefreshingAnimationBeginAction;
+/** 结束刷新的回调 */
+@property (copy, nonatomic, nullable) MJRefreshComponentAction endRefreshingCompletionBlock;
+/** 结束刷新状态 */
+- (void)endRefreshing;
+- (void)endRefreshingWithCompletionBlock:(void (^)(void))completionBlock;
+/** 是否正在刷新 */
+@property (assign, nonatomic, readonly, getter=isRefreshing) BOOL refreshing;
+
+/** 刷新状态 一般交给子类内部实现 */
+@property (assign, nonatomic) MJRefreshState state;
+
+#pragma mark - 交给子类去访问
+/** 记录scrollView刚开始的inset */
+@property (assign, nonatomic, readonly) UIEdgeInsets scrollViewOriginalInset;
+/** 父控件 */
+@property (weak, nonatomic, readonly) UIScrollView *scrollView;
+
+#pragma mark - 交给子类们去实现
+/** 初始化 */
+- (void)prepare NS_REQUIRES_SUPER;
+/** 摆放子控件frame */
+- (void)placeSubviews NS_REQUIRES_SUPER;
+/** 当scrollView的contentOffset发生改变的时候调用 */
+- (void)scrollViewContentOffsetDidChange:(nullable NSDictionary *)change NS_REQUIRES_SUPER;
+/** 当scrollView的contentSize发生改变的时候调用 */
+- (void)scrollViewContentSizeDidChange:(nullable NSDictionary *)change NS_REQUIRES_SUPER;
+/** 当scrollView的拖拽状态发生改变的时候调用 */
+- (void)scrollViewPanStateDidChange:(nullable NSDictionary *)change NS_REQUIRES_SUPER;
+
+/** 多语言配置 language 发生变化时调用
+ 
+ `MJRefreshConfig.defaultConfig.language` 发生改变时调用.
+ 
+ ⚠️ 父类会调用 `placeSubviews` 方法, 请勿在 placeSubviews 中调用本方法, 造成死循环. 子类在需要重新布局时, 在配置完修改后, 最后再调用 super 方法, 否则可能导致配置修改后, 定位先于修改执行.
+ */
+- (void)i18nDidChange NS_REQUIRES_SUPER;
+
+#pragma mark - 其他
+/** 拉拽的百分比(交给子类重写) */
+@property (assign, nonatomic) CGFloat pullingPercent;
+/** 根据拖拽比例自动切换透明度 */
+@property (assign, nonatomic, getter=isAutoChangeAlpha) BOOL autoChangeAlpha MJRefreshDeprecated("请使用automaticallyChangeAlpha属性");
+/** 根据拖拽比例自动切换透明度 */
+@property (assign, nonatomic, getter=isAutomaticallyChangeAlpha) BOOL automaticallyChangeAlpha;
+@end
+
+@interface UILabel(MJRefresh)
++ (instancetype)mj_label;
+- (CGFloat)mj_textWidth;
+@end
+
+@interface MJRefreshComponent (ChainingGrammar)
+
+#pragma mark - <<< 为 Swift 扩展链式语法 >>> -
+/// 自动变化透明度
+- (instancetype)autoChangeTransparency:(BOOL)isAutoChange;
+/// 刷新开始后立即调用的回调
+- (instancetype)afterBeginningAction:(MJRefreshComponentAction)action;
+/// 刷新动画开始后立即调用的回调
+- (instancetype)endingAnimationBeginningAction:(MJRefreshComponentAction)action;
+/// 刷新结束后立即调用的回调
+- (instancetype)afterEndingAction:(MJRefreshComponentAction)action;
+
+
+/// 需要子类必须实现
+/// @param scrollView 赋值给的 ScrollView 的 Header/Footer/Trailer
+- (instancetype)linkTo:(UIScrollView *)scrollView;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 323 - 0
Pods/MJRefresh/MJRefresh/Base/MJRefreshComponent.m

@@ -0,0 +1,323 @@
+//  代码地址: https://github.com/CoderMJLee/MJRefresh
+//  MJRefreshComponent.m
+//  MJRefresh
+//
+//  Created by MJ Lee on 15/3/4.
+//  Copyright (c) 2015年 小码哥. All rights reserved.
+//
+
+#import "MJRefreshComponent.h"
+#import "MJRefreshConst.h"
+#import "MJRefreshConfig.h"
+#import "UIView+MJExtension.h"
+#import "UIScrollView+MJExtension.h"
+#import "UIScrollView+MJRefresh.h"
+#import "NSBundle+MJRefresh.h"
+
+@interface MJRefreshComponent()
+@property (strong, nonatomic) UIPanGestureRecognizer *pan;
+@end
+
+@implementation MJRefreshComponent
+#pragma mark - 初始化
+- (instancetype)initWithFrame:(CGRect)frame
+{
+    if (self = [super initWithFrame:frame]) {
+        // 准备工作
+        [self prepare];
+        
+        // 默认是普通状态
+        self.state = MJRefreshStateIdle;
+        self.fastAnimationDuration = 0.25;
+        self.slowAnimationDuration = 0.4;
+    }
+    return self;
+}
+
+- (void)prepare
+{
+    // 基本属性
+    self.autoresizingMask = UIViewAutoresizingFlexibleWidth;
+    self.backgroundColor = [UIColor clearColor];
+}
+
+- (void)layoutSubviews
+{
+    [self placeSubviews];
+    
+    [super layoutSubviews];
+}
+
+- (void)placeSubviews{}
+
+- (void)willMoveToSuperview:(UIView *)newSuperview
+{
+    [super willMoveToSuperview:newSuperview];
+    
+    // 如果不是UIScrollView,不做任何事情
+    if (newSuperview && ![newSuperview isKindOfClass:[UIScrollView class]]) return;
+    
+    // 旧的父控件移除监听
+    [self removeObservers];
+    
+    if (newSuperview) { // 新的父控件
+        // 记录UIScrollView
+        _scrollView = (UIScrollView *)newSuperview;
+        
+        // 设置宽度
+        self.mj_w = _scrollView.mj_w;
+        // 设置位置
+        self.mj_x = -_scrollView.mj_insetL;
+    
+        // 设置永远支持垂直弹簧效果
+        _scrollView.alwaysBounceVertical = YES;
+        // 记录UIScrollView最开始的contentInset
+        _scrollViewOriginalInset = _scrollView.mj_inset;
+        
+        // 添加监听
+        [self addObservers];
+    }
+}
+
+- (void)drawRect:(CGRect)rect
+{
+    [super drawRect:rect];
+    
+    if (self.state == MJRefreshStateWillRefresh) {
+        // 预防view还没显示出来就调用了beginRefreshing
+        self.state = MJRefreshStateRefreshing;
+    }
+}
+
+#pragma mark - KVO监听
+- (void)addObservers
+{
+    NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
+    [self.scrollView addObserver:self forKeyPath:MJRefreshKeyPathContentOffset options:options context:nil];
+    [self.scrollView addObserver:self forKeyPath:MJRefreshKeyPathContentSize options:options context:nil];
+    self.pan = self.scrollView.panGestureRecognizer;
+    [self.pan addObserver:self forKeyPath:MJRefreshKeyPathPanState options:options context:nil];
+    
+    [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(i18nDidChange) name:MJRefreshDidChangeLanguageNotification object:MJRefreshConfig.defaultConfig];
+}
+
+- (void)removeObservers
+{
+    [self.superview removeObserver:self forKeyPath:MJRefreshKeyPathContentOffset];
+    [self.superview removeObserver:self forKeyPath:MJRefreshKeyPathContentSize];
+    [self.pan removeObserver:self forKeyPath:MJRefreshKeyPathPanState];
+    self.pan = nil;
+}
+
+- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
+{
+    // 遇到这些情况就直接返回
+    if (!self.userInteractionEnabled) return;
+    
+    // 这个就算看不见也需要处理
+    if ([keyPath isEqualToString:MJRefreshKeyPathContentSize]) {
+        [self scrollViewContentSizeDidChange:change];
+    }
+    
+    // 看不见
+    if (self.hidden) return;
+    if ([keyPath isEqualToString:MJRefreshKeyPathContentOffset]) {
+        [self scrollViewContentOffsetDidChange:change];
+    } else if ([keyPath isEqualToString:MJRefreshKeyPathPanState]) {
+        [self scrollViewPanStateDidChange:change];
+    }
+}
+
+- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change{}
+- (void)scrollViewContentSizeDidChange:(NSDictionary *)change{}
+- (void)scrollViewPanStateDidChange:(NSDictionary *)change{}
+
+- (void)i18nDidChange {
+    [self placeSubviews];
+}
+
+#pragma mark - 公共方法
+#pragma mark 设置回调对象和回调方法
+- (void)setRefreshingTarget:(id)target refreshingAction:(SEL)action
+{
+    self.refreshingTarget = target;
+    self.refreshingAction = action;
+}
+
+- (void)setState:(MJRefreshState)state
+{
+    _state = state;
+    
+    // 加入主队列的目的是等setState:方法调用完毕、设置完文字后再去布局子控件
+    MJRefreshDispatchAsyncOnMainQueue([self setNeedsLayout];)
+}
+
+#pragma mark 进入刷新状态
+- (void)beginRefreshing
+{
+    [UIView animateWithDuration:self.fastAnimationDuration animations:^{
+        self.alpha = 1.0;
+    }];
+    self.pullingPercent = 1.0;
+    // 只要正在刷新,就完全显示
+    if (self.window) {
+        self.state = MJRefreshStateRefreshing;
+    } else {
+        // 预防正在刷新中时,调用本方法使得header inset回置失败
+        if (self.state != MJRefreshStateRefreshing) {
+            self.state = MJRefreshStateWillRefresh;
+            // 刷新(预防从另一个控制器回到这个控制器的情况,回来要重新刷新一下)
+            [self setNeedsDisplay];
+        }
+    }
+}
+
+- (void)beginRefreshingWithCompletionBlock:(void (^)(void))completionBlock
+{
+    self.beginRefreshingCompletionBlock = completionBlock;
+    
+    [self beginRefreshing];
+}
+
+#pragma mark 结束刷新状态
+- (void)endRefreshing
+{
+    MJRefreshDispatchAsyncOnMainQueue(self.state = MJRefreshStateIdle;)
+}
+
+- (void)endRefreshingWithCompletionBlock:(void (^)(void))completionBlock
+{
+    self.endRefreshingCompletionBlock = completionBlock;
+    
+    [self endRefreshing];
+}
+
+#pragma mark 是否正在刷新
+- (BOOL)isRefreshing
+{
+    return self.state == MJRefreshStateRefreshing || self.state == MJRefreshStateWillRefresh;
+}
+
+#pragma mark 自动切换透明度
+- (void)setAutoChangeAlpha:(BOOL)autoChangeAlpha
+{
+    self.automaticallyChangeAlpha = autoChangeAlpha;
+}
+
+- (BOOL)isAutoChangeAlpha
+{
+    return self.isAutomaticallyChangeAlpha;
+}
+
+- (void)setAutomaticallyChangeAlpha:(BOOL)automaticallyChangeAlpha
+{
+    _automaticallyChangeAlpha = automaticallyChangeAlpha;
+    
+    if (self.isRefreshing) return;
+    
+    if (automaticallyChangeAlpha) {
+        self.alpha = self.pullingPercent;
+    } else {
+        self.alpha = 1.0;
+    }
+}
+
+#pragma mark 根据拖拽进度设置透明度
+- (void)setPullingPercent:(CGFloat)pullingPercent
+{
+    _pullingPercent = pullingPercent;
+    
+    if (self.isRefreshing) return;
+    
+    if (self.isAutomaticallyChangeAlpha) {
+        self.alpha = pullingPercent;
+    }
+}
+
+#pragma mark - 内部方法
+- (void)executeRefreshingCallback
+{
+    if (self.refreshingBlock) {
+        self.refreshingBlock();
+    }
+    if ([self.refreshingTarget respondsToSelector:self.refreshingAction]) {
+        MJRefreshMsgSend(MJRefreshMsgTarget(self.refreshingTarget), self.refreshingAction, self);
+    }
+    if (self.beginRefreshingCompletionBlock) {
+        self.beginRefreshingCompletionBlock();
+    }
+}
+
+#pragma mark - 刷新动画时间控制
+- (instancetype)setAnimationDisabled {
+    self.fastAnimationDuration = 0;
+    self.slowAnimationDuration = 0;
+    
+    return self;
+}
+
+#pragma mark - <<< Deprecation compatible function >>> -
+- (void)setEndRefreshingAnimateCompletionBlock:(MJRefreshComponentEndRefreshingCompletionBlock)endRefreshingAnimateCompletionBlock {
+    _endRefreshingAnimationBeginAction = endRefreshingAnimateCompletionBlock;
+}
+@end
+
+@implementation UILabel(MJRefresh)
++ (instancetype)mj_label
+{
+    UILabel *label = [[self alloc] init];
+    label.font = MJRefreshLabelFont;
+    label.textColor = MJRefreshLabelTextColor;
+    label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
+    label.textAlignment = NSTextAlignmentCenter;
+    label.backgroundColor = [UIColor clearColor];
+    return label;
+}
+
+- (CGFloat)mj_textWidth {
+    CGFloat stringWidth = 0;
+    CGSize size = CGSizeMake(MAXFLOAT, MAXFLOAT);
+    
+    if (self.attributedText) {
+        if (self.attributedText.length == 0) { return 0; }
+        stringWidth = [self.attributedText boundingRectWithSize:size
+                                                        options:NSStringDrawingUsesLineFragmentOrigin
+                                                        context:nil].size.width;
+    } else {
+        if (self.text.length == 0) { return 0; }
+        NSAssert(self.font != nil, @"请检查 mj_label's `font` 是否设置正确");
+        stringWidth = [self.text boundingRectWithSize:size
+                                              options:NSStringDrawingUsesLineFragmentOrigin
+                                           attributes:@{NSFontAttributeName:self.font}
+                                              context:nil].size.width;
+    }
+    return stringWidth;
+}
+@end
+
+
+#pragma mark - <<< 为 Swift 扩展链式语法 >>> -
+@implementation MJRefreshComponent (ChainingGrammar)
+
+- (instancetype)autoChangeTransparency:(BOOL)isAutoChange {
+    self.automaticallyChangeAlpha = isAutoChange;
+    return self;
+}
+- (instancetype)afterBeginningAction:(MJRefreshComponentAction)action {
+    self.beginRefreshingCompletionBlock = action;
+    return self;
+}
+- (instancetype)endingAnimationBeginningAction:(MJRefreshComponentAction)action {
+    self.endRefreshingAnimationBeginAction = action;
+    return self;
+}
+- (instancetype)afterEndingAction:(MJRefreshComponentAction)action {
+    self.endRefreshingCompletionBlock = action;
+    return self;
+}
+
+- (instancetype)linkTo:(UIScrollView *)scrollView {
+    return self;
+}
+
+@end

+ 37 - 0
Pods/MJRefresh/MJRefresh/Base/MJRefreshFooter.h

@@ -0,0 +1,37 @@
+//  代码地址: https://github.com/CoderMJLee/MJRefresh
+//  MJRefreshFooter.h
+//  MJRefresh
+//
+//  Created by MJ Lee on 15/3/5.
+//  Copyright (c) 2015年 小码哥. All rights reserved.
+//  上拉刷新控件
+
+#if __has_include(<MJRefresh/MJRefreshComponent.h>)
+#import <MJRefresh/MJRefreshComponent.h>
+#else
+#import "MJRefreshComponent.h"
+#endif
+
+NS_ASSUME_NONNULL_BEGIN
+
+@interface MJRefreshFooter : MJRefreshComponent
+/** 创建footer */
++ (instancetype)footerWithRefreshingBlock:(MJRefreshComponentAction)refreshingBlock;
+/** 创建footer */
++ (instancetype)footerWithRefreshingTarget:(id)target refreshingAction:(SEL)action;
+
+/** 提示没有更多的数据 */
+- (void)endRefreshingWithNoMoreData;
+- (void)noticeNoMoreData MJRefreshDeprecated("使用endRefreshingWithNoMoreData");
+
+/** 重置没有更多的数据(消除没有更多数据的状态) */
+- (void)resetNoMoreData;
+
+/** 忽略多少scrollView的contentInset的bottom */
+@property (assign, nonatomic) CGFloat ignoredScrollViewContentInsetBottom;
+
+/** 自动根据有无数据来显示和隐藏(有数据就显示,没有数据隐藏。默认是NO) */
+@property (assign, nonatomic, getter=isAutomaticallyHidden) BOOL automaticallyHidden MJRefreshDeprecated("已废弃此属性,开发者请自行控制footer的显示和隐藏");
+@end
+
+NS_ASSUME_NONNULL_END

+ 71 - 0
Pods/MJRefresh/MJRefresh/Base/MJRefreshFooter.m

@@ -0,0 +1,71 @@
+//  代码地址: https://github.com/CoderMJLee/MJRefresh
+//  MJRefreshFooter.m
+//  MJRefresh
+//
+//  Created by MJ Lee on 15/3/5.
+//  Copyright (c) 2015年 小码哥. All rights reserved.
+//
+
+#import "MJRefreshFooter.h"
+#import "UIScrollView+MJRefresh.h"
+#import "UIView+MJExtension.h"
+
+@interface MJRefreshFooter()
+
+@end
+
+@implementation MJRefreshFooter
+#pragma mark - 构造方法
++ (instancetype)footerWithRefreshingBlock:(MJRefreshComponentAction)refreshingBlock
+{
+    MJRefreshFooter *cmp = [[self alloc] init];
+    cmp.refreshingBlock = refreshingBlock;
+    return cmp;
+}
++ (instancetype)footerWithRefreshingTarget:(id)target refreshingAction:(SEL)action
+{
+    MJRefreshFooter *cmp = [[self alloc] init];
+    [cmp setRefreshingTarget:target refreshingAction:action];
+    return cmp;
+}
+
+#pragma mark - 重写父类的方法
+- (void)prepare
+{
+    [super prepare];
+    
+    // 设置自己的高度
+    self.mj_h = MJRefreshFooterHeight;
+    
+    // 默认不会自动隐藏
+//    self.automaticallyHidden = NO;
+}
+
+#pragma mark . 链式语法部分 .
+
+- (instancetype)linkTo:(UIScrollView *)scrollView {
+    scrollView.mj_footer = self;
+    return self;
+}
+
+#pragma mark - 公共方法
+- (void)endRefreshingWithNoMoreData
+{
+    MJRefreshDispatchAsyncOnMainQueue(self.state = MJRefreshStateNoMoreData;)
+}
+
+- (void)noticeNoMoreData
+{
+    [self endRefreshingWithNoMoreData];
+}
+
+- (void)resetNoMoreData
+{
+    MJRefreshDispatchAsyncOnMainQueue(self.state = MJRefreshStateIdle;)
+}
+
+- (void)setAutomaticallyHidden:(BOOL)automaticallyHidden
+{
+    _automaticallyHidden = automaticallyHidden;
+}
+@end

+ 35 - 0
Pods/MJRefresh/MJRefresh/Base/MJRefreshHeader.h

@@ -0,0 +1,35 @@
+//  代码地址: https://github.com/CoderMJLee/MJRefresh
+//  MJRefreshHeader.h
+//  MJRefresh
+//
+//  Created by MJ Lee on 15/3/4.
+//  Copyright (c) 2015年 小码哥. All rights reserved.
+//  下拉刷新控件:负责监控用户下拉的状态
+
+#if __has_include(<MJRefresh/MJRefreshComponent.h>)
+#import <MJRefresh/MJRefreshComponent.h>
+#else
+#import "MJRefreshComponent.h"
+#endif
+
+NS_ASSUME_NONNULL_BEGIN
+
+@interface MJRefreshHeader : MJRefreshComponent
+/** 创建header */
++ (instancetype)headerWithRefreshingBlock:(MJRefreshComponentAction)refreshingBlock;
+/** 创建header */
++ (instancetype)headerWithRefreshingTarget:(id)target refreshingAction:(SEL)action;
+
+/** 这个key用来存储上一次下拉刷新成功的时间 */
+@property (copy, nonatomic) NSString *lastUpdatedTimeKey;
+/** 上一次下拉刷新成功的时间 */
+@property (strong, nonatomic, readonly, nullable) NSDate *lastUpdatedTime;
+
+/** 忽略多少scrollView的contentInset的top */
+@property (assign, nonatomic) CGFloat ignoredScrollViewContentInsetTop;
+
+/** 默认是关闭状态, 如果遇到 CollectionView 的动画异常问题可以尝试打开 */
+@property (nonatomic) BOOL isCollectionViewAnimationBug;
+@end
+
+NS_ASSUME_NONNULL_END

+ 297 - 0
Pods/MJRefresh/MJRefresh/Base/MJRefreshHeader.m

@@ -0,0 +1,297 @@
+//  代码地址: https://github.com/CoderMJLee/MJRefresh
+//  MJRefreshHeader.m
+//  MJRefresh
+//
+//  Created by MJ Lee on 15/3/4.
+//  Copyright (c) 2015年 小码哥. All rights reserved.
+//
+
+#import "MJRefreshHeader.h"
+#import "UIView+MJExtension.h"
+#import "UIScrollView+MJExtension.h"
+#import "UIScrollView+MJRefresh.h"
+
+NSString * const MJRefreshHeaderRefreshing2IdleBoundsKey = @"MJRefreshHeaderRefreshing2IdleBounds";
+NSString * const MJRefreshHeaderRefreshingBoundsKey = @"MJRefreshHeaderRefreshingBounds";
+
+@interface MJRefreshHeader() <CAAnimationDelegate>
+@property (assign, nonatomic) CGFloat insetTDelta;
+@end
+
+@implementation MJRefreshHeader
+#pragma mark - 构造方法
++ (instancetype)headerWithRefreshingBlock:(MJRefreshComponentAction)refreshingBlock
+{
+    MJRefreshHeader *cmp = [[self alloc] init];
+    cmp.refreshingBlock = refreshingBlock;
+    return cmp;
+}
++ (instancetype)headerWithRefreshingTarget:(id)target refreshingAction:(SEL)action
+{
+    MJRefreshHeader *cmp = [[self alloc] init];
+    [cmp setRefreshingTarget:target refreshingAction:action];
+    return cmp;
+}
+
+#pragma mark - 覆盖父类的方法
+- (void)prepare
+{
+    [super prepare];
+    
+    // 设置key
+    self.lastUpdatedTimeKey = MJRefreshHeaderLastUpdatedTimeKey;
+    
+    // 设置高度
+    self.mj_h = MJRefreshHeaderHeight;
+}
+
+- (void)placeSubviews
+{
+    [super placeSubviews];
+    
+    // 设置y值(当自己的高度发生改变了,肯定要重新调整Y值,所以放到placeSubviews方法中设置y值)
+    self.mj_y = - self.mj_h - self.ignoredScrollViewContentInsetTop;
+}
+
+- (void)resetInset {
+    if (@available(iOS 11.0, *)) {
+    } else {
+        // 如果 iOS 10 及以下系统在刷新时, push 新的 VC, 等待刷新完成后回来, 会导致顶部 Insets.top 异常, 不能 resetInset, 检查一下这种特殊情况
+        if (!self.window) { return; }
+    }
+    
+    // sectionheader停留解决
+    CGFloat insetT = - self.scrollView.mj_offsetY > _scrollViewOriginalInset.top ? - self.scrollView.mj_offsetY : _scrollViewOriginalInset.top;
+    insetT = insetT > self.mj_h + _scrollViewOriginalInset.top ? self.mj_h + _scrollViewOriginalInset.top : insetT;
+    self.insetTDelta = _scrollViewOriginalInset.top - insetT;
+    // 避免 CollectionView 在使用根据 Autolayout 和 内容自动伸缩 Cell, 刷新时导致的 Layout 异常渲染问题
+    if (self.scrollView.mj_insetT != insetT) {
+        self.scrollView.mj_insetT = insetT;
+    }
+}
+
+- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change
+{
+    [super scrollViewContentOffsetDidChange:change];
+    
+    // 在刷新的refreshing状态
+    if (self.state == MJRefreshStateRefreshing) {
+        [self resetInset];
+        return;
+    }
+    
+    // 跳转到下一个控制器时,contentInset可能会变
+    _scrollViewOriginalInset = self.scrollView.mj_inset;
+    
+    // 当前的contentOffset
+    CGFloat offsetY = self.scrollView.mj_offsetY;
+    // 头部控件刚好出现的offsetY
+    CGFloat happenOffsetY = - self.scrollViewOriginalInset.top;
+    
+    // 如果是向上滚动到看不见头部控件,直接返回
+    // >= -> >
+    if (offsetY > happenOffsetY) return;
+    
+    // 普通 和 即将刷新 的临界点
+    CGFloat normal2pullingOffsetY = happenOffsetY - self.mj_h;
+    CGFloat pullingPercent = (happenOffsetY - offsetY) / self.mj_h;
+    
+    if (self.scrollView.isDragging) { // 如果正在拖拽
+        self.pullingPercent = pullingPercent;
+        if (self.state == MJRefreshStateIdle && offsetY < normal2pullingOffsetY) {
+            // 转为即将刷新状态
+            self.state = MJRefreshStatePulling;
+        } else if (self.state == MJRefreshStatePulling && offsetY >= normal2pullingOffsetY) {
+            // 转为普通状态
+            self.state = MJRefreshStateIdle;
+        }
+    } else if (self.state == MJRefreshStatePulling) {// 即将刷新 && 手松开
+        // 开始刷新
+        [self beginRefreshing];
+    } else if (pullingPercent < 1) {
+        self.pullingPercent = pullingPercent;
+    }
+}
+
+- (void)setState:(MJRefreshState)state
+{
+    MJRefreshCheckState
+    
+    // 根据状态做事情
+    if (state == MJRefreshStateIdle) {
+        if (oldState != MJRefreshStateRefreshing) return;
+        
+        [self headerEndingAction];
+    } else if (state == MJRefreshStateRefreshing) {
+        [self headerRefreshingAction];
+    }
+}
+
+- (void)headerEndingAction {
+    // 保存刷新时间
+    [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:self.lastUpdatedTimeKey];
+    [[NSUserDefaults standardUserDefaults] synchronize];
+    
+    // 默认使用 UIViewAnimation 动画
+    if (!self.isCollectionViewAnimationBug) {
+        // 恢复inset和offset
+        [UIView animateWithDuration:self.slowAnimationDuration animations:^{
+            self.scrollView.mj_insetT += self.insetTDelta;
+            
+            if (self.endRefreshingAnimationBeginAction) {
+                self.endRefreshingAnimationBeginAction();
+            }
+            // 自动调整透明度
+            if (self.isAutomaticallyChangeAlpha) self.alpha = 0.0;
+        } completion:^(BOOL finished) {
+            self.pullingPercent = 0.0;
+            
+            if (self.endRefreshingCompletionBlock) {
+                self.endRefreshingCompletionBlock();
+            }
+        }];
+        
+        return;
+    }
+    
+    /**
+     这个解决方法的思路出自 https://github.com/CoderMJLee/MJRefresh/pull/844
+     修改了用+ [UIView animateWithDuration: animations:]实现的修改contentInset的动画
+     fix issue#225 https://github.com/CoderMJLee/MJRefresh/issues/225
+     另一种解法 pull#737 https://github.com/CoderMJLee/MJRefresh/pull/737
+     
+     同时, 处理了 Refreshing 中的动画替换.
+    */
+    
+    // 由于修改 Inset 会导致 self.pullingPercent 联动设置 self.alpha, 故提前获取 alpha 值, 后续用于还原 alpha 动画
+    CGFloat viewAlpha = self.alpha;
+    
+    self.scrollView.mj_insetT += self.insetTDelta;
+    // 禁用交互, 如果不禁用可能会引起渲染问题.
+    self.scrollView.userInteractionEnabled = NO;
+
+    //CAAnimation keyPath 不支持 contentInset 用Bounds的动画代替
+    CABasicAnimation *boundsAnimation = [CABasicAnimation animationWithKeyPath:@"bounds"];
+    boundsAnimation.fromValue = [NSValue valueWithCGRect:CGRectOffset(self.scrollView.bounds, 0, self.insetTDelta)];
+    boundsAnimation.duration = self.slowAnimationDuration;
+    //在delegate里移除
+    boundsAnimation.removedOnCompletion = NO;
+    boundsAnimation.fillMode = kCAFillModeBoth;
+    boundsAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
+    boundsAnimation.delegate = self;
+    [boundsAnimation setValue:MJRefreshHeaderRefreshing2IdleBoundsKey forKey:@"identity"];
+
+    [self.scrollView.layer addAnimation:boundsAnimation forKey:MJRefreshHeaderRefreshing2IdleBoundsKey];
+    
+    if (self.endRefreshingAnimationBeginAction) {
+        self.endRefreshingAnimationBeginAction();
+    }
+    // 自动调整透明度的动画
+    if (self.isAutomaticallyChangeAlpha) {
+        CABasicAnimation *opacityAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
+        opacityAnimation.fromValue = @(viewAlpha);
+        opacityAnimation.toValue = @(0.0);
+        opacityAnimation.duration = self.slowAnimationDuration;
+        opacityAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
+        [self.layer addAnimation:opacityAnimation forKey:@"MJRefreshHeaderRefreshing2IdleOpacity"];
+
+        // 由于修改了 inset 导致, pullingPercent 被设置值, alpha 已经被提前修改为 0 了. 所以这里不用置 0, 但为了代码的严谨性, 不依赖其他的特殊实现方式, 这里还是置 0.
+        self.alpha = 0;
+    }
+}
+
+- (void)headerRefreshingAction {
+    // 默认使用 UIViewAnimation 动画
+    if (!self.isCollectionViewAnimationBug) {
+        [UIView animateWithDuration:self.fastAnimationDuration animations:^{
+            if (self.scrollView.panGestureRecognizer.state != UIGestureRecognizerStateCancelled) {
+                CGFloat top = self.scrollViewOriginalInset.top + self.mj_h;
+                // 增加滚动区域top
+                self.scrollView.mj_insetT = top;
+                // 设置滚动位置
+                CGPoint offset = self.scrollView.contentOffset;
+                offset.y = -top;
+                [self.scrollView setContentOffset:offset animated:NO];
+            }
+        } completion:^(BOOL finished) {
+            [self executeRefreshingCallback];
+        }];
+        return;
+    }
+    
+    if (self.scrollView.panGestureRecognizer.state != UIGestureRecognizerStateCancelled) {
+        CGFloat top = self.scrollViewOriginalInset.top + self.mj_h;
+        // 禁用交互, 如果不禁用可能会引起渲染问题.
+        self.scrollView.userInteractionEnabled = NO;
+
+        // CAAnimation keyPath不支持 contentOffset 用Bounds的动画代替
+        CABasicAnimation *boundsAnimation = [CABasicAnimation animationWithKeyPath:@"bounds"];
+        CGRect bounds = self.scrollView.bounds;
+        bounds.origin.y = -top;
+        boundsAnimation.fromValue = [NSValue valueWithCGRect:self.scrollView.bounds];
+        boundsAnimation.toValue = [NSValue valueWithCGRect:bounds];
+        boundsAnimation.duration = self.fastAnimationDuration;
+        //在delegate里移除
+        boundsAnimation.removedOnCompletion = NO;
+        boundsAnimation.fillMode = kCAFillModeBoth;
+        boundsAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
+        boundsAnimation.delegate = self;
+        [boundsAnimation setValue:MJRefreshHeaderRefreshingBoundsKey forKey:@"identity"];
+        [self.scrollView.layer addAnimation:boundsAnimation forKey:MJRefreshHeaderRefreshingBoundsKey];
+    } else {
+        [self executeRefreshingCallback];
+    }
+}
+
+#pragma mark . 链式语法部分 .
+
+- (instancetype)linkTo:(UIScrollView *)scrollView {
+    scrollView.mj_header = self;
+    return self;
+}
+
+#pragma mark - CAAnimationDelegate
+- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
+    NSString *identity = [anim valueForKey:@"identity"];
+    if ([identity isEqualToString:MJRefreshHeaderRefreshing2IdleBoundsKey]) {
+        self.pullingPercent = 0.0;
+        self.scrollView.userInteractionEnabled = YES;
+        if (self.endRefreshingCompletionBlock) {
+            self.endRefreshingCompletionBlock();
+        }
+    } else if ([identity isEqualToString:MJRefreshHeaderRefreshingBoundsKey]) {
+        // 避免出现 end 先于 Refreshing 状态
+        if (self.state != MJRefreshStateIdle) {
+            CGFloat top = self.scrollViewOriginalInset.top + self.mj_h;
+            self.scrollView.mj_insetT = top;
+            // 设置最终滚动位置
+            CGPoint offset = self.scrollView.contentOffset;
+            offset.y = -top;
+            [self.scrollView setContentOffset:offset animated:NO];
+         }
+        self.scrollView.userInteractionEnabled = YES;
+        [self executeRefreshingCallback];
+    }
+    
+    if ([self.scrollView.layer animationForKey:MJRefreshHeaderRefreshing2IdleBoundsKey]) {
+        [self.scrollView.layer removeAnimationForKey:MJRefreshHeaderRefreshing2IdleBoundsKey];
+    }
+    
+    if ([self.scrollView.layer animationForKey:MJRefreshHeaderRefreshingBoundsKey]) {
+        [self.scrollView.layer removeAnimationForKey:MJRefreshHeaderRefreshingBoundsKey];
+    }
+}
+
+#pragma mark - 公共方法
+- (NSDate *)lastUpdatedTime
+{
+    return [[NSUserDefaults standardUserDefaults] objectForKey:self.lastUpdatedTimeKey];
+}
+
+- (void)setIgnoredScrollViewContentInsetTop:(CGFloat)ignoredScrollViewContentInsetTop {
+    _ignoredScrollViewContentInsetTop = ignoredScrollViewContentInsetTop;
+    
+    self.mj_y = - self.mj_h - _ignoredScrollViewContentInsetTop;
+}
+
+@end

+ 30 - 0
Pods/MJRefresh/MJRefresh/Base/MJRefreshTrailer.h

@@ -0,0 +1,30 @@
+//
+//  MJRefreshTrailer.h
+//  MJRefresh
+//
+//  Created by kinarobin on 2020/5/3.
+//  Copyright © 2020 小码哥. All rights reserved.
+//
+
+#if __has_include(<MJRefresh/MJRefreshComponent.h>)
+#import <MJRefresh/MJRefreshComponent.h>
+#else
+#import "MJRefreshComponent.h"
+#endif
+
+NS_ASSUME_NONNULL_BEGIN
+
+@interface MJRefreshTrailer : MJRefreshComponent
+
+/** 创建trailer*/
++ (instancetype)trailerWithRefreshingBlock:(MJRefreshComponentAction)refreshingBlock;
+/** 创建trailer */
++ (instancetype)trailerWithRefreshingTarget:(id)target refreshingAction:(SEL)action;
+
+/** 忽略多少scrollView的contentInset的right */
+@property (assign, nonatomic) CGFloat ignoredScrollViewContentInsetRight;
+
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 179 - 0
Pods/MJRefresh/MJRefresh/Base/MJRefreshTrailer.m

@@ -0,0 +1,179 @@
+//
+//  MJRefreshTrailer.m
+//  MJRefresh
+//
+//  Created by kinarobin on 2020/5/3.
+//  Copyright © 2020 小码哥. All rights reserved.
+//
+
+#import "MJRefreshTrailer.h"
+#import "UIView+MJExtension.h"
+#import "UIScrollView+MJRefresh.h"
+#import "UIScrollView+MJExtension.h"
+
+@interface MJRefreshTrailer()
+@property (assign, nonatomic) NSInteger lastRefreshCount;
+@property (assign, nonatomic) CGFloat lastRightDelta;
+@end
+
+@implementation MJRefreshTrailer
+
+#pragma mark - 构造方法
++ (instancetype)trailerWithRefreshingBlock:(MJRefreshComponentAction)refreshingBlock {
+    MJRefreshTrailer *cmp = [[self alloc] init];
+    cmp.refreshingBlock = refreshingBlock;
+    return cmp;
+}
+
++ (instancetype)trailerWithRefreshingTarget:(id)target refreshingAction:(SEL)action {
+    MJRefreshTrailer *cmp = [[self alloc] init];
+    [cmp setRefreshingTarget:target refreshingAction:action];
+    return cmp;
+}
+
+- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change {
+    [super scrollViewContentOffsetDidChange:change];
+    
+    // 如果正在刷新,直接返回
+    if (self.state == MJRefreshStateRefreshing) return;
+    
+    _scrollViewOriginalInset = self.scrollView.mj_inset;
+    
+    // 当前的contentOffset
+    CGFloat currentOffsetX = self.scrollView.mj_offsetX;
+    // 尾部控件刚好出现的offsetX
+    CGFloat happenOffsetX = [self happenOffsetX];
+    // 如果是向右滚动到看不见右边控件,直接返回
+    if (currentOffsetX <= happenOffsetX) return;
+    
+    CGFloat pullingPercent = (currentOffsetX - happenOffsetX) / self.mj_w;
+    
+    // 如果已全部加载,仅设置pullingPercent,然后返回
+    if (self.state == MJRefreshStateNoMoreData) {
+        self.pullingPercent = pullingPercent;
+        return;
+    }
+    
+    if (self.scrollView.isDragging) {
+        self.pullingPercent = pullingPercent;
+        // 普通 和 即将刷新 的临界点
+        CGFloat normal2pullingOffsetX = happenOffsetX + self.mj_w;
+        
+        if (self.state == MJRefreshStateIdle && currentOffsetX > normal2pullingOffsetX) {
+            self.state = MJRefreshStatePulling;
+        } else if (self.state == MJRefreshStatePulling && currentOffsetX <= normal2pullingOffsetX) {
+            // 转为普通状态
+            self.state = MJRefreshStateIdle;
+        }
+    } else if (self.state == MJRefreshStatePulling) {// 即将刷新 && 手松开
+        // 开始刷新
+        [self beginRefreshing];
+    } else if (pullingPercent < 1) {
+        self.pullingPercent = pullingPercent;
+    }
+}
+
+- (void)setState:(MJRefreshState)state {
+    MJRefreshCheckState
+    // 根据状态来设置属性
+    if (state == MJRefreshStateNoMoreData || state == MJRefreshStateIdle) {
+        // 刷新完毕
+        if (MJRefreshStateRefreshing == oldState) {
+            [UIView animateWithDuration:self.slowAnimationDuration animations:^{
+                if (self.endRefreshingAnimationBeginAction) {
+                    self.endRefreshingAnimationBeginAction();
+                }
+                
+                self.scrollView.mj_insetR -= self.lastRightDelta;
+                // 自动调整透明度
+                if (self.isAutomaticallyChangeAlpha) self.alpha = 0.0;
+            } completion:^(BOOL finished) {
+                self.pullingPercent = 0.0;
+                
+                if (self.endRefreshingCompletionBlock) {
+                    self.endRefreshingCompletionBlock();
+                }
+            }];
+        }
+        
+        CGFloat deltaW = [self widthForContentBreakView];
+        // 刚刷新完毕
+        if (MJRefreshStateRefreshing == oldState && deltaW > 0 && self.scrollView.mj_totalDataCount != self.lastRefreshCount) {
+            self.scrollView.mj_offsetX = self.scrollView.mj_offsetX;
+        }
+    } else if (state == MJRefreshStateRefreshing) {
+        // 记录刷新前的数量
+        self.lastRefreshCount = self.scrollView.mj_totalDataCount;
+        
+        [UIView animateWithDuration:self.fastAnimationDuration animations:^{
+            CGFloat right = self.mj_w + self.scrollViewOriginalInset.right;
+            CGFloat deltaW = [self widthForContentBreakView];
+            if (deltaW < 0) { // 如果内容宽度小于view的宽度
+                right -= deltaW;
+            }
+            self.lastRightDelta = right - self.scrollView.mj_insetR;
+            self.scrollView.mj_insetR = right;
+            
+            // 设置滚动位置
+            CGPoint offset = self.scrollView.contentOffset;
+            offset.x = [self happenOffsetX] + self.mj_w;
+            [self.scrollView setContentOffset:offset animated:NO];
+        } completion:^(BOOL finished) {
+            [self executeRefreshingCallback];
+        }];
+    }
+}
+
+- (void)scrollViewContentSizeDidChange:(NSDictionary *)change {
+    [super scrollViewContentSizeDidChange:change];
+    
+    // 内容的宽度
+    CGFloat contentWidth = self.scrollView.mj_contentW + self.ignoredScrollViewContentInsetRight;
+    // 表格的宽度
+    CGFloat scrollWidth = self.scrollView.mj_w - self.scrollViewOriginalInset.left - self.scrollViewOriginalInset.right + self.ignoredScrollViewContentInsetRight;
+    // 设置位置和尺寸
+    self.mj_x = MAX(contentWidth, scrollWidth);
+}
+
+- (void)placeSubviews {
+    [super placeSubviews];
+    
+    self.mj_h = _scrollView.mj_h;
+    // 设置自己的宽度
+    self.mj_w = MJRefreshTrailWidth;
+}
+
+- (void)willMoveToSuperview:(UIView *)newSuperview {
+    [super willMoveToSuperview:newSuperview];
+    
+    if (newSuperview) {
+        // 设置支持水平弹簧效果
+        _scrollView.alwaysBounceHorizontal = YES;
+        _scrollView.alwaysBounceVertical = NO;
+    }
+}
+
+#pragma mark . 链式语法部分 .
+
+- (instancetype)linkTo:(UIScrollView *)scrollView {
+    scrollView.mj_trailer = self;
+    return self;
+}
+
+#pragma mark - 刚好看到上拉刷新控件时的contentOffset.x
+- (CGFloat)happenOffsetX {
+    CGFloat deltaW = [self widthForContentBreakView];
+    if (deltaW > 0) {
+        return deltaW - self.scrollViewOriginalInset.left;
+    } else {
+        return - self.scrollViewOriginalInset.left;
+    }
+}
+
+#pragma mark 获得scrollView的内容 超出 view 的宽度
+- (CGFloat)widthForContentBreakView {
+    CGFloat w = self.scrollView.frame.size.width - self.scrollViewOriginalInset.right - self.scrollViewOriginalInset.left;
+    return self.scrollView.contentSize.width - w;
+}
+
+@end

+ 25 - 0
Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoGifFooter.h

@@ -0,0 +1,25 @@
+//
+//  MJRefreshAutoGifFooter.h
+//  MJRefresh
+//
+//  Created by MJ Lee on 15/4/24.
+//  Copyright (c) 2015年 小码哥. All rights reserved.
+//
+
+#if __has_include(<MJRefresh/MJRefreshAutoStateFooter.h>)
+#import <MJRefresh/MJRefreshAutoStateFooter.h>
+#else
+#import "MJRefreshAutoStateFooter.h"
+#endif
+
+NS_ASSUME_NONNULL_BEGIN
+
+@interface MJRefreshAutoGifFooter : MJRefreshAutoStateFooter
+@property (weak, nonatomic, readonly) UIImageView *gifView;
+
+/** 设置state状态下的动画图片images 动画持续时间duration*/
+- (instancetype)setImages:(NSArray *)images duration:(NSTimeInterval)duration forState:(MJRefreshState)state;
+- (instancetype)setImages:(NSArray *)images forState:(MJRefreshState)state;
+@end
+
+NS_ASSUME_NONNULL_END

+ 121 - 0
Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoGifFooter.m

@@ -0,0 +1,121 @@
+//
+//  MJRefreshAutoGifFooter.m
+//  MJRefresh
+//
+//  Created by MJ Lee on 15/4/24.
+//  Copyright (c) 2015年 小码哥. All rights reserved.
+//
+
+#import "MJRefreshAutoGifFooter.h"
+#import "NSBundle+MJRefresh.h"
+#import "UIView+MJExtension.h"
+#import "UIScrollView+MJExtension.h"
+#import "UIScrollView+MJRefresh.h"
+
+@interface MJRefreshAutoGifFooter()
+{
+    __unsafe_unretained UIImageView *_gifView;
+}
+/** 所有状态对应的动画图片 */
+@property (strong, nonatomic) NSMutableDictionary *stateImages;
+/** 所有状态对应的动画时间 */
+@property (strong, nonatomic) NSMutableDictionary *stateDurations;
+@end
+
+@implementation MJRefreshAutoGifFooter
+#pragma mark - 懒加载
+- (UIImageView *)gifView
+{
+    if (!_gifView) {
+        UIImageView *gifView = [[UIImageView alloc] init];
+        [self addSubview:_gifView = gifView];
+    }
+    return _gifView;
+}
+
+- (NSMutableDictionary *)stateImages
+{
+    if (!_stateImages) {
+        self.stateImages = [NSMutableDictionary dictionary];
+    }
+    return _stateImages;
+}
+
+- (NSMutableDictionary *)stateDurations
+{
+    if (!_stateDurations) {
+        self.stateDurations = [NSMutableDictionary dictionary];
+    }
+    return _stateDurations;
+}
+
+#pragma mark - 公共方法
+- (instancetype)setImages:(NSArray *)images duration:(NSTimeInterval)duration forState:(MJRefreshState)state
+{
+    if (images == nil) return self;
+    
+    self.stateImages[@(state)] = images;
+    self.stateDurations[@(state)] = @(duration);
+    
+    /* 根据图片设置控件的高度 */
+    UIImage *image = [images firstObject];
+    if (image.size.height > self.mj_h) {
+        self.mj_h = image.size.height;
+    }
+    return self;
+}
+
+- (instancetype)setImages:(NSArray *)images forState:(MJRefreshState)state
+{
+    return [self setImages:images duration:images.count * 0.1 forState:state];
+}
+
+#pragma mark - 实现父类的方法
+- (void)prepare
+{
+    [super prepare];
+    
+    // 初始化间距
+    self.labelLeftInset = 20;
+}
+
+- (void)placeSubviews
+{
+    [super placeSubviews];
+    
+    if (self.gifView.constraints.count) return;
+    
+    self.gifView.frame = self.bounds;
+    if (self.isRefreshingTitleHidden) {
+        self.gifView.contentMode = UIViewContentModeCenter;
+    } else {
+        self.gifView.contentMode = UIViewContentModeRight;
+        self.gifView.mj_w = self.mj_w * 0.5 - self.labelLeftInset - self.stateLabel.mj_textWidth * 0.5;
+    }
+}
+
+- (void)setState:(MJRefreshState)state
+{
+    MJRefreshCheckState
+    
+    // 根据状态做事情
+    if (state == MJRefreshStateRefreshing) {
+        NSArray *images = self.stateImages[@(state)];
+        if (images.count == 0) return;
+        [self.gifView stopAnimating];
+        
+        self.gifView.hidden = NO;
+        if (images.count == 1) { // 单张图片
+            self.gifView.image = [images lastObject];
+        } else { // 多张图片
+            self.gifView.animationImages = images;
+            self.gifView.animationDuration = [self.stateDurations[@(state)] doubleValue];
+            [self.gifView startAnimating];
+        }
+    } else if (state == MJRefreshStateNoMoreData || state == MJRefreshStateIdle) {
+        [self.gifView stopAnimating];
+        self.gifView.hidden = YES;
+    }
+}
+@end
+

+ 25 - 0
Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoNormalFooter.h

@@ -0,0 +1,25 @@
+//
+//  MJRefreshAutoNormalFooter.h
+//  MJRefresh
+//
+//  Created by MJ Lee on 15/4/24.
+//  Copyright (c) 2015年 小码哥. All rights reserved.
+//
+
+#if __has_include(<MJRefresh/MJRefreshAutoStateFooter.h>)
+#import <MJRefresh/MJRefreshAutoStateFooter.h>
+#else
+#import "MJRefreshAutoStateFooter.h"
+#endif
+
+NS_ASSUME_NONNULL_BEGIN
+
+@interface MJRefreshAutoNormalFooter : MJRefreshAutoStateFooter
+@property (weak, nonatomic, readonly) UIActivityIndicatorView *loadingView;
+
+/** 菊花的样式 */
+@property (assign, nonatomic) UIActivityIndicatorViewStyle activityIndicatorViewStyle MJRefreshDeprecated("first deprecated in 3.2.2 - Use `loadingView` property");
+@end
+
+
+NS_ASSUME_NONNULL_END

+ 81 - 0
Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoNormalFooter.m

@@ -0,0 +1,81 @@
+//
+//  MJRefreshAutoNormalFooter.m
+//  MJRefresh
+//
+//  Created by MJ Lee on 15/4/24.
+//  Copyright (c) 2015年 小码哥. All rights reserved.
+//
+
+#import "MJRefreshAutoNormalFooter.h"
+#import "NSBundle+MJRefresh.h"
+#import "UIView+MJExtension.h"
+#import "UIScrollView+MJExtension.h"
+#import "UIScrollView+MJRefresh.h"
+
+@interface MJRefreshAutoNormalFooter()
+@property (weak, nonatomic) UIActivityIndicatorView *loadingView;
+@end
+
+@implementation MJRefreshAutoNormalFooter
+#pragma mark - 懒加载子控件
+- (UIActivityIndicatorView *)loadingView
+{
+    if (!_loadingView) {
+        UIActivityIndicatorView *loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:_activityIndicatorViewStyle];
+        loadingView.hidesWhenStopped = YES;
+        [self addSubview:_loadingView = loadingView];
+    }
+    return _loadingView;
+}
+
+- (void)setActivityIndicatorViewStyle:(UIActivityIndicatorViewStyle)activityIndicatorViewStyle
+{
+    _activityIndicatorViewStyle = activityIndicatorViewStyle;
+    
+    [self.loadingView removeFromSuperview];
+    self.loadingView = nil;
+    [self setNeedsLayout];
+}
+#pragma mark - 重写父类的方法
+- (void)prepare
+{
+    [super prepare];
+    
+#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
+    if (@available(iOS 13.0, *)) {
+        _activityIndicatorViewStyle = UIActivityIndicatorViewStyleMedium;
+        return;
+    }
+#endif
+        
+    _activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
+}
+
+- (void)placeSubviews
+{
+    [super placeSubviews];
+    
+    if (self.loadingView.constraints.count) return;
+    
+    // 圈圈
+    CGFloat loadingCenterX = self.mj_w * 0.5;
+    if (!self.isRefreshingTitleHidden) {
+        loadingCenterX -= self.stateLabel.mj_textWidth * 0.5 + self.labelLeftInset;
+    }
+    CGFloat loadingCenterY = self.mj_h * 0.5;
+    self.loadingView.center = CGPointMake(loadingCenterX, loadingCenterY);
+}
+
+- (void)setState:(MJRefreshState)state
+{
+    MJRefreshCheckState
+    
+    // 根据状态做事情
+    if (state == MJRefreshStateNoMoreData || state == MJRefreshStateIdle) {
+        [self.loadingView stopAnimating];
+    } else if (state == MJRefreshStateRefreshing) {
+        [self.loadingView startAnimating];
+    }
+}
+
+@end

+ 30 - 0
Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoStateFooter.h

@@ -0,0 +1,30 @@
+//
+//  MJRefreshAutoStateFooter.h
+//  MJRefresh
+//
+//  Created by MJ Lee on 15/6/13.
+//  Copyright © 2015年 小码哥. All rights reserved.
+//
+
+#if __has_include(<MJRefresh/MJRefreshAutoFooter.h>)
+#import <MJRefresh/MJRefreshAutoFooter.h>
+#else
+#import "MJRefreshAutoFooter.h"
+#endif
+
+NS_ASSUME_NONNULL_BEGIN
+
+@interface MJRefreshAutoStateFooter : MJRefreshAutoFooter
+/** 文字距离圈圈、箭头的距离 */
+@property (assign, nonatomic) CGFloat labelLeftInset;
+/** 显示刷新状态的label */
+@property (weak, nonatomic, readonly) UILabel *stateLabel;
+
+/** 设置state状态下的文字 */
+- (instancetype)setTitle:(NSString *)title forState:(MJRefreshState)state;
+
+/** 隐藏刷新状态的文字 */
+@property (assign, nonatomic, getter=isRefreshingTitleHidden) BOOL refreshingTitleHidden;
+@end
+
+NS_ASSUME_NONNULL_END

+ 119 - 0
Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoStateFooter.m

@@ -0,0 +1,119 @@
+//
+//  MJRefreshAutoStateFooter.m
+//  MJRefresh
+//
+//  Created by MJ Lee on 15/6/13.
+//  Copyright © 2015年 小码哥. All rights reserved.
+//
+
+#import "MJRefreshAutoStateFooter.h"
+#import "NSBundle+MJRefresh.h"
+
+@interface MJRefreshAutoFooter (TapTriggerFix)
+
+- (void)beginRefreshingWithoutValidation;
+@end
+
+
+@implementation MJRefreshAutoFooter (TapTriggerFix)
+
+- (void)beginRefreshingWithoutValidation {
+    [super beginRefreshing];
+}
+
+@end
+
+@interface MJRefreshAutoStateFooter()
+{
+    /** 显示刷新状态的label */
+    __unsafe_unretained UILabel *_stateLabel;
+}
+/** 所有状态对应的文字 */
+@property (strong, nonatomic) NSMutableDictionary *stateTitles;
+@end
+
+@implementation MJRefreshAutoStateFooter
+#pragma mark - 懒加载
+- (NSMutableDictionary *)stateTitles
+{
+    if (!_stateTitles) {
+        self.stateTitles = [NSMutableDictionary dictionary];
+    }
+    return _stateTitles;
+}
+
+- (UILabel *)stateLabel
+{
+    if (!_stateLabel) {
+        [self addSubview:_stateLabel = [UILabel mj_label]];
+    }
+    return _stateLabel;
+}
+
+#pragma mark - 公共方法
+- (instancetype)setTitle:(NSString *)title forState:(MJRefreshState)state
+{
+    if (title == nil) return self;
+    self.stateTitles[@(state)] = title;
+    self.stateLabel.text = self.stateTitles[@(self.state)];
+    return self;
+}
+
+#pragma mark - 私有方法
+- (void)stateLabelClick
+{
+    if (self.state == MJRefreshStateIdle) {
+        [super beginRefreshingWithoutValidation];
+    }
+}
+
+- (void)textConfiguration {
+    // 初始化文字
+    [self setTitle:[NSBundle mj_localizedStringForKey:MJRefreshAutoFooterIdleText] forState:MJRefreshStateIdle];
+    [self setTitle:[NSBundle mj_localizedStringForKey:MJRefreshAutoFooterRefreshingText] forState:MJRefreshStateRefreshing];
+    [self setTitle:[NSBundle mj_localizedStringForKey:MJRefreshAutoFooterNoMoreDataText] forState:MJRefreshStateNoMoreData];
+}
+
+#pragma mark - 重写父类的方法
+- (void)prepare
+{
+    [super prepare];
+    
+    // 初始化间距
+    self.labelLeftInset = MJRefreshLabelLeftInset;
+    
+    [self textConfiguration];
+    
+    // 监听label
+    self.stateLabel.userInteractionEnabled = YES;
+    [self.stateLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(stateLabelClick)]];
+}
+
+- (void)i18nDidChange {
+    [self textConfiguration];
+    
+    [super i18nDidChange];
+}
+
+
+- (void)placeSubviews
+{
+    [super placeSubviews];
+    
+    if (self.stateLabel.constraints.count) return;
+    
+    // 状态标签
+    self.stateLabel.frame = self.bounds;
+}
+
+- (void)setState:(MJRefreshState)state
+{
+    MJRefreshCheckState
+    
+    if (self.isRefreshingTitleHidden && state == MJRefreshStateRefreshing) {
+        self.stateLabel.text = nil;
+    } else {
+        self.stateLabel.text = self.stateTitles[@(state)];
+    }
+}
+@end

+ 25 - 0
Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackGifFooter.h

@@ -0,0 +1,25 @@
+//
+//  MJRefreshBackGifFooter.h
+//  MJRefresh
+//
+//  Created by MJ Lee on 15/4/24.
+//  Copyright (c) 2015年 小码哥. All rights reserved.
+//
+
+#if __has_include(<MJRefresh/MJRefreshBackStateFooter.h>)
+#import <MJRefresh/MJRefreshBackStateFooter.h>
+#else
+#import "MJRefreshBackStateFooter.h"
+#endif
+
+NS_ASSUME_NONNULL_BEGIN
+
+@interface MJRefreshBackGifFooter : MJRefreshBackStateFooter
+@property (weak, nonatomic, readonly) UIImageView *gifView;
+
+/** 设置state状态下的动画图片images 动画持续时间duration*/
+- (instancetype)setImages:(NSArray *)images duration:(NSTimeInterval)duration forState:(MJRefreshState)state;
+- (instancetype)setImages:(NSArray *)images forState:(MJRefreshState)state;
+@end
+
+NS_ASSUME_NONNULL_END

+ 132 - 0
Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackGifFooter.m

@@ -0,0 +1,132 @@
+//
+//  MJRefreshBackGifFooter.m
+//  MJRefresh
+//
+//  Created by MJ Lee on 15/4/24.
+//  Copyright (c) 2015年 小码哥. All rights reserved.
+//
+
+#import "MJRefreshBackGifFooter.h"
+#import "NSBundle+MJRefresh.h"
+#import "UIView+MJExtension.h"
+#import "UIScrollView+MJExtension.h"
+#import "UIScrollView+MJRefresh.h"
+
+@interface MJRefreshBackGifFooter()
+{
+    __unsafe_unretained UIImageView *_gifView;
+}
+/** 所有状态对应的动画图片 */
+@property (strong, nonatomic) NSMutableDictionary *stateImages;
+/** 所有状态对应的动画时间 */
+@property (strong, nonatomic) NSMutableDictionary *stateDurations;
+@end
+
+@implementation MJRefreshBackGifFooter
+#pragma mark - 懒加载
+- (UIImageView *)gifView
+{
+    if (!_gifView) {
+        UIImageView *gifView = [[UIImageView alloc] init];
+        [self addSubview:_gifView = gifView];
+    }
+    return _gifView;
+}
+
+- (NSMutableDictionary *)stateImages
+{
+    if (!_stateImages) {
+        self.stateImages = [NSMutableDictionary dictionary];
+    }
+    return _stateImages;
+}
+
+- (NSMutableDictionary *)stateDurations
+{
+    if (!_stateDurations) {
+        self.stateDurations = [NSMutableDictionary dictionary];
+    }
+    return _stateDurations;
+}
+
+#pragma mark - 公共方法
+- (instancetype)setImages:(NSArray *)images duration:(NSTimeInterval)duration forState:(MJRefreshState)state
+{
+    if (images == nil) return self;
+    
+    self.stateImages[@(state)] = images;
+    self.stateDurations[@(state)] = @(duration);
+    
+    /* 根据图片设置控件的高度 */
+    UIImage *image = [images firstObject];
+    if (image.size.height > self.mj_h) {
+        self.mj_h = image.size.height;
+    }
+    return self;
+}
+
+- (instancetype)setImages:(NSArray *)images forState:(MJRefreshState)state
+{
+    return [self setImages:images duration:images.count * 0.1 forState:state];
+}
+
+#pragma mark - 实现父类的方法
+- (void)prepare
+{
+    [super prepare];
+    
+    // 初始化间距
+    self.labelLeftInset = 20;
+}
+
+- (void)setPullingPercent:(CGFloat)pullingPercent
+{
+    [super setPullingPercent:pullingPercent];
+    NSArray *images = self.stateImages[@(MJRefreshStateIdle)];
+    if (self.state != MJRefreshStateIdle || images.count == 0) return;
+    [self.gifView stopAnimating];
+    NSUInteger index =  images.count * pullingPercent;
+    if (index >= images.count) index = images.count - 1;
+    self.gifView.image = images[index];
+}
+
+- (void)placeSubviews
+{
+    [super placeSubviews];
+    
+    if (self.gifView.constraints.count) return;
+    
+    self.gifView.frame = self.bounds;
+    if (self.stateLabel.hidden) {
+        self.gifView.contentMode = UIViewContentModeCenter;
+    } else {
+        self.gifView.contentMode = UIViewContentModeRight;
+        self.gifView.mj_w = self.mj_w * 0.5 - self.labelLeftInset - self.stateLabel.mj_textWidth * 0.5;
+    }
+}
+
+- (void)setState:(MJRefreshState)state
+{
+    MJRefreshCheckState
+    
+    // 根据状态做事情
+    if (state == MJRefreshStatePulling || state == MJRefreshStateRefreshing) {
+        NSArray *images = self.stateImages[@(state)];
+        if (images.count == 0) return;
+        
+        self.gifView.hidden = NO;
+        [self.gifView stopAnimating];
+        if (images.count == 1) { // 单张图片
+            self.gifView.image = [images lastObject];
+        } else { // 多张图片
+            self.gifView.animationImages = images;
+            self.gifView.animationDuration = [self.stateDurations[@(state)] doubleValue];
+            [self.gifView startAnimating];
+        }
+    } else if (state == MJRefreshStateIdle) {
+        self.gifView.hidden = NO;
+    } else if (state == MJRefreshStateNoMoreData) {
+        self.gifView.hidden = YES;
+    }
+}
+@end

Неке датотеке нису приказане због велике количине промена