Explorar el Código

基本开发完毕,同时适配了 ipad 审核

100Years hace 3 meses
commit
5ac1e46162
Se han modificado 100 ficheros con 31465 adiciones y 0 borrados
  1. 56 0
      Podfile
  2. 60 0
      Podfile.lock
  3. 19 0
      Pods/Alamofire/LICENSE
  4. 227 0
      Pods/Alamofire/README.md
  5. 870 0
      Pods/Alamofire/Source/AFError.swift
  6. 40 0
      Pods/Alamofire/Source/Alamofire.swift
  7. 61 0
      Pods/Alamofire/Source/AlamofireExtended.swift
  8. 403 0
      Pods/Alamofire/Source/AuthenticationInterceptor.swift
  9. 109 0
      Pods/Alamofire/Source/CachedResponseHandler.swift
  10. 655 0
      Pods/Alamofire/Source/Combine.swift
  11. 704 0
      Pods/Alamofire/Source/Concurrency.swift
  12. 37 0
      Pods/Alamofire/Source/DispatchQueue+Alamofire.swift
  13. 892 0
      Pods/Alamofire/Source/EventMonitor.swift
  14. 447 0
      Pods/Alamofire/Source/HTTPHeaders.swift
  15. 56 0
      Pods/Alamofire/Source/HTTPMethod.swift
  16. 584 0
      Pods/Alamofire/Source/MultipartFormData.swift
  17. 89 0
      Pods/Alamofire/Source/MultipartUpload.swift
  18. 267 0
      Pods/Alamofire/Source/NetworkReachabilityManager.swift
  19. 115 0
      Pods/Alamofire/Source/Notifications.swift
  20. 49 0
      Pods/Alamofire/Source/OperationQueue+Alamofire.swift
  21. 217 0
      Pods/Alamofire/Source/ParameterEncoder.swift
  22. 342 0
      Pods/Alamofire/Source/ParameterEncoding.swift
  23. 161 0
      Pods/Alamofire/Source/Protected.swift
  24. 113 0
      Pods/Alamofire/Source/RedirectHandler.swift
  25. 1912 0
      Pods/Alamofire/Source/Request.swift
  26. 357 0
      Pods/Alamofire/Source/RequestInterceptor.swift
  27. 149 0
      Pods/Alamofire/Source/RequestTaskMap.swift
  28. 453 0
      Pods/Alamofire/Source/Response.swift
  29. 1282 0
      Pods/Alamofire/Source/ResponseSerialization.swift
  30. 120 0
      Pods/Alamofire/Source/Result+Alamofire.swift
  31. 434 0
      Pods/Alamofire/Source/RetryPolicy.swift
  32. 743 0
      Pods/Alamofire/Source/ServerTrustEvaluation.swift
  33. 1264 0
      Pods/Alamofire/Source/Session.swift
  34. 336 0
      Pods/Alamofire/Source/SessionDelegate.swift
  35. 55 0
      Pods/Alamofire/Source/StringEncoding+Alamofire.swift
  36. 105 0
      Pods/Alamofire/Source/URLConvertible+URLRequestConvertible.swift
  37. 982 0
      Pods/Alamofire/Source/URLEncodedFormEncoder.swift
  38. 39 0
      Pods/Alamofire/Source/URLRequest+Alamofire.swift
  39. 46 0
      Pods/Alamofire/Source/URLSessionConfiguration+Alamofire.swift
  40. 302 0
      Pods/Alamofire/Source/Validation.swift
  41. 57 0
      Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/Categories/IQNSArray+Sort.swift
  42. 117 0
      Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/Categories/IQUIScrollView+Additions.swift
  43. 93 0
      Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/Categories/IQUITextFieldView+Additions.swift
  44. 324 0
      Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/Categories/IQUIView+Hierarchy.swift
  45. 54 0
      Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/Categories/IQUIViewController+Additions.swift
  46. 150 0
      Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/Constants/IQKeyboardManagerConstants.swift
  47. 24 0
      Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/Constants/IQKeyboardManagerConstantsInternal.swift
  48. 111 0
      Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQKeyboardManager+Debug.swift
  49. 193 0
      Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQKeyboardManager+Internal.swift
  50. 77 0
      Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQKeyboardManager+OrientationNotification.swift
  51. 717 0
      Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQKeyboardManager+Position.swift
  52. 368 0
      Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQKeyboardManager+Toolbar.swift
  53. 365 0
      Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQKeyboardManager+UIKeyboardNotification.swift
  54. 227 0
      Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQKeyboardManager+UITextFieldViewNotification.swift
  55. 424 0
      Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQKeyboardManager.swift
  56. 645 0
      Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQKeyboardReturnKeyHandler.swift
  57. 189 0
      Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQTextView/IQTextView.swift
  58. 99 0
      Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQToolbar/IQBarButtonItem.swift
  59. 45 0
      Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQToolbar/IQInvocation.swift
  60. 29 0
      Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQToolbar/IQPreviousNextView.swift
  61. 167 0
      Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQToolbar/IQTitleBarButtonItem.swift
  62. 252 0
      Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQToolbar/IQToolbar.swift
  63. 80 0
      Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQToolbar/IQUIView+IQKeyboardToolbar.swift
  64. 21 0
      Pods/IQKeyboardManagerSwift/LICENSE.md
  65. 223 0
      Pods/IQKeyboardManagerSwift/README.md
  66. 22 0
      Pods/Kingfisher/LICENSE
  67. 259 0
      Pods/Kingfisher/README.md
  68. 137 0
      Pods/Kingfisher/Sources/Cache/CacheSerializer.swift
  69. 616 0
      Pods/Kingfisher/Sources/Cache/DiskStorage.swift
  70. 123 0
      Pods/Kingfisher/Sources/Cache/FormatIndicatedCacheSerializer.swift
  71. 882 0
      Pods/Kingfisher/Sources/Cache/ImageCache.swift
  72. 283 0
      Pods/Kingfisher/Sources/Cache/MemoryStorage.swift
  73. 110 0
      Pods/Kingfisher/Sources/Cache/Storage.swift
  74. 245 0
      Pods/Kingfisher/Sources/Extensions/CPListItem+Kingfisher.swift
  75. 537 0
      Pods/Kingfisher/Sources/Extensions/ImageView+Kingfisher.swift
  76. 362 0
      Pods/Kingfisher/Sources/Extensions/NSButton+Kingfisher.swift
  77. 271 0
      Pods/Kingfisher/Sources/Extensions/NSTextAttachment+Kingfisher.swift
  78. 209 0
      Pods/Kingfisher/Sources/Extensions/TVMonogramView+Kingfisher.swift
  79. 400 0
      Pods/Kingfisher/Sources/Extensions/UIButton+Kingfisher.swift
  80. 204 0
      Pods/Kingfisher/Sources/Extensions/WKInterfaceImage+Kingfisher.swift
  81. 151 0
      Pods/Kingfisher/Sources/General/ImageSource/AVAssetImageDataProvider.swift
  82. 190 0
      Pods/Kingfisher/Sources/General/ImageSource/ImageDataProvider.swift
  83. 121 0
      Pods/Kingfisher/Sources/General/ImageSource/Resource.swift
  84. 116 0
      Pods/Kingfisher/Sources/General/ImageSource/Source.swift
  85. 442 0
      Pods/Kingfisher/Sources/General/KF.swift
  86. 711 0
      Pods/Kingfisher/Sources/General/KFOptionsSetter.swift
  87. 106 0
      Pods/Kingfisher/Sources/General/Kingfisher.swift
  88. 474 0
      Pods/Kingfisher/Sources/General/KingfisherError.swift
  89. 807 0
      Pods/Kingfisher/Sources/General/KingfisherManager.swift
  90. 400 0
      Pods/Kingfisher/Sources/General/KingfisherOptionsInfo.swift
  91. 152 0
      Pods/Kingfisher/Sources/Image/Filter.swift
  92. 177 0
      Pods/Kingfisher/Sources/Image/GIFAnimatedImage.swift
  93. 88 0
      Pods/Kingfisher/Sources/Image/GraphicsContext.swift
  94. 426 0
      Pods/Kingfisher/Sources/Image/Image.swift
  95. 636 0
      Pods/Kingfisher/Sources/Image/ImageDrawing.swift
  96. 130 0
      Pods/Kingfisher/Sources/Image/ImageFormat.swift
  97. 922 0
      Pods/Kingfisher/Sources/Image/ImageProcessor.swift
  98. 353 0
      Pods/Kingfisher/Sources/Image/ImageProgressive.swift
  99. 118 0
      Pods/Kingfisher/Sources/Image/ImageTransition.swift
  100. 82 0
      Pods/Kingfisher/Sources/Image/Placeholder.swift

+ 56 - 0
Podfile

@@ -0,0 +1,56 @@
+#source 'https://github.com/CocoaPods/Specs.git'
+
+project 'TSLiveWallpaper.xcodeproj'
+platform :ios, '14.0'
+
+inhibit_all_warnings!
+
+
+target 'TSLiveWallpaper' do
+  use_frameworks!
+
+  pod 'ObjectMapper', '4.2'
+  pod 'SnapKit'
+
+  pod 'Toast-Swift'
+  pod 'Kingfisher', '7.10.0'
+  pod 'Alamofire', '5.6.4'
+  pod 'Masonry'
+
+#  pod 'SOZOChromoplast'
+  pod 'TZImagePickerController'
+
+
+  pod 'MJRefresh', '3.7.5'
+  pod 'IQKeyboardManagerSwift', '6.5.12'
+  pod 'TYCyclePagerView'
+  # pod 'YYModel'
+# banner
+  ##pod 'SDCycleScrollView','>= 1.82'
+  pod "WARangeSlider"
+
+end
+
+
+post_install do |installer|
+  installer.pods_project.targets.each do |target|
+    target.build_configurations.each do |config|
+      config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '14.0'
+#      config.build_settings['EXCLUDED_ARCHS[sdk=iphonesimulator*]'] = 'arm64'
+    end
+  end
+  installer.aggregate_targets.each do |target|
+    target.xcconfigs.each do |variant, xcconfig|
+      xcconfig_path = target.client_root + target.xcconfig_relative_path(variant)
+      IO.write(xcconfig_path, IO.read(xcconfig_path).gsub("DT_TOOLCHAIN_DIR", "TOOLCHAIN_DIR"))
+    end
+  end
+  installer.pods_project.targets.each do |target|
+    target.build_configurations.each do |config|
+      if config.base_configuration_reference.is_a? Xcodeproj::Project::Object::PBXFileReference
+        xcconfig_path = config.base_configuration_reference.real_path
+        IO.write(xcconfig_path, IO.read(xcconfig_path).gsub("DT_TOOLCHAIN_DIR", "TOOLCHAIN_DIR"))
+      end
+    end
+  end
+end

+ 60 - 0
Podfile.lock

@@ -0,0 +1,60 @@
+PODS:
+  - Alamofire (5.6.4)
+  - IQKeyboardManagerSwift (6.5.12)
+  - Kingfisher (7.10.0)
+  - Masonry (1.1.0)
+  - MJRefresh (3.7.5)
+  - ObjectMapper (4.2.0)
+  - SnapKit (5.7.1)
+  - Toast-Swift (5.1.1)
+  - TYCyclePagerView (1.2.0)
+  - TZImagePickerController (3.8.8):
+    - TZImagePickerController/Basic (= 3.8.8)
+    - TZImagePickerController/Location (= 3.8.8)
+  - TZImagePickerController/Basic (3.8.8)
+  - TZImagePickerController/Location (3.8.8)
+  - WARangeSlider (1.2.0)
+
+DEPENDENCIES:
+  - Alamofire (= 5.6.4)
+  - IQKeyboardManagerSwift (= 6.5.12)
+  - Kingfisher (= 7.10.0)
+  - Masonry
+  - MJRefresh (= 3.7.5)
+  - ObjectMapper (= 4.2)
+  - SnapKit
+  - Toast-Swift
+  - TYCyclePagerView
+  - TZImagePickerController
+  - WARangeSlider
+
+SPEC REPOS:
+  trunk:
+    - Alamofire
+    - IQKeyboardManagerSwift
+    - Kingfisher
+    - Masonry
+    - MJRefresh
+    - ObjectMapper
+    - SnapKit
+    - Toast-Swift
+    - TYCyclePagerView
+    - TZImagePickerController
+    - WARangeSlider
+
+SPEC CHECKSUMS:
+  Alamofire: 4e95d97098eacb88856099c4fc79b526a299e48c
+  IQKeyboardManagerSwift: 371b08cb39664fb56030f5345c815a4ffc74bbc0
+  Kingfisher: a18f05d3b6d37d8650ee4a3e61d57a28fc6207f6
+  Masonry: 678fab65091a9290e40e2832a55e7ab731aad201
+  MJRefresh: fdf5e979eb406a0341468932d1dfc8b7f9fce961
+  ObjectMapper: 1eb41f610210777375fa806bf161dc39fb832b81
+  SnapKit: d612e99e678a2d3b95bf60b0705ed0a35c03484a
+  Toast-Swift: 7a03a532afe3a560d4044bc7c237e2864d295173
+  TYCyclePagerView: 2b051dade0615c70784aa34f40c646feeddb7344
+  TZImagePickerController: d084a7b97c82d387e7669dd86dc9a9057500aacf
+  WARangeSlider: 03f195d4dc5419e6b0d9043cc94fdf418dfe804d
+
+PODFILE CHECKSUM: 2b76774c2c825040601161b5ceaa0e459a7f8c05
+
+COCOAPODS: 1.16.2

+ 19 - 0
Pods/Alamofire/LICENSE

@@ -0,0 +1,19 @@
+Copyright (c) 2014-2022 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.

+ 227 - 0
Pods/Alamofire/README.md

@@ -0,0 +1,227 @@
+![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/master/Resources/AlamofireLogo.png)
+
+[![Swift](https://img.shields.io/badge/Swift-5.3_5.4_5.5_5.6-orange?style=flat-square)](https://img.shields.io/badge/Swift-5.3_5.4_5.5_5.6-Orange?style=flat-square)
+[![Platforms](https://img.shields.io/badge/Platforms-macOS_iOS_tvOS_watchOS_Linux_Windows-yellowgreen?style=flat-square)](https://img.shields.io/badge/Platforms-macOS_iOS_tvOS_watchOS_Linux_Windows-Green?style=flat-square)
+[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg?style=flat-square)](https://img.shields.io/cocoapods/v/Alamofire.svg)
+[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat-square)](https://github.com/Carthage/Carthage)
+[![Swift Package Manager](https://img.shields.io/badge/Swift_Package_Manager-compatible-orange?style=flat-square)](https://img.shields.io/badge/Swift_Package_Manager-compatible-orange?style=flat-square)
+[![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat-square)](https://twitter.com/AlamofireSF)
+[![Swift Forums](https://img.shields.io/badge/Swift_Forums-Alamofire-orange?style=flat-square)](https://forums.swift.org/c/related-projects/alamofire/37)
+
+Alamofire is an HTTP networking library written in Swift.
+
+- [Features](#features)
+- [Component Libraries](#component-libraries)
+- [Requirements](#requirements)
+- [Migration Guides](#migration-guides)
+- [Communication](#communication)
+- [Installation](#installation)
+- [Contributing](#contributing)
+- [Usage](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#using-alamofire)
+  - [**Introduction -**](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#introduction) [Making Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#making-requests), [Response Handling](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-handling), [Response Validation](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-validation), [Response Caching](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-caching)
+  - **HTTP -** [HTTP Methods](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#http-methods), [Parameters and Parameter Encoder](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md##request-parameters-and-parameter-encoders), [HTTP Headers](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#http-headers), [Authentication](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#authentication)
+  - **Large Data -** [Downloading Data to a File](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#downloading-data-to-a-file), [Uploading Data to a Server](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#uploading-data-to-a-server)
+  - **Tools -** [Statistical Metrics](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#statistical-metrics), [cURL Command Output](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#curl-command-output)
+- [Advanced Usage](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md)
+  - **URL Session -** [Session Manager](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#session), [Session Delegate](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#sessiondelegate), [Request](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#request)
+  - **Routing -** [Routing Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#routing-requests), [Adapting and Retrying Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#adapting-and-retrying-requests-with-requestinterceptor)
+  - **Model Objects -** [Custom Response Handlers](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#customizing-response-handlers)
+  - **Advanced Concurrency -** [Swift Concurrency](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#using-alamofire-with-swift-concurrency) and [Combine](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#using-alamofire-with-combine)
+  - **Connection -** [Security](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#security), [Network Reachability](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#network-reachability)
+- [Open Radars](#open-radars)
+- [FAQ](#faq)
+- [Credits](#credits)
+- [Donations](#donations)
+- [License](#license)
+
+## Features
+
+- [x] Chainable Request / Response Methods
+- [x] Swift Concurrency Support Back to iOS 13, macOS 10.15, tvOS 13, and watchOS 6.
+- [x] Combine Support
+- [x] URL / JSON Parameter Encoding
+- [x] Upload File / Data / Stream / MultipartFormData
+- [x] Download File using Request or Resume Data
+- [x] Authentication with `URLCredential`
+- [x] HTTP Response Validation
+- [x] Upload and Download Progress Closures with Progress
+- [x] cURL Command Output
+- [x] Dynamically Adapt and Retry Requests
+- [x] TLS Certificate and Public Key Pinning
+- [x] Network Reachability
+- [x] Comprehensive Unit and Integration Test Coverage
+- [x] [Complete Documentation](https://alamofire.github.io/Alamofire)
+
+## Component Libraries
+
+In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem.
+
+- [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache, and a priority-based image downloading system.
+- [AlamofireNetworkActivityIndicator](https://github.com/Alamofire/AlamofireNetworkActivityIndicator) - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support `URLSession` instances not managed by Alamofire.
+
+## Requirements
+
+| Platform | Minimum Swift Version | Installation | Status |
+| --- | --- | --- | --- |
+| iOS 10.0+ / macOS 10.12+ / tvOS 10.0+ / watchOS 3.0+ | 5.3 | [CocoaPods](#cocoapods), [Carthage](#carthage), [Swift Package Manager](#swift-package-manager), [Manual](#manually) | Fully Tested |
+| Linux | Latest Only | [Swift Package Manager](#swift-package-manager) | Building But Unsupported |
+| Windows | Latest Only | [Swift Package Manager](#swift-package-manager) | Building But Unsupported |
+
+#### Known Issues on Linux and Windows
+
+Alamofire builds on Linux and Windows but there are missing features and many issues in the underlying `swift-corelibs-foundation` that prevent full functionality and may cause crashes. These include:
+- `ServerTrustManager` and associated certificate functionality is unavailable, so there is no certificate pinning and no client certificate support.
+- Various methods of HTTP authentication may crash, including HTTP Basic and HTTP Digest. Crashes may occur if responses contain server challenges.
+- Cache control through `CachedResponseHandler` and associated APIs is unavailable, as the underlying delegate methods aren't called.
+- `URLSessionTaskMetrics` are never gathered.
+
+Due to these issues, Alamofire is unsupported on Linux and Windows. Please report any crashes to the [Swift bug reporter](https://bugs.swift.org).
+
+## Migration Guides
+
+- [Alamofire 5.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%205.0%20Migration%20Guide.md)
+- [Alamofire 4.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md)
+- [Alamofire 3.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md)
+- [Alamofire 2.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%202.0%20Migration%20Guide.md)
+
+## Communication
+- If you **need help with making network requests** using Alamofire, use [Stack Overflow](https://stackoverflow.com/questions/tagged/alamofire) and tag `alamofire`.
+- If you need to **find or understand an API**, check [our documentation](http://alamofire.github.io/Alamofire/) or [Apple's documentation for `URLSession`](https://developer.apple.com/documentation/foundation/url_loading_system), on top of which Alamofire is built.
+- If you need **help with an Alamofire feature**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire).
+- If you'd like to **discuss Alamofire best practices**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire).
+- If you'd like to **discuss a feature request**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). 
+- If you **found a bug**, open an issue here on GitHub and follow the guide. The more detail the better!
+
+## Installation
+
+### CocoaPods
+
+[CocoaPods](https://cocoapods.org) is a dependency manager for Cocoa projects. For usage and installation instructions, visit their website. To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`:
+
+```ruby
+pod 'Alamofire'
+```
+
+### Carthage
+
+[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`:
+
+```ogdl
+github "Alamofire/Alamofire"
+```
+
+### Swift Package Manager
+
+The [Swift Package Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the `swift` compiler. 
+
+Once you have your Swift package set up, adding Alamofire as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`.
+
+```swift
+dependencies: [
+    .package(url: "https://github.com/Alamofire/Alamofire.git", .upToNextMajor(from: "5.6.1"))
+]
+```
+
+### Manually
+
+If you prefer not to use any of the aforementioned dependency managers, you can integrate Alamofire into your project manually.
+
+#### Embedded Framework
+
+- Open up Terminal, `cd` into your top-level project directory, and run the following command "if" your project is not initialized as a git repository:
+
+  ```bash
+  $ git init
+  ```
+
+- Add Alamofire as a git [submodule](https://git-scm.com/docs/git-submodule) by running the following command:
+
+  ```bash
+  $ git submodule add https://github.com/Alamofire/Alamofire.git
+  ```
+
+- Open the new `Alamofire` folder, and drag the `Alamofire.xcodeproj` into the Project Navigator of your application's Xcode project.
+
+    > It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter.
+
+- Select the `Alamofire.xcodeproj` in the Project Navigator and verify the deployment target matches that of your application target.
+- Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar.
+- In the tab bar at the top of that window, open the "General" panel.
+- Click on the `+` button under the "Embedded Binaries" section.
+- You will see two different `Alamofire.xcodeproj` folders each with two different versions of the `Alamofire.framework` nested inside a `Products` folder.
+
+    > It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`.
+
+- Select the top `Alamofire.framework` for iOS and the bottom one for macOS.
+
+    > You can verify which one you selected by inspecting the build log for your project. The build target for `Alamofire` will be listed as `Alamofire iOS`, `Alamofire macOS`, `Alamofire tvOS`, or `Alamofire watchOS`.
+
+- And that's it!
+
+  > The `Alamofire.framework` is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device.
+
+## Contributing
+
+Before contributing to Alamofire, please read the instructions detailed in our [contribution guide](https://github.com/Alamofire/Alamofire/blob/master/CONTRIBUTING.md).
+
+## Open Radars
+
+The following radars have some effect on the current implementation of Alamofire.
+
+- [`rdar://21349340`](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in the test case
+- `rdar://26870455` - Background URL Session Configurations do not work in the simulator
+- `rdar://26849668` - Some URLProtocol APIs do not properly handle `URLRequest`
+
+## Resolved Radars
+
+The following radars have been resolved over time after being filed against the Alamofire project.
+
+- [`rdar://26761490`](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage.
+  - (Resolved): 9/1/17 in Xcode 9 beta 6.
+- [`rdar://36082113`](http://openradar.appspot.com/radar?id=4942308441063424) - `URLSessionTaskMetrics` failing to link on watchOS 3.0+
+  - (Resolved): Just add `CFNetwork` to your linked frameworks.
+- `FB7624529` - `urlSession(_:task:didFinishCollecting:)` never called on watchOS
+  - (Resolved): Metrics now collected on watchOS 7+.
+
+## FAQ
+
+### What's the origin of the name Alamofire?
+
+Alamofire is named after the [Alamo Fire flower](https://aggie-horticulture.tamu.edu/wildseed/alamofire.html), a hybrid variant of the Bluebonnet, the official state flower of Texas.
+
+## Credits
+
+Alamofire is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). You can follow them on Twitter at [@AlamofireSF](https://twitter.com/AlamofireSF) for project updates and releases.
+
+### Security Disclosure
+
+If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker.
+
+## Sponsorship
+
+The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise money to officially stay registered as a federal non-profit organization.
+Registering will allow Foundation members to gain some legal protections and also allow us to put donations to use, tax-free.
+Sponsoring the ASF will enable us to:
+
+- Pay our yearly legal fees to keep the non-profit in good status
+- Pay for our mail servers to help us stay on top of all questions and security issues
+- Potentially fund test servers to make it easier for us to test the edge cases
+- Potentially fund developers to work on one of our projects full-time
+
+The community adoption of the ASF libraries has been amazing.
+We are greatly humbled by your enthusiasm around the projects and want to continue to do everything we can to move the needle forward.
+With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members.
+If you use any of our libraries for work, see if your employers would be interested in donating.
+Any amount you can donate, whether once or monthly, to help us reach our goal would be greatly appreciated.
+
+[Sponsor Alamofire](https://github.com/sponsors/Alamofire)
+
+## Supporters
+
+[MacStadium](https://macstadium.com) provides Alamofire with a free, hosted Mac mini.
+
+![Powered by MacStadium](https://raw.githubusercontent.com/Alamofire/Alamofire/master/Resources/MacStadiumLogo.png)
+
+## License
+
+Alamofire is released under the MIT license. [See LICENSE](https://github.com/Alamofire/Alamofire/blob/master/LICENSE) for details.

+ 870 - 0
Pods/Alamofire/Source/AFError.swift

@@ -0,0 +1,870 @@
+//
+//  AFError.swift
+//
+//  Copyright (c) 2014-2018 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
+
+/// `AFError` is the error type returned by Alamofire. It encompasses a few different types of errors, each with
+/// their own associated reasons.
+public enum AFError: Error {
+    /// The underlying reason the `.multipartEncodingFailed` error occurred.
+    public enum MultipartEncodingFailureReason {
+        /// The `fileURL` provided for reading an encodable body part isn't a file `URL`.
+        case bodyPartURLInvalid(url: URL)
+        /// The filename of the `fileURL` provided has either an empty `lastPathComponent` or `pathExtension.
+        case bodyPartFilenameInvalid(in: URL)
+        /// The file at the `fileURL` provided was not reachable.
+        case bodyPartFileNotReachable(at: URL)
+        /// Attempting to check the reachability of the `fileURL` provided threw an error.
+        case bodyPartFileNotReachableWithError(atURL: URL, error: Error)
+        /// The file at the `fileURL` provided is actually a directory.
+        case bodyPartFileIsDirectory(at: URL)
+        /// The size of the file at the `fileURL` provided was not returned by the system.
+        case bodyPartFileSizeNotAvailable(at: URL)
+        /// The attempt to find the size of the file at the `fileURL` provided threw an error.
+        case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error)
+        /// An `InputStream` could not be created for the provided `fileURL`.
+        case bodyPartInputStreamCreationFailed(for: URL)
+        /// An `OutputStream` could not be created when attempting to write the encoded data to disk.
+        case outputStreamCreationFailed(for: URL)
+        /// The encoded body data could not be written to disk because a file already exists at the provided `fileURL`.
+        case outputStreamFileAlreadyExists(at: URL)
+        /// The `fileURL` provided for writing the encoded body data to disk is not a file `URL`.
+        case outputStreamURLInvalid(url: URL)
+        /// The attempt to write the encoded body data to disk failed with an underlying error.
+        case outputStreamWriteFailed(error: Error)
+        /// The attempt to read an encoded body part `InputStream` failed with underlying system error.
+        case inputStreamReadFailed(error: Error)
+    }
+
+    /// Represents unexpected input stream length that occur when encoding the `MultipartFormData`. Instances will be
+    /// embedded within an `AFError.multipartEncodingFailed` `.inputStreamReadFailed` case.
+    public struct UnexpectedInputStreamLength: Error {
+        /// The expected byte count to read.
+        public var bytesExpected: UInt64
+        /// The actual byte count read.
+        public var bytesRead: UInt64
+    }
+
+    /// The underlying reason the `.parameterEncodingFailed` error occurred.
+    public enum ParameterEncodingFailureReason {
+        /// The `URLRequest` did not have a `URL` to encode.
+        case missingURL
+        /// JSON serialization failed with an underlying system error during the encoding process.
+        case jsonEncodingFailed(error: Error)
+        /// Custom parameter encoding failed due to the associated `Error`.
+        case customEncodingFailed(error: Error)
+    }
+
+    /// The underlying reason the `.parameterEncoderFailed` error occurred.
+    public enum ParameterEncoderFailureReason {
+        /// Possible missing components.
+        public enum RequiredComponent {
+            /// The `URL` was missing or unable to be extracted from the passed `URLRequest` or during encoding.
+            case url
+            /// The `HTTPMethod` could not be extracted from the passed `URLRequest`.
+            case httpMethod(rawValue: String)
+        }
+
+        /// A `RequiredComponent` was missing during encoding.
+        case missingRequiredComponent(RequiredComponent)
+        /// The underlying encoder failed with the associated error.
+        case encoderFailed(error: Error)
+    }
+
+    /// The underlying reason the `.responseValidationFailed` error occurred.
+    public enum ResponseValidationFailureReason {
+        /// The data file containing the server response did not exist.
+        case dataFileNil
+        /// The data file containing the server response at the associated `URL` could not be read.
+        case dataFileReadFailed(at: URL)
+        /// The response did not contain a `Content-Type` and the `acceptableContentTypes` provided did not contain a
+        /// wildcard type.
+        case missingContentType(acceptableContentTypes: [String])
+        /// The response `Content-Type` did not match any type in the provided `acceptableContentTypes`.
+        case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String)
+        /// The response status code was not acceptable.
+        case unacceptableStatusCode(code: Int)
+        /// Custom response validation failed due to the associated `Error`.
+        case customValidationFailed(error: Error)
+    }
+
+    /// The underlying reason the response serialization error occurred.
+    public enum ResponseSerializationFailureReason {
+        /// The server response contained no data or the data was zero length.
+        case inputDataNilOrZeroLength
+        /// The file containing the server response did not exist.
+        case inputFileNil
+        /// The file containing the server response could not be read from the associated `URL`.
+        case inputFileReadFailed(at: URL)
+        /// String serialization failed using the provided `String.Encoding`.
+        case stringSerializationFailed(encoding: String.Encoding)
+        /// JSON serialization failed with an underlying system error.
+        case jsonSerializationFailed(error: Error)
+        /// A `DataDecoder` failed to decode the response due to the associated `Error`.
+        case decodingFailed(error: Error)
+        /// A custom response serializer failed due to the associated `Error`.
+        case customSerializationFailed(error: Error)
+        /// Generic serialization failed for an empty response that wasn't type `Empty` but instead the associated type.
+        case invalidEmptyResponse(type: String)
+    }
+
+    #if !(os(Linux) || os(Windows))
+    /// Underlying reason a server trust evaluation error occurred.
+    public enum ServerTrustFailureReason {
+        /// The output of a server trust evaluation.
+        public struct Output {
+            /// The host for which the evaluation was performed.
+            public let host: String
+            /// The `SecTrust` value which was evaluated.
+            public let trust: SecTrust
+            /// The `OSStatus` of evaluation operation.
+            public let status: OSStatus
+            /// The result of the evaluation operation.
+            public let result: SecTrustResultType
+
+            /// Creates an `Output` value from the provided values.
+            init(_ host: String, _ trust: SecTrust, _ status: OSStatus, _ result: SecTrustResultType) {
+                self.host = host
+                self.trust = trust
+                self.status = status
+                self.result = result
+            }
+        }
+
+        /// No `ServerTrustEvaluator` was found for the associated host.
+        case noRequiredEvaluator(host: String)
+        /// No certificates were found with which to perform the trust evaluation.
+        case noCertificatesFound
+        /// No public keys were found with which to perform the trust evaluation.
+        case noPublicKeysFound
+        /// During evaluation, application of the associated `SecPolicy` failed.
+        case policyApplicationFailed(trust: SecTrust, policy: SecPolicy, status: OSStatus)
+        /// During evaluation, setting the associated anchor certificates failed.
+        case settingAnchorCertificatesFailed(status: OSStatus, certificates: [SecCertificate])
+        /// During evaluation, creation of the revocation policy failed.
+        case revocationPolicyCreationFailed
+        /// `SecTrust` evaluation failed with the associated `Error`, if one was produced.
+        case trustEvaluationFailed(error: Error?)
+        /// Default evaluation failed with the associated `Output`.
+        case defaultEvaluationFailed(output: Output)
+        /// Host validation failed with the associated `Output`.
+        case hostValidationFailed(output: Output)
+        /// Revocation check failed with the associated `Output` and options.
+        case revocationCheckFailed(output: Output, options: RevocationTrustEvaluator.Options)
+        /// Certificate pinning failed.
+        case certificatePinningFailed(host: String, trust: SecTrust, pinnedCertificates: [SecCertificate], serverCertificates: [SecCertificate])
+        /// Public key pinning failed.
+        case publicKeyPinningFailed(host: String, trust: SecTrust, pinnedKeys: [SecKey], serverKeys: [SecKey])
+        /// Custom server trust evaluation failed due to the associated `Error`.
+        case customEvaluationFailed(error: Error)
+    }
+    #endif
+
+    /// The underlying reason the `.urlRequestValidationFailed`
+    public enum URLRequestValidationFailureReason {
+        /// URLRequest with GET method had body data.
+        case bodyDataInGETRequest(Data)
+    }
+
+    ///  `UploadableConvertible` threw an error in `createUploadable()`.
+    case createUploadableFailed(error: Error)
+    ///  `URLRequestConvertible` threw an error in `asURLRequest()`.
+    case createURLRequestFailed(error: Error)
+    /// `SessionDelegate` threw an error while attempting to move downloaded file to destination URL.
+    case downloadedFileMoveFailed(error: Error, source: URL, destination: URL)
+    /// `Request` was explicitly cancelled.
+    case explicitlyCancelled
+    /// `URLConvertible` type failed to create a valid `URL`.
+    case invalidURL(url: URLConvertible)
+    /// Multipart form encoding failed.
+    case multipartEncodingFailed(reason: MultipartEncodingFailureReason)
+    /// `ParameterEncoding` threw an error during the encoding process.
+    case parameterEncodingFailed(reason: ParameterEncodingFailureReason)
+    /// `ParameterEncoder` threw an error while running the encoder.
+    case parameterEncoderFailed(reason: ParameterEncoderFailureReason)
+    /// `RequestAdapter` threw an error during adaptation.
+    case requestAdaptationFailed(error: Error)
+    /// `RequestRetrier` threw an error during the request retry process.
+    case requestRetryFailed(retryError: Error, originalError: Error)
+    /// Response validation failed.
+    case responseValidationFailed(reason: ResponseValidationFailureReason)
+    /// Response serialization failed.
+    case responseSerializationFailed(reason: ResponseSerializationFailureReason)
+    #if !(os(Linux) || os(Windows))
+    /// `ServerTrustEvaluating` instance threw an error during trust evaluation.
+    case serverTrustEvaluationFailed(reason: ServerTrustFailureReason)
+    #endif
+    /// `Session` which issued the `Request` was deinitialized, most likely because its reference went out of scope.
+    case sessionDeinitialized
+    /// `Session` was explicitly invalidated, possibly with the `Error` produced by the underlying `URLSession`.
+    case sessionInvalidated(error: Error?)
+    /// `URLSessionTask` completed with error.
+    case sessionTaskFailed(error: Error)
+    /// `URLRequest` failed validation.
+    case urlRequestValidationFailed(reason: URLRequestValidationFailureReason)
+}
+
+extension Error {
+    /// Returns the instance cast as an `AFError`.
+    public var asAFError: AFError? {
+        self as? AFError
+    }
+
+    /// Returns the instance cast as an `AFError`. If casting fails, a `fatalError` with the specified `message` is thrown.
+    public func asAFError(orFailWith message: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) -> AFError {
+        guard let afError = self as? AFError else {
+            fatalError(message(), file: file, line: line)
+        }
+        return afError
+    }
+
+    /// Casts the instance as `AFError` or returns `defaultAFError`
+    func asAFError(or defaultAFError: @autoclosure () -> AFError) -> AFError {
+        self as? AFError ?? defaultAFError()
+    }
+}
+
+// MARK: - Error Booleans
+
+extension AFError {
+    /// Returns whether the instance is `.sessionDeinitialized`.
+    public var isSessionDeinitializedError: Bool {
+        if case .sessionDeinitialized = self { return true }
+        return false
+    }
+
+    /// Returns whether the instance is `.sessionInvalidated`.
+    public var isSessionInvalidatedError: Bool {
+        if case .sessionInvalidated = self { return true }
+        return false
+    }
+
+    /// Returns whether the instance is `.explicitlyCancelled`.
+    public var isExplicitlyCancelledError: Bool {
+        if case .explicitlyCancelled = self { return true }
+        return false
+    }
+
+    /// Returns whether the instance is `.invalidURL`.
+    public var isInvalidURLError: Bool {
+        if case .invalidURL = self { return true }
+        return false
+    }
+
+    /// Returns whether the instance is `.parameterEncodingFailed`. When `true`, the `underlyingError` property will
+    /// contain the associated value.
+    public var isParameterEncodingError: Bool {
+        if case .parameterEncodingFailed = self { return true }
+        return false
+    }
+
+    /// Returns whether the instance is `.parameterEncoderFailed`. When `true`, the `underlyingError` property will
+    /// contain the associated value.
+    public var isParameterEncoderError: Bool {
+        if case .parameterEncoderFailed = self { return true }
+        return false
+    }
+
+    /// Returns whether the instance is `.multipartEncodingFailed`. When `true`, the `url` and `underlyingError`
+    /// properties will contain the associated values.
+    public var isMultipartEncodingError: Bool {
+        if case .multipartEncodingFailed = self { return true }
+        return false
+    }
+
+    /// Returns whether the instance is `.requestAdaptationFailed`. When `true`, the `underlyingError` property will
+    /// contain the associated value.
+    public var isRequestAdaptationError: Bool {
+        if case .requestAdaptationFailed = self { return true }
+        return false
+    }
+
+    /// Returns whether the instance is `.responseValidationFailed`. When `true`, the `acceptableContentTypes`,
+    /// `responseContentType`,  `responseCode`, and `underlyingError` properties will contain the associated values.
+    public var isResponseValidationError: Bool {
+        if case .responseValidationFailed = self { return true }
+        return false
+    }
+
+    /// Returns whether the instance is `.responseSerializationFailed`. When `true`, the `failedStringEncoding` and
+    /// `underlyingError` properties will contain the associated values.
+    public var isResponseSerializationError: Bool {
+        if case .responseSerializationFailed = self { return true }
+        return false
+    }
+
+    #if !(os(Linux) || os(Windows))
+    /// Returns whether the instance is `.serverTrustEvaluationFailed`. When `true`, the `underlyingError` property will
+    /// contain the associated value.
+    public var isServerTrustEvaluationError: Bool {
+        if case .serverTrustEvaluationFailed = self { return true }
+        return false
+    }
+    #endif
+
+    /// Returns whether the instance is `requestRetryFailed`. When `true`, the `underlyingError` property will
+    /// contain the associated value.
+    public var isRequestRetryError: Bool {
+        if case .requestRetryFailed = self { return true }
+        return false
+    }
+
+    /// Returns whether the instance is `createUploadableFailed`. When `true`, the `underlyingError` property will
+    /// contain the associated value.
+    public var isCreateUploadableError: Bool {
+        if case .createUploadableFailed = self { return true }
+        return false
+    }
+
+    /// Returns whether the instance is `createURLRequestFailed`. When `true`, the `underlyingError` property will
+    /// contain the associated value.
+    public var isCreateURLRequestError: Bool {
+        if case .createURLRequestFailed = self { return true }
+        return false
+    }
+
+    /// Returns whether the instance is `downloadedFileMoveFailed`. When `true`, the `destination` and `underlyingError` properties will
+    /// contain the associated values.
+    public var isDownloadedFileMoveError: Bool {
+        if case .downloadedFileMoveFailed = self { return true }
+        return false
+    }
+
+    /// Returns whether the instance is `createURLRequestFailed`. When `true`, the `underlyingError` property will
+    /// contain the associated value.
+    public var isSessionTaskError: Bool {
+        if case .sessionTaskFailed = self { return true }
+        return false
+    }
+}
+
+// MARK: - Convenience Properties
+
+extension AFError {
+    /// The `URLConvertible` associated with the error.
+    public var urlConvertible: URLConvertible? {
+        guard case let .invalidURL(url) = self else { return nil }
+        return url
+    }
+
+    /// The `URL` associated with the error.
+    public var url: URL? {
+        guard case let .multipartEncodingFailed(reason) = self else { return nil }
+        return reason.url
+    }
+
+    /// The underlying `Error` responsible for generating the failure associated with `.sessionInvalidated`,
+    /// `.parameterEncodingFailed`, `.parameterEncoderFailed`, `.multipartEncodingFailed`, `.requestAdaptationFailed`,
+    /// `.responseSerializationFailed`, `.requestRetryFailed` errors.
+    public var underlyingError: Error? {
+        switch self {
+        case let .multipartEncodingFailed(reason):
+            return reason.underlyingError
+        case let .parameterEncodingFailed(reason):
+            return reason.underlyingError
+        case let .parameterEncoderFailed(reason):
+            return reason.underlyingError
+        case let .requestAdaptationFailed(error):
+            return error
+        case let .requestRetryFailed(retryError, _):
+            return retryError
+        case let .responseValidationFailed(reason):
+            return reason.underlyingError
+        case let .responseSerializationFailed(reason):
+            return reason.underlyingError
+        #if !(os(Linux) || os(Windows))
+        case let .serverTrustEvaluationFailed(reason):
+            return reason.underlyingError
+        #endif
+        case let .sessionInvalidated(error):
+            return error
+        case let .createUploadableFailed(error):
+            return error
+        case let .createURLRequestFailed(error):
+            return error
+        case let .downloadedFileMoveFailed(error, _, _):
+            return error
+        case let .sessionTaskFailed(error):
+            return error
+        case .explicitlyCancelled,
+             .invalidURL,
+             .sessionDeinitialized,
+             .urlRequestValidationFailed:
+            return nil
+        }
+    }
+
+    /// The acceptable `Content-Type`s of a `.responseValidationFailed` error.
+    public var acceptableContentTypes: [String]? {
+        guard case let .responseValidationFailed(reason) = self else { return nil }
+        return reason.acceptableContentTypes
+    }
+
+    /// The response `Content-Type` of a `.responseValidationFailed` error.
+    public var responseContentType: String? {
+        guard case let .responseValidationFailed(reason) = self else { return nil }
+        return reason.responseContentType
+    }
+
+    /// The response code of a `.responseValidationFailed` error.
+    public var responseCode: Int? {
+        guard case let .responseValidationFailed(reason) = self else { return nil }
+        return reason.responseCode
+    }
+
+    /// The `String.Encoding` associated with a failed `.stringResponse()` call.
+    public var failedStringEncoding: String.Encoding? {
+        guard case let .responseSerializationFailed(reason) = self else { return nil }
+        return reason.failedStringEncoding
+    }
+
+    /// The `source` URL of a `.downloadedFileMoveFailed` error.
+    public var sourceURL: URL? {
+        guard case let .downloadedFileMoveFailed(_, source, _) = self else { return nil }
+        return source
+    }
+
+    /// The `destination` URL of a `.downloadedFileMoveFailed` error.
+    public var destinationURL: URL? {
+        guard case let .downloadedFileMoveFailed(_, _, destination) = self else { return nil }
+        return destination
+    }
+
+    #if !(os(Linux) || os(Windows))
+    /// The download resume data of any underlying network error. Only produced by `DownloadRequest`s.
+    public var downloadResumeData: Data? {
+        (underlyingError as? URLError)?.userInfo[NSURLSessionDownloadTaskResumeData] as? Data
+    }
+    #endif
+}
+
+extension AFError.ParameterEncodingFailureReason {
+    var underlyingError: Error? {
+        switch self {
+        case let .jsonEncodingFailed(error),
+             let .customEncodingFailed(error):
+            return error
+        case .missingURL:
+            return nil
+        }
+    }
+}
+
+extension AFError.ParameterEncoderFailureReason {
+    var underlyingError: Error? {
+        switch self {
+        case let .encoderFailed(error):
+            return error
+        case .missingRequiredComponent:
+            return nil
+        }
+    }
+}
+
+extension AFError.MultipartEncodingFailureReason {
+    var url: URL? {
+        switch self {
+        case let .bodyPartURLInvalid(url),
+             let .bodyPartFilenameInvalid(url),
+             let .bodyPartFileNotReachable(url),
+             let .bodyPartFileIsDirectory(url),
+             let .bodyPartFileSizeNotAvailable(url),
+             let .bodyPartInputStreamCreationFailed(url),
+             let .outputStreamCreationFailed(url),
+             let .outputStreamFileAlreadyExists(url),
+             let .outputStreamURLInvalid(url),
+             let .bodyPartFileNotReachableWithError(url, _),
+             let .bodyPartFileSizeQueryFailedWithError(url, _):
+            return url
+        case .outputStreamWriteFailed,
+             .inputStreamReadFailed:
+            return nil
+        }
+    }
+
+    var underlyingError: Error? {
+        switch self {
+        case let .bodyPartFileNotReachableWithError(_, error),
+             let .bodyPartFileSizeQueryFailedWithError(_, error),
+             let .outputStreamWriteFailed(error),
+             let .inputStreamReadFailed(error):
+            return error
+        case .bodyPartURLInvalid,
+             .bodyPartFilenameInvalid,
+             .bodyPartFileNotReachable,
+             .bodyPartFileIsDirectory,
+             .bodyPartFileSizeNotAvailable,
+             .bodyPartInputStreamCreationFailed,
+             .outputStreamCreationFailed,
+             .outputStreamFileAlreadyExists,
+             .outputStreamURLInvalid:
+            return nil
+        }
+    }
+}
+
+extension AFError.ResponseValidationFailureReason {
+    var acceptableContentTypes: [String]? {
+        switch self {
+        case let .missingContentType(types),
+             let .unacceptableContentType(types, _):
+            return types
+        case .dataFileNil,
+             .dataFileReadFailed,
+             .unacceptableStatusCode,
+             .customValidationFailed:
+            return nil
+        }
+    }
+
+    var responseContentType: String? {
+        switch self {
+        case let .unacceptableContentType(_, responseType):
+            return responseType
+        case .dataFileNil,
+             .dataFileReadFailed,
+             .missingContentType,
+             .unacceptableStatusCode,
+             .customValidationFailed:
+            return nil
+        }
+    }
+
+    var responseCode: Int? {
+        switch self {
+        case let .unacceptableStatusCode(code):
+            return code
+        case .dataFileNil,
+             .dataFileReadFailed,
+             .missingContentType,
+             .unacceptableContentType,
+             .customValidationFailed:
+            return nil
+        }
+    }
+
+    var underlyingError: Error? {
+        switch self {
+        case let .customValidationFailed(error):
+            return error
+        case .dataFileNil,
+             .dataFileReadFailed,
+             .missingContentType,
+             .unacceptableContentType,
+             .unacceptableStatusCode:
+            return nil
+        }
+    }
+}
+
+extension AFError.ResponseSerializationFailureReason {
+    var failedStringEncoding: String.Encoding? {
+        switch self {
+        case let .stringSerializationFailed(encoding):
+            return encoding
+        case .inputDataNilOrZeroLength,
+             .inputFileNil,
+             .inputFileReadFailed(_),
+             .jsonSerializationFailed(_),
+             .decodingFailed(_),
+             .customSerializationFailed(_),
+             .invalidEmptyResponse:
+            return nil
+        }
+    }
+
+    var underlyingError: Error? {
+        switch self {
+        case let .jsonSerializationFailed(error),
+             let .decodingFailed(error),
+             let .customSerializationFailed(error):
+            return error
+        case .inputDataNilOrZeroLength,
+             .inputFileNil,
+             .inputFileReadFailed,
+             .stringSerializationFailed,
+             .invalidEmptyResponse:
+            return nil
+        }
+    }
+}
+
+#if !(os(Linux) || os(Windows))
+extension AFError.ServerTrustFailureReason {
+    var output: AFError.ServerTrustFailureReason.Output? {
+        switch self {
+        case let .defaultEvaluationFailed(output),
+             let .hostValidationFailed(output),
+             let .revocationCheckFailed(output, _):
+            return output
+        case .noRequiredEvaluator,
+             .noCertificatesFound,
+             .noPublicKeysFound,
+             .policyApplicationFailed,
+             .settingAnchorCertificatesFailed,
+             .revocationPolicyCreationFailed,
+             .trustEvaluationFailed,
+             .certificatePinningFailed,
+             .publicKeyPinningFailed,
+             .customEvaluationFailed:
+            return nil
+        }
+    }
+
+    var underlyingError: Error? {
+        switch self {
+        case let .customEvaluationFailed(error):
+            return error
+        case let .trustEvaluationFailed(error):
+            return error
+        case .noRequiredEvaluator,
+             .noCertificatesFound,
+             .noPublicKeysFound,
+             .policyApplicationFailed,
+             .settingAnchorCertificatesFailed,
+             .revocationPolicyCreationFailed,
+             .defaultEvaluationFailed,
+             .hostValidationFailed,
+             .revocationCheckFailed,
+             .certificatePinningFailed,
+             .publicKeyPinningFailed:
+            return nil
+        }
+    }
+}
+#endif
+
+// MARK: - Error Descriptions
+
+extension AFError: LocalizedError {
+    public var errorDescription: String? {
+        switch self {
+        case .explicitlyCancelled:
+            return "Request explicitly cancelled."
+        case let .invalidURL(url):
+            return "URL is not valid: \(url)"
+        case let .parameterEncodingFailed(reason):
+            return reason.localizedDescription
+        case let .parameterEncoderFailed(reason):
+            return reason.localizedDescription
+        case let .multipartEncodingFailed(reason):
+            return reason.localizedDescription
+        case let .requestAdaptationFailed(error):
+            return "Request adaption failed with error: \(error.localizedDescription)"
+        case let .responseValidationFailed(reason):
+            return reason.localizedDescription
+        case let .responseSerializationFailed(reason):
+            return reason.localizedDescription
+        case let .requestRetryFailed(retryError, originalError):
+            return """
+            Request retry failed with retry error: \(retryError.localizedDescription), \
+            original error: \(originalError.localizedDescription)
+            """
+        case .sessionDeinitialized:
+            return """
+            Session was invalidated without error, so it was likely deinitialized unexpectedly. \
+            Be sure to retain a reference to your Session for the duration of your requests.
+            """
+        case let .sessionInvalidated(error):
+            return "Session was invalidated with error: \(error?.localizedDescription ?? "No description.")"
+        #if !(os(Linux) || os(Windows))
+        case let .serverTrustEvaluationFailed(reason):
+            return "Server trust evaluation failed due to reason: \(reason.localizedDescription)"
+        #endif
+        case let .urlRequestValidationFailed(reason):
+            return "URLRequest validation failed due to reason: \(reason.localizedDescription)"
+        case let .createUploadableFailed(error):
+            return "Uploadable creation failed with error: \(error.localizedDescription)"
+        case let .createURLRequestFailed(error):
+            return "URLRequest creation failed with error: \(error.localizedDescription)"
+        case let .downloadedFileMoveFailed(error, source, destination):
+            return "Moving downloaded file from: \(source) to: \(destination) failed with error: \(error.localizedDescription)"
+        case let .sessionTaskFailed(error):
+            return "URLSessionTask failed with error: \(error.localizedDescription)"
+        }
+    }
+}
+
+extension AFError.ParameterEncodingFailureReason {
+    var localizedDescription: String {
+        switch self {
+        case .missingURL:
+            return "URL request to encode was missing a URL"
+        case let .jsonEncodingFailed(error):
+            return "JSON could not be encoded because of error:\n\(error.localizedDescription)"
+        case let .customEncodingFailed(error):
+            return "Custom parameter encoder failed with error: \(error.localizedDescription)"
+        }
+    }
+}
+
+extension AFError.ParameterEncoderFailureReason {
+    var localizedDescription: String {
+        switch self {
+        case let .missingRequiredComponent(component):
+            return "Encoding failed due to a missing request component: \(component)"
+        case let .encoderFailed(error):
+            return "The underlying encoder failed with the error: \(error)"
+        }
+    }
+}
+
+extension AFError.MultipartEncodingFailureReason {
+    var localizedDescription: String {
+        switch self {
+        case let .bodyPartURLInvalid(url):
+            return "The URL provided is not a file URL: \(url)"
+        case let .bodyPartFilenameInvalid(url):
+            return "The URL provided does not have a valid filename: \(url)"
+        case let .bodyPartFileNotReachable(url):
+            return "The URL provided is not reachable: \(url)"
+        case let .bodyPartFileNotReachableWithError(url, error):
+            return """
+            The system returned an error while checking the provided URL for reachability.
+            URL: \(url)
+            Error: \(error)
+            """
+        case let .bodyPartFileIsDirectory(url):
+            return "The URL provided is a directory: \(url)"
+        case let .bodyPartFileSizeNotAvailable(url):
+            return "Could not fetch the file size from the provided URL: \(url)"
+        case let .bodyPartFileSizeQueryFailedWithError(url, error):
+            return """
+            The system returned an error while attempting to fetch the file size from the provided URL.
+            URL: \(url)
+            Error: \(error)
+            """
+        case let .bodyPartInputStreamCreationFailed(url):
+            return "Failed to create an InputStream for the provided URL: \(url)"
+        case let .outputStreamCreationFailed(url):
+            return "Failed to create an OutputStream for URL: \(url)"
+        case let .outputStreamFileAlreadyExists(url):
+            return "A file already exists at the provided URL: \(url)"
+        case let .outputStreamURLInvalid(url):
+            return "The provided OutputStream URL is invalid: \(url)"
+        case let .outputStreamWriteFailed(error):
+            return "OutputStream write failed with error: \(error)"
+        case let .inputStreamReadFailed(error):
+            return "InputStream read failed with error: \(error)"
+        }
+    }
+}
+
+extension AFError.ResponseSerializationFailureReason {
+    var localizedDescription: String {
+        switch self {
+        case .inputDataNilOrZeroLength:
+            return "Response could not be serialized, input data was nil or zero length."
+        case .inputFileNil:
+            return "Response could not be serialized, input file was nil."
+        case let .inputFileReadFailed(url):
+            return "Response could not be serialized, input file could not be read: \(url)."
+        case let .stringSerializationFailed(encoding):
+            return "String could not be serialized with encoding: \(encoding)."
+        case let .jsonSerializationFailed(error):
+            return "JSON could not be serialized because of error:\n\(error.localizedDescription)"
+        case let .invalidEmptyResponse(type):
+            return """
+            Empty response could not be serialized to type: \(type). \
+            Use Empty as the expected type for such responses.
+            """
+        case let .decodingFailed(error):
+            return "Response could not be decoded because of error:\n\(error.localizedDescription)"
+        case let .customSerializationFailed(error):
+            return "Custom response serializer failed with error:\n\(error.localizedDescription)"
+        }
+    }
+}
+
+extension AFError.ResponseValidationFailureReason {
+    var localizedDescription: String {
+        switch self {
+        case .dataFileNil:
+            return "Response could not be validated, data file was nil."
+        case let .dataFileReadFailed(url):
+            return "Response could not be validated, data file could not be read: \(url)."
+        case let .missingContentType(types):
+            return """
+            Response Content-Type was missing and acceptable content types \
+            (\(types.joined(separator: ","))) do not match "*/*".
+            """
+        case let .unacceptableContentType(acceptableTypes, responseType):
+            return """
+            Response Content-Type "\(responseType)" does not match any acceptable types: \
+            \(acceptableTypes.joined(separator: ",")).
+            """
+        case let .unacceptableStatusCode(code):
+            return "Response status code was unacceptable: \(code)."
+        case let .customValidationFailed(error):
+            return "Custom response validation failed with error: \(error.localizedDescription)"
+        }
+    }
+}
+
+#if !(os(Linux) || os(Windows))
+extension AFError.ServerTrustFailureReason {
+    var localizedDescription: String {
+        switch self {
+        case let .noRequiredEvaluator(host):
+            return "A ServerTrustEvaluating value is required for host \(host) but none was found."
+        case .noCertificatesFound:
+            return "No certificates were found or provided for evaluation."
+        case .noPublicKeysFound:
+            return "No public keys were found or provided for evaluation."
+        case .policyApplicationFailed:
+            return "Attempting to set a SecPolicy failed."
+        case .settingAnchorCertificatesFailed:
+            return "Attempting to set the provided certificates as anchor certificates failed."
+        case .revocationPolicyCreationFailed:
+            return "Attempting to create a revocation policy failed."
+        case let .trustEvaluationFailed(error):
+            return "SecTrust evaluation failed with error: \(error?.localizedDescription ?? "None")"
+        case let .defaultEvaluationFailed(output):
+            return "Default evaluation failed for host \(output.host)."
+        case let .hostValidationFailed(output):
+            return "Host validation failed for host \(output.host)."
+        case let .revocationCheckFailed(output, _):
+            return "Revocation check failed for host \(output.host)."
+        case let .certificatePinningFailed(host, _, _, _):
+            return "Certificate pinning failed for host \(host)."
+        case let .publicKeyPinningFailed(host, _, _, _):
+            return "Public key pinning failed for host \(host)."
+        case let .customEvaluationFailed(error):
+            return "Custom trust evaluation failed with error: \(error.localizedDescription)"
+        }
+    }
+}
+#endif
+
+extension AFError.URLRequestValidationFailureReason {
+    var localizedDescription: String {
+        switch self {
+        case let .bodyDataInGETRequest(data):
+            return """
+            Invalid URLRequest: Requests with GET method cannot have body data:
+            \(String(decoding: data, as: UTF8.self))
+            """
+        }
+    }
+}

+ 40 - 0
Pods/Alamofire/Source/Alamofire.swift

@@ -0,0 +1,40 @@
+//
+//  Alamofire.swift
+//
+//  Copyright (c) 2014-2021 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 Dispatch
+import Foundation
+#if canImport(FoundationNetworking)
+@_exported import FoundationNetworking
+#endif
+
+// Enforce minimum Swift version for all platforms and build systems.
+#if swift(<5.3)
+#error("Alamofire doesn't support Swift versions below 5.3.")
+#endif
+
+/// Reference to `Session.default` for quick bootstrapping and examples.
+public let AF = Session.default
+
+/// Current Alamofire version. Necessary since SPM doesn't use dynamic libraries. Plus this will be more accurate.
+let version = "5.6.4"

+ 61 - 0
Pods/Alamofire/Source/AlamofireExtended.swift

@@ -0,0 +1,61 @@
+//
+//  AlamofireExtended.swift
+//
+//  Copyright (c) 2019 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.
+//
+
+/// Type that acts as a generic extension point for all `AlamofireExtended` types.
+public struct AlamofireExtension<ExtendedType> {
+    /// Stores the type or meta-type of any extended type.
+    public private(set) var type: ExtendedType
+
+    /// Create an instance from the provided value.
+    ///
+    /// - Parameter type: Instance being extended.
+    public init(_ type: ExtendedType) {
+        self.type = type
+    }
+}
+
+/// Protocol describing the `af` extension points for Alamofire extended types.
+public protocol AlamofireExtended {
+    /// Type being extended.
+    associatedtype ExtendedType
+
+    /// Static Alamofire extension point.
+    static var af: AlamofireExtension<ExtendedType>.Type { get set }
+    /// Instance Alamofire extension point.
+    var af: AlamofireExtension<ExtendedType> { get set }
+}
+
+extension AlamofireExtended {
+    /// Static Alamofire extension point.
+    public static var af: AlamofireExtension<Self>.Type {
+        get { AlamofireExtension<Self>.self }
+        set {}
+    }
+
+    /// Instance Alamofire extension point.
+    public var af: AlamofireExtension<Self> {
+        get { AlamofireExtension(self) }
+        set {}
+    }
+}

+ 403 - 0
Pods/Alamofire/Source/AuthenticationInterceptor.swift

@@ -0,0 +1,403 @@
+//
+//  AuthenticationInterceptor.swift
+//
+//  Copyright (c) 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.
+//
+
+import Foundation
+
+/// Types adopting the `AuthenticationCredential` protocol can be used to authenticate `URLRequest`s.
+///
+/// One common example of an `AuthenticationCredential` is an OAuth2 credential containing an access token used to
+/// authenticate all requests on behalf of a user. The access token generally has an expiration window of 60 minutes
+/// which will then require a refresh of the credential using the refresh token to generate a new access token.
+public protocol AuthenticationCredential {
+    /// Whether the credential requires a refresh. This property should always return `true` when the credential is
+    /// expired. It is also wise to consider returning `true` when the credential will expire in several seconds or
+    /// minutes depending on the expiration window of the credential.
+    ///
+    /// For example, if the credential is valid for 60 minutes, then it would be wise to return `true` when the
+    /// credential is only valid for 5 minutes or less. That ensures the credential will not expire as it is passed
+    /// around backend services.
+    var requiresRefresh: Bool { get }
+}
+
+// MARK: -
+
+/// Types adopting the `Authenticator` protocol can be used to authenticate `URLRequest`s with an
+/// `AuthenticationCredential` as well as refresh the `AuthenticationCredential` when required.
+public protocol Authenticator: AnyObject {
+    /// The type of credential associated with the `Authenticator` instance.
+    associatedtype Credential: AuthenticationCredential
+
+    /// Applies the `Credential` to the `URLRequest`.
+    ///
+    /// In the case of OAuth2, the access token of the `Credential` would be added to the `URLRequest` as a Bearer
+    /// token to the `Authorization` header.
+    ///
+    /// - Parameters:
+    ///   - credential: The `Credential`.
+    ///   - urlRequest: The `URLRequest`.
+    func apply(_ credential: Credential, to urlRequest: inout URLRequest)
+
+    /// Refreshes the `Credential` and executes the `completion` closure with the `Result` once complete.
+    ///
+    /// Refresh can be called in one of two ways. It can be called before the `Request` is actually executed due to
+    /// a `requiresRefresh` returning `true` during the adapt portion of the `Request` creation process. It can also
+    /// be triggered by a failed `Request` where the authentication server denied access due to an expired or
+    /// invalidated access token.
+    ///
+    /// In the case of OAuth2, this method would use the refresh token of the `Credential` to generate a new
+    /// `Credential` using the authentication service. Once complete, the `completion` closure should be called with
+    /// the new `Credential`, or the error that occurred.
+    ///
+    /// In general, if the refresh call fails with certain status codes from the authentication server (commonly a 401),
+    /// the refresh token in the `Credential` can no longer be used to generate a valid `Credential`. In these cases,
+    /// you will need to reauthenticate the user with their username / password.
+    ///
+    /// Please note, these are just general examples of common use cases. They are not meant to solve your specific
+    /// authentication server challenges. Please work with your authentication server team to ensure your
+    /// `Authenticator` logic matches their expectations.
+    ///
+    /// - Parameters:
+    ///   - credential: The `Credential` to refresh.
+    ///   - session:    The `Session` requiring the refresh.
+    ///   - completion: The closure to be executed once the refresh is complete.
+    func refresh(_ credential: Credential, for session: Session, completion: @escaping (Result<Credential, Error>) -> Void)
+
+    /// Determines whether the `URLRequest` failed due to an authentication error based on the `HTTPURLResponse`.
+    ///
+    /// If the authentication server **CANNOT** invalidate credentials after they are issued, then simply return `false`
+    /// for this method. If the authentication server **CAN** invalidate credentials due to security breaches, then you
+    /// will need to work with your authentication server team to understand how to identify when this occurs.
+    ///
+    /// In the case of OAuth2, where an authentication server can invalidate credentials, you will need to inspect the
+    /// `HTTPURLResponse` or possibly the `Error` for when this occurs. This is commonly handled by the authentication
+    /// server returning a 401 status code and some additional header to indicate an OAuth2 failure occurred.
+    ///
+    /// It is very important to understand how your authentication server works to be able to implement this correctly.
+    /// For example, if your authentication server returns a 401 when an OAuth2 error occurs, and your downstream
+    /// service also returns a 401 when you are not authorized to perform that operation, how do you know which layer
+    /// of the backend returned you a 401? You do not want to trigger a refresh unless you know your authentication
+    /// server is actually the layer rejecting the request. Again, work with your authentication server team to understand
+    /// how to identify an OAuth2 401 error vs. a downstream 401 error to avoid endless refresh loops.
+    ///
+    /// - Parameters:
+    ///   - urlRequest: The `URLRequest`.
+    ///   - response:   The `HTTPURLResponse`.
+    ///   - error:      The `Error`.
+    ///
+    /// - Returns: `true` if the `URLRequest` failed due to an authentication error, `false` otherwise.
+    func didRequest(_ urlRequest: URLRequest, with response: HTTPURLResponse, failDueToAuthenticationError error: Error) -> Bool
+
+    /// Determines whether the `URLRequest` is authenticated with the `Credential`.
+    ///
+    /// If the authentication server **CANNOT** invalidate credentials after they are issued, then simply return `true`
+    /// for this method. If the authentication server **CAN** invalidate credentials due to security breaches, then
+    /// read on.
+    ///
+    /// When an authentication server can invalidate credentials, it means that you may have a non-expired credential
+    /// that appears to be valid, but will be rejected by the authentication server when used. Generally when this
+    /// happens, a number of requests are all sent when the application is foregrounded, and all of them will be
+    /// rejected by the authentication server in the order they are received. The first failed request will trigger a
+    /// refresh internally, which will update the credential, and then retry all the queued requests with the new
+    /// credential. However, it is possible that some of the original requests will not return from the authentication
+    /// server until the refresh has completed. This is where this method comes in.
+    ///
+    /// When the authentication server rejects a credential, we need to check to make sure we haven't refreshed the
+    /// credential while the request was in flight. If it has already refreshed, then we don't need to trigger an
+    /// additional refresh. If it hasn't refreshed, then we need to refresh.
+    ///
+    /// Now that it is understood how the result of this method is used in the refresh lifecyle, let's walk through how
+    /// to implement it. You should return `true` in this method if the `URLRequest` is authenticated in a way that
+    /// matches the values in the `Credential`. In the case of OAuth2, this would mean that the Bearer token in the
+    /// `Authorization` header of the `URLRequest` matches the access token in the `Credential`. If it matches, then we
+    /// know the `Credential` was used to authenticate the `URLRequest` and should return `true`. If the Bearer token
+    /// did not match the access token, then you should return `false`.
+    ///
+    /// - Parameters:
+    ///   - urlRequest: The `URLRequest`.
+    ///   - credential: The `Credential`.
+    ///
+    /// - Returns: `true` if the `URLRequest` is authenticated with the `Credential`, `false` otherwise.
+    func isRequest(_ urlRequest: URLRequest, authenticatedWith credential: Credential) -> Bool
+}
+
+// MARK: -
+
+/// Represents various authentication failures that occur when using the `AuthenticationInterceptor`. All errors are
+/// still vended from Alamofire as `AFError` types. The `AuthenticationError` instances will be embedded within
+/// `AFError` `.requestAdaptationFailed` or `.requestRetryFailed` cases.
+public enum AuthenticationError: Error {
+    /// The credential was missing so the request could not be authenticated.
+    case missingCredential
+    /// The credential was refreshed too many times within the `RefreshWindow`.
+    case excessiveRefresh
+}
+
+// MARK: -
+
+/// The `AuthenticationInterceptor` class manages the queuing and threading complexity of authenticating requests.
+/// It relies on an `Authenticator` type to handle the actual `URLRequest` authentication and `Credential` refresh.
+public class AuthenticationInterceptor<AuthenticatorType>: RequestInterceptor where AuthenticatorType: Authenticator {
+    // MARK: Typealiases
+
+    /// Type of credential used to authenticate requests.
+    public typealias Credential = AuthenticatorType.Credential
+
+    // MARK: Helper Types
+
+    /// Type that defines a time window used to identify excessive refresh calls. When enabled, prior to executing a
+    /// refresh, the `AuthenticationInterceptor` compares the timestamp history of previous refresh calls against the
+    /// `RefreshWindow`. If more refreshes have occurred within the refresh window than allowed, the refresh is
+    /// cancelled and an `AuthorizationError.excessiveRefresh` error is thrown.
+    public struct RefreshWindow {
+        /// `TimeInterval` defining the duration of the time window before the current time in which the number of
+        /// refresh attempts is compared against `maximumAttempts`. For example, if `interval` is 30 seconds, then the
+        /// `RefreshWindow` represents the past 30 seconds. If more attempts occurred in the past 30 seconds than
+        /// `maximumAttempts`, an `.excessiveRefresh` error will be thrown.
+        public let interval: TimeInterval
+
+        /// Total refresh attempts allowed within `interval` before throwing an `.excessiveRefresh` error.
+        public let maximumAttempts: Int
+
+        /// Creates a `RefreshWindow` instance from the specified `interval` and `maximumAttempts`.
+        ///
+        /// - Parameters:
+        ///   - interval:        `TimeInterval` defining the duration of the time window before the current time.
+        ///   - maximumAttempts: The maximum attempts allowed within the `TimeInterval`.
+        public init(interval: TimeInterval = 30.0, maximumAttempts: Int = 5) {
+            self.interval = interval
+            self.maximumAttempts = maximumAttempts
+        }
+    }
+
+    private struct AdaptOperation {
+        let urlRequest: URLRequest
+        let session: Session
+        let completion: (Result<URLRequest, Error>) -> Void
+    }
+
+    private enum AdaptResult {
+        case adapt(Credential)
+        case doNotAdapt(AuthenticationError)
+        case adaptDeferred
+    }
+
+    private struct MutableState {
+        var credential: Credential?
+
+        var isRefreshing = false
+        var refreshTimestamps: [TimeInterval] = []
+        var refreshWindow: RefreshWindow?
+
+        var adaptOperations: [AdaptOperation] = []
+        var requestsToRetry: [(RetryResult) -> Void] = []
+    }
+
+    // MARK: Properties
+
+    /// The `Credential` used to authenticate requests.
+    public var credential: Credential? {
+        get { $mutableState.credential }
+        set { $mutableState.credential = newValue }
+    }
+
+    let authenticator: AuthenticatorType
+    let queue = DispatchQueue(label: "org.alamofire.authentication.inspector")
+
+    @Protected
+    private var mutableState: MutableState
+
+    // MARK: Initialization
+
+    /// Creates an `AuthenticationInterceptor` instance from the specified parameters.
+    ///
+    /// A `nil` `RefreshWindow` will result in the `AuthenticationInterceptor` not checking for excessive refresh calls.
+    /// It is recommended to always use a `RefreshWindow` to avoid endless refresh cycles.
+    ///
+    /// - Parameters:
+    ///   - authenticator: The `Authenticator` type.
+    ///   - credential:    The `Credential` if it exists. `nil` by default.
+    ///   - refreshWindow: The `RefreshWindow` used to identify excessive refresh calls. `RefreshWindow()` by default.
+    public init(authenticator: AuthenticatorType,
+                credential: Credential? = nil,
+                refreshWindow: RefreshWindow? = RefreshWindow()) {
+        self.authenticator = authenticator
+        mutableState = MutableState(credential: credential, refreshWindow: refreshWindow)
+    }
+
+    // MARK: Adapt
+
+    public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
+        let adaptResult: AdaptResult = $mutableState.write { mutableState in
+            // Queue the adapt operation if a refresh is already in place.
+            guard !mutableState.isRefreshing else {
+                let operation = AdaptOperation(urlRequest: urlRequest, session: session, completion: completion)
+                mutableState.adaptOperations.append(operation)
+                return .adaptDeferred
+            }
+
+            // Throw missing credential error is the credential is missing.
+            guard let credential = mutableState.credential else {
+                let error = AuthenticationError.missingCredential
+                return .doNotAdapt(error)
+            }
+
+            // Queue the adapt operation and trigger refresh operation if credential requires refresh.
+            guard !credential.requiresRefresh else {
+                let operation = AdaptOperation(urlRequest: urlRequest, session: session, completion: completion)
+                mutableState.adaptOperations.append(operation)
+                refresh(credential, for: session, insideLock: &mutableState)
+                return .adaptDeferred
+            }
+
+            return .adapt(credential)
+        }
+
+        switch adaptResult {
+        case let .adapt(credential):
+            var authenticatedRequest = urlRequest
+            authenticator.apply(credential, to: &authenticatedRequest)
+            completion(.success(authenticatedRequest))
+
+        case let .doNotAdapt(adaptError):
+            completion(.failure(adaptError))
+
+        case .adaptDeferred:
+            // No-op: adapt operation captured during refresh.
+            break
+        }
+    }
+
+    // MARK: Retry
+
+    public func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) {
+        // Do not attempt retry if there was not an original request and response from the server.
+        guard let urlRequest = request.request, let response = request.response else {
+            completion(.doNotRetry)
+            return
+        }
+
+        // Do not attempt retry unless the `Authenticator` verifies failure was due to authentication error (i.e. 401 status code).
+        guard authenticator.didRequest(urlRequest, with: response, failDueToAuthenticationError: error) else {
+            completion(.doNotRetry)
+            return
+        }
+
+        // Do not attempt retry if there is no credential.
+        guard let credential = credential else {
+            let error = AuthenticationError.missingCredential
+            completion(.doNotRetryWithError(error))
+            return
+        }
+
+        // Retry the request if the `Authenticator` verifies it was authenticated with a previous credential.
+        guard authenticator.isRequest(urlRequest, authenticatedWith: credential) else {
+            completion(.retry)
+            return
+        }
+
+        $mutableState.write { mutableState in
+            mutableState.requestsToRetry.append(completion)
+
+            guard !mutableState.isRefreshing else { return }
+
+            refresh(credential, for: session, insideLock: &mutableState)
+        }
+    }
+
+    // MARK: Refresh
+
+    private func refresh(_ credential: Credential, for session: Session, insideLock mutableState: inout MutableState) {
+        guard !isRefreshExcessive(insideLock: &mutableState) else {
+            let error = AuthenticationError.excessiveRefresh
+            handleRefreshFailure(error, insideLock: &mutableState)
+            return
+        }
+
+        mutableState.refreshTimestamps.append(ProcessInfo.processInfo.systemUptime)
+        mutableState.isRefreshing = true
+
+        // Dispatch to queue to hop out of the lock in case authenticator.refresh is implemented synchronously.
+        queue.async {
+            self.authenticator.refresh(credential, for: session) { result in
+                self.$mutableState.write { mutableState in
+                    switch result {
+                    case let .success(credential):
+                        self.handleRefreshSuccess(credential, insideLock: &mutableState)
+                    case let .failure(error):
+                        self.handleRefreshFailure(error, insideLock: &mutableState)
+                    }
+                }
+            }
+        }
+    }
+
+    private func isRefreshExcessive(insideLock mutableState: inout MutableState) -> Bool {
+        guard let refreshWindow = mutableState.refreshWindow else { return false }
+
+        let refreshWindowMin = ProcessInfo.processInfo.systemUptime - refreshWindow.interval
+
+        let refreshAttemptsWithinWindow = mutableState.refreshTimestamps.reduce(into: 0) { attempts, refreshTimestamp in
+            guard refreshWindowMin <= refreshTimestamp else { return }
+            attempts += 1
+        }
+
+        let isRefreshExcessive = refreshAttemptsWithinWindow >= refreshWindow.maximumAttempts
+
+        return isRefreshExcessive
+    }
+
+    private func handleRefreshSuccess(_ credential: Credential, insideLock mutableState: inout MutableState) {
+        mutableState.credential = credential
+
+        let adaptOperations = mutableState.adaptOperations
+        let requestsToRetry = mutableState.requestsToRetry
+
+        mutableState.adaptOperations.removeAll()
+        mutableState.requestsToRetry.removeAll()
+
+        mutableState.isRefreshing = false
+
+        // Dispatch to queue to hop out of the mutable state lock
+        queue.async {
+            adaptOperations.forEach { self.adapt($0.urlRequest, for: $0.session, completion: $0.completion) }
+            requestsToRetry.forEach { $0(.retry) }
+        }
+    }
+
+    private func handleRefreshFailure(_ error: Error, insideLock mutableState: inout MutableState) {
+        let adaptOperations = mutableState.adaptOperations
+        let requestsToRetry = mutableState.requestsToRetry
+
+        mutableState.adaptOperations.removeAll()
+        mutableState.requestsToRetry.removeAll()
+
+        mutableState.isRefreshing = false
+
+        // Dispatch to queue to hop out of the mutable state lock
+        queue.async {
+            adaptOperations.forEach { $0.completion(.failure(error)) }
+            requestsToRetry.forEach { $0(.doNotRetryWithError(error)) }
+        }
+    }
+}

+ 109 - 0
Pods/Alamofire/Source/CachedResponseHandler.swift

@@ -0,0 +1,109 @@
+//
+//  CachedResponseHandler.swift
+//
+//  Copyright (c) 2019 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
+
+/// A type that handles whether the data task should store the HTTP response in the cache.
+public protocol CachedResponseHandler {
+    /// Determines whether the HTTP response should be stored in the cache.
+    ///
+    /// The `completion` closure should be passed one of three possible options:
+    ///
+    ///   1. The cached response provided by the server (this is the most common use case).
+    ///   2. A modified version of the cached response (you may want to modify it in some way before caching).
+    ///   3. A `nil` value to prevent the cached response from being stored in the cache.
+    ///
+    /// - Parameters:
+    ///   - task:       The data task whose request resulted in the cached response.
+    ///   - response:   The cached response to potentially store in the cache.
+    ///   - completion: The closure to execute containing cached response, a modified response, or `nil`.
+    func dataTask(_ task: URLSessionDataTask,
+                  willCacheResponse response: CachedURLResponse,
+                  completion: @escaping (CachedURLResponse?) -> Void)
+}
+
+// MARK: -
+
+/// `ResponseCacher` is a convenience `CachedResponseHandler` making it easy to cache, not cache, or modify a cached
+/// response.
+public struct ResponseCacher {
+    /// Defines the behavior of the `ResponseCacher` type.
+    public enum Behavior {
+        /// Stores the cached response in the cache.
+        case cache
+        /// Prevents the cached response from being stored in the cache.
+        case doNotCache
+        /// Modifies the cached response before storing it in the cache.
+        case modify((URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)
+    }
+
+    /// Returns a `ResponseCacher` with a `.cache` `Behavior`.
+    public static let cache = ResponseCacher(behavior: .cache)
+    /// Returns a `ResponseCacher` with a `.doNotCache` `Behavior`.
+    public static let doNotCache = ResponseCacher(behavior: .doNotCache)
+
+    /// The `Behavior` of the `ResponseCacher`.
+    public let behavior: Behavior
+
+    /// Creates a `ResponseCacher` instance from the `Behavior`.
+    ///
+    /// - Parameter behavior: The `Behavior`.
+    public init(behavior: Behavior) {
+        self.behavior = behavior
+    }
+}
+
+extension ResponseCacher: CachedResponseHandler {
+    public func dataTask(_ task: URLSessionDataTask,
+                         willCacheResponse response: CachedURLResponse,
+                         completion: @escaping (CachedURLResponse?) -> Void) {
+        switch behavior {
+        case .cache:
+            completion(response)
+        case .doNotCache:
+            completion(nil)
+        case let .modify(closure):
+            let response = closure(task, response)
+            completion(response)
+        }
+    }
+}
+
+#if swift(>=5.5)
+extension CachedResponseHandler where Self == ResponseCacher {
+    /// Provides a `ResponseCacher` which caches the response, if allowed. Equivalent to `ResponseCacher.cache`.
+    public static var cache: ResponseCacher { .cache }
+
+    /// Provides a `ResponseCacher` which does not cache the response. Equivalent to `ResponseCacher.doNotCache`.
+    public static var doNotCache: ResponseCacher { .doNotCache }
+
+    /// Creates a `ResponseCacher` which modifies the proposed `CachedURLResponse` using the provided closure.
+    ///
+    /// - Parameter closure: Closure used to modify the `CachedURLResponse`.
+    /// - Returns:           The `ResponseCacher`.
+    public static func modify(using closure: @escaping ((URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)) -> ResponseCacher {
+        ResponseCacher(behavior: .modify(closure))
+    }
+}
+#endif

+ 655 - 0
Pods/Alamofire/Source/Combine.swift

@@ -0,0 +1,655 @@
+//
+//  Combine.swift
+//
+//  Copyright (c) 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.
+//
+
+#if !((os(iOS) && (arch(i386) || arch(arm))) || os(Windows) || os(Linux))
+
+import Combine
+import Dispatch
+import Foundation
+
+// MARK: - DataRequest / UploadRequest
+
+/// A Combine `Publisher` that publishes the `DataResponse<Value, AFError>` of the provided `DataRequest`.
+@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
+public struct DataResponsePublisher<Value>: Publisher {
+    public typealias Output = DataResponse<Value, AFError>
+    public typealias Failure = Never
+
+    private typealias Handler = (@escaping (_ response: DataResponse<Value, AFError>) -> Void) -> DataRequest
+
+    private let request: DataRequest
+    private let responseHandler: Handler
+
+    /// Creates an instance which will serialize responses using the provided `ResponseSerializer`.
+    ///
+    /// - Parameters:
+    ///   - request:    `DataRequest` for which to publish the response.
+    ///   - queue:      `DispatchQueue` on which the `DataResponse` value will be published. `.main` by default.
+    ///   - serializer: `ResponseSerializer` used to produce the published `DataResponse`.
+    public init<Serializer: ResponseSerializer>(_ request: DataRequest, queue: DispatchQueue, serializer: Serializer)
+        where Value == Serializer.SerializedObject {
+        self.request = request
+        responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) }
+    }
+
+    /// Creates an instance which will serialize responses using the provided `DataResponseSerializerProtocol`.
+    ///
+    /// - Parameters:
+    ///   - request:    `DataRequest` for which to publish the response.
+    ///   - queue:      `DispatchQueue` on which the `DataResponse` value will be published. `.main` by default.
+    ///   - serializer: `DataResponseSerializerProtocol` used to produce the published `DataResponse`.
+    public init<Serializer: DataResponseSerializerProtocol>(_ request: DataRequest,
+                                                            queue: DispatchQueue,
+                                                            serializer: Serializer)
+        where Value == Serializer.SerializedObject {
+        self.request = request
+        responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) }
+    }
+
+    /// Publishes only the `Result` of the `DataResponse` value.
+    ///
+    /// - Returns: The `AnyPublisher` publishing the `Result<Value, AFError>` value.
+    public func result() -> AnyPublisher<Result<Value, AFError>, Never> {
+        map(\.result).eraseToAnyPublisher()
+    }
+
+    /// Publishes the `Result` of the `DataResponse` as a single `Value` or fail with the `AFError` instance.
+    ///
+    /// - Returns: The `AnyPublisher<Value, AFError>` publishing the stream.
+    public func value() -> AnyPublisher<Value, AFError> {
+        setFailureType(to: AFError.self).flatMap(\.result.publisher).eraseToAnyPublisher()
+    }
+
+    public func receive<S>(subscriber: S) where S: Subscriber, DataResponsePublisher.Failure == S.Failure, DataResponsePublisher.Output == S.Input {
+        subscriber.receive(subscription: Inner(request: request,
+                                               responseHandler: responseHandler,
+                                               downstream: subscriber))
+    }
+
+    private final class Inner<Downstream: Subscriber>: Subscription
+        where Downstream.Input == Output {
+        typealias Failure = Downstream.Failure
+
+        @Protected
+        private var downstream: Downstream?
+        private let request: DataRequest
+        private let responseHandler: Handler
+
+        init(request: DataRequest, responseHandler: @escaping Handler, downstream: Downstream) {
+            self.request = request
+            self.responseHandler = responseHandler
+            self.downstream = downstream
+        }
+
+        func request(_ demand: Subscribers.Demand) {
+            assert(demand > 0)
+
+            guard let downstream = downstream else { return }
+
+            self.downstream = nil
+            responseHandler { response in
+                _ = downstream.receive(response)
+                downstream.receive(completion: .finished)
+            }.resume()
+        }
+
+        func cancel() {
+            request.cancel()
+            downstream = nil
+        }
+    }
+}
+
+@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
+extension DataResponsePublisher where Value == Data? {
+    /// Creates an instance which publishes a `DataResponse<Data?, AFError>` value without serialization.
+    @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
+    public init(_ request: DataRequest, queue: DispatchQueue) {
+        self.request = request
+        responseHandler = { request.response(queue: queue, completionHandler: $0) }
+    }
+}
+
+extension DataRequest {
+    /// Creates a `DataResponsePublisher` for this instance using the given `ResponseSerializer` and `DispatchQueue`.
+    ///
+    /// - Parameters:
+    ///   - serializer: `ResponseSerializer` used to serialize response `Data`.
+    ///   - queue:      `DispatchQueue` on which the `DataResponse` will be published. `.main` by default.
+    ///
+    /// - Returns:      The `DataResponsePublisher`.
+    @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
+    public func publishResponse<Serializer: ResponseSerializer, T>(using serializer: Serializer, on queue: DispatchQueue = .main) -> DataResponsePublisher<T>
+        where Serializer.SerializedObject == T {
+        DataResponsePublisher(self, queue: queue, serializer: serializer)
+    }
+
+    /// Creates a `DataResponsePublisher` for this instance and uses a `DataResponseSerializer` to serialize the
+    /// response.
+    ///
+    /// - Parameters:
+    ///   - queue:               `DispatchQueue` on which the `DataResponse` will be published. `.main` by default.
+    ///   - preprocessor:        `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()`
+    ///                          by default.
+    ///   - emptyResponseCodes:  `Set<Int>` of HTTP status codes for which empty responses are allowed. `[204, 205]` by
+    ///                          default.
+    ///   - emptyRequestMethods: `Set<HTTPMethod>` of `HTTPMethod`s for which empty responses are allowed, regardless of
+    ///                          status code. `[.head]` by default.
+    /// - Returns:               The `DataResponsePublisher`.
+    @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
+    public func publishData(queue: DispatchQueue = .main,
+                            preprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
+                            emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
+                            emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher<Data> {
+        publishResponse(using: DataResponseSerializer(dataPreprocessor: preprocessor,
+                                                      emptyResponseCodes: emptyResponseCodes,
+                                                      emptyRequestMethods: emptyRequestMethods),
+                        on: queue)
+    }
+
+    /// Creates a `DataResponsePublisher` for this instance and uses a `StringResponseSerializer` to serialize the
+    /// response.
+    ///
+    /// - Parameters:
+    ///   - queue:               `DispatchQueue` on which the `DataResponse` will be published. `.main` by default.
+    ///   - preprocessor:        `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()`
+    ///                          by default.
+    ///   - encoding:            `String.Encoding` to parse the response. `nil` by default, in which case the encoding
+    ///                          will be determined by the server response, falling back to the default HTTP character
+    ///                          set, `ISO-8859-1`.
+    ///   - emptyResponseCodes:  `Set<Int>` of HTTP status codes for which empty responses are allowed. `[204, 205]` by
+    ///                          default.
+    ///   - emptyRequestMethods: `Set<HTTPMethod>` of `HTTPMethod`s for which empty responses are allowed, regardless of
+    ///                          status code. `[.head]` by default.
+    ///
+    /// - Returns:               The `DataResponsePublisher`.
+    @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
+    public func publishString(queue: DispatchQueue = .main,
+                              preprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
+                              encoding: String.Encoding? = nil,
+                              emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
+                              emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher<String> {
+        publishResponse(using: StringResponseSerializer(dataPreprocessor: preprocessor,
+                                                        encoding: encoding,
+                                                        emptyResponseCodes: emptyResponseCodes,
+                                                        emptyRequestMethods: emptyRequestMethods),
+                        on: queue)
+    }
+
+    @_disfavoredOverload
+    @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
+    @available(*, deprecated, message: "Renamed publishDecodable(type:queue:preprocessor:decoder:emptyResponseCodes:emptyRequestMethods).")
+    public func publishDecodable<T: Decodable>(type: T.Type = T.self,
+                                               queue: DispatchQueue = .main,
+                                               preprocessor: DataPreprocessor = DecodableResponseSerializer<T>.defaultDataPreprocessor,
+                                               decoder: DataDecoder = JSONDecoder(),
+                                               emptyResponseCodes: Set<Int> = DecodableResponseSerializer<T>.defaultEmptyResponseCodes,
+                                               emptyResponseMethods: Set<HTTPMethod> = DecodableResponseSerializer<T>.defaultEmptyRequestMethods) -> DataResponsePublisher<T> {
+        publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor,
+                                                           decoder: decoder,
+                                                           emptyResponseCodes: emptyResponseCodes,
+                                                           emptyRequestMethods: emptyResponseMethods),
+                        on: queue)
+    }
+
+    /// Creates a `DataResponsePublisher` for this instance and uses a `DecodableResponseSerializer` to serialize the
+    /// response.
+    ///
+    /// - Parameters:
+    ///   - type:                `Decodable` type to which to decode response `Data`. Inferred from the context by
+    ///                          default.
+    ///   - queue:               `DispatchQueue` on which the `DataResponse` will be published. `.main` by default.
+    ///   - preprocessor:        `DataPreprocessor` which filters the `Data` before serialization.
+    ///                          `PassthroughPreprocessor()` by default.
+    ///   - decoder:             `DataDecoder` instance used to decode response `Data`. `JSONDecoder()` by default.
+    ///   - emptyResponseCodes:  `Set<Int>` of HTTP status codes for which empty responses are allowed. `[204, 205]` by
+    ///                          default.
+    ///   - emptyRequestMethods: `Set<HTTPMethod>` of `HTTPMethod`s for which empty responses are allowed, regardless of
+    ///                          status code. `[.head]` by default.
+    ///
+    /// - Returns:               The `DataResponsePublisher`.
+    @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
+    public func publishDecodable<T: Decodable>(type: T.Type = T.self,
+                                               queue: DispatchQueue = .main,
+                                               preprocessor: DataPreprocessor = DecodableResponseSerializer<T>.defaultDataPreprocessor,
+                                               decoder: DataDecoder = JSONDecoder(),
+                                               emptyResponseCodes: Set<Int> = DecodableResponseSerializer<T>.defaultEmptyResponseCodes,
+                                               emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer<T>.defaultEmptyRequestMethods) -> DataResponsePublisher<T> {
+        publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor,
+                                                           decoder: decoder,
+                                                           emptyResponseCodes: emptyResponseCodes,
+                                                           emptyRequestMethods: emptyRequestMethods),
+                        on: queue)
+    }
+
+    /// Creates a `DataResponsePublisher` for this instance which does not serialize the response before publishing.
+    ///
+    ///   - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default.
+    ///
+    /// - Returns: The `DataResponsePublisher`.
+    @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
+    public func publishUnserialized(queue: DispatchQueue = .main) -> DataResponsePublisher<Data?> {
+        DataResponsePublisher(self, queue: queue)
+    }
+}
+
+// A Combine `Publisher` that publishes a sequence of `Stream<Value, AFError>` values received by the provided `DataStreamRequest`.
+@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
+public struct DataStreamPublisher<Value>: Publisher {
+    public typealias Output = DataStreamRequest.Stream<Value, AFError>
+    public typealias Failure = Never
+
+    private typealias Handler = (@escaping DataStreamRequest.Handler<Value, AFError>) -> DataStreamRequest
+
+    private let request: DataStreamRequest
+    private let streamHandler: Handler
+
+    /// Creates an instance which will serialize responses using the provided `DataStreamSerializer`.
+    ///
+    /// - Parameters:
+    ///   - request:    `DataStreamRequest` for which to publish the response.
+    ///   - queue:      `DispatchQueue` on which the `Stream<Value, AFError>` values will be published. `.main` by
+    ///                 default.
+    ///   - serializer: `DataStreamSerializer` used to produce the published `Stream<Value, AFError>` values.
+    public init<Serializer: DataStreamSerializer>(_ request: DataStreamRequest, queue: DispatchQueue, serializer: Serializer)
+        where Value == Serializer.SerializedObject {
+        self.request = request
+        streamHandler = { request.responseStream(using: serializer, on: queue, stream: $0) }
+    }
+
+    /// Publishes only the `Result` of the `DataStreamRequest.Stream`'s `Event`s.
+    ///
+    /// - Returns: The `AnyPublisher` publishing the `Result<Value, AFError>` value.
+    public func result() -> AnyPublisher<Result<Value, AFError>, Never> {
+        compactMap { stream in
+            switch stream.event {
+            case let .stream(result):
+                return result
+            // If the stream has completed with an error, send the error value downstream as a `.failure`.
+            case let .complete(completion):
+                return completion.error.map(Result.failure)
+            }
+        }
+        .eraseToAnyPublisher()
+    }
+
+    /// Publishes the streamed values of the `DataStreamRequest.Stream` as a sequence of `Value` or fail with the
+    /// `AFError` instance.
+    ///
+    /// - Returns: The `AnyPublisher<Value, AFError>` publishing the stream.
+    public func value() -> AnyPublisher<Value, AFError> {
+        result().setFailureType(to: AFError.self).flatMap(\.publisher).eraseToAnyPublisher()
+    }
+
+    public func receive<S>(subscriber: S) where S: Subscriber, DataStreamPublisher.Failure == S.Failure, DataStreamPublisher.Output == S.Input {
+        subscriber.receive(subscription: Inner(request: request,
+                                               streamHandler: streamHandler,
+                                               downstream: subscriber))
+    }
+
+    private final class Inner<Downstream: Subscriber>: Subscription
+        where Downstream.Input == Output {
+        typealias Failure = Downstream.Failure
+
+        @Protected
+        private var downstream: Downstream?
+        private let request: DataStreamRequest
+        private let streamHandler: Handler
+
+        init(request: DataStreamRequest, streamHandler: @escaping Handler, downstream: Downstream) {
+            self.request = request
+            self.streamHandler = streamHandler
+            self.downstream = downstream
+        }
+
+        func request(_ demand: Subscribers.Demand) {
+            assert(demand > 0)
+
+            guard let downstream = downstream else { return }
+
+            self.downstream = nil
+            streamHandler { stream in
+                _ = downstream.receive(stream)
+                if case .complete = stream.event {
+                    downstream.receive(completion: .finished)
+                }
+            }.resume()
+        }
+
+        func cancel() {
+            request.cancel()
+            downstream = nil
+        }
+    }
+}
+
+extension DataStreamRequest {
+    /// Creates a `DataStreamPublisher` for this instance using the given `DataStreamSerializer` and `DispatchQueue`.
+    ///
+    /// - Parameters:
+    ///   - serializer: `DataStreamSerializer` used to serialize the streamed `Data`.
+    ///   - queue:      `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default.
+    /// - Returns:      The `DataStreamPublisher`.
+    @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
+    public func publishStream<Serializer: DataStreamSerializer>(using serializer: Serializer,
+                                                                on queue: DispatchQueue = .main) -> DataStreamPublisher<Serializer.SerializedObject> {
+        DataStreamPublisher(self, queue: queue, serializer: serializer)
+    }
+
+    /// Creates a `DataStreamPublisher` for this instance which uses a `PassthroughStreamSerializer` to stream `Data`
+    /// unserialized.
+    ///
+    /// - Parameters:
+    ///   - queue:      `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default.
+    /// - Returns:      The `DataStreamPublisher`.
+    @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
+    public func publishData(queue: DispatchQueue = .main) -> DataStreamPublisher<Data> {
+        publishStream(using: PassthroughStreamSerializer(), on: queue)
+    }
+
+    /// Creates a `DataStreamPublisher` for this instance which uses a `StringStreamSerializer` to serialize stream
+    /// `Data` values into `String` values.
+    ///
+    /// - Parameters:
+    ///   - queue:      `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default.
+    /// - Returns:      The `DataStreamPublisher`.
+    @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
+    public func publishString(queue: DispatchQueue = .main) -> DataStreamPublisher<String> {
+        publishStream(using: StringStreamSerializer(), on: queue)
+    }
+
+    /// Creates a `DataStreamPublisher` for this instance which uses a `DecodableStreamSerializer` with the provided
+    /// parameters to serialize stream `Data` values into the provided type.
+    ///
+    /// - Parameters:
+    ///   - type:         `Decodable` type to which to decode stream `Data`. Inferred from the context by default.
+    ///   - queue:        `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default.
+    ///   - decoder:      `DataDecoder` instance used to decode stream `Data`. `JSONDecoder()` by default.
+    ///   - preprocessor: `DataPreprocessor` which filters incoming stream `Data` before serialization.
+    ///                   `PassthroughPreprocessor()` by default.
+    /// - Returns:        The `DataStreamPublisher`.
+    @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
+    public func publishDecodable<T: Decodable>(type: T.Type = T.self,
+                                               queue: DispatchQueue = .main,
+                                               decoder: DataDecoder = JSONDecoder(),
+                                               preprocessor: DataPreprocessor = PassthroughPreprocessor()) -> DataStreamPublisher<T> {
+        publishStream(using: DecodableStreamSerializer(decoder: decoder,
+                                                       dataPreprocessor: preprocessor),
+                      on: queue)
+    }
+}
+
+/// A Combine `Publisher` that publishes the `DownloadResponse<Value, AFError>` of the provided `DownloadRequest`.
+@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
+public struct DownloadResponsePublisher<Value>: Publisher {
+    public typealias Output = DownloadResponse<Value, AFError>
+    public typealias Failure = Never
+
+    private typealias Handler = (@escaping (_ response: DownloadResponse<Value, AFError>) -> Void) -> DownloadRequest
+
+    private let request: DownloadRequest
+    private let responseHandler: Handler
+
+    /// Creates an instance which will serialize responses using the provided `ResponseSerializer`.
+    ///
+    /// - Parameters:
+    ///   - request:    `DownloadRequest` for which to publish the response.
+    ///   - queue:      `DispatchQueue` on which the `DownloadResponse` value will be published. `.main` by default.
+    ///   - serializer: `ResponseSerializer` used to produce the published `DownloadResponse`.
+    public init<Serializer: ResponseSerializer>(_ request: DownloadRequest, queue: DispatchQueue, serializer: Serializer)
+        where Value == Serializer.SerializedObject {
+        self.request = request
+        responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) }
+    }
+
+    /// Creates an instance which will serialize responses using the provided `DownloadResponseSerializerProtocol` value.
+    ///
+    /// - Parameters:
+    ///   - request:    `DownloadRequest` for which to publish the response.
+    ///   - queue:      `DispatchQueue` on which the `DataResponse` value will be published. `.main` by default.
+    ///   - serializer: `DownloadResponseSerializerProtocol` used to produce the published `DownloadResponse`.
+    @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
+    public init<Serializer: DownloadResponseSerializerProtocol>(_ request: DownloadRequest,
+                                                                queue: DispatchQueue,
+                                                                serializer: Serializer)
+        where Value == Serializer.SerializedObject {
+        self.request = request
+        responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) }
+    }
+
+    /// Publishes only the `Result` of the `DownloadResponse` value.
+    ///
+    /// - Returns: The `AnyPublisher` publishing the `Result<Value, AFError>` value.
+    public func result() -> AnyPublisher<Result<Value, AFError>, Never> {
+        map(\.result).eraseToAnyPublisher()
+    }
+
+    /// Publishes the `Result` of the `DownloadResponse` as a single `Value` or fail with the `AFError` instance.
+    ///
+    /// - Returns: The `AnyPublisher<Value, AFError>` publishing the stream.
+    public func value() -> AnyPublisher<Value, AFError> {
+        setFailureType(to: AFError.self).flatMap(\.result.publisher).eraseToAnyPublisher()
+    }
+
+    public func receive<S>(subscriber: S) where S: Subscriber, DownloadResponsePublisher.Failure == S.Failure, DownloadResponsePublisher.Output == S.Input {
+        subscriber.receive(subscription: Inner(request: request,
+                                               responseHandler: responseHandler,
+                                               downstream: subscriber))
+    }
+
+    private final class Inner<Downstream: Subscriber>: Subscription
+        where Downstream.Input == Output {
+        typealias Failure = Downstream.Failure
+
+        @Protected
+        private var downstream: Downstream?
+        private let request: DownloadRequest
+        private let responseHandler: Handler
+
+        init(request: DownloadRequest, responseHandler: @escaping Handler, downstream: Downstream) {
+            self.request = request
+            self.responseHandler = responseHandler
+            self.downstream = downstream
+        }
+
+        func request(_ demand: Subscribers.Demand) {
+            assert(demand > 0)
+
+            guard let downstream = downstream else { return }
+
+            self.downstream = nil
+            responseHandler { response in
+                _ = downstream.receive(response)
+                downstream.receive(completion: .finished)
+            }.resume()
+        }
+
+        func cancel() {
+            request.cancel()
+            downstream = nil
+        }
+    }
+}
+
+extension DownloadRequest {
+    /// Creates a `DownloadResponsePublisher` for this instance using the given `ResponseSerializer` and `DispatchQueue`.
+    ///
+    /// - Parameters:
+    ///   - serializer: `ResponseSerializer` used to serialize the response `Data` from disk.
+    ///   - queue:      `DispatchQueue` on which the `DownloadResponse` will be published.`.main` by default.
+    ///
+    /// - Returns:      The `DownloadResponsePublisher`.
+    @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
+    public func publishResponse<Serializer: ResponseSerializer, T>(using serializer: Serializer, on queue: DispatchQueue = .main) -> DownloadResponsePublisher<T>
+        where Serializer.SerializedObject == T {
+        DownloadResponsePublisher(self, queue: queue, serializer: serializer)
+    }
+
+    /// Creates a `DownloadResponsePublisher` for this instance using the given `DownloadResponseSerializerProtocol` and
+    /// `DispatchQueue`.
+    ///
+    /// - Parameters:
+    ///   - serializer: `DownloadResponseSerializer` used to serialize the response `Data` from disk.
+    ///   - queue:      `DispatchQueue` on which the `DownloadResponse` will be published.`.main` by default.
+    ///
+    /// - Returns:      The `DownloadResponsePublisher`.
+    @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
+    public func publishResponse<Serializer: DownloadResponseSerializerProtocol, T>(using serializer: Serializer, on queue: DispatchQueue = .main) -> DownloadResponsePublisher<T>
+        where Serializer.SerializedObject == T {
+        DownloadResponsePublisher(self, queue: queue, serializer: serializer)
+    }
+
+    /// Creates a `DownloadResponsePublisher` for this instance and uses a `URLResponseSerializer` to serialize the
+    /// response.
+    ///
+    /// - Parameter queue: `DispatchQueue` on which the `DownloadResponse` will be published. `.main` by default.
+    ///
+    /// - Returns:         The `DownloadResponsePublisher`.
+    @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
+    public func publishURL(queue: DispatchQueue = .main) -> DownloadResponsePublisher<URL> {
+        publishResponse(using: URLResponseSerializer(), on: queue)
+    }
+
+    /// Creates a `DownloadResponsePublisher` for this instance and uses a `DataResponseSerializer` to serialize the
+    /// response.
+    ///
+    /// - Parameters:
+    ///   - queue:               `DispatchQueue` on which the `DownloadResponse` will be published. `.main` by default.
+    ///   - preprocessor:        `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()`
+    ///                          by default.
+    ///   - emptyResponseCodes:  `Set<Int>` of HTTP status codes for which empty responses are allowed. `[204, 205]` by
+    ///                          default.
+    ///   - emptyRequestMethods: `Set<HTTPMethod>` of `HTTPMethod`s for which empty responses are allowed, regardless of
+    ///                          status code. `[.head]` by default.
+    ///
+    /// - Returns:               The `DownloadResponsePublisher`.
+    @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
+    public func publishData(queue: DispatchQueue = .main,
+                            preprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
+                            emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
+                            emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher<Data> {
+        publishResponse(using: DataResponseSerializer(dataPreprocessor: preprocessor,
+                                                      emptyResponseCodes: emptyResponseCodes,
+                                                      emptyRequestMethods: emptyRequestMethods),
+                        on: queue)
+    }
+
+    /// Creates a `DownloadResponsePublisher` for this instance and uses a `StringResponseSerializer` to serialize the
+    /// response.
+    ///
+    /// - Parameters:
+    ///   - queue:               `DispatchQueue` on which the `DataResponse` will be published. `.main` by default.
+    ///   - preprocessor:        `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()`
+    ///                          by default.
+    ///   - encoding:            `String.Encoding` to parse the response. `nil` by default, in which case the encoding
+    ///                          will be determined by the server response, falling back to the default HTTP character
+    ///                          set, `ISO-8859-1`.
+    ///   - emptyResponseCodes:  `Set<Int>` of HTTP status codes for which empty responses are allowed. `[204, 205]` by
+    ///                          default.
+    ///   - emptyRequestMethods: `Set<HTTPMethod>` of `HTTPMethod`s for which empty responses are allowed, regardless of
+    ///                          status code. `[.head]` by default.
+    ///
+    /// - Returns:               The `DownloadResponsePublisher`.
+    @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
+    public func publishString(queue: DispatchQueue = .main,
+                              preprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
+                              encoding: String.Encoding? = nil,
+                              emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
+                              emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher<String> {
+        publishResponse(using: StringResponseSerializer(dataPreprocessor: preprocessor,
+                                                        encoding: encoding,
+                                                        emptyResponseCodes: emptyResponseCodes,
+                                                        emptyRequestMethods: emptyRequestMethods),
+                        on: queue)
+    }
+
+    @_disfavoredOverload
+    @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
+    @available(*, deprecated, message: "Renamed publishDecodable(type:queue:preprocessor:decoder:emptyResponseCodes:emptyRequestMethods).")
+    public func publishDecodable<T: Decodable>(type: T.Type = T.self,
+                                               queue: DispatchQueue = .main,
+                                               preprocessor: DataPreprocessor = DecodableResponseSerializer<T>.defaultDataPreprocessor,
+                                               decoder: DataDecoder = JSONDecoder(),
+                                               emptyResponseCodes: Set<Int> = DecodableResponseSerializer<T>.defaultEmptyResponseCodes,
+                                               emptyResponseMethods: Set<HTTPMethod> = DecodableResponseSerializer<T>.defaultEmptyRequestMethods) -> DownloadResponsePublisher<T> {
+        publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor,
+                                                           decoder: decoder,
+                                                           emptyResponseCodes: emptyResponseCodes,
+                                                           emptyRequestMethods: emptyResponseMethods),
+                        on: queue)
+    }
+
+    /// Creates a `DownloadResponsePublisher` for this instance and uses a `DecodableResponseSerializer` to serialize
+    /// the response.
+    ///
+    /// - Parameters:
+    ///   - type:                `Decodable` type to which to decode response `Data`. Inferred from the context by default.
+    ///   - queue:               `DispatchQueue` on which the `DataResponse` will be published. `.main` by default.
+    ///   - preprocessor:        `DataPreprocessor` which filters the `Data` before serialization.
+    ///                          `PassthroughPreprocessor()` by default.
+    ///   - decoder:             `DataDecoder` instance used to decode response `Data`. `JSONDecoder()` by default.
+    ///   - emptyResponseCodes:  `Set<Int>` of HTTP status codes for which empty responses are allowed. `[204, 205]` by
+    ///                          default.
+    ///   - emptyRequestMethods: `Set<HTTPMethod>` of `HTTPMethod`s for which empty responses are allowed, regardless
+    ///                          of status code. `[.head]` by default.
+    ///
+    /// - Returns:               The `DownloadResponsePublisher`.
+    @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
+    public func publishDecodable<T: Decodable>(type: T.Type = T.self,
+                                               queue: DispatchQueue = .main,
+                                               preprocessor: DataPreprocessor = DecodableResponseSerializer<T>.defaultDataPreprocessor,
+                                               decoder: DataDecoder = JSONDecoder(),
+                                               emptyResponseCodes: Set<Int> = DecodableResponseSerializer<T>.defaultEmptyResponseCodes,
+                                               emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer<T>.defaultEmptyRequestMethods) -> DownloadResponsePublisher<T> {
+        publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor,
+                                                           decoder: decoder,
+                                                           emptyResponseCodes: emptyResponseCodes,
+                                                           emptyRequestMethods: emptyRequestMethods),
+                        on: queue)
+    }
+}
+
+@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
+extension DownloadResponsePublisher where Value == URL? {
+    /// Creates an instance which publishes a `DownloadResponse<URL?, AFError>` value without serialization.
+    @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
+    public init(_ request: DownloadRequest, queue: DispatchQueue) {
+        self.request = request
+        responseHandler = { request.response(queue: queue, completionHandler: $0) }
+    }
+}
+
+extension DownloadRequest {
+    /// Creates a `DownloadResponsePublisher` for this instance which does not serialize the response before publishing.
+    ///
+    /// - Parameter queue: `DispatchQueue` on which the `DownloadResponse` will be published. `.main` by default.
+    ///
+    /// - Returns:         The `DownloadResponsePublisher`.
+    @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
+    public func publishUnserialized(on queue: DispatchQueue = .main) -> DownloadResponsePublisher<URL?> {
+        DownloadResponsePublisher(self, queue: queue)
+    }
+}
+
+#endif

+ 704 - 0
Pods/Alamofire/Source/Concurrency.swift

@@ -0,0 +1,704 @@
+//
+//  Concurrency.swift
+//
+//  Copyright (c) 2021 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.
+//
+
+#if compiler(>=5.6.0) && canImport(_Concurrency)
+
+import Foundation
+
+// MARK: - Request Event Streams
+
+@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
+extension Request {
+    /// Creates a `StreamOf<Progress>` for the instance's upload progress.
+    ///
+    /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default.
+    ///
+    /// - Returns:                   The `StreamOf<Progress>`.
+    public func uploadProgress(bufferingPolicy: StreamOf<Progress>.BufferingPolicy = .unbounded) -> StreamOf<Progress> {
+        stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in
+            uploadProgress(queue: .singleEventQueue) { progress in
+                continuation.yield(progress)
+            }
+        }
+    }
+
+    /// Creates a `StreamOf<Progress>` for the instance's download progress.
+    ///
+    /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default.
+    ///
+    /// - Returns:                   The `StreamOf<Progress>`.
+    public func downloadProgress(bufferingPolicy: StreamOf<Progress>.BufferingPolicy = .unbounded) -> StreamOf<Progress> {
+        stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in
+            downloadProgress(queue: .singleEventQueue) { progress in
+                continuation.yield(progress)
+            }
+        }
+    }
+
+    /// Creates a `StreamOf<URLRequest>` for the `URLRequest`s produced for the instance.
+    ///
+    /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default.
+    ///
+    /// - Returns:                   The `StreamOf<URLRequest>`.
+    public func urlRequests(bufferingPolicy: StreamOf<URLRequest>.BufferingPolicy = .unbounded) -> StreamOf<URLRequest> {
+        stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in
+            onURLRequestCreation(on: .singleEventQueue) { request in
+                continuation.yield(request)
+            }
+        }
+    }
+
+    /// Creates a `StreamOf<URLSessionTask>` for the `URLSessionTask`s produced for the instance.
+    ///
+    /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default.
+    ///
+    /// - Returns:                   The `StreamOf<URLSessionTask>`.
+    public func urlSessionTasks(bufferingPolicy: StreamOf<URLSessionTask>.BufferingPolicy = .unbounded) -> StreamOf<URLSessionTask> {
+        stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in
+            onURLSessionTaskCreation(on: .singleEventQueue) { task in
+                continuation.yield(task)
+            }
+        }
+    }
+
+    /// Creates a `StreamOf<String>` for the cURL descriptions produced for the instance.
+    ///
+    /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default.
+    ///
+    /// - Returns:                   The `StreamOf<String>`.
+    public func cURLDescriptions(bufferingPolicy: StreamOf<String>.BufferingPolicy = .unbounded) -> StreamOf<String> {
+        stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in
+            cURLDescription(on: .singleEventQueue) { description in
+                continuation.yield(description)
+            }
+        }
+    }
+
+    private func stream<T>(of type: T.Type = T.self,
+                           bufferingPolicy: StreamOf<T>.BufferingPolicy = .unbounded,
+                           yielder: @escaping (StreamOf<T>.Continuation) -> Void) -> StreamOf<T> {
+        StreamOf<T>(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in
+            yielder(continuation)
+            // Must come after serializers run in order to catch retry progress.
+            onFinish {
+                continuation.finish()
+            }
+        }
+    }
+}
+
+// MARK: - DataTask
+
+/// Value used to `await` a `DataResponse` and associated values.
+@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
+public struct DataTask<Value> {
+    /// `DataResponse` produced by the `DataRequest` and its response handler.
+    public var response: DataResponse<Value, AFError> {
+        get async {
+            if shouldAutomaticallyCancel {
+                return await withTaskCancellationHandler {
+                    await task.value
+                } onCancel: {
+                    self.cancel()
+                }
+            } else {
+                return await task.value
+            }
+        }
+    }
+
+    /// `Result` of any response serialization performed for the `response`.
+    public var result: Result<Value, AFError> {
+        get async { await response.result }
+    }
+
+    /// `Value` returned by the `response`.
+    public var value: Value {
+        get async throws {
+            try await result.get()
+        }
+    }
+
+    private let request: DataRequest
+    private let task: Task<DataResponse<Value, AFError>, Never>
+    private let shouldAutomaticallyCancel: Bool
+
+    fileprivate init(request: DataRequest, task: Task<DataResponse<Value, AFError>, Never>, shouldAutomaticallyCancel: Bool) {
+        self.request = request
+        self.task = task
+        self.shouldAutomaticallyCancel = shouldAutomaticallyCancel
+    }
+
+    /// Cancel the underlying `DataRequest` and `Task`.
+    public func cancel() {
+        task.cancel()
+    }
+
+    /// Resume the underlying `DataRequest`.
+    public func resume() {
+        request.resume()
+    }
+
+    /// Suspend the underlying `DataRequest`.
+    public func suspend() {
+        request.suspend()
+    }
+}
+
+@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
+extension DataRequest {
+    /// Creates a `DataTask` to `await` a `Data` value.
+    ///
+    /// - Parameters:
+    ///   - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the
+    ///                                enclosing async context is cancelled. Only applies to `DataTask`'s async
+    ///                                properties. `false` by default.
+    ///   - dataPreprocessor:          `DataPreprocessor` which processes the received `Data` before completion.
+    ///   - emptyResponseCodes:        HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
+    ///   - emptyRequestMethods:       `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
+    ///
+    /// - Returns: The `DataTask`.
+    public func serializingData(automaticallyCancelling shouldAutomaticallyCancel: Bool = false,
+                                dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
+                                emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
+                                emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods) -> DataTask<Data> {
+        serializingResponse(using: DataResponseSerializer(dataPreprocessor: dataPreprocessor,
+                                                          emptyResponseCodes: emptyResponseCodes,
+                                                          emptyRequestMethods: emptyRequestMethods),
+                            automaticallyCancelling: shouldAutomaticallyCancel)
+    }
+
+    /// Creates a `DataTask` to `await` serialization of a `Decodable` value.
+    ///
+    /// - Parameters:
+    ///   - type:                      `Decodable` type to decode from response data.
+    ///   - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the
+    ///                                enclosing async context is cancelled. Only applies to `DataTask`'s async
+    ///                                properties. `false` by default.
+    ///   - dataPreprocessor:          `DataPreprocessor` which processes the received `Data` before calling the serializer.
+    ///                                `PassthroughPreprocessor()` by default.
+    ///   - decoder:                   `DataDecoder` to use to decode the response. `JSONDecoder()` by default.
+    ///   - emptyResponseCodes:        HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
+    ///   - emptyRequestMethods:       `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
+    ///
+    /// - Returns: The `DataTask`.
+    public func serializingDecodable<Value: Decodable>(_ type: Value.Type = Value.self,
+                                                       automaticallyCancelling shouldAutomaticallyCancel: Bool = false,
+                                                       dataPreprocessor: DataPreprocessor = DecodableResponseSerializer<Value>.defaultDataPreprocessor,
+                                                       decoder: DataDecoder = JSONDecoder(),
+                                                       emptyResponseCodes: Set<Int> = DecodableResponseSerializer<Value>.defaultEmptyResponseCodes,
+                                                       emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer<Value>.defaultEmptyRequestMethods) -> DataTask<Value> {
+        serializingResponse(using: DecodableResponseSerializer<Value>(dataPreprocessor: dataPreprocessor,
+                                                                      decoder: decoder,
+                                                                      emptyResponseCodes: emptyResponseCodes,
+                                                                      emptyRequestMethods: emptyRequestMethods),
+                            automaticallyCancelling: shouldAutomaticallyCancel)
+    }
+
+    /// Creates a `DataTask` to `await` serialization of a `String` value.
+    ///
+    /// - Parameters:
+    ///   - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the
+    ///                                enclosing async context is cancelled. Only applies to `DataTask`'s async
+    ///                                properties. `false` by default.
+    ///   - dataPreprocessor:          `DataPreprocessor` which processes the received `Data` before calling the serializer.
+    ///                                `PassthroughPreprocessor()` by default.
+    ///   - encoding:                  `String.Encoding` to use during serialization. Defaults to `nil`, in which case
+    ///                                the encoding will be determined from the server response, falling back to the
+    ///                                default HTTP character set, `ISO-8859-1`.
+    ///   - emptyResponseCodes:        HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
+    ///   - emptyRequestMethods:       `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
+    ///
+    /// - Returns: The `DataTask`.
+    public func serializingString(automaticallyCancelling shouldAutomaticallyCancel: Bool = false,
+                                  dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
+                                  encoding: String.Encoding? = nil,
+                                  emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
+                                  emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods) -> DataTask<String> {
+        serializingResponse(using: StringResponseSerializer(dataPreprocessor: dataPreprocessor,
+                                                            encoding: encoding,
+                                                            emptyResponseCodes: emptyResponseCodes,
+                                                            emptyRequestMethods: emptyRequestMethods),
+                            automaticallyCancelling: shouldAutomaticallyCancel)
+    }
+
+    /// Creates a `DataTask` to `await` serialization using the provided `ResponseSerializer` instance.
+    ///
+    /// - Parameters:
+    ///   - serializer:                `ResponseSerializer` responsible for serializing the request, response, and data.
+    ///   - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the
+    ///                                enclosing async context is cancelled. Only applies to `DataTask`'s async
+    ///                                properties. `false` by default.
+    ///
+    /// - Returns: The `DataTask`.
+    public func serializingResponse<Serializer: ResponseSerializer>(using serializer: Serializer,
+                                                                    automaticallyCancelling shouldAutomaticallyCancel: Bool = false)
+        -> DataTask<Serializer.SerializedObject> {
+        dataTask(automaticallyCancelling: shouldAutomaticallyCancel) {
+            self.response(queue: .singleEventQueue,
+                          responseSerializer: serializer,
+                          completionHandler: $0)
+        }
+    }
+
+    /// Creates a `DataTask` to `await` serialization using the provided `DataResponseSerializerProtocol` instance.
+    ///
+    /// - Parameters:
+    ///   - serializer:                `DataResponseSerializerProtocol` responsible for serializing the request,
+    ///                                response, and data.
+    ///   - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the
+    ///                                enclosing async context is cancelled. Only applies to `DataTask`'s async
+    ///                                properties. `false` by default.
+    ///
+    /// - Returns: The `DataTask`.
+    public func serializingResponse<Serializer: DataResponseSerializerProtocol>(using serializer: Serializer,
+                                                                                automaticallyCancelling shouldAutomaticallyCancel: Bool = false)
+        -> DataTask<Serializer.SerializedObject> {
+        dataTask(automaticallyCancelling: shouldAutomaticallyCancel) {
+            self.response(queue: .singleEventQueue,
+                          responseSerializer: serializer,
+                          completionHandler: $0)
+        }
+    }
+
+    private func dataTask<Value>(automaticallyCancelling shouldAutomaticallyCancel: Bool,
+                                 forResponse onResponse: @escaping (@escaping (DataResponse<Value, AFError>) -> Void) -> Void)
+        -> DataTask<Value> {
+        let task = Task {
+            await withTaskCancellationHandler {
+                await withCheckedContinuation { continuation in
+                    onResponse {
+                        continuation.resume(returning: $0)
+                    }
+                }
+            } onCancel: {
+                self.cancel()
+            }
+        }
+
+        return DataTask<Value>(request: self, task: task, shouldAutomaticallyCancel: shouldAutomaticallyCancel)
+    }
+}
+
+// MARK: - DownloadTask
+
+/// Value used to `await` a `DownloadResponse` and associated values.
+@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
+public struct DownloadTask<Value> {
+    /// `DownloadResponse` produced by the `DownloadRequest` and its response handler.
+    public var response: DownloadResponse<Value, AFError> {
+        get async {
+            if shouldAutomaticallyCancel {
+                return await withTaskCancellationHandler {
+                    await task.value
+                } onCancel: {
+                    self.cancel()
+                }
+            } else {
+                return await task.value
+            }
+        }
+    }
+
+    /// `Result` of any response serialization performed for the `response`.
+    public var result: Result<Value, AFError> {
+        get async { await response.result }
+    }
+
+    /// `Value` returned by the `response`.
+    public var value: Value {
+        get async throws {
+            try await result.get()
+        }
+    }
+
+    private let task: Task<AFDownloadResponse<Value>, Never>
+    private let request: DownloadRequest
+    private let shouldAutomaticallyCancel: Bool
+
+    fileprivate init(request: DownloadRequest, task: Task<AFDownloadResponse<Value>, Never>, shouldAutomaticallyCancel: Bool) {
+        self.request = request
+        self.task = task
+        self.shouldAutomaticallyCancel = shouldAutomaticallyCancel
+    }
+
+    /// Cancel the underlying `DownloadRequest` and `Task`.
+    public func cancel() {
+        task.cancel()
+    }
+
+    /// Resume the underlying `DownloadRequest`.
+    public func resume() {
+        request.resume()
+    }
+
+    /// Suspend the underlying `DownloadRequest`.
+    public func suspend() {
+        request.suspend()
+    }
+}
+
+@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
+extension DownloadRequest {
+    /// Creates a `DownloadTask` to `await` a `Data` value.
+    ///
+    /// - Parameters:
+    ///   - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the
+    ///                                enclosing async context is cancelled. Only applies to `DownloadTask`'s async
+    ///                                properties. `false` by default.
+    ///   - dataPreprocessor:          `DataPreprocessor` which processes the received `Data` before completion.
+    ///   - emptyResponseCodes:        HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
+    ///   - emptyRequestMethods:       `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
+    ///
+    /// - Returns:                   The `DownloadTask`.
+    public func serializingData(automaticallyCancelling shouldAutomaticallyCancel: Bool = false,
+                                dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
+                                emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
+                                emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods) -> DownloadTask<Data> {
+        serializingDownload(using: DataResponseSerializer(dataPreprocessor: dataPreprocessor,
+                                                          emptyResponseCodes: emptyResponseCodes,
+                                                          emptyRequestMethods: emptyRequestMethods),
+                            automaticallyCancelling: shouldAutomaticallyCancel)
+    }
+
+    /// Creates a `DownloadTask` to `await` serialization of a `Decodable` value.
+    ///
+    /// - Note: This serializer reads the entire response into memory before parsing.
+    ///
+    /// - Parameters:
+    ///   - type:                      `Decodable` type to decode from response data.
+    ///   - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the
+    ///                                enclosing async context is cancelled. Only applies to `DownloadTask`'s async
+    ///                                properties. `false` by default.
+    ///   - dataPreprocessor:          `DataPreprocessor` which processes the received `Data` before calling the serializer.
+    ///                                `PassthroughPreprocessor()` by default.
+    ///   - decoder:                   `DataDecoder` to use to decode the response. `JSONDecoder()` by default.
+    ///   - emptyResponseCodes:        HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
+    ///   - emptyRequestMethods:       `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
+    ///
+    /// - Returns:                   The `DownloadTask`.
+    public func serializingDecodable<Value: Decodable>(_ type: Value.Type = Value.self,
+                                                       automaticallyCancelling shouldAutomaticallyCancel: Bool = false,
+                                                       dataPreprocessor: DataPreprocessor = DecodableResponseSerializer<Value>.defaultDataPreprocessor,
+                                                       decoder: DataDecoder = JSONDecoder(),
+                                                       emptyResponseCodes: Set<Int> = DecodableResponseSerializer<Value>.defaultEmptyResponseCodes,
+                                                       emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer<Value>.defaultEmptyRequestMethods) -> DownloadTask<Value> {
+        serializingDownload(using: DecodableResponseSerializer<Value>(dataPreprocessor: dataPreprocessor,
+                                                                      decoder: decoder,
+                                                                      emptyResponseCodes: emptyResponseCodes,
+                                                                      emptyRequestMethods: emptyRequestMethods),
+                            automaticallyCancelling: shouldAutomaticallyCancel)
+    }
+
+    /// Creates a `DownloadTask` to `await` serialization of the downloaded file's `URL` on disk.
+    ///
+    /// - Parameters:
+    ///   - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the
+    ///                                enclosing async context is cancelled. Only applies to `DownloadTask`'s async
+    ///                                properties. `false` by default.
+    ///
+    /// - Returns: The `DownloadTask`.
+    public func serializingDownloadedFileURL(automaticallyCancelling shouldAutomaticallyCancel: Bool = false) -> DownloadTask<URL> {
+        serializingDownload(using: URLResponseSerializer(),
+                            automaticallyCancelling: shouldAutomaticallyCancel)
+    }
+
+    /// Creates a `DownloadTask` to `await` serialization of a `String` value.
+    ///
+    /// - Parameters:
+    ///   - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the
+    ///                                enclosing async context is cancelled. Only applies to `DownloadTask`'s async
+    ///                                properties. `false` by default.
+    ///   - dataPreprocessor:          `DataPreprocessor` which processes the received `Data` before calling the
+    ///                                serializer. `PassthroughPreprocessor()` by default.
+    ///   - encoding:                  `String.Encoding` to use during serialization. Defaults to `nil`, in which case
+    ///                                the encoding will be determined from the server response, falling back to the
+    ///                                default HTTP character set, `ISO-8859-1`.
+    ///   - emptyResponseCodes:        HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
+    ///   - emptyRequestMethods:       `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
+    ///
+    /// - Returns:                   The `DownloadTask`.
+    public func serializingString(automaticallyCancelling shouldAutomaticallyCancel: Bool = false,
+                                  dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
+                                  encoding: String.Encoding? = nil,
+                                  emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
+                                  emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods) -> DownloadTask<String> {
+        serializingDownload(using: StringResponseSerializer(dataPreprocessor: dataPreprocessor,
+                                                            encoding: encoding,
+                                                            emptyResponseCodes: emptyResponseCodes,
+                                                            emptyRequestMethods: emptyRequestMethods),
+                            automaticallyCancelling: shouldAutomaticallyCancel)
+    }
+
+    /// Creates a `DownloadTask` to `await` serialization using the provided `ResponseSerializer` instance.
+    ///
+    /// - Parameters:
+    ///   - serializer:                `ResponseSerializer` responsible for serializing the request, response, and data.
+    ///   - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the
+    ///                                enclosing async context is cancelled. Only applies to `DownloadTask`'s async
+    ///                                properties. `false` by default.
+    ///
+    /// - Returns: The `DownloadTask`.
+    public func serializingDownload<Serializer: ResponseSerializer>(using serializer: Serializer,
+                                                                    automaticallyCancelling shouldAutomaticallyCancel: Bool = false)
+        -> DownloadTask<Serializer.SerializedObject> {
+        downloadTask(automaticallyCancelling: shouldAutomaticallyCancel) {
+            self.response(queue: .singleEventQueue,
+                          responseSerializer: serializer,
+                          completionHandler: $0)
+        }
+    }
+
+    /// Creates a `DownloadTask` to `await` serialization using the provided `DownloadResponseSerializerProtocol`
+    /// instance.
+    ///
+    /// - Parameters:
+    ///   - serializer:                `DownloadResponseSerializerProtocol` responsible for serializing the request,
+    ///                                response, and data.
+    ///   - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the
+    ///                                enclosing async context is cancelled. Only applies to `DownloadTask`'s async
+    ///                                properties. `false` by default.
+    ///
+    /// - Returns: The `DownloadTask`.
+    public func serializingDownload<Serializer: DownloadResponseSerializerProtocol>(using serializer: Serializer,
+                                                                                    automaticallyCancelling shouldAutomaticallyCancel: Bool = false)
+        -> DownloadTask<Serializer.SerializedObject> {
+        downloadTask(automaticallyCancelling: shouldAutomaticallyCancel) {
+            self.response(queue: .singleEventQueue,
+                          responseSerializer: serializer,
+                          completionHandler: $0)
+        }
+    }
+
+    private func downloadTask<Value>(automaticallyCancelling shouldAutomaticallyCancel: Bool,
+                                     forResponse onResponse: @escaping (@escaping (DownloadResponse<Value, AFError>) -> Void) -> Void)
+        -> DownloadTask<Value> {
+        let task = Task {
+            await withTaskCancellationHandler {
+                await withCheckedContinuation { continuation in
+                    onResponse {
+                        continuation.resume(returning: $0)
+                    }
+                }
+            } onCancel: {
+                self.cancel()
+            }
+        }
+
+        return DownloadTask<Value>(request: self, task: task, shouldAutomaticallyCancel: shouldAutomaticallyCancel)
+    }
+}
+
+// MARK: - DataStreamTask
+
+@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
+public struct DataStreamTask {
+    // Type of created streams.
+    public typealias Stream<Success, Failure: Error> = StreamOf<DataStreamRequest.Stream<Success, Failure>>
+
+    private let request: DataStreamRequest
+
+    fileprivate init(request: DataStreamRequest) {
+        self.request = request
+    }
+
+    /// Creates a `Stream` of `Data` values from the underlying `DataStreamRequest`.
+    ///
+    /// - Parameters:
+    ///   - shouldAutomaticallyCancel: `Bool` indicating whether the underlying `DataStreamRequest` should be canceled
+    ///                                which observation of the stream stops. `true` by default.
+    ///   - bufferingPolicy: `         BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default.
+    ///
+    /// - Returns:                   The `Stream`.
+    public func streamingData(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, bufferingPolicy: Stream<Data, Never>.BufferingPolicy = .unbounded) -> Stream<Data, Never> {
+        createStream(automaticallyCancelling: shouldAutomaticallyCancel, bufferingPolicy: bufferingPolicy) { onStream in
+            self.request.responseStream(on: .streamCompletionQueue(forRequestID: request.id), stream: onStream)
+        }
+    }
+
+    /// Creates a `Stream` of `UTF-8` `String`s from the underlying `DataStreamRequest`.
+    ///
+    /// - Parameters:
+    ///   - shouldAutomaticallyCancel: `Bool` indicating whether the underlying `DataStreamRequest` should be canceled
+    ///                                which observation of the stream stops. `true` by default.
+    ///   - bufferingPolicy: `         BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default.
+    /// - Returns:
+    public func streamingStrings(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, bufferingPolicy: Stream<String, Never>.BufferingPolicy = .unbounded) -> Stream<String, Never> {
+        createStream(automaticallyCancelling: shouldAutomaticallyCancel, bufferingPolicy: bufferingPolicy) { onStream in
+            self.request.responseStreamString(on: .streamCompletionQueue(forRequestID: request.id), stream: onStream)
+        }
+    }
+
+    /// Creates a `Stream` of `Decodable` values from the underlying `DataStreamRequest`.
+    ///
+    /// - Parameters:
+    ///   - type:                      `Decodable` type to be serialized from stream payloads.
+    ///   - shouldAutomaticallyCancel: `Bool` indicating whether the underlying `DataStreamRequest` should be canceled
+    ///                                which observation of the stream stops. `true` by default.
+    ///   - bufferingPolicy:           `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default.
+    ///
+    /// - Returns:            The `Stream`.
+    public func streamingDecodables<T>(_ type: T.Type = T.self,
+                                       automaticallyCancelling shouldAutomaticallyCancel: Bool = true,
+                                       bufferingPolicy: Stream<T, AFError>.BufferingPolicy = .unbounded)
+        -> Stream<T, AFError> where T: Decodable {
+        streamingResponses(serializedUsing: DecodableStreamSerializer<T>(),
+                           automaticallyCancelling: shouldAutomaticallyCancel,
+                           bufferingPolicy: bufferingPolicy)
+    }
+
+    /// Creates a `Stream` of values using the provided `DataStreamSerializer` from the underlying `DataStreamRequest`.
+    ///
+    /// - Parameters:
+    ///   - serializer:                `DataStreamSerializer` to use to serialize incoming `Data`.
+    ///   - shouldAutomaticallyCancel: `Bool` indicating whether the underlying `DataStreamRequest` should be canceled
+    ///                                which observation of the stream stops. `true` by default.
+    ///   - bufferingPolicy:           `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default.
+    ///
+    /// - Returns:           The `Stream`.
+    public func streamingResponses<Serializer: DataStreamSerializer>(serializedUsing serializer: Serializer,
+                                                                     automaticallyCancelling shouldAutomaticallyCancel: Bool = true,
+                                                                     bufferingPolicy: Stream<Serializer.SerializedObject, AFError>.BufferingPolicy = .unbounded)
+        -> Stream<Serializer.SerializedObject, AFError> {
+        createStream(automaticallyCancelling: shouldAutomaticallyCancel, bufferingPolicy: bufferingPolicy) { onStream in
+            self.request.responseStream(using: serializer,
+                                        on: .streamCompletionQueue(forRequestID: request.id),
+                                        stream: onStream)
+        }
+    }
+
+    private func createStream<Success, Failure: Error>(automaticallyCancelling shouldAutomaticallyCancel: Bool = true,
+                                                       bufferingPolicy: Stream<Success, Failure>.BufferingPolicy = .unbounded,
+                                                       forResponse onResponse: @escaping (@escaping (DataStreamRequest.Stream<Success, Failure>) -> Void) -> Void)
+        -> Stream<Success, Failure> {
+        StreamOf(bufferingPolicy: bufferingPolicy) {
+            guard shouldAutomaticallyCancel,
+                  request.isInitialized || request.isResumed || request.isSuspended else { return }
+
+            cancel()
+        } builder: { continuation in
+            onResponse { stream in
+                continuation.yield(stream)
+                if case .complete = stream.event {
+                    continuation.finish()
+                }
+            }
+        }
+    }
+
+    /// Cancel the underlying `DataStreamRequest`.
+    public func cancel() {
+        request.cancel()
+    }
+
+    /// Resume the underlying `DataStreamRequest`.
+    public func resume() {
+        request.resume()
+    }
+
+    /// Suspend the underlying `DataStreamRequest`.
+    public func suspend() {
+        request.suspend()
+    }
+}
+
+@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
+extension DataStreamRequest {
+    /// Creates a `DataStreamTask` used to `await` streams of serialized values.
+    ///
+    /// - Returns: The `DataStreamTask`.
+    public func streamTask() -> DataStreamTask {
+        DataStreamTask(request: self)
+    }
+}
+
+extension DispatchQueue {
+    fileprivate static let singleEventQueue = DispatchQueue(label: "org.alamofire.concurrencySingleEventQueue",
+                                                            attributes: .concurrent)
+
+    fileprivate static func streamCompletionQueue(forRequestID id: UUID) -> DispatchQueue {
+        DispatchQueue(label: "org.alamofire.concurrencyStreamCompletionQueue-\(id)", target: .singleEventQueue)
+    }
+}
+
+/// An asynchronous sequence generated from an underlying `AsyncStream`. Only produced by Alamofire.
+@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
+public struct StreamOf<Element>: AsyncSequence {
+    public typealias AsyncIterator = Iterator
+    public typealias BufferingPolicy = AsyncStream<Element>.Continuation.BufferingPolicy
+    fileprivate typealias Continuation = AsyncStream<Element>.Continuation
+
+    private let bufferingPolicy: BufferingPolicy
+    private let onTermination: (() -> Void)?
+    private let builder: (Continuation) -> Void
+
+    fileprivate init(bufferingPolicy: BufferingPolicy = .unbounded,
+                     onTermination: (() -> Void)? = nil,
+                     builder: @escaping (Continuation) -> Void) {
+        self.bufferingPolicy = bufferingPolicy
+        self.onTermination = onTermination
+        self.builder = builder
+    }
+
+    public func makeAsyncIterator() -> Iterator {
+        var continuation: AsyncStream<Element>.Continuation?
+        let stream = AsyncStream<Element> { innerContinuation in
+            continuation = innerContinuation
+            builder(innerContinuation)
+        }
+
+        return Iterator(iterator: stream.makeAsyncIterator()) {
+            continuation?.finish()
+            self.onTermination?()
+        }
+    }
+
+    public struct Iterator: AsyncIteratorProtocol {
+        private final class Token {
+            private let onDeinit: () -> Void
+
+            init(onDeinit: @escaping () -> Void) {
+                self.onDeinit = onDeinit
+            }
+
+            deinit {
+                onDeinit()
+            }
+        }
+
+        private var iterator: AsyncStream<Element>.AsyncIterator
+        private let token: Token
+
+        init(iterator: AsyncStream<Element>.AsyncIterator, onCancellation: @escaping () -> Void) {
+            self.iterator = iterator
+            token = Token(onDeinit: onCancellation)
+        }
+
+        public mutating func next() async -> Element? {
+            await iterator.next()
+        }
+    }
+}
+
+#endif

+ 37 - 0
Pods/Alamofire/Source/DispatchQueue+Alamofire.swift

@@ -0,0 +1,37 @@
+//
+//  DispatchQueue+Alamofire.swift
+//
+//  Copyright (c) 2014-2018 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 Dispatch
+import Foundation
+
+extension DispatchQueue {
+    /// Execute the provided closure after a `TimeInterval`.
+    ///
+    /// - Parameters:
+    ///   - delay:   `TimeInterval` to delay execution.
+    ///   - closure: Closure to execute.
+    func after(_ delay: TimeInterval, execute closure: @escaping () -> Void) {
+        asyncAfter(deadline: .now() + delay, execute: closure)
+    }
+}

+ 892 - 0
Pods/Alamofire/Source/EventMonitor.swift

@@ -0,0 +1,892 @@
+//
+//  EventMonitor.swift
+//
+//  Copyright (c) 2014-2018 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
+
+/// Protocol outlining the lifetime events inside Alamofire. It includes both events received from the various
+/// `URLSession` delegate protocols as well as various events from the lifetime of `Request` and its subclasses.
+public protocol EventMonitor {
+    /// The `DispatchQueue` onto which Alamofire's root `CompositeEventMonitor` will dispatch events. `.main` by default.
+    var queue: DispatchQueue { get }
+
+    // MARK: - URLSession Events
+
+    // MARK: URLSessionDelegate Events
+
+    /// Event called during `URLSessionDelegate`'s `urlSession(_:didBecomeInvalidWithError:)` method.
+    func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?)
+
+    // MARK: URLSessionTaskDelegate Events
+
+    /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didReceive:completionHandler:)` method.
+    func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge)
+
+    /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)` method.
+    func urlSession(_ session: URLSession,
+                    task: URLSessionTask,
+                    didSendBodyData bytesSent: Int64,
+                    totalBytesSent: Int64,
+                    totalBytesExpectedToSend: Int64)
+
+    /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:needNewBodyStream:)` method.
+    func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask)
+
+    /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` method.
+    func urlSession(_ session: URLSession,
+                    task: URLSessionTask,
+                    willPerformHTTPRedirection response: HTTPURLResponse,
+                    newRequest request: URLRequest)
+
+    /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didFinishCollecting:)` method.
+    func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics)
+
+    /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didCompleteWithError:)` method.
+    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
+
+    /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:taskIsWaitingForConnectivity:)` method.
+    @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
+    func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask)
+
+    // MARK: URLSessionDataDelegate Events
+
+    /// Event called during `URLSessionDataDelegate`'s `urlSession(_:dataTask:didReceive:)` method.
+    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data)
+
+    /// Event called during `URLSessionDataDelegate`'s `urlSession(_:dataTask:willCacheResponse:completionHandler:)` method.
+    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse)
+
+    // MARK: URLSessionDownloadDelegate Events
+
+    /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)` method.
+    func urlSession(_ session: URLSession,
+                    downloadTask: URLSessionDownloadTask,
+                    didResumeAtOffset fileOffset: Int64,
+                    expectedTotalBytes: Int64)
+
+    /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)` method.
+    func urlSession(_ session: URLSession,
+                    downloadTask: URLSessionDownloadTask,
+                    didWriteData bytesWritten: Int64,
+                    totalBytesWritten: Int64,
+                    totalBytesExpectedToWrite: Int64)
+
+    /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didFinishDownloadingTo:)` method.
+    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)
+
+    // MARK: - Request Events
+
+    /// Event called when a `URLRequest` is first created for a `Request`. If a `RequestAdapter` is active, the
+    /// `URLRequest` will be adapted before being issued.
+    func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest)
+
+    /// Event called when the attempt to create a `URLRequest` from a `Request`'s original `URLRequestConvertible` value fails.
+    func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError)
+
+    /// Event called when a `RequestAdapter` adapts the `Request`'s initial `URLRequest`.
+    func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest)
+
+    /// Event called when a `RequestAdapter` fails to adapt the `Request`'s initial `URLRequest`.
+    func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError)
+
+    /// Event called when a final `URLRequest` is created for a `Request`.
+    func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest)
+
+    /// Event called when a `URLSessionTask` subclass instance is created for a `Request`.
+    func request(_ request: Request, didCreateTask task: URLSessionTask)
+
+    /// Event called when a `Request` receives a `URLSessionTaskMetrics` value.
+    func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics)
+
+    /// Event called when a `Request` fails due to an error created by Alamofire. e.g. When certificate pinning fails.
+    func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError)
+
+    /// Event called when a `Request`'s task completes, possibly with an error. A `Request` may receive this event
+    /// multiple times if it is retried.
+    func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?)
+
+    /// Event called when a `Request` is about to be retried.
+    func requestIsRetrying(_ request: Request)
+
+    /// Event called when a `Request` finishes and response serializers are being called.
+    func requestDidFinish(_ request: Request)
+
+    /// Event called when a `Request` receives a `resume` call.
+    func requestDidResume(_ request: Request)
+
+    /// Event called when a `Request`'s associated `URLSessionTask` is resumed.
+    func request(_ request: Request, didResumeTask task: URLSessionTask)
+
+    /// Event called when a `Request` receives a `suspend` call.
+    func requestDidSuspend(_ request: Request)
+
+    /// Event called when a `Request`'s associated `URLSessionTask` is suspended.
+    func request(_ request: Request, didSuspendTask task: URLSessionTask)
+
+    /// Event called when a `Request` receives a `cancel` call.
+    func requestDidCancel(_ request: Request)
+
+    /// Event called when a `Request`'s associated `URLSessionTask` is cancelled.
+    func request(_ request: Request, didCancelTask task: URLSessionTask)
+
+    // MARK: DataRequest Events
+
+    /// Event called when a `DataRequest` calls a `Validation`.
+    func request(_ request: DataRequest,
+                 didValidateRequest urlRequest: URLRequest?,
+                 response: HTTPURLResponse,
+                 data: Data?,
+                 withResult result: Request.ValidationResult)
+
+    /// Event called when a `DataRequest` creates a `DataResponse<Data?>` value without calling a `ResponseSerializer`.
+    func request(_ request: DataRequest, didParseResponse response: DataResponse<Data?, AFError>)
+
+    /// Event called when a `DataRequest` calls a `ResponseSerializer` and creates a generic `DataResponse<Value, AFError>`.
+    func request<Value>(_ request: DataRequest, didParseResponse response: DataResponse<Value, AFError>)
+
+    // MARK: DataStreamRequest Events
+
+    /// Event called when a `DataStreamRequest` calls a `Validation` closure.
+    ///
+    /// - Parameters:
+    ///   - request:    `DataStreamRequest` which is calling the `Validation`.
+    ///   - urlRequest: `URLRequest` of the request being validated.
+    ///   - response:   `HTTPURLResponse` of the request being validated.
+    ///   - result:      Produced `ValidationResult`.
+    func request(_ request: DataStreamRequest,
+                 didValidateRequest urlRequest: URLRequest?,
+                 response: HTTPURLResponse,
+                 withResult result: Request.ValidationResult)
+
+    /// Event called when a `DataStreamSerializer` produces a value from streamed `Data`.
+    ///
+    /// - Parameters:
+    ///   - request: `DataStreamRequest` for which the value was serialized.
+    ///   - result:  `Result` of the serialization attempt.
+    func request<Value>(_ request: DataStreamRequest, didParseStream result: Result<Value, AFError>)
+
+    // MARK: UploadRequest Events
+
+    /// Event called when an `UploadRequest` creates its `Uploadable` value, indicating the type of upload it represents.
+    func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable)
+
+    /// Event called when an `UploadRequest` failed to create its `Uploadable` value due to an error.
+    func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError)
+
+    /// Event called when an `UploadRequest` provides the `InputStream` from its `Uploadable` value. This only occurs if
+    /// the `InputStream` does not wrap a `Data` value or file `URL`.
+    func request(_ request: UploadRequest, didProvideInputStream stream: InputStream)
+
+    // MARK: DownloadRequest Events
+
+    /// Event called when a `DownloadRequest`'s `URLSessionDownloadTask` finishes and the temporary file has been moved.
+    func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result<URL, AFError>)
+
+    /// Event called when a `DownloadRequest`'s `Destination` closure is called and creates the destination URL the
+    /// downloaded file will be moved to.
+    func request(_ request: DownloadRequest, didCreateDestinationURL url: URL)
+
+    /// Event called when a `DownloadRequest` calls a `Validation`.
+    func request(_ request: DownloadRequest,
+                 didValidateRequest urlRequest: URLRequest?,
+                 response: HTTPURLResponse,
+                 fileURL: URL?,
+                 withResult result: Request.ValidationResult)
+
+    /// Event called when a `DownloadRequest` creates a `DownloadResponse<URL?, AFError>` without calling a `ResponseSerializer`.
+    func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse<URL?, AFError>)
+
+    /// Event called when a `DownloadRequest` calls a `DownloadResponseSerializer` and creates a generic `DownloadResponse<Value, AFError>`
+    func request<Value>(_ request: DownloadRequest, didParseResponse response: DownloadResponse<Value, AFError>)
+}
+
+extension EventMonitor {
+    /// The default queue on which `CompositeEventMonitor`s will call the `EventMonitor` methods. `.main` by default.
+    public var queue: DispatchQueue { .main }
+
+    // MARK: Default Implementations
+
+    public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {}
+    public func urlSession(_ session: URLSession,
+                           task: URLSessionTask,
+                           didReceive challenge: URLAuthenticationChallenge) {}
+    public func urlSession(_ session: URLSession,
+                           task: URLSessionTask,
+                           didSendBodyData bytesSent: Int64,
+                           totalBytesSent: Int64,
+                           totalBytesExpectedToSend: Int64) {}
+    public func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) {}
+    public func urlSession(_ session: URLSession,
+                           task: URLSessionTask,
+                           willPerformHTTPRedirection response: HTTPURLResponse,
+                           newRequest request: URLRequest) {}
+    public func urlSession(_ session: URLSession,
+                           task: URLSessionTask,
+                           didFinishCollecting metrics: URLSessionTaskMetrics) {}
+    public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {}
+    public func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {}
+    public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {}
+    public func urlSession(_ session: URLSession,
+                           dataTask: URLSessionDataTask,
+                           willCacheResponse proposedResponse: CachedURLResponse) {}
+    public func urlSession(_ session: URLSession,
+                           downloadTask: URLSessionDownloadTask,
+                           didResumeAtOffset fileOffset: Int64,
+                           expectedTotalBytes: Int64) {}
+    public func urlSession(_ session: URLSession,
+                           downloadTask: URLSessionDownloadTask,
+                           didWriteData bytesWritten: Int64,
+                           totalBytesWritten: Int64,
+                           totalBytesExpectedToWrite: Int64) {}
+    public func urlSession(_ session: URLSession,
+                           downloadTask: URLSessionDownloadTask,
+                           didFinishDownloadingTo location: URL) {}
+    public func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) {}
+    public func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) {}
+    public func request(_ request: Request,
+                        didAdaptInitialRequest initialRequest: URLRequest,
+                        to adaptedRequest: URLRequest) {}
+    public func request(_ request: Request,
+                        didFailToAdaptURLRequest initialRequest: URLRequest,
+                        withError error: AFError) {}
+    public func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) {}
+    public func request(_ request: Request, didCreateTask task: URLSessionTask) {}
+    public func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) {}
+    public func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) {}
+    public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) {}
+    public func requestIsRetrying(_ request: Request) {}
+    public func requestDidFinish(_ request: Request) {}
+    public func requestDidResume(_ request: Request) {}
+    public func request(_ request: Request, didResumeTask task: URLSessionTask) {}
+    public func requestDidSuspend(_ request: Request) {}
+    public func request(_ request: Request, didSuspendTask task: URLSessionTask) {}
+    public func requestDidCancel(_ request: Request) {}
+    public func request(_ request: Request, didCancelTask task: URLSessionTask) {}
+    public func request(_ request: DataRequest,
+                        didValidateRequest urlRequest: URLRequest?,
+                        response: HTTPURLResponse,
+                        data: Data?,
+                        withResult result: Request.ValidationResult) {}
+    public func request(_ request: DataRequest, didParseResponse response: DataResponse<Data?, AFError>) {}
+    public func request<Value>(_ request: DataRequest, didParseResponse response: DataResponse<Value, AFError>) {}
+    public func request(_ request: DataStreamRequest,
+                        didValidateRequest urlRequest: URLRequest?,
+                        response: HTTPURLResponse,
+                        withResult result: Request.ValidationResult) {}
+    public func request<Value>(_ request: DataStreamRequest, didParseStream result: Result<Value, AFError>) {}
+    public func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) {}
+    public func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) {}
+    public func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) {}
+    public func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result<URL, AFError>) {}
+    public func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) {}
+    public func request(_ request: DownloadRequest,
+                        didValidateRequest urlRequest: URLRequest?,
+                        response: HTTPURLResponse,
+                        fileURL: URL?,
+                        withResult result: Request.ValidationResult) {}
+    public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse<URL?, AFError>) {}
+    public func request<Value>(_ request: DownloadRequest, didParseResponse response: DownloadResponse<Value, AFError>) {}
+}
+
+/// An `EventMonitor` which can contain multiple `EventMonitor`s and calls their methods on their queues.
+public final class CompositeEventMonitor: EventMonitor {
+    public let queue = DispatchQueue(label: "org.alamofire.compositeEventMonitor", qos: .utility)
+
+    let monitors: [EventMonitor]
+
+    init(monitors: [EventMonitor]) {
+        self.monitors = monitors
+    }
+
+    func performEvent(_ event: @escaping (EventMonitor) -> Void) {
+        queue.async {
+            for monitor in self.monitors {
+                monitor.queue.async { event(monitor) }
+            }
+        }
+    }
+
+    public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
+        performEvent { $0.urlSession(session, didBecomeInvalidWithError: error) }
+    }
+
+    public func urlSession(_ session: URLSession,
+                           task: URLSessionTask,
+                           didReceive challenge: URLAuthenticationChallenge) {
+        performEvent { $0.urlSession(session, task: task, didReceive: challenge) }
+    }
+
+    public func urlSession(_ session: URLSession,
+                           task: URLSessionTask,
+                           didSendBodyData bytesSent: Int64,
+                           totalBytesSent: Int64,
+                           totalBytesExpectedToSend: Int64) {
+        performEvent {
+            $0.urlSession(session,
+                          task: task,
+                          didSendBodyData: bytesSent,
+                          totalBytesSent: totalBytesSent,
+                          totalBytesExpectedToSend: totalBytesExpectedToSend)
+        }
+    }
+
+    public func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) {
+        performEvent {
+            $0.urlSession(session, taskNeedsNewBodyStream: task)
+        }
+    }
+
+    public func urlSession(_ session: URLSession,
+                           task: URLSessionTask,
+                           willPerformHTTPRedirection response: HTTPURLResponse,
+                           newRequest request: URLRequest) {
+        performEvent {
+            $0.urlSession(session,
+                          task: task,
+                          willPerformHTTPRedirection: response,
+                          newRequest: request)
+        }
+    }
+
+    public func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
+        performEvent { $0.urlSession(session, task: task, didFinishCollecting: metrics) }
+    }
+
+    public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
+        performEvent { $0.urlSession(session, task: task, didCompleteWithError: error) }
+    }
+
+    @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
+    public func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {
+        performEvent { $0.urlSession(session, taskIsWaitingForConnectivity: task) }
+    }
+
+    public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
+        performEvent { $0.urlSession(session, dataTask: dataTask, didReceive: data) }
+    }
+
+    public func urlSession(_ session: URLSession,
+                           dataTask: URLSessionDataTask,
+                           willCacheResponse proposedResponse: CachedURLResponse) {
+        performEvent { $0.urlSession(session, dataTask: dataTask, willCacheResponse: proposedResponse) }
+    }
+
+    public func urlSession(_ session: URLSession,
+                           downloadTask: URLSessionDownloadTask,
+                           didResumeAtOffset fileOffset: Int64,
+                           expectedTotalBytes: Int64) {
+        performEvent {
+            $0.urlSession(session,
+                          downloadTask: downloadTask,
+                          didResumeAtOffset: fileOffset,
+                          expectedTotalBytes: expectedTotalBytes)
+        }
+    }
+
+    public func urlSession(_ session: URLSession,
+                           downloadTask: URLSessionDownloadTask,
+                           didWriteData bytesWritten: Int64,
+                           totalBytesWritten: Int64,
+                           totalBytesExpectedToWrite: Int64) {
+        performEvent {
+            $0.urlSession(session,
+                          downloadTask: downloadTask,
+                          didWriteData: bytesWritten,
+                          totalBytesWritten: totalBytesWritten,
+                          totalBytesExpectedToWrite: totalBytesExpectedToWrite)
+        }
+    }
+
+    public func urlSession(_ session: URLSession,
+                           downloadTask: URLSessionDownloadTask,
+                           didFinishDownloadingTo location: URL) {
+        performEvent { $0.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) }
+    }
+
+    public func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) {
+        performEvent { $0.request(request, didCreateInitialURLRequest: urlRequest) }
+    }
+
+    public func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) {
+        performEvent { $0.request(request, didFailToCreateURLRequestWithError: error) }
+    }
+
+    public func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) {
+        performEvent { $0.request(request, didAdaptInitialRequest: initialRequest, to: adaptedRequest) }
+    }
+
+    public func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError) {
+        performEvent { $0.request(request, didFailToAdaptURLRequest: initialRequest, withError: error) }
+    }
+
+    public func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) {
+        performEvent { $0.request(request, didCreateURLRequest: urlRequest) }
+    }
+
+    public func request(_ request: Request, didCreateTask task: URLSessionTask) {
+        performEvent { $0.request(request, didCreateTask: task) }
+    }
+
+    public func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) {
+        performEvent { $0.request(request, didGatherMetrics: metrics) }
+    }
+
+    public func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) {
+        performEvent { $0.request(request, didFailTask: task, earlyWithError: error) }
+    }
+
+    public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) {
+        performEvent { $0.request(request, didCompleteTask: task, with: error) }
+    }
+
+    public func requestIsRetrying(_ request: Request) {
+        performEvent { $0.requestIsRetrying(request) }
+    }
+
+    public func requestDidFinish(_ request: Request) {
+        performEvent { $0.requestDidFinish(request) }
+    }
+
+    public func requestDidResume(_ request: Request) {
+        performEvent { $0.requestDidResume(request) }
+    }
+
+    public func request(_ request: Request, didResumeTask task: URLSessionTask) {
+        performEvent { $0.request(request, didResumeTask: task) }
+    }
+
+    public func requestDidSuspend(_ request: Request) {
+        performEvent { $0.requestDidSuspend(request) }
+    }
+
+    public func request(_ request: Request, didSuspendTask task: URLSessionTask) {
+        performEvent { $0.request(request, didSuspendTask: task) }
+    }
+
+    public func requestDidCancel(_ request: Request) {
+        performEvent { $0.requestDidCancel(request) }
+    }
+
+    public func request(_ request: Request, didCancelTask task: URLSessionTask) {
+        performEvent { $0.request(request, didCancelTask: task) }
+    }
+
+    public func request(_ request: DataRequest,
+                        didValidateRequest urlRequest: URLRequest?,
+                        response: HTTPURLResponse,
+                        data: Data?,
+                        withResult result: Request.ValidationResult) {
+        performEvent { $0.request(request,
+                                  didValidateRequest: urlRequest,
+                                  response: response,
+                                  data: data,
+                                  withResult: result)
+        }
+    }
+
+    public func request(_ request: DataRequest, didParseResponse response: DataResponse<Data?, AFError>) {
+        performEvent { $0.request(request, didParseResponse: response) }
+    }
+
+    public func request<Value>(_ request: DataRequest, didParseResponse response: DataResponse<Value, AFError>) {
+        performEvent { $0.request(request, didParseResponse: response) }
+    }
+
+    public func request(_ request: DataStreamRequest,
+                        didValidateRequest urlRequest: URLRequest?,
+                        response: HTTPURLResponse,
+                        withResult result: Request.ValidationResult) {
+        performEvent { $0.request(request,
+                                  didValidateRequest: urlRequest,
+                                  response: response,
+                                  withResult: result)
+        }
+    }
+
+    public func request<Value>(_ request: DataStreamRequest, didParseStream result: Result<Value, AFError>) {
+        performEvent { $0.request(request, didParseStream: result) }
+    }
+
+    public func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) {
+        performEvent { $0.request(request, didCreateUploadable: uploadable) }
+    }
+
+    public func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) {
+        performEvent { $0.request(request, didFailToCreateUploadableWithError: error) }
+    }
+
+    public func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) {
+        performEvent { $0.request(request, didProvideInputStream: stream) }
+    }
+
+    public func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result<URL, AFError>) {
+        performEvent { $0.request(request, didFinishDownloadingUsing: task, with: result) }
+    }
+
+    public func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) {
+        performEvent { $0.request(request, didCreateDestinationURL: url) }
+    }
+
+    public func request(_ request: DownloadRequest,
+                        didValidateRequest urlRequest: URLRequest?,
+                        response: HTTPURLResponse,
+                        fileURL: URL?,
+                        withResult result: Request.ValidationResult) {
+        performEvent { $0.request(request,
+                                  didValidateRequest: urlRequest,
+                                  response: response,
+                                  fileURL: fileURL,
+                                  withResult: result) }
+    }
+
+    public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse<URL?, AFError>) {
+        performEvent { $0.request(request, didParseResponse: response) }
+    }
+
+    public func request<Value>(_ request: DownloadRequest, didParseResponse response: DownloadResponse<Value, AFError>) {
+        performEvent { $0.request(request, didParseResponse: response) }
+    }
+}
+
+/// `EventMonitor` that allows optional closures to be set to receive events.
+open class ClosureEventMonitor: EventMonitor {
+    /// Closure called on the `urlSession(_:didBecomeInvalidWithError:)` event.
+    open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)?
+
+    /// Closure called on the `urlSession(_:task:didReceive:completionHandler:)`.
+    open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> Void)?
+
+    /// Closure that receives `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)` event.
+    open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)?
+
+    /// Closure called on the `urlSession(_:task:needNewBodyStream:)` event.
+    open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> Void)?
+
+    /// Closure called on the `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` event.
+    open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> Void)?
+
+    /// Closure called on the `urlSession(_:task:didFinishCollecting:)` event.
+    open var taskDidFinishCollectingMetrics: ((URLSession, URLSessionTask, URLSessionTaskMetrics) -> Void)?
+
+    /// Closure called on the `urlSession(_:task:didCompleteWithError:)` event.
+    open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)?
+
+    /// Closure called on the `urlSession(_:taskIsWaitingForConnectivity:)` event.
+    open var taskIsWaitingForConnectivity: ((URLSession, URLSessionTask) -> Void)?
+
+    /// Closure that receives the `urlSession(_:dataTask:didReceive:)` event.
+    open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)?
+
+    /// Closure called on the `urlSession(_:dataTask:willCacheResponse:completionHandler:)` event.
+    open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> Void)?
+
+    /// Closure called on the `urlSession(_:downloadTask:didFinishDownloadingTo:)` event.
+    open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)?
+
+    /// Closure called on the `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)`
+    /// event.
+    open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
+
+    /// Closure called on the `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)` event.
+    open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)?
+
+    // MARK: - Request Events
+
+    /// Closure called on the `request(_:didCreateInitialURLRequest:)` event.
+    open var requestDidCreateInitialURLRequest: ((Request, URLRequest) -> Void)?
+
+    /// Closure called on the `request(_:didFailToCreateURLRequestWithError:)` event.
+    open var requestDidFailToCreateURLRequestWithError: ((Request, AFError) -> Void)?
+
+    /// Closure called on the `request(_:didAdaptInitialRequest:to:)` event.
+    open var requestDidAdaptInitialRequestToAdaptedRequest: ((Request, URLRequest, URLRequest) -> Void)?
+
+    /// Closure called on the `request(_:didFailToAdaptURLRequest:withError:)` event.
+    open var requestDidFailToAdaptURLRequestWithError: ((Request, URLRequest, AFError) -> Void)?
+
+    /// Closure called on the `request(_:didCreateURLRequest:)` event.
+    open var requestDidCreateURLRequest: ((Request, URLRequest) -> Void)?
+
+    /// Closure called on the `request(_:didCreateTask:)` event.
+    open var requestDidCreateTask: ((Request, URLSessionTask) -> Void)?
+
+    /// Closure called on the `request(_:didGatherMetrics:)` event.
+    open var requestDidGatherMetrics: ((Request, URLSessionTaskMetrics) -> Void)?
+
+    /// Closure called on the `request(_:didFailTask:earlyWithError:)` event.
+    open var requestDidFailTaskEarlyWithError: ((Request, URLSessionTask, AFError) -> Void)?
+
+    /// Closure called on the `request(_:didCompleteTask:with:)` event.
+    open var requestDidCompleteTaskWithError: ((Request, URLSessionTask, AFError?) -> Void)?
+
+    /// Closure called on the `requestIsRetrying(_:)` event.
+    open var requestIsRetrying: ((Request) -> Void)?
+
+    /// Closure called on the `requestDidFinish(_:)` event.
+    open var requestDidFinish: ((Request) -> Void)?
+
+    /// Closure called on the `requestDidResume(_:)` event.
+    open var requestDidResume: ((Request) -> Void)?
+
+    /// Closure called on the `request(_:didResumeTask:)` event.
+    open var requestDidResumeTask: ((Request, URLSessionTask) -> Void)?
+
+    /// Closure called on the `requestDidSuspend(_:)` event.
+    open var requestDidSuspend: ((Request) -> Void)?
+
+    /// Closure called on the `request(_:didSuspendTask:)` event.
+    open var requestDidSuspendTask: ((Request, URLSessionTask) -> Void)?
+
+    /// Closure called on the `requestDidCancel(_:)` event.
+    open var requestDidCancel: ((Request) -> Void)?
+
+    /// Closure called on the `request(_:didCancelTask:)` event.
+    open var requestDidCancelTask: ((Request, URLSessionTask) -> Void)?
+
+    /// Closure called on the `request(_:didValidateRequest:response:data:withResult:)` event.
+    open var requestDidValidateRequestResponseDataWithResult: ((DataRequest, URLRequest?, HTTPURLResponse, Data?, Request.ValidationResult) -> Void)?
+
+    /// Closure called on the `request(_:didParseResponse:)` event.
+    open var requestDidParseResponse: ((DataRequest, DataResponse<Data?, AFError>) -> Void)?
+
+    /// Closure called on the `request(_:didValidateRequest:response:withResult:)` event.
+    open var requestDidValidateRequestResponseWithResult: ((DataStreamRequest, URLRequest?, HTTPURLResponse, Request.ValidationResult) -> Void)?
+
+    /// Closure called on the `request(_:didCreateUploadable:)` event.
+    open var requestDidCreateUploadable: ((UploadRequest, UploadRequest.Uploadable) -> Void)?
+
+    /// Closure called on the `request(_:didFailToCreateUploadableWithError:)` event.
+    open var requestDidFailToCreateUploadableWithError: ((UploadRequest, AFError) -> Void)?
+
+    /// Closure called on the `request(_:didProvideInputStream:)` event.
+    open var requestDidProvideInputStream: ((UploadRequest, InputStream) -> Void)?
+
+    /// Closure called on the `request(_:didFinishDownloadingUsing:with:)` event.
+    open var requestDidFinishDownloadingUsingTaskWithResult: ((DownloadRequest, URLSessionTask, Result<URL, AFError>) -> Void)?
+
+    /// Closure called on the `request(_:didCreateDestinationURL:)` event.
+    open var requestDidCreateDestinationURL: ((DownloadRequest, URL) -> Void)?
+
+    /// Closure called on the `request(_:didValidateRequest:response:temporaryURL:destinationURL:withResult:)` event.
+    open var requestDidValidateRequestResponseFileURLWithResult: ((DownloadRequest, URLRequest?, HTTPURLResponse, URL?, Request.ValidationResult) -> Void)?
+
+    /// Closure called on the `request(_:didParseResponse:)` event.
+    open var requestDidParseDownloadResponse: ((DownloadRequest, DownloadResponse<URL?, AFError>) -> Void)?
+
+    public let queue: DispatchQueue
+
+    /// Creates an instance using the provided queue.
+    ///
+    /// - Parameter queue: `DispatchQueue` on which events will fired. `.main` by default.
+    public init(queue: DispatchQueue = .main) {
+        self.queue = queue
+    }
+
+    open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
+        sessionDidBecomeInvalidWithError?(session, error)
+    }
+
+    open func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge) {
+        taskDidReceiveChallenge?(session, task, challenge)
+    }
+
+    open func urlSession(_ session: URLSession,
+                         task: URLSessionTask,
+                         didSendBodyData bytesSent: Int64,
+                         totalBytesSent: Int64,
+                         totalBytesExpectedToSend: Int64) {
+        taskDidSendBodyData?(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
+    }
+
+    open func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) {
+        taskNeedNewBodyStream?(session, task)
+    }
+
+    open func urlSession(_ session: URLSession,
+                         task: URLSessionTask,
+                         willPerformHTTPRedirection response: HTTPURLResponse,
+                         newRequest request: URLRequest) {
+        taskWillPerformHTTPRedirection?(session, task, response, request)
+    }
+
+    open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
+        taskDidFinishCollectingMetrics?(session, task, metrics)
+    }
+
+    open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
+        taskDidComplete?(session, task, error)
+    }
+
+    open func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {
+        taskIsWaitingForConnectivity?(session, task)
+    }
+
+    open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
+        dataTaskDidReceiveData?(session, dataTask, data)
+    }
+
+    open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse) {
+        dataTaskWillCacheResponse?(session, dataTask, proposedResponse)
+    }
+
+    open func urlSession(_ session: URLSession,
+                         downloadTask: URLSessionDownloadTask,
+                         didResumeAtOffset fileOffset: Int64,
+                         expectedTotalBytes: Int64) {
+        downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes)
+    }
+
+    open func urlSession(_ session: URLSession,
+                         downloadTask: URLSessionDownloadTask,
+                         didWriteData bytesWritten: Int64,
+                         totalBytesWritten: Int64,
+                         totalBytesExpectedToWrite: Int64) {
+        downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
+    }
+
+    open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
+        downloadTaskDidFinishDownloadingToURL?(session, downloadTask, location)
+    }
+
+    // MARK: Request Events
+
+    open func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) {
+        requestDidCreateInitialURLRequest?(request, urlRequest)
+    }
+
+    open func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) {
+        requestDidFailToCreateURLRequestWithError?(request, error)
+    }
+
+    open func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) {
+        requestDidAdaptInitialRequestToAdaptedRequest?(request, initialRequest, adaptedRequest)
+    }
+
+    open func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError) {
+        requestDidFailToAdaptURLRequestWithError?(request, initialRequest, error)
+    }
+
+    open func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) {
+        requestDidCreateURLRequest?(request, urlRequest)
+    }
+
+    open func request(_ request: Request, didCreateTask task: URLSessionTask) {
+        requestDidCreateTask?(request, task)
+    }
+
+    open func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) {
+        requestDidGatherMetrics?(request, metrics)
+    }
+
+    open func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) {
+        requestDidFailTaskEarlyWithError?(request, task, error)
+    }
+
+    open func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) {
+        requestDidCompleteTaskWithError?(request, task, error)
+    }
+
+    open func requestIsRetrying(_ request: Request) {
+        requestIsRetrying?(request)
+    }
+
+    open func requestDidFinish(_ request: Request) {
+        requestDidFinish?(request)
+    }
+
+    open func requestDidResume(_ request: Request) {
+        requestDidResume?(request)
+    }
+
+    public func request(_ request: Request, didResumeTask task: URLSessionTask) {
+        requestDidResumeTask?(request, task)
+    }
+
+    open func requestDidSuspend(_ request: Request) {
+        requestDidSuspend?(request)
+    }
+
+    public func request(_ request: Request, didSuspendTask task: URLSessionTask) {
+        requestDidSuspendTask?(request, task)
+    }
+
+    open func requestDidCancel(_ request: Request) {
+        requestDidCancel?(request)
+    }
+
+    public func request(_ request: Request, didCancelTask task: URLSessionTask) {
+        requestDidCancelTask?(request, task)
+    }
+
+    open func request(_ request: DataRequest,
+                      didValidateRequest urlRequest: URLRequest?,
+                      response: HTTPURLResponse,
+                      data: Data?,
+                      withResult result: Request.ValidationResult) {
+        requestDidValidateRequestResponseDataWithResult?(request, urlRequest, response, data, result)
+    }
+
+    open func request(_ request: DataRequest, didParseResponse response: DataResponse<Data?, AFError>) {
+        requestDidParseResponse?(request, response)
+    }
+
+    public func request(_ request: DataStreamRequest, didValidateRequest urlRequest: URLRequest?, response: HTTPURLResponse, withResult result: Request.ValidationResult) {
+        requestDidValidateRequestResponseWithResult?(request, urlRequest, response, result)
+    }
+
+    open func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) {
+        requestDidCreateUploadable?(request, uploadable)
+    }
+
+    open func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) {
+        requestDidFailToCreateUploadableWithError?(request, error)
+    }
+
+    open func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) {
+        requestDidProvideInputStream?(request, stream)
+    }
+
+    open func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result<URL, AFError>) {
+        requestDidFinishDownloadingUsingTaskWithResult?(request, task, result)
+    }
+
+    open func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) {
+        requestDidCreateDestinationURL?(request, url)
+    }
+
+    open func request(_ request: DownloadRequest,
+                      didValidateRequest urlRequest: URLRequest?,
+                      response: HTTPURLResponse,
+                      fileURL: URL?,
+                      withResult result: Request.ValidationResult) {
+        requestDidValidateRequestResponseFileURLWithResult?(request,
+                                                            urlRequest,
+                                                            response,
+                                                            fileURL,
+                                                            result)
+    }
+
+    open func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse<URL?, AFError>) {
+        requestDidParseDownloadResponse?(request, response)
+    }
+}

+ 447 - 0
Pods/Alamofire/Source/HTTPHeaders.swift

@@ -0,0 +1,447 @@
+//
+//  HTTPHeaders.swift
+//
+//  Copyright (c) 2014-2018 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
+
+/// An order-preserving and case-insensitive representation of HTTP headers.
+public struct HTTPHeaders {
+    private var headers: [HTTPHeader] = []
+
+    /// Creates an empty instance.
+    public init() {}
+
+    /// Creates an instance from an array of `HTTPHeader`s. Duplicate case-insensitive names are collapsed into the last
+    /// name and value encountered.
+    public init(_ headers: [HTTPHeader]) {
+        self.init()
+
+        headers.forEach { update($0) }
+    }
+
+    /// Creates an instance from a `[String: String]`. Duplicate case-insensitive names are collapsed into the last name
+    /// and value encountered.
+    public init(_ dictionary: [String: String]) {
+        self.init()
+
+        dictionary.forEach { update(HTTPHeader(name: $0.key, value: $0.value)) }
+    }
+
+    /// Case-insensitively updates or appends an `HTTPHeader` into the instance using the provided `name` and `value`.
+    ///
+    /// - Parameters:
+    ///   - name:  The `HTTPHeader` name.
+    ///   - value: The `HTTPHeader value.
+    public mutating func add(name: String, value: String) {
+        update(HTTPHeader(name: name, value: value))
+    }
+
+    /// Case-insensitively updates or appends the provided `HTTPHeader` into the instance.
+    ///
+    /// - Parameter header: The `HTTPHeader` to update or append.
+    public mutating func add(_ header: HTTPHeader) {
+        update(header)
+    }
+
+    /// Case-insensitively updates or appends an `HTTPHeader` into the instance using the provided `name` and `value`.
+    ///
+    /// - Parameters:
+    ///   - name:  The `HTTPHeader` name.
+    ///   - value: The `HTTPHeader value.
+    public mutating func update(name: String, value: String) {
+        update(HTTPHeader(name: name, value: value))
+    }
+
+    /// Case-insensitively updates or appends the provided `HTTPHeader` into the instance.
+    ///
+    /// - Parameter header: The `HTTPHeader` to update or append.
+    public mutating func update(_ header: HTTPHeader) {
+        guard let index = headers.index(of: header.name) else {
+            headers.append(header)
+            return
+        }
+
+        headers.replaceSubrange(index...index, with: [header])
+    }
+
+    /// Case-insensitively removes an `HTTPHeader`, if it exists, from the instance.
+    ///
+    /// - Parameter name: The name of the `HTTPHeader` to remove.
+    public mutating func remove(name: String) {
+        guard let index = headers.index(of: name) else { return }
+
+        headers.remove(at: index)
+    }
+
+    /// Sort the current instance by header name, case insensitively.
+    public mutating func sort() {
+        headers.sort { $0.name.lowercased() < $1.name.lowercased() }
+    }
+
+    /// Returns an instance sorted by header name.
+    ///
+    /// - Returns: A copy of the current instance sorted by name.
+    public func sorted() -> HTTPHeaders {
+        var headers = self
+        headers.sort()
+
+        return headers
+    }
+
+    /// Case-insensitively find a header's value by name.
+    ///
+    /// - Parameter name: The name of the header to search for, case-insensitively.
+    ///
+    /// - Returns:        The value of header, if it exists.
+    public func value(for name: String) -> String? {
+        guard let index = headers.index(of: name) else { return nil }
+
+        return headers[index].value
+    }
+
+    /// Case-insensitively access the header with the given name.
+    ///
+    /// - Parameter name: The name of the header.
+    public subscript(_ name: String) -> String? {
+        get { value(for: name) }
+        set {
+            if let value = newValue {
+                update(name: name, value: value)
+            } else {
+                remove(name: name)
+            }
+        }
+    }
+
+    /// The dictionary representation of all headers.
+    ///
+    /// This representation does not preserve the current order of the instance.
+    public var dictionary: [String: String] {
+        let namesAndValues = headers.map { ($0.name, $0.value) }
+
+        return Dictionary(namesAndValues, uniquingKeysWith: { _, last in last })
+    }
+}
+
+extension HTTPHeaders: ExpressibleByDictionaryLiteral {
+    public init(dictionaryLiteral elements: (String, String)...) {
+        self.init()
+
+        elements.forEach { update(name: $0.0, value: $0.1) }
+    }
+}
+
+extension HTTPHeaders: ExpressibleByArrayLiteral {
+    public init(arrayLiteral elements: HTTPHeader...) {
+        self.init(elements)
+    }
+}
+
+extension HTTPHeaders: Sequence {
+    public func makeIterator() -> IndexingIterator<[HTTPHeader]> {
+        headers.makeIterator()
+    }
+}
+
+extension HTTPHeaders: Collection {
+    public var startIndex: Int {
+        headers.startIndex
+    }
+
+    public var endIndex: Int {
+        headers.endIndex
+    }
+
+    public subscript(position: Int) -> HTTPHeader {
+        headers[position]
+    }
+
+    public func index(after i: Int) -> Int {
+        headers.index(after: i)
+    }
+}
+
+extension HTTPHeaders: CustomStringConvertible {
+    public var description: String {
+        headers.map(\.description)
+            .joined(separator: "\n")
+    }
+}
+
+// MARK: - HTTPHeader
+
+/// A representation of a single HTTP header's name / value pair.
+public struct HTTPHeader: Hashable {
+    /// Name of the header.
+    public let name: String
+
+    /// Value of the header.
+    public let value: String
+
+    /// Creates an instance from the given `name` and `value`.
+    ///
+    /// - Parameters:
+    ///   - name:  The name of the header.
+    ///   - value: The value of the header.
+    public init(name: String, value: String) {
+        self.name = name
+        self.value = value
+    }
+}
+
+extension HTTPHeader: CustomStringConvertible {
+    public var description: String {
+        "\(name): \(value)"
+    }
+}
+
+extension HTTPHeader {
+    /// Returns an `Accept` header.
+    ///
+    /// - Parameter value: The `Accept` value.
+    /// - Returns:         The header.
+    public static func accept(_ value: String) -> HTTPHeader {
+        HTTPHeader(name: "Accept", value: value)
+    }
+
+    /// Returns an `Accept-Charset` header.
+    ///
+    /// - Parameter value: The `Accept-Charset` value.
+    /// - Returns:         The header.
+    public static func acceptCharset(_ value: String) -> HTTPHeader {
+        HTTPHeader(name: "Accept-Charset", value: value)
+    }
+
+    /// Returns an `Accept-Language` header.
+    ///
+    /// Alamofire offers a default Accept-Language header that accumulates and encodes the system's preferred languages.
+    /// Use `HTTPHeader.defaultAcceptLanguage`.
+    ///
+    /// - Parameter value: The `Accept-Language` value.
+    ///
+    /// - Returns:         The header.
+    public static func acceptLanguage(_ value: String) -> HTTPHeader {
+        HTTPHeader(name: "Accept-Language", value: value)
+    }
+
+    /// Returns an `Accept-Encoding` header.
+    ///
+    /// Alamofire offers a default accept encoding value that provides the most common values. Use
+    /// `HTTPHeader.defaultAcceptEncoding`.
+    ///
+    /// - Parameter value: The `Accept-Encoding` value.
+    ///
+    /// - Returns:         The header
+    public static func acceptEncoding(_ value: String) -> HTTPHeader {
+        HTTPHeader(name: "Accept-Encoding", value: value)
+    }
+
+    /// Returns a `Basic` `Authorization` header using the `username` and `password` provided.
+    ///
+    /// - Parameters:
+    ///   - username: The username of the header.
+    ///   - password: The password of the header.
+    ///
+    /// - Returns:    The header.
+    public static func authorization(username: String, password: String) -> HTTPHeader {
+        let credential = Data("\(username):\(password)".utf8).base64EncodedString()
+
+        return authorization("Basic \(credential)")
+    }
+
+    /// Returns a `Bearer` `Authorization` header using the `bearerToken` provided
+    ///
+    /// - Parameter bearerToken: The bearer token.
+    ///
+    /// - Returns:               The header.
+    public static func authorization(bearerToken: String) -> HTTPHeader {
+        authorization("Bearer \(bearerToken)")
+    }
+
+    /// Returns an `Authorization` header.
+    ///
+    /// Alamofire provides built-in methods to produce `Authorization` headers. For a Basic `Authorization` header use
+    /// `HTTPHeader.authorization(username:password:)`. For a Bearer `Authorization` header, use
+    /// `HTTPHeader.authorization(bearerToken:)`.
+    ///
+    /// - Parameter value: The `Authorization` value.
+    ///
+    /// - Returns:         The header.
+    public static func authorization(_ value: String) -> HTTPHeader {
+        HTTPHeader(name: "Authorization", value: value)
+    }
+
+    /// Returns a `Content-Disposition` header.
+    ///
+    /// - Parameter value: The `Content-Disposition` value.
+    ///
+    /// - Returns:         The header.
+    public static func contentDisposition(_ value: String) -> HTTPHeader {
+        HTTPHeader(name: "Content-Disposition", value: value)
+    }
+
+    /// Returns a `Content-Type` header.
+    ///
+    /// All Alamofire `ParameterEncoding`s and `ParameterEncoder`s set the `Content-Type` of the request, so it may not be necessary to manually
+    /// set this value.
+    ///
+    /// - Parameter value: The `Content-Type` value.
+    ///
+    /// - Returns:         The header.
+    public static func contentType(_ value: String) -> HTTPHeader {
+        HTTPHeader(name: "Content-Type", value: value)
+    }
+
+    /// Returns a `User-Agent` header.
+    ///
+    /// - Parameter value: The `User-Agent` value.
+    ///
+    /// - Returns:         The header.
+    public static func userAgent(_ value: String) -> HTTPHeader {
+        HTTPHeader(name: "User-Agent", value: value)
+    }
+}
+
+extension Array where Element == HTTPHeader {
+    /// Case-insensitively finds the index of an `HTTPHeader` with the provided name, if it exists.
+    func index(of name: String) -> Int? {
+        let lowercasedName = name.lowercased()
+        return firstIndex { $0.name.lowercased() == lowercasedName }
+    }
+}
+
+// MARK: - Defaults
+
+extension HTTPHeaders {
+    /// The default set of `HTTPHeaders` used by Alamofire. Includes `Accept-Encoding`, `Accept-Language`, and
+    /// `User-Agent`.
+    public static let `default`: HTTPHeaders = [.defaultAcceptEncoding,
+                                                .defaultAcceptLanguage,
+                                                .defaultUserAgent]
+}
+
+extension HTTPHeader {
+    /// Returns Alamofire's default `Accept-Encoding` header, appropriate for the encodings supported by particular OS
+    /// versions.
+    ///
+    /// See the [Accept-Encoding HTTP header documentation](https://tools.ietf.org/html/rfc7230#section-4.2.3) .
+    public static let defaultAcceptEncoding: HTTPHeader = {
+        let encodings: [String]
+        if #available(iOS 11.0, macOS 10.13, tvOS 11.0, watchOS 4.0, *) {
+            encodings = ["br", "gzip", "deflate"]
+        } else {
+            encodings = ["gzip", "deflate"]
+        }
+
+        return .acceptEncoding(encodings.qualityEncoded())
+    }()
+
+    /// Returns Alamofire's default `Accept-Language` header, generated by querying `Locale` for the user's
+    /// `preferredLanguages`.
+    ///
+    /// See the [Accept-Language HTTP header documentation](https://tools.ietf.org/html/rfc7231#section-5.3.5).
+    public static let defaultAcceptLanguage: HTTPHeader = .acceptLanguage(Locale.preferredLanguages.prefix(6).qualityEncoded())
+
+    /// Returns Alamofire's default `User-Agent` header.
+    ///
+    /// See the [User-Agent header documentation](https://tools.ietf.org/html/rfc7231#section-5.5.3).
+    ///
+    /// Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 13.0.0) Alamofire/5.0.0`
+    public static let defaultUserAgent: HTTPHeader = {
+        let info = Bundle.main.infoDictionary
+        let executable = (info?["CFBundleExecutable"] as? String) ??
+            (ProcessInfo.processInfo.arguments.first?.split(separator: "/").last.map(String.init)) ??
+            "Unknown"
+        let bundle = info?["CFBundleIdentifier"] as? String ?? "Unknown"
+        let appVersion = info?["CFBundleShortVersionString"] as? String ?? "Unknown"
+        let appBuild = info?["CFBundleVersion"] as? String ?? "Unknown"
+
+        let osNameVersion: String = {
+            let version = ProcessInfo.processInfo.operatingSystemVersion
+            let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"
+            let osName: String = {
+                #if os(iOS)
+                #if targetEnvironment(macCatalyst)
+                return "macOS(Catalyst)"
+                #else
+                return "iOS"
+                #endif
+                #elseif os(watchOS)
+                return "watchOS"
+                #elseif os(tvOS)
+                return "tvOS"
+                #elseif os(macOS)
+                return "macOS"
+                #elseif os(Linux)
+                return "Linux"
+                #elseif os(Windows)
+                return "Windows"
+                #else
+                return "Unknown"
+                #endif
+            }()
+
+            return "\(osName) \(versionString)"
+        }()
+
+        let alamofireVersion = "Alamofire/\(version)"
+
+        let userAgent = "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)"
+
+        return .userAgent(userAgent)
+    }()
+}
+
+extension Collection where Element == String {
+    func qualityEncoded() -> String {
+        enumerated().map { index, encoding in
+            let quality = 1.0 - (Double(index) * 0.1)
+            return "\(encoding);q=\(quality)"
+        }.joined(separator: ", ")
+    }
+}
+
+// MARK: - System Type Extensions
+
+extension URLRequest {
+    /// Returns `allHTTPHeaderFields` as `HTTPHeaders`.
+    public var headers: HTTPHeaders {
+        get { allHTTPHeaderFields.map(HTTPHeaders.init) ?? HTTPHeaders() }
+        set { allHTTPHeaderFields = newValue.dictionary }
+    }
+}
+
+extension HTTPURLResponse {
+    /// Returns `allHeaderFields` as `HTTPHeaders`.
+    public var headers: HTTPHeaders {
+        (allHeaderFields as? [String: String]).map(HTTPHeaders.init) ?? HTTPHeaders()
+    }
+}
+
+extension URLSessionConfiguration {
+    /// Returns `httpAdditionalHeaders` as `HTTPHeaders`.
+    public var headers: HTTPHeaders {
+        get { (httpAdditionalHeaders as? [String: String]).map(HTTPHeaders.init) ?? HTTPHeaders() }
+        set { httpAdditionalHeaders = newValue.dictionary }
+    }
+}

+ 56 - 0
Pods/Alamofire/Source/HTTPMethod.swift

@@ -0,0 +1,56 @@
+//
+//  HTTPMethod.swift
+//
+//  Copyright (c) 2014-2018 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.
+//
+
+/// Type representing HTTP methods. Raw `String` value is stored and compared case-sensitively, so
+/// `HTTPMethod.get != HTTPMethod(rawValue: "get")`.
+///
+/// See https://tools.ietf.org/html/rfc7231#section-4.3
+public struct HTTPMethod: RawRepresentable, Equatable, Hashable {
+    /// `CONNECT` method.
+    public static let connect = HTTPMethod(rawValue: "CONNECT")
+    /// `DELETE` method.
+    public static let delete = HTTPMethod(rawValue: "DELETE")
+    /// `GET` method.
+    public static let get = HTTPMethod(rawValue: "GET")
+    /// `HEAD` method.
+    public static let head = HTTPMethod(rawValue: "HEAD")
+    /// `OPTIONS` method.
+    public static let options = HTTPMethod(rawValue: "OPTIONS")
+    /// `PATCH` method.
+    public static let patch = HTTPMethod(rawValue: "PATCH")
+    /// `POST` method.
+    public static let post = HTTPMethod(rawValue: "POST")
+    /// `PUT` method.
+    public static let put = HTTPMethod(rawValue: "PUT")
+    /// `QUERY` method.
+    public static let query = HTTPMethod(rawValue: "QUERY")
+    /// `TRACE` method.
+    public static let trace = HTTPMethod(rawValue: "TRACE")
+
+    public let rawValue: String
+
+    public init(rawValue: String) {
+        self.rawValue = rawValue
+    }
+}

+ 584 - 0
Pods/Alamofire/Source/MultipartFormData.swift

@@ -0,0 +1,584 @@
+//
+//  MultipartFormData.swift
+//
+//  Copyright (c) 2014-2018 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
+
+#if os(iOS) || os(watchOS) || os(tvOS)
+import MobileCoreServices
+#elseif os(macOS)
+import CoreServices
+#endif
+
+/// Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode
+/// multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead
+/// to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the
+/// data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for
+/// larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset.
+///
+/// For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well
+/// and the w3 form documentation.
+///
+/// - https://www.ietf.org/rfc/rfc2388.txt
+/// - https://www.ietf.org/rfc/rfc2045.txt
+/// - https://www.w3.org/TR/html401/interact/forms.html#h-17.13
+open class MultipartFormData {
+    // MARK: - Helper Types
+
+    enum EncodingCharacters {
+        static let crlf = "\r\n"
+    }
+
+    enum BoundaryGenerator {
+        enum BoundaryType {
+            case initial, encapsulated, final
+        }
+
+        static func randomBoundary() -> String {
+            let first = UInt32.random(in: UInt32.min...UInt32.max)
+            let second = UInt32.random(in: UInt32.min...UInt32.max)
+
+            return String(format: "alamofire.boundary.%08x%08x", first, second)
+        }
+
+        static func boundaryData(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data {
+            let boundaryText: String
+
+            switch boundaryType {
+            case .initial:
+                boundaryText = "--\(boundary)\(EncodingCharacters.crlf)"
+            case .encapsulated:
+                boundaryText = "\(EncodingCharacters.crlf)--\(boundary)\(EncodingCharacters.crlf)"
+            case .final:
+                boundaryText = "\(EncodingCharacters.crlf)--\(boundary)--\(EncodingCharacters.crlf)"
+            }
+
+            return Data(boundaryText.utf8)
+        }
+    }
+
+    class BodyPart {
+        let headers: HTTPHeaders
+        let bodyStream: InputStream
+        let bodyContentLength: UInt64
+        var hasInitialBoundary = false
+        var hasFinalBoundary = false
+
+        init(headers: HTTPHeaders, bodyStream: InputStream, bodyContentLength: UInt64) {
+            self.headers = headers
+            self.bodyStream = bodyStream
+            self.bodyContentLength = bodyContentLength
+        }
+    }
+
+    // MARK: - Properties
+
+    /// Default memory threshold used when encoding `MultipartFormData`, in bytes.
+    public static let encodingMemoryThreshold: UInt64 = 10_000_000
+
+    /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`.
+    open lazy var contentType: String = "multipart/form-data; boundary=\(self.boundary)"
+
+    /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries.
+    public var contentLength: UInt64 { bodyParts.reduce(0) { $0 + $1.bodyContentLength } }
+
+    /// The boundary used to separate the body parts in the encoded form data.
+    public let boundary: String
+
+    let fileManager: FileManager
+
+    private var bodyParts: [BodyPart]
+    private var bodyPartError: AFError?
+    private let streamBufferSize: Int
+
+    // MARK: - Lifecycle
+
+    /// Creates an instance.
+    ///
+    /// - Parameters:
+    ///   - fileManager: `FileManager` to use for file operations, if needed.
+    ///   - boundary: Boundary `String` used to separate body parts.
+    public init(fileManager: FileManager = .default, boundary: String? = nil) {
+        self.fileManager = fileManager
+        self.boundary = boundary ?? BoundaryGenerator.randomBoundary()
+        bodyParts = []
+
+        //
+        // The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more
+        // information, please refer to the following article:
+        //   - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html
+        //
+        streamBufferSize = 1024
+    }
+
+    // MARK: - Body Parts
+
+    /// Creates a body part from the data and appends it to the instance.
+    ///
+    /// The body part data will be encoded using the following format:
+    ///
+    /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
+    /// - `Content-Type: #{mimeType}` (HTTP Header)
+    /// - Encoded file data
+    /// - Multipart form boundary
+    ///
+    /// - Parameters:
+    ///   - data:     `Data` to encoding into the instance.
+    ///   - name:     Name to associate with the `Data` in the `Content-Disposition` HTTP header.
+    ///   - fileName: Filename to associate with the `Data` in the `Content-Disposition` HTTP header.
+    ///   - mimeType: MIME type to associate with the data in the `Content-Type` HTTP header.
+    public func append(_ data: Data, withName name: String, fileName: String? = nil, mimeType: String? = nil) {
+        let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType)
+        let stream = InputStream(data: data)
+        let length = UInt64(data.count)
+
+        append(stream, withLength: length, headers: headers)
+    }
+
+    /// Creates a body part from the file and appends it to the instance.
+    ///
+    /// The body part data will be encoded using the following format:
+    ///
+    /// - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header)
+    /// - `Content-Type: #{generated mimeType}` (HTTP Header)
+    /// - Encoded file data
+    /// - Multipart form boundary
+    ///
+    /// The filename in the `Content-Disposition` HTTP header is generated from the last path component of the
+    /// `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the
+    /// system associated MIME type.
+    ///
+    /// - Parameters:
+    ///   - fileURL: `URL` of the file whose content will be encoded into the instance.
+    ///   - name:    Name to associate with the file content in the `Content-Disposition` HTTP header.
+    public func append(_ fileURL: URL, withName name: String) {
+        let fileName = fileURL.lastPathComponent
+        let pathExtension = fileURL.pathExtension
+
+        if !fileName.isEmpty && !pathExtension.isEmpty {
+            let mime = mimeType(forPathExtension: pathExtension)
+            append(fileURL, withName: name, fileName: fileName, mimeType: mime)
+        } else {
+            setBodyPartError(withReason: .bodyPartFilenameInvalid(in: fileURL))
+        }
+    }
+
+    /// Creates a body part from the file and appends it to the instance.
+    ///
+    /// The body part data will be encoded using the following format:
+    ///
+    /// - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header)
+    /// - Content-Type: #{mimeType} (HTTP Header)
+    /// - Encoded file data
+    /// - Multipart form boundary
+    ///
+    /// - Parameters:
+    ///   - fileURL:  `URL` of the file whose content will be encoded into the instance.
+    ///   - name:     Name to associate with the file content in the `Content-Disposition` HTTP header.
+    ///   - fileName: Filename to associate with the file content in the `Content-Disposition` HTTP header.
+    ///   - mimeType: MIME type to associate with the file content in the `Content-Type` HTTP header.
+    public func append(_ fileURL: URL, withName name: String, fileName: String, mimeType: String) {
+        let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType)
+
+        //============================================================
+        //                 Check 1 - is file URL?
+        //============================================================
+
+        guard fileURL.isFileURL else {
+            setBodyPartError(withReason: .bodyPartURLInvalid(url: fileURL))
+            return
+        }
+
+        //============================================================
+        //              Check 2 - is file URL reachable?
+        //============================================================
+
+        #if !(os(Linux) || os(Windows))
+        do {
+            let isReachable = try fileURL.checkPromisedItemIsReachable()
+            guard isReachable else {
+                setBodyPartError(withReason: .bodyPartFileNotReachable(at: fileURL))
+                return
+            }
+        } catch {
+            setBodyPartError(withReason: .bodyPartFileNotReachableWithError(atURL: fileURL, error: error))
+            return
+        }
+        #endif
+
+        //============================================================
+        //            Check 3 - is file URL a directory?
+        //============================================================
+
+        var isDirectory: ObjCBool = false
+        let path = fileURL.path
+
+        guard fileManager.fileExists(atPath: path, isDirectory: &isDirectory) && !isDirectory.boolValue else {
+            setBodyPartError(withReason: .bodyPartFileIsDirectory(at: fileURL))
+            return
+        }
+
+        //============================================================
+        //          Check 4 - can the file size be extracted?
+        //============================================================
+
+        let bodyContentLength: UInt64
+
+        do {
+            guard let fileSize = try fileManager.attributesOfItem(atPath: path)[.size] as? NSNumber else {
+                setBodyPartError(withReason: .bodyPartFileSizeNotAvailable(at: fileURL))
+                return
+            }
+
+            bodyContentLength = fileSize.uint64Value
+        } catch {
+            setBodyPartError(withReason: .bodyPartFileSizeQueryFailedWithError(forURL: fileURL, error: error))
+            return
+        }
+
+        //============================================================
+        //       Check 5 - can a stream be created from file URL?
+        //============================================================
+
+        guard let stream = InputStream(url: fileURL) else {
+            setBodyPartError(withReason: .bodyPartInputStreamCreationFailed(for: fileURL))
+            return
+        }
+
+        append(stream, withLength: bodyContentLength, headers: headers)
+    }
+
+    /// Creates a body part from the stream and appends it to the instance.
+    ///
+    /// The body part data will be encoded using the following format:
+    ///
+    /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
+    /// - `Content-Type: #{mimeType}` (HTTP Header)
+    /// - Encoded stream data
+    /// - Multipart form boundary
+    ///
+    /// - Parameters:
+    ///   - stream:   `InputStream` to encode into the instance.
+    ///   - length:   Length, in bytes, of the stream.
+    ///   - name:     Name to associate with the stream content in the `Content-Disposition` HTTP header.
+    ///   - fileName: Filename to associate with the stream content in the `Content-Disposition` HTTP header.
+    ///   - mimeType: MIME type to associate with the stream content in the `Content-Type` HTTP header.
+    public func append(_ stream: InputStream,
+                       withLength length: UInt64,
+                       name: String,
+                       fileName: String,
+                       mimeType: String) {
+        let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType)
+        append(stream, withLength: length, headers: headers)
+    }
+
+    /// Creates a body part with the stream, length, and headers and appends it to the instance.
+    ///
+    /// The body part data will be encoded using the following format:
+    ///
+    /// - HTTP headers
+    /// - Encoded stream data
+    /// - Multipart form boundary
+    ///
+    /// - Parameters:
+    ///   - stream:  `InputStream` to encode into the instance.
+    ///   - length:  Length, in bytes, of the stream.
+    ///   - headers: `HTTPHeaders` for the body part.
+    public func append(_ stream: InputStream, withLength length: UInt64, headers: HTTPHeaders) {
+        let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length)
+        bodyParts.append(bodyPart)
+    }
+
+    // MARK: - Data Encoding
+
+    /// Encodes all appended body parts into a single `Data` value.
+    ///
+    /// - Note: This method will load all the appended body parts into memory all at the same time. This method should
+    ///         only be used when the encoded data will have a small memory footprint. For large data cases, please use
+    ///         the `writeEncodedData(to:))` method.
+    ///
+    /// - Returns: The encoded `Data`, if encoding is successful.
+    /// - Throws:  An `AFError` if encoding encounters an error.
+    public func encode() throws -> Data {
+        if let bodyPartError = bodyPartError {
+            throw bodyPartError
+        }
+
+        var encoded = Data()
+
+        bodyParts.first?.hasInitialBoundary = true
+        bodyParts.last?.hasFinalBoundary = true
+
+        for bodyPart in bodyParts {
+            let encodedData = try encode(bodyPart)
+            encoded.append(encodedData)
+        }
+
+        return encoded
+    }
+
+    /// Writes all appended body parts to the given file `URL`.
+    ///
+    /// This process is facilitated by reading and writing with input and output streams, respectively. Thus,
+    /// this approach is very memory efficient and should be used for large body part data.
+    ///
+    /// - Parameter fileURL: File `URL` to which to write the form data.
+    /// - Throws:            An `AFError` if encoding encounters an error.
+    public func writeEncodedData(to fileURL: URL) throws {
+        if let bodyPartError = bodyPartError {
+            throw bodyPartError
+        }
+
+        if fileManager.fileExists(atPath: fileURL.path) {
+            throw AFError.multipartEncodingFailed(reason: .outputStreamFileAlreadyExists(at: fileURL))
+        } else if !fileURL.isFileURL {
+            throw AFError.multipartEncodingFailed(reason: .outputStreamURLInvalid(url: fileURL))
+        }
+
+        guard let outputStream = OutputStream(url: fileURL, append: false) else {
+            throw AFError.multipartEncodingFailed(reason: .outputStreamCreationFailed(for: fileURL))
+        }
+
+        outputStream.open()
+        defer { outputStream.close() }
+
+        bodyParts.first?.hasInitialBoundary = true
+        bodyParts.last?.hasFinalBoundary = true
+
+        for bodyPart in bodyParts {
+            try write(bodyPart, to: outputStream)
+        }
+    }
+
+    // MARK: - Private - Body Part Encoding
+
+    private func encode(_ bodyPart: BodyPart) throws -> Data {
+        var encoded = Data()
+
+        let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
+        encoded.append(initialData)
+
+        let headerData = encodeHeaders(for: bodyPart)
+        encoded.append(headerData)
+
+        let bodyStreamData = try encodeBodyStream(for: bodyPart)
+        encoded.append(bodyStreamData)
+
+        if bodyPart.hasFinalBoundary {
+            encoded.append(finalBoundaryData())
+        }
+
+        return encoded
+    }
+
+    private func encodeHeaders(for bodyPart: BodyPart) -> Data {
+        let headerText = bodyPart.headers.map { "\($0.name): \($0.value)\(EncodingCharacters.crlf)" }
+            .joined()
+            + EncodingCharacters.crlf
+
+        return Data(headerText.utf8)
+    }
+
+    private func encodeBodyStream(for bodyPart: BodyPart) throws -> Data {
+        let inputStream = bodyPart.bodyStream
+        inputStream.open()
+        defer { inputStream.close() }
+
+        var encoded = Data()
+
+        while inputStream.hasBytesAvailable {
+            var buffer = [UInt8](repeating: 0, count: streamBufferSize)
+            let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
+
+            if let error = inputStream.streamError {
+                throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error))
+            }
+
+            if bytesRead > 0 {
+                encoded.append(buffer, count: bytesRead)
+            } else {
+                break
+            }
+        }
+
+        guard UInt64(encoded.count) == bodyPart.bodyContentLength else {
+            let error = AFError.UnexpectedInputStreamLength(bytesExpected: bodyPart.bodyContentLength,
+                                                            bytesRead: UInt64(encoded.count))
+            throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error))
+        }
+
+        return encoded
+    }
+
+    // MARK: - Private - Writing Body Part to Output Stream
+
+    private func write(_ bodyPart: BodyPart, to outputStream: OutputStream) throws {
+        try writeInitialBoundaryData(for: bodyPart, to: outputStream)
+        try writeHeaderData(for: bodyPart, to: outputStream)
+        try writeBodyStream(for: bodyPart, to: outputStream)
+        try writeFinalBoundaryData(for: bodyPart, to: outputStream)
+    }
+
+    private func writeInitialBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws {
+        let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
+        return try write(initialData, to: outputStream)
+    }
+
+    private func writeHeaderData(for bodyPart: BodyPart, to outputStream: OutputStream) throws {
+        let headerData = encodeHeaders(for: bodyPart)
+        return try write(headerData, to: outputStream)
+    }
+
+    private func writeBodyStream(for bodyPart: BodyPart, to outputStream: OutputStream) throws {
+        let inputStream = bodyPart.bodyStream
+
+        inputStream.open()
+        defer { inputStream.close() }
+
+        while inputStream.hasBytesAvailable {
+            var buffer = [UInt8](repeating: 0, count: streamBufferSize)
+            let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
+
+            if let streamError = inputStream.streamError {
+                throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: streamError))
+            }
+
+            if bytesRead > 0 {
+                if buffer.count != bytesRead {
+                    buffer = Array(buffer[0..<bytesRead])
+                }
+
+                try write(&buffer, to: outputStream)
+            } else {
+                break
+            }
+        }
+    }
+
+    private func writeFinalBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws {
+        if bodyPart.hasFinalBoundary {
+            return try write(finalBoundaryData(), to: outputStream)
+        }
+    }
+
+    // MARK: - Private - Writing Buffered Data to Output Stream
+
+    private func write(_ data: Data, to outputStream: OutputStream) throws {
+        var buffer = [UInt8](repeating: 0, count: data.count)
+        data.copyBytes(to: &buffer, count: data.count)
+
+        return try write(&buffer, to: outputStream)
+    }
+
+    private func write(_ buffer: inout [UInt8], to outputStream: OutputStream) throws {
+        var bytesToWrite = buffer.count
+
+        while bytesToWrite > 0, outputStream.hasSpaceAvailable {
+            let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite)
+
+            if let error = outputStream.streamError {
+                throw AFError.multipartEncodingFailed(reason: .outputStreamWriteFailed(error: error))
+            }
+
+            bytesToWrite -= bytesWritten
+
+            if bytesToWrite > 0 {
+                buffer = Array(buffer[bytesWritten..<buffer.count])
+            }
+        }
+    }
+
+    // MARK: - Private - Content Headers
+
+    private func contentHeaders(withName name: String, fileName: String? = nil, mimeType: String? = nil) -> HTTPHeaders {
+        var disposition = "form-data; name=\"\(name)\""
+        if let fileName = fileName { disposition += "; filename=\"\(fileName)\"" }
+
+        var headers: HTTPHeaders = [.contentDisposition(disposition)]
+        if let mimeType = mimeType { headers.add(.contentType(mimeType)) }
+
+        return headers
+    }
+
+    // MARK: - Private - Boundary Encoding
+
+    private func initialBoundaryData() -> Data {
+        BoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary)
+    }
+
+    private func encapsulatedBoundaryData() -> Data {
+        BoundaryGenerator.boundaryData(forBoundaryType: .encapsulated, boundary: boundary)
+    }
+
+    private func finalBoundaryData() -> Data {
+        BoundaryGenerator.boundaryData(forBoundaryType: .final, boundary: boundary)
+    }
+
+    // MARK: - Private - Errors
+
+    private func setBodyPartError(withReason reason: AFError.MultipartEncodingFailureReason) {
+        guard bodyPartError == nil else { return }
+        bodyPartError = AFError.multipartEncodingFailed(reason: reason)
+    }
+}
+
+#if canImport(UniformTypeIdentifiers)
+import UniformTypeIdentifiers
+
+extension MultipartFormData {
+    // MARK: - Private - Mime Type
+
+    private func mimeType(forPathExtension pathExtension: String) -> String {
+        if #available(iOS 14, macOS 11, tvOS 14, watchOS 7, *) {
+            return UTType(filenameExtension: pathExtension)?.preferredMIMEType ?? "application/octet-stream"
+        } else {
+            if
+                let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(),
+                let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() {
+                return contentType as String
+            }
+
+            return "application/octet-stream"
+        }
+    }
+}
+
+#else
+
+extension MultipartFormData {
+    // MARK: - Private - Mime Type
+
+    private func mimeType(forPathExtension pathExtension: String) -> String {
+        #if !(os(Linux) || os(Windows))
+        if
+            let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(),
+            let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() {
+            return contentType as String
+        }
+        #endif
+
+        return "application/octet-stream"
+    }
+}
+
+#endif

+ 89 - 0
Pods/Alamofire/Source/MultipartUpload.swift

@@ -0,0 +1,89 @@
+//
+//  MultipartUpload.swift
+//
+//  Copyright (c) 2014-2018 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
+
+/// Internal type which encapsulates a `MultipartFormData` upload.
+final class MultipartUpload {
+    lazy var result = Result { try build() }
+
+    @Protected
+    private(set) var multipartFormData: MultipartFormData
+    let encodingMemoryThreshold: UInt64
+    let request: URLRequestConvertible
+    let fileManager: FileManager
+
+    init(encodingMemoryThreshold: UInt64,
+         request: URLRequestConvertible,
+         multipartFormData: MultipartFormData) {
+        self.encodingMemoryThreshold = encodingMemoryThreshold
+        self.request = request
+        fileManager = multipartFormData.fileManager
+        self.multipartFormData = multipartFormData
+    }
+
+    func build() throws -> UploadRequest.Uploadable {
+        let uploadable: UploadRequest.Uploadable
+        if $multipartFormData.contentLength < encodingMemoryThreshold {
+            let data = try $multipartFormData.read { try $0.encode() }
+
+            uploadable = .data(data)
+        } else {
+            let tempDirectoryURL = fileManager.temporaryDirectory
+            let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data")
+            let fileName = UUID().uuidString
+            let fileURL = directoryURL.appendingPathComponent(fileName)
+
+            try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
+
+            do {
+                try $multipartFormData.read { try $0.writeEncodedData(to: fileURL) }
+            } catch {
+                // Cleanup after attempted write if it fails.
+                try? fileManager.removeItem(at: fileURL)
+                throw error
+            }
+
+            uploadable = .file(fileURL, shouldRemove: true)
+        }
+
+        return uploadable
+    }
+}
+
+extension MultipartUpload: UploadConvertible {
+    func asURLRequest() throws -> URLRequest {
+        var urlRequest = try request.asURLRequest()
+
+        $multipartFormData.read { multipartFormData in
+            urlRequest.headers.add(.contentType(multipartFormData.contentType))
+        }
+
+        return urlRequest
+    }
+
+    func createUploadable() throws -> UploadRequest.Uploadable {
+        try result.get()
+    }
+}

+ 267 - 0
Pods/Alamofire/Source/NetworkReachabilityManager.swift

@@ -0,0 +1,267 @@
+//
+//  NetworkReachabilityManager.swift
+//
+//  Copyright (c) 2014-2018 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.
+//
+
+#if !(os(watchOS) || os(Linux) || os(Windows))
+
+import Foundation
+import SystemConfiguration
+
+/// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both cellular and
+/// WiFi network interfaces.
+///
+/// Reachability can be used to determine background information about why a network operation failed, or to retry
+/// network requests 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.
+open class NetworkReachabilityManager {
+    /// Defines the various states of network reachability.
+    public enum NetworkReachabilityStatus {
+        /// It is unknown whether the network is reachable.
+        case unknown
+        /// The network is not reachable.
+        case notReachable
+        /// The network is reachable on the associated `ConnectionType`.
+        case reachable(ConnectionType)
+
+        init(_ flags: SCNetworkReachabilityFlags) {
+            guard flags.isActuallyReachable else { self = .notReachable; return }
+
+            var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi)
+
+            if flags.isCellular { networkStatus = .reachable(.cellular) }
+
+            self = networkStatus
+        }
+
+        /// Defines the various connection types detected by reachability flags.
+        public enum ConnectionType {
+            /// The connection type is either over Ethernet or WiFi.
+            case ethernetOrWiFi
+            /// The connection type is a cellular connection.
+            case cellular
+        }
+    }
+
+    /// A closure executed when the network reachability status changes. The closure takes a single argument: the
+    /// network reachability status.
+    public typealias Listener = (NetworkReachabilityStatus) -> Void
+
+    /// Default `NetworkReachabilityManager` for the zero address and a `listenerQueue` of `.main`.
+    public static let `default` = NetworkReachabilityManager()
+
+    // MARK: - Properties
+
+    /// Whether the network is currently reachable.
+    open var isReachable: Bool { isReachableOnCellular || isReachableOnEthernetOrWiFi }
+
+    /// Whether the network is currently reachable over the cellular interface.
+    ///
+    /// - Note: Using this property to decide whether to make a high or low bandwidth request is not recommended.
+    ///         Instead, set the `allowsCellularAccess` on any `URLRequest`s being issued.
+    ///
+    open var isReachableOnCellular: Bool { status == .reachable(.cellular) }
+
+    /// Whether the network is currently reachable over Ethernet or WiFi interface.
+    open var isReachableOnEthernetOrWiFi: Bool { status == .reachable(.ethernetOrWiFi) }
+
+    /// `DispatchQueue` on which reachability will update.
+    public let reachabilityQueue = DispatchQueue(label: "org.alamofire.reachabilityQueue")
+
+    /// Flags of the current reachability type, if any.
+    open var flags: SCNetworkReachabilityFlags? {
+        var flags = SCNetworkReachabilityFlags()
+
+        return (SCNetworkReachabilityGetFlags(reachability, &flags)) ? flags : nil
+    }
+
+    /// The current network reachability status.
+    open var status: NetworkReachabilityStatus {
+        flags.map(NetworkReachabilityStatus.init) ?? .unknown
+    }
+
+    /// Mutable state storage.
+    struct MutableState {
+        /// A closure executed when the network reachability status changes.
+        var listener: Listener?
+        /// `DispatchQueue` on which listeners will be called.
+        var listenerQueue: DispatchQueue?
+        /// Previously calculated status.
+        var previousStatus: NetworkReachabilityStatus?
+    }
+
+    /// `SCNetworkReachability` instance providing notifications.
+    private let reachability: SCNetworkReachability
+
+    /// Protected storage for mutable state.
+    @Protected
+    private var mutableState = MutableState()
+
+    // MARK: - Initialization
+
+    /// Creates an instance with the specified host.
+    ///
+    /// - Note: The `host` value must *not* contain a scheme, just the hostname.
+    ///
+    /// - Parameters:
+    ///   - host:          Host used to evaluate network reachability. Must *not* include the scheme (e.g. `https`).
+    public convenience init?(host: String) {
+        guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil }
+
+        self.init(reachability: reachability)
+    }
+
+    /// Creates an instance that monitors the address 0.0.0.0.
+    ///
+    /// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing
+    /// status of the device, both IPv4 and IPv6.
+    public convenience init?() {
+        var zero = sockaddr()
+        zero.sa_len = UInt8(MemoryLayout<sockaddr>.size)
+        zero.sa_family = sa_family_t(AF_INET)
+
+        guard let reachability = SCNetworkReachabilityCreateWithAddress(nil, &zero) else { return nil }
+
+        self.init(reachability: reachability)
+    }
+
+    private init(reachability: SCNetworkReachability) {
+        self.reachability = reachability
+    }
+
+    deinit {
+        stopListening()
+    }
+
+    // MARK: - Listening
+
+    /// Starts listening for changes in network reachability status.
+    ///
+    /// - Note: Stops and removes any existing listener.
+    ///
+    /// - Parameters:
+    ///   - queue:    `DispatchQueue` on which to call the `listener` closure. `.main` by default.
+    ///   - listener: `Listener` closure called when reachability changes.
+    ///
+    /// - Returns: `true` if listening was started successfully, `false` otherwise.
+    @discardableResult
+    open func startListening(onQueue queue: DispatchQueue = .main,
+                             onUpdatePerforming listener: @escaping Listener) -> Bool {
+        stopListening()
+
+        $mutableState.write { state in
+            state.listenerQueue = queue
+            state.listener = listener
+        }
+
+        var context = SCNetworkReachabilityContext(version: 0,
+                                                   info: Unmanaged.passUnretained(self).toOpaque(),
+                                                   retain: nil,
+                                                   release: nil,
+                                                   copyDescription: nil)
+        let callback: SCNetworkReachabilityCallBack = { _, flags, info in
+            guard let info = info else { return }
+
+            let instance = Unmanaged<NetworkReachabilityManager>.fromOpaque(info).takeUnretainedValue()
+            instance.notifyListener(flags)
+        }
+
+        let queueAdded = SCNetworkReachabilitySetDispatchQueue(reachability, reachabilityQueue)
+        let callbackAdded = SCNetworkReachabilitySetCallback(reachability, callback, &context)
+
+        // Manually call listener to give initial state, since the framework may not.
+        if let currentFlags = flags {
+            reachabilityQueue.async {
+                self.notifyListener(currentFlags)
+            }
+        }
+
+        return callbackAdded && queueAdded
+    }
+
+    /// Stops listening for changes in network reachability status.
+    open func stopListening() {
+        SCNetworkReachabilitySetCallback(reachability, nil, nil)
+        SCNetworkReachabilitySetDispatchQueue(reachability, nil)
+        $mutableState.write { state in
+            state.listener = nil
+            state.listenerQueue = nil
+            state.previousStatus = nil
+        }
+    }
+
+    // MARK: - Internal - Listener Notification
+
+    /// Calls the `listener` closure of the `listenerQueue` if the computed status hasn't changed.
+    ///
+    /// - Note: Should only be called from the `reachabilityQueue`.
+    ///
+    /// - Parameter flags: `SCNetworkReachabilityFlags` to use to calculate the status.
+    func notifyListener(_ flags: SCNetworkReachabilityFlags) {
+        let newStatus = NetworkReachabilityStatus(flags)
+
+        $mutableState.write { state in
+            guard state.previousStatus != newStatus else { return }
+
+            state.previousStatus = newStatus
+
+            let listener = state.listener
+            state.listenerQueue?.async { listener?(newStatus) }
+        }
+    }
+}
+
+// MARK: -
+
+extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {}
+
+extension SCNetworkReachabilityFlags {
+    var isReachable: Bool { contains(.reachable) }
+    var isConnectionRequired: Bool { contains(.connectionRequired) }
+    var canConnectAutomatically: Bool { contains(.connectionOnDemand) || contains(.connectionOnTraffic) }
+    var canConnectWithoutUserInteraction: Bool { canConnectAutomatically && !contains(.interventionRequired) }
+    var isActuallyReachable: Bool { isReachable && (!isConnectionRequired || canConnectWithoutUserInteraction) }
+    var isCellular: Bool {
+        #if os(iOS) || os(tvOS)
+        return contains(.isWWAN)
+        #else
+        return false
+        #endif
+    }
+
+    /// Human readable `String` for all states, to help with debugging.
+    var readableDescription: String {
+        let W = isCellular ? "W" : "-"
+        let R = isReachable ? "R" : "-"
+        let c = isConnectionRequired ? "c" : "-"
+        let t = contains(.transientConnection) ? "t" : "-"
+        let i = contains(.interventionRequired) ? "i" : "-"
+        let C = contains(.connectionOnTraffic) ? "C" : "-"
+        let D = contains(.connectionOnDemand) ? "D" : "-"
+        let l = contains(.isLocalAddress) ? "l" : "-"
+        let d = contains(.isDirect) ? "d" : "-"
+        let a = contains(.connectionAutomatic) ? "a" : "-"
+
+        return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)\(a)"
+    }
+}
+#endif

+ 115 - 0
Pods/Alamofire/Source/Notifications.swift

@@ -0,0 +1,115 @@
+//
+//  Notifications.swift
+//
+//  Copyright (c) 2014-2018 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
+
+extension Request {
+    /// Posted when a `Request` is resumed. The `Notification` contains the resumed `Request`.
+    public static let didResumeNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didResume")
+    /// Posted when a `Request` is suspended. The `Notification` contains the suspended `Request`.
+    public static let didSuspendNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didSuspend")
+    /// Posted when a `Request` is cancelled. The `Notification` contains the cancelled `Request`.
+    public static let didCancelNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didCancel")
+    /// Posted when a `Request` is finished. The `Notification` contains the completed `Request`.
+    public static let didFinishNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didFinish")
+
+    /// Posted when a `URLSessionTask` is resumed. The `Notification` contains the `Request` associated with the `URLSessionTask`.
+    public static let didResumeTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didResumeTask")
+    /// Posted when a `URLSessionTask` is suspended. The `Notification` contains the `Request` associated with the `URLSessionTask`.
+    public static let didSuspendTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didSuspendTask")
+    /// Posted when a `URLSessionTask` is cancelled. The `Notification` contains the `Request` associated with the `URLSessionTask`.
+    public static let didCancelTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didCancelTask")
+    /// Posted when a `URLSessionTask` is completed. The `Notification` contains the `Request` associated with the `URLSessionTask`.
+    public static let didCompleteTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didCompleteTask")
+}
+
+// MARK: -
+
+extension Notification {
+    /// The `Request` contained by the instance's `userInfo`, `nil` otherwise.
+    public var request: Request? {
+        userInfo?[String.requestKey] as? Request
+    }
+
+    /// Convenience initializer for a `Notification` containing a `Request` payload.
+    ///
+    /// - Parameters:
+    ///   - name:    The name of the notification.
+    ///   - request: The `Request` payload.
+    init(name: Notification.Name, request: Request) {
+        self.init(name: name, object: nil, userInfo: [String.requestKey: request])
+    }
+}
+
+extension NotificationCenter {
+    /// Convenience function for posting notifications with `Request` payloads.
+    ///
+    /// - Parameters:
+    ///   - name:    The name of the notification.
+    ///   - request: The `Request` payload.
+    func postNotification(named name: Notification.Name, with request: Request) {
+        let notification = Notification(name: name, request: request)
+        post(notification)
+    }
+}
+
+extension String {
+    /// User info dictionary key representing the `Request` associated with the notification.
+    fileprivate static let requestKey = "org.alamofire.notification.key.request"
+}
+
+/// `EventMonitor` that provides Alamofire's notifications.
+public final class AlamofireNotifications: EventMonitor {
+    public func requestDidResume(_ request: Request) {
+        NotificationCenter.default.postNotification(named: Request.didResumeNotification, with: request)
+    }
+
+    public func requestDidSuspend(_ request: Request) {
+        NotificationCenter.default.postNotification(named: Request.didSuspendNotification, with: request)
+    }
+
+    public func requestDidCancel(_ request: Request) {
+        NotificationCenter.default.postNotification(named: Request.didCancelNotification, with: request)
+    }
+
+    public func requestDidFinish(_ request: Request) {
+        NotificationCenter.default.postNotification(named: Request.didFinishNotification, with: request)
+    }
+
+    public func request(_ request: Request, didResumeTask task: URLSessionTask) {
+        NotificationCenter.default.postNotification(named: Request.didResumeTaskNotification, with: request)
+    }
+
+    public func request(_ request: Request, didSuspendTask task: URLSessionTask) {
+        NotificationCenter.default.postNotification(named: Request.didSuspendTaskNotification, with: request)
+    }
+
+    public func request(_ request: Request, didCancelTask task: URLSessionTask) {
+        NotificationCenter.default.postNotification(named: Request.didCancelTaskNotification, with: request)
+    }
+
+    public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) {
+        NotificationCenter.default.postNotification(named: Request.didCompleteTaskNotification, with: request)
+    }
+}

+ 49 - 0
Pods/Alamofire/Source/OperationQueue+Alamofire.swift

@@ -0,0 +1,49 @@
+//
+//  OperationQueue+Alamofire.swift
+//
+//  Copyright (c) 2014-2018 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
+
+extension OperationQueue {
+    /// Creates an instance using the provided parameters.
+    ///
+    /// - Parameters:
+    ///   - qualityOfService:            `QualityOfService` to be applied to the queue. `.default` by default.
+    ///   - maxConcurrentOperationCount: Maximum concurrent operations.
+    ///                                  `OperationQueue.defaultMaxConcurrentOperationCount` by default.
+    ///   - underlyingQueue: Underlying  `DispatchQueue`. `nil` by default.
+    ///   - name:                        Name for the queue. `nil` by default.
+    ///   - startSuspended:              Whether the queue starts suspended. `false` by default.
+    convenience init(qualityOfService: QualityOfService = .default,
+                     maxConcurrentOperationCount: Int = OperationQueue.defaultMaxConcurrentOperationCount,
+                     underlyingQueue: DispatchQueue? = nil,
+                     name: String? = nil,
+                     startSuspended: Bool = false) {
+        self.init()
+        self.qualityOfService = qualityOfService
+        self.maxConcurrentOperationCount = maxConcurrentOperationCount
+        self.underlyingQueue = underlyingQueue
+        self.name = name
+        isSuspended = startSuspended
+    }
+}

+ 217 - 0
Pods/Alamofire/Source/ParameterEncoder.swift

@@ -0,0 +1,217 @@
+//
+//  ParameterEncoder.swift
+//
+//  Copyright (c) 2014-2018 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
+
+/// A type that can encode any `Encodable` type into a `URLRequest`.
+public protocol ParameterEncoder {
+    /// Encode the provided `Encodable` parameters into `request`.
+    ///
+    /// - Parameters:
+    ///   - parameters: The `Encodable` parameter value.
+    ///   - request:    The `URLRequest` into which to encode the parameters.
+    ///
+    /// - Returns:      A `URLRequest` with the result of the encoding.
+    /// - Throws:       An `Error` when encoding fails. For Alamofire provided encoders, this will be an instance of
+    ///                 `AFError.parameterEncoderFailed` with an associated `ParameterEncoderFailureReason`.
+    func encode<Parameters: Encodable>(_ parameters: Parameters?, into request: URLRequest) throws -> URLRequest
+}
+
+/// A `ParameterEncoder` that encodes types as JSON body data.
+///
+/// If no `Content-Type` header is already set on the provided `URLRequest`s, it's set to `application/json`.
+open class JSONParameterEncoder: ParameterEncoder {
+    /// Returns an encoder with default parameters.
+    public static var `default`: JSONParameterEncoder { JSONParameterEncoder() }
+
+    /// Returns an encoder with `JSONEncoder.outputFormatting` set to `.prettyPrinted`.
+    public static var prettyPrinted: JSONParameterEncoder {
+        let encoder = JSONEncoder()
+        encoder.outputFormatting = .prettyPrinted
+
+        return JSONParameterEncoder(encoder: encoder)
+    }
+
+    /// Returns an encoder with `JSONEncoder.outputFormatting` set to `.sortedKeys`.
+    @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
+    public static var sortedKeys: JSONParameterEncoder {
+        let encoder = JSONEncoder()
+        encoder.outputFormatting = .sortedKeys
+
+        return JSONParameterEncoder(encoder: encoder)
+    }
+
+    /// `JSONEncoder` used to encode parameters.
+    public let encoder: JSONEncoder
+
+    /// Creates an instance with the provided `JSONEncoder`.
+    ///
+    /// - Parameter encoder: The `JSONEncoder`. `JSONEncoder()` by default.
+    public init(encoder: JSONEncoder = JSONEncoder()) {
+        self.encoder = encoder
+    }
+
+    open func encode<Parameters: Encodable>(_ parameters: Parameters?,
+                                            into request: URLRequest) throws -> URLRequest {
+        guard let parameters = parameters else { return request }
+
+        var request = request
+
+        do {
+            let data = try encoder.encode(parameters)
+            request.httpBody = data
+            if request.headers["Content-Type"] == nil {
+                request.headers.update(.contentType("application/json"))
+            }
+        } catch {
+            throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
+        }
+
+        return request
+    }
+}
+
+#if swift(>=5.5)
+extension ParameterEncoder where Self == JSONParameterEncoder {
+    /// Provides a default `JSONParameterEncoder` instance.
+    public static var json: JSONParameterEncoder { JSONParameterEncoder() }
+
+    /// Creates a `JSONParameterEncoder` using the provided `JSONEncoder`.
+    ///
+    /// - Parameter encoder: `JSONEncoder` used to encode parameters. `JSONEncoder()` by default.
+    /// - Returns:           The `JSONParameterEncoder`.
+    public static func json(encoder: JSONEncoder = JSONEncoder()) -> JSONParameterEncoder {
+        JSONParameterEncoder(encoder: encoder)
+    }
+}
+#endif
+
+/// A `ParameterEncoder` that encodes types as URL-encoded query strings to be set on the URL or as body data, depending
+/// on the `Destination` set.
+///
+/// If no `Content-Type` header is already set on the provided `URLRequest`s, it will be set to
+/// `application/x-www-form-urlencoded; charset=utf-8`.
+///
+/// Encoding behavior can be customized by passing an instance of `URLEncodedFormEncoder` to the initializer.
+open class URLEncodedFormParameterEncoder: ParameterEncoder {
+    /// Defines where the URL-encoded string should be set for each `URLRequest`.
+    public enum Destination {
+        /// Applies the encoded query string to any existing query string for `.get`, `.head`, and `.delete` request.
+        /// Sets it to the `httpBody` for all other methods.
+        case methodDependent
+        /// Applies the encoded query string to any existing query string from the `URLRequest`.
+        case queryString
+        /// Applies the encoded query string to the `httpBody` of the `URLRequest`.
+        case httpBody
+
+        /// Determines whether the URL-encoded string should be applied to the `URLRequest`'s `url`.
+        ///
+        /// - Parameter method: The `HTTPMethod`.
+        ///
+        /// - Returns:          Whether the URL-encoded string should be applied to a `URL`.
+        func encodesParametersInURL(for method: HTTPMethod) -> Bool {
+            switch self {
+            case .methodDependent: return [.get, .head, .delete].contains(method)
+            case .queryString: return true
+            case .httpBody: return false
+            }
+        }
+    }
+
+    /// Returns an encoder with default parameters.
+    public static var `default`: URLEncodedFormParameterEncoder { URLEncodedFormParameterEncoder() }
+
+    /// The `URLEncodedFormEncoder` to use.
+    public let encoder: URLEncodedFormEncoder
+
+    /// The `Destination` for the URL-encoded string.
+    public let destination: Destination
+
+    /// Creates an instance with the provided `URLEncodedFormEncoder` instance and `Destination` value.
+    ///
+    /// - Parameters:
+    ///   - encoder:     The `URLEncodedFormEncoder`. `URLEncodedFormEncoder()` by default.
+    ///   - destination: The `Destination`. `.methodDependent` by default.
+    public init(encoder: URLEncodedFormEncoder = URLEncodedFormEncoder(), destination: Destination = .methodDependent) {
+        self.encoder = encoder
+        self.destination = destination
+    }
+
+    open func encode<Parameters: Encodable>(_ parameters: Parameters?,
+                                            into request: URLRequest) throws -> URLRequest {
+        guard let parameters = parameters else { return request }
+
+        var request = request
+
+        guard let url = request.url else {
+            throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.url))
+        }
+
+        guard let method = request.method else {
+            let rawValue = request.method?.rawValue ?? "nil"
+            throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.httpMethod(rawValue: rawValue)))
+        }
+
+        if destination.encodesParametersInURL(for: method),
+           var components = URLComponents(url: url, resolvingAgainstBaseURL: false) {
+            let query: String = try Result<String, Error> { try encoder.encode(parameters) }
+                .mapError { AFError.parameterEncoderFailed(reason: .encoderFailed(error: $0)) }.get()
+            let newQueryString = [components.percentEncodedQuery, query].compactMap { $0 }.joinedWithAmpersands()
+            components.percentEncodedQuery = newQueryString.isEmpty ? nil : newQueryString
+
+            guard let newURL = components.url else {
+                throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.url))
+            }
+
+            request.url = newURL
+        } else {
+            if request.headers["Content-Type"] == nil {
+                request.headers.update(.contentType("application/x-www-form-urlencoded; charset=utf-8"))
+            }
+
+            request.httpBody = try Result<Data, Error> { try encoder.encode(parameters) }
+                .mapError { AFError.parameterEncoderFailed(reason: .encoderFailed(error: $0)) }.get()
+        }
+
+        return request
+    }
+}
+
+#if swift(>=5.5)
+extension ParameterEncoder where Self == URLEncodedFormParameterEncoder {
+    /// Provides a default `URLEncodedFormParameterEncoder` instance.
+    public static var urlEncodedForm: URLEncodedFormParameterEncoder { URLEncodedFormParameterEncoder() }
+
+    /// Creates a `URLEncodedFormParameterEncoder` with the provided encoder and destination.
+    ///
+    /// - Parameters:
+    ///   - encoder:     `URLEncodedFormEncoder` used to encode the parameters. `URLEncodedFormEncoder()` by default.
+    ///   - destination: `Destination` to which to encode the parameters. `.methodDependent` by default.
+    /// - Returns:       The `URLEncodedFormParameterEncoder`.
+    public static func urlEncodedForm(encoder: URLEncodedFormEncoder = URLEncodedFormEncoder(),
+                                      destination: URLEncodedFormParameterEncoder.Destination = .methodDependent) -> URLEncodedFormParameterEncoder {
+        URLEncodedFormParameterEncoder(encoder: encoder, destination: destination)
+    }
+}
+#endif

+ 342 - 0
Pods/Alamofire/Source/ParameterEncoding.swift

@@ -0,0 +1,342 @@
+//
+//  ParameterEncoding.swift
+//
+//  Copyright (c) 2014-2018 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
+
+/// A dictionary of parameters to apply to a `URLRequest`.
+public typealias Parameters = [String: Any]
+
+/// A type used to define how a set of parameters are applied to a `URLRequest`.
+public protocol ParameterEncoding {
+    /// Creates a `URLRequest` by encoding parameters and applying them on the passed request.
+    ///
+    /// - Parameters:
+    ///   - urlRequest: `URLRequestConvertible` value onto which parameters will be encoded.
+    ///   - parameters: `Parameters` to encode onto the request.
+    ///
+    /// - Returns:      The encoded `URLRequest`.
+    /// - Throws:       Any `Error` produced during parameter encoding.
+    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest
+}
+
+// MARK: -
+
+/// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP
+/// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as
+/// the HTTP body depends on the destination of the encoding.
+///
+/// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to
+/// `application/x-www-form-urlencoded; charset=utf-8`.
+///
+/// There is no published specification for how to encode collection types. By default the convention of appending
+/// `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for
+/// nested dictionary values (`foo[bar]=baz`) is used. Optionally, `ArrayEncoding` can be used to omit the
+/// square brackets appended to array keys.
+///
+/// `BoolEncoding` can be used to configure how boolean values are encoded. The default behavior is to encode
+/// `true` as 1 and `false` as 0.
+public struct URLEncoding: ParameterEncoding {
+    // MARK: Helper Types
+
+    /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the
+    /// resulting URL request.
+    public enum Destination {
+        /// Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` requests and
+        /// sets as the HTTP body for requests with any other HTTP method.
+        case methodDependent
+        /// Sets or appends encoded query string result to existing query string.
+        case queryString
+        /// Sets encoded query string result as the HTTP body of the URL request.
+        case httpBody
+
+        func encodesParametersInURL(for method: HTTPMethod) -> Bool {
+            switch self {
+            case .methodDependent: return [.get, .head, .delete].contains(method)
+            case .queryString: return true
+            case .httpBody: return false
+            }
+        }
+    }
+
+    /// Configures how `Array` parameters are encoded.
+    public enum ArrayEncoding {
+        /// An empty set of square brackets is appended to the key for every value. This is the default behavior.
+        case brackets
+        /// No brackets are appended. The key is encoded as is.
+        case noBrackets
+        /// Brackets containing the item index are appended. This matches the jQuery and Node.js behavior.
+        case indexInBrackets
+
+        func encode(key: String, atIndex index: Int) -> String {
+            switch self {
+            case .brackets:
+                return "\(key)[]"
+            case .noBrackets:
+                return key
+            case .indexInBrackets:
+                return "\(key)[\(index)]"
+            }
+        }
+    }
+
+    /// Configures how `Bool` parameters are encoded.
+    public enum BoolEncoding {
+        /// Encode `true` as `1` and `false` as `0`. This is the default behavior.
+        case numeric
+        /// Encode `true` and `false` as string literals.
+        case literal
+
+        func encode(value: Bool) -> String {
+            switch self {
+            case .numeric:
+                return value ? "1" : "0"
+            case .literal:
+                return value ? "true" : "false"
+            }
+        }
+    }
+
+    // MARK: Properties
+
+    /// Returns a default `URLEncoding` instance with a `.methodDependent` destination.
+    public static var `default`: URLEncoding { URLEncoding() }
+
+    /// Returns a `URLEncoding` instance with a `.queryString` destination.
+    public static var queryString: URLEncoding { URLEncoding(destination: .queryString) }
+
+    /// Returns a `URLEncoding` instance with an `.httpBody` destination.
+    public static var httpBody: URLEncoding { URLEncoding(destination: .httpBody) }
+
+    /// The destination defining where the encoded query string is to be applied to the URL request.
+    public let destination: Destination
+
+    /// The encoding to use for `Array` parameters.
+    public let arrayEncoding: ArrayEncoding
+
+    /// The encoding to use for `Bool` parameters.
+    public let boolEncoding: BoolEncoding
+
+    // MARK: Initialization
+
+    /// Creates an instance using the specified parameters.
+    ///
+    /// - Parameters:
+    ///   - destination:   `Destination` defining where the encoded query string will be applied. `.methodDependent` by
+    ///                    default.
+    ///   - arrayEncoding: `ArrayEncoding` to use. `.brackets` by default.
+    ///   - boolEncoding:  `BoolEncoding` to use. `.numeric` by default.
+    public init(destination: Destination = .methodDependent,
+                arrayEncoding: ArrayEncoding = .brackets,
+                boolEncoding: BoolEncoding = .numeric) {
+        self.destination = destination
+        self.arrayEncoding = arrayEncoding
+        self.boolEncoding = boolEncoding
+    }
+
+    // MARK: Encoding
+
+    public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
+        var urlRequest = try urlRequest.asURLRequest()
+
+        guard let parameters = parameters else { return urlRequest }
+
+        if let method = urlRequest.method, destination.encodesParametersInURL(for: method) {
+            guard let url = urlRequest.url else {
+                throw AFError.parameterEncodingFailed(reason: .missingURL)
+            }
+
+            if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty {
+                let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
+                urlComponents.percentEncodedQuery = percentEncodedQuery
+                urlRequest.url = urlComponents.url
+            }
+        } else {
+            if urlRequest.headers["Content-Type"] == nil {
+                urlRequest.headers.update(.contentType("application/x-www-form-urlencoded; charset=utf-8"))
+            }
+
+            urlRequest.httpBody = Data(query(parameters).utf8)
+        }
+
+        return urlRequest
+    }
+
+    /// Creates a percent-escaped, URL encoded query string components from the given key-value pair recursively.
+    ///
+    /// - Parameters:
+    ///   - key:   Key of the query component.
+    ///   - value: Value of the query component.
+    ///
+    /// - Returns: The percent-escaped, URL encoded query string components.
+    public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] {
+        var components: [(String, String)] = []
+        switch value {
+        case let dictionary as [String: Any]:
+            for (nestedKey, value) in dictionary {
+                components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value)
+            }
+        case let array as [Any]:
+            for (index, value) in array.enumerated() {
+                components += queryComponents(fromKey: arrayEncoding.encode(key: key, atIndex: index), value: value)
+            }
+        case let number as NSNumber:
+            if number.isBool {
+                components.append((escape(key), escape(boolEncoding.encode(value: number.boolValue))))
+            } else {
+                components.append((escape(key), escape("\(number)")))
+            }
+        case let bool as Bool:
+            components.append((escape(key), escape(boolEncoding.encode(value: bool))))
+        default:
+            components.append((escape(key), escape("\(value)")))
+        }
+        return components
+    }
+
+    /// Creates a percent-escaped string following RFC 3986 for a query string key or value.
+    ///
+    /// - Parameter string: `String` to be percent-escaped.
+    ///
+    /// - Returns:          The percent-escaped `String`.
+    public func escape(_ string: String) -> String {
+        string.addingPercentEncoding(withAllowedCharacters: .afURLQueryAllowed) ?? string
+    }
+
+    private func query(_ parameters: [String: Any]) -> String {
+        var components: [(String, String)] = []
+
+        for key in parameters.keys.sorted(by: <) {
+            let value = parameters[key]!
+            components += queryComponents(fromKey: key, value: value)
+        }
+        return components.map { "\($0)=\($1)" }.joined(separator: "&")
+    }
+}
+
+// MARK: -
+
+/// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the
+/// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
+public struct JSONEncoding: ParameterEncoding {
+    public enum Error: Swift.Error {
+        case invalidJSONObject
+    }
+
+    // MARK: Properties
+
+    /// Returns a `JSONEncoding` instance with default writing options.
+    public static var `default`: JSONEncoding { JSONEncoding() }
+
+    /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options.
+    public static var prettyPrinted: JSONEncoding { JSONEncoding(options: .prettyPrinted) }
+
+    /// The options for writing the parameters as JSON data.
+    public let options: JSONSerialization.WritingOptions
+
+    // MARK: Initialization
+
+    /// Creates an instance using the specified `WritingOptions`.
+    ///
+    /// - Parameter options: `JSONSerialization.WritingOptions` to use.
+    public init(options: JSONSerialization.WritingOptions = []) {
+        self.options = options
+    }
+
+    // MARK: Encoding
+
+    public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
+        var urlRequest = try urlRequest.asURLRequest()
+
+        guard let parameters = parameters else { return urlRequest }
+
+        guard JSONSerialization.isValidJSONObject(parameters) else {
+            throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: Error.invalidJSONObject))
+        }
+
+        do {
+            let data = try JSONSerialization.data(withJSONObject: parameters, options: options)
+
+            if urlRequest.headers["Content-Type"] == nil {
+                urlRequest.headers.update(.contentType("application/json"))
+            }
+
+            urlRequest.httpBody = data
+        } catch {
+            throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
+        }
+
+        return urlRequest
+    }
+
+    /// Encodes any JSON compatible object into a `URLRequest`.
+    ///
+    /// - Parameters:
+    ///   - urlRequest: `URLRequestConvertible` value into which the object will be encoded.
+    ///   - jsonObject: `Any` value (must be JSON compatible` to be encoded into the `URLRequest`. `nil` by default.
+    ///
+    /// - Returns:      The encoded `URLRequest`.
+    /// - Throws:       Any `Error` produced during encoding.
+    public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest {
+        var urlRequest = try urlRequest.asURLRequest()
+
+        guard let jsonObject = jsonObject else { return urlRequest }
+
+        guard JSONSerialization.isValidJSONObject(jsonObject) else {
+            throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: Error.invalidJSONObject))
+        }
+
+        do {
+            let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options)
+
+            if urlRequest.headers["Content-Type"] == nil {
+                urlRequest.headers.update(.contentType("application/json"))
+            }
+
+            urlRequest.httpBody = data
+        } catch {
+            throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
+        }
+
+        return urlRequest
+    }
+}
+
+extension JSONEncoding.Error {
+    public var localizedDescription: String {
+        """
+        Invalid JSON object provided for parameter or object encoding. \
+        This is most likely due to a value which can't be represented in Objective-C.
+        """
+    }
+}
+
+// MARK: -
+
+extension NSNumber {
+    fileprivate var isBool: Bool {
+        // Use Obj-C type encoding to check whether the underlying type is a `Bool`, as it's guaranteed as part of
+        // swift-corelibs-foundation, per [this discussion on the Swift forums](https://forums.swift.org/t/alamofire-on-linux-possible-but-not-release-ready/34553/22).
+        String(cString: objCType) == "c"
+    }
+}

+ 161 - 0
Pods/Alamofire/Source/Protected.swift

@@ -0,0 +1,161 @@
+//
+//  Protected.swift
+//
+//  Copyright (c) 2014-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.
+//
+
+import Foundation
+
+private protocol Lock {
+    func lock()
+    func unlock()
+}
+
+extension Lock {
+    /// Executes a closure returning a value while acquiring the lock.
+    ///
+    /// - Parameter closure: The closure to run.
+    ///
+    /// - Returns:           The value the closure generated.
+    func around<T>(_ closure: () throws -> T) rethrows -> T {
+        lock(); defer { unlock() }
+        return try closure()
+    }
+
+    /// Execute a closure while acquiring the lock.
+    ///
+    /// - Parameter closure: The closure to run.
+    func around(_ closure: () throws -> Void) rethrows {
+        lock(); defer { unlock() }
+        try closure()
+    }
+}
+
+#if os(Linux) || os(Windows)
+
+extension NSLock: Lock {}
+
+#endif
+
+#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
+/// An `os_unfair_lock` wrapper.
+final class UnfairLock: Lock {
+    private let unfairLock: os_unfair_lock_t
+
+    init() {
+        unfairLock = .allocate(capacity: 1)
+        unfairLock.initialize(to: os_unfair_lock())
+    }
+
+    deinit {
+        unfairLock.deinitialize(count: 1)
+        unfairLock.deallocate()
+    }
+
+    fileprivate func lock() {
+        os_unfair_lock_lock(unfairLock)
+    }
+
+    fileprivate func unlock() {
+        os_unfair_lock_unlock(unfairLock)
+    }
+}
+#endif
+
+/// A thread-safe wrapper around a value.
+@propertyWrapper
+@dynamicMemberLookup
+final class Protected<T> {
+    #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
+    private let lock = UnfairLock()
+    #elseif os(Linux) || os(Windows)
+    private let lock = NSLock()
+    #endif
+    private var value: T
+
+    init(_ value: T) {
+        self.value = value
+    }
+
+    /// The contained value. Unsafe for anything more than direct read or write.
+    var wrappedValue: T {
+        get { lock.around { value } }
+        set { lock.around { value = newValue } }
+    }
+
+    var projectedValue: Protected<T> { self }
+
+    init(wrappedValue: T) {
+        value = wrappedValue
+    }
+
+    /// Synchronously read or transform the contained value.
+    ///
+    /// - Parameter closure: The closure to execute.
+    ///
+    /// - Returns:           The return value of the closure passed.
+    func read<U>(_ closure: (T) throws -> U) rethrows -> U {
+        try lock.around { try closure(self.value) }
+    }
+
+    /// Synchronously modify the protected value.
+    ///
+    /// - Parameter closure: The closure to execute.
+    ///
+    /// - Returns:           The modified value.
+    @discardableResult
+    func write<U>(_ closure: (inout T) throws -> U) rethrows -> U {
+        try lock.around { try closure(&self.value) }
+    }
+
+    subscript<Property>(dynamicMember keyPath: WritableKeyPath<T, Property>) -> Property {
+        get { lock.around { value[keyPath: keyPath] } }
+        set { lock.around { value[keyPath: keyPath] = newValue } }
+    }
+
+    subscript<Property>(dynamicMember keyPath: KeyPath<T, Property>) -> Property {
+        lock.around { value[keyPath: keyPath] }
+    }
+}
+
+extension Protected where T == Request.MutableState {
+    /// Attempts to transition to the passed `State`.
+    ///
+    /// - Parameter state: The `State` to attempt transition to.
+    ///
+    /// - Returns:         Whether the transition occurred.
+    func attemptToTransitionTo(_ state: Request.State) -> Bool {
+        lock.around {
+            guard value.state.canTransitionTo(state) else { return false }
+
+            value.state = state
+
+            return true
+        }
+    }
+
+    /// Perform a closure while locked with the provided `Request.State`.
+    ///
+    /// - Parameter perform: The closure to perform while locked.
+    func withState(perform: (Request.State) -> Void) {
+        lock.around { perform(value.state) }
+    }
+}

+ 113 - 0
Pods/Alamofire/Source/RedirectHandler.swift

@@ -0,0 +1,113 @@
+//
+//  RedirectHandler.swift
+//
+//  Copyright (c) 2014-2018 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
+
+/// A type that handles how an HTTP redirect response from a remote server should be redirected to the new request.
+public protocol RedirectHandler {
+    /// Determines how the HTTP redirect response should be redirected to the new request.
+    ///
+    /// The `completion` closure should be passed one of three possible options:
+    ///
+    ///   1. The new request specified by the redirect (this is the most common use case).
+    ///   2. A modified version of the new request (you may want to route it somewhere else).
+    ///   3. A `nil` value to deny the redirect request and return the body of the redirect response.
+    ///
+    /// - Parameters:
+    ///   - task:       The `URLSessionTask` whose request resulted in a redirect.
+    ///   - request:    The `URLRequest` to the new location specified by the redirect response.
+    ///   - response:   The `HTTPURLResponse` containing the server's response to the original request.
+    ///   - completion: The closure to execute containing the new `URLRequest`, a modified `URLRequest`, or `nil`.
+    func task(_ task: URLSessionTask,
+              willBeRedirectedTo request: URLRequest,
+              for response: HTTPURLResponse,
+              completion: @escaping (URLRequest?) -> Void)
+}
+
+// MARK: -
+
+/// `Redirector` is a convenience `RedirectHandler` making it easy to follow, not follow, or modify a redirect.
+public struct Redirector {
+    /// Defines the behavior of the `Redirector` type.
+    public enum Behavior {
+        /// Follow the redirect as defined in the response.
+        case follow
+        /// Do not follow the redirect defined in the response.
+        case doNotFollow
+        /// Modify the redirect request defined in the response.
+        case modify((URLSessionTask, URLRequest, HTTPURLResponse) -> URLRequest?)
+    }
+
+    /// Returns a `Redirector` with a `.follow` `Behavior`.
+    public static let follow = Redirector(behavior: .follow)
+    /// Returns a `Redirector` with a `.doNotFollow` `Behavior`.
+    public static let doNotFollow = Redirector(behavior: .doNotFollow)
+
+    /// The `Behavior` of the `Redirector`.
+    public let behavior: Behavior
+
+    /// Creates a `Redirector` instance from the `Behavior`.
+    ///
+    /// - Parameter behavior: The `Behavior`.
+    public init(behavior: Behavior) {
+        self.behavior = behavior
+    }
+}
+
+// MARK: -
+
+extension Redirector: RedirectHandler {
+    public func task(_ task: URLSessionTask,
+                     willBeRedirectedTo request: URLRequest,
+                     for response: HTTPURLResponse,
+                     completion: @escaping (URLRequest?) -> Void) {
+        switch behavior {
+        case .follow:
+            completion(request)
+        case .doNotFollow:
+            completion(nil)
+        case let .modify(closure):
+            let request = closure(task, request, response)
+            completion(request)
+        }
+    }
+}
+
+#if swift(>=5.5)
+extension RedirectHandler where Self == Redirector {
+    /// Provides a `Redirector` which follows redirects. Equivalent to `Redirector.follow`.
+    public static var follow: Redirector { .follow }
+
+    /// Provides a `Redirector` which does not follow redirects. Equivalent to `Redirector.doNotFollow`.
+    public static var doNotFollow: Redirector { .doNotFollow }
+
+    /// Creates a `Redirector` which modifies the redirected `URLRequest` using the provided closure.
+    ///
+    /// - Parameter closure: Closure used to modify the redirect.
+    /// - Returns:           The `Redirector`.
+    public static func modify(using closure: @escaping (URLSessionTask, URLRequest, HTTPURLResponse) -> URLRequest?) -> Redirector {
+        Redirector(behavior: .modify(closure))
+    }
+}
+#endif

+ 1912 - 0
Pods/Alamofire/Source/Request.swift

@@ -0,0 +1,1912 @@
+//
+//  Request.swift
+//
+//  Copyright (c) 2014-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.
+//
+
+import Foundation
+
+/// `Request` is the common superclass of all Alamofire request types and provides common state, delegate, and callback
+/// handling.
+public class Request {
+    /// State of the `Request`, with managed transitions between states set when calling `resume()`, `suspend()`, or
+    /// `cancel()` on the `Request`.
+    public enum State {
+        /// Initial state of the `Request`.
+        case initialized
+        /// `State` set when `resume()` is called. Any tasks created for the `Request` will have `resume()` called on
+        /// them in this state.
+        case resumed
+        /// `State` set when `suspend()` is called. Any tasks created for the `Request` will have `suspend()` called on
+        /// them in this state.
+        case suspended
+        /// `State` set when `cancel()` is called. Any tasks created for the `Request` will have `cancel()` called on
+        /// them. Unlike `resumed` or `suspended`, once in the `cancelled` state, the `Request` can no longer transition
+        /// to any other state.
+        case cancelled
+        /// `State` set when all response serialization completion closures have been cleared on the `Request` and
+        /// enqueued on their respective queues.
+        case finished
+
+        /// Determines whether `self` can be transitioned to the provided `State`.
+        func canTransitionTo(_ state: State) -> Bool {
+            switch (self, state) {
+            case (.initialized, _):
+                return true
+            case (_, .initialized), (.cancelled, _), (.finished, _):
+                return false
+            case (.resumed, .cancelled), (.suspended, .cancelled), (.resumed, .suspended), (.suspended, .resumed):
+                return true
+            case (.suspended, .suspended), (.resumed, .resumed):
+                return false
+            case (_, .finished):
+                return true
+            }
+        }
+    }
+
+    // MARK: - Initial State
+
+    /// `UUID` providing a unique identifier for the `Request`, used in the `Hashable` and `Equatable` conformances.
+    public let id: UUID
+    /// The serial queue for all internal async actions.
+    public let underlyingQueue: DispatchQueue
+    /// The queue used for all serialization actions. By default it's a serial queue that targets `underlyingQueue`.
+    public let serializationQueue: DispatchQueue
+    /// `EventMonitor` used for event callbacks.
+    public let eventMonitor: EventMonitor?
+    /// The `Request`'s interceptor.
+    public let interceptor: RequestInterceptor?
+    /// The `Request`'s delegate.
+    public private(set) weak var delegate: RequestDelegate?
+
+    // MARK: - Mutable State
+
+    /// Type encapsulating all mutable state that may need to be accessed from anything other than the `underlyingQueue`.
+    struct MutableState {
+        /// State of the `Request`.
+        var state: State = .initialized
+        /// `ProgressHandler` and `DispatchQueue` provided for upload progress callbacks.
+        var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)?
+        /// `ProgressHandler` and `DispatchQueue` provided for download progress callbacks.
+        var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)?
+        /// `RedirectHandler` provided for to handle request redirection.
+        var redirectHandler: RedirectHandler?
+        /// `CachedResponseHandler` provided to handle response caching.
+        var cachedResponseHandler: CachedResponseHandler?
+        /// Queue and closure called when the `Request` is able to create a cURL description of itself.
+        var cURLHandler: (queue: DispatchQueue, handler: (String) -> Void)?
+        /// Queue and closure called when the `Request` creates a `URLRequest`.
+        var urlRequestHandler: (queue: DispatchQueue, handler: (URLRequest) -> Void)?
+        /// Queue and closure called when the `Request` creates a `URLSessionTask`.
+        var urlSessionTaskHandler: (queue: DispatchQueue, handler: (URLSessionTask) -> Void)?
+        /// Response serialization closures that handle response parsing.
+        var responseSerializers: [() -> Void] = []
+        /// Response serialization completion closures executed once all response serializers are complete.
+        var responseSerializerCompletions: [() -> Void] = []
+        /// Whether response serializer processing is finished.
+        var responseSerializerProcessingFinished = false
+        /// `URLCredential` used for authentication challenges.
+        var credential: URLCredential?
+        /// All `URLRequest`s created by Alamofire on behalf of the `Request`.
+        var requests: [URLRequest] = []
+        /// All `URLSessionTask`s created by Alamofire on behalf of the `Request`.
+        var tasks: [URLSessionTask] = []
+        /// All `URLSessionTaskMetrics` values gathered by Alamofire on behalf of the `Request`. Should correspond
+        /// exactly the the `tasks` created.
+        var metrics: [URLSessionTaskMetrics] = []
+        /// Number of times any retriers provided retried the `Request`.
+        var retryCount = 0
+        /// Final `AFError` for the `Request`, whether from various internal Alamofire calls or as a result of a `task`.
+        var error: AFError?
+        /// Whether the instance has had `finish()` called and is running the serializers. Should be replaced with a
+        /// representation in the state machine in the future.
+        var isFinishing = false
+        /// Actions to run when requests are finished. Use for concurrency support.
+        var finishHandlers: [() -> Void] = []
+    }
+
+    /// Protected `MutableState` value that provides thread-safe access to state values.
+    @Protected
+    fileprivate var mutableState = MutableState()
+
+    /// `State` of the `Request`.
+    public var state: State { $mutableState.state }
+    /// Returns whether `state` is `.initialized`.
+    public var isInitialized: Bool { state == .initialized }
+    /// Returns whether `state is `.resumed`.
+    public var isResumed: Bool { state == .resumed }
+    /// Returns whether `state` is `.suspended`.
+    public var isSuspended: Bool { state == .suspended }
+    /// Returns whether `state` is `.cancelled`.
+    public var isCancelled: Bool { state == .cancelled }
+    /// Returns whether `state` is `.finished`.
+    public var isFinished: Bool { state == .finished }
+
+    // MARK: Progress
+
+    /// Closure type executed when monitoring the upload or download progress of a request.
+    public typealias ProgressHandler = (Progress) -> Void
+
+    /// `Progress` of the upload of the body of the executed `URLRequest`. Reset to `0` if the `Request` is retried.
+    public let uploadProgress = Progress(totalUnitCount: 0)
+    /// `Progress` of the download of any response data. Reset to `0` if the `Request` is retried.
+    public let downloadProgress = Progress(totalUnitCount: 0)
+    /// `ProgressHandler` called when `uploadProgress` is updated, on the provided `DispatchQueue`.
+    private var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? {
+        get { $mutableState.uploadProgressHandler }
+        set { $mutableState.uploadProgressHandler = newValue }
+    }
+
+    /// `ProgressHandler` called when `downloadProgress` is updated, on the provided `DispatchQueue`.
+    fileprivate var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? {
+        get { $mutableState.downloadProgressHandler }
+        set { $mutableState.downloadProgressHandler = newValue }
+    }
+
+    // MARK: Redirect Handling
+
+    /// `RedirectHandler` set on the instance.
+    public private(set) var redirectHandler: RedirectHandler? {
+        get { $mutableState.redirectHandler }
+        set { $mutableState.redirectHandler = newValue }
+    }
+
+    // MARK: Cached Response Handling
+
+    /// `CachedResponseHandler` set on the instance.
+    public private(set) var cachedResponseHandler: CachedResponseHandler? {
+        get { $mutableState.cachedResponseHandler }
+        set { $mutableState.cachedResponseHandler = newValue }
+    }
+
+    // MARK: URLCredential
+
+    /// `URLCredential` used for authentication challenges. Created by calling one of the `authenticate` methods.
+    public private(set) var credential: URLCredential? {
+        get { $mutableState.credential }
+        set { $mutableState.credential = newValue }
+    }
+
+    // MARK: Validators
+
+    /// `Validator` callback closures that store the validation calls enqueued.
+    @Protected
+    fileprivate var validators: [() -> Void] = []
+
+    // MARK: URLRequests
+
+    /// All `URLRequests` created on behalf of the `Request`, including original and adapted requests.
+    public var requests: [URLRequest] { $mutableState.requests }
+    /// First `URLRequest` created on behalf of the `Request`. May not be the first one actually executed.
+    public var firstRequest: URLRequest? { requests.first }
+    /// Last `URLRequest` created on behalf of the `Request`.
+    public var lastRequest: URLRequest? { requests.last }
+    /// Current `URLRequest` created on behalf of the `Request`.
+    public var request: URLRequest? { lastRequest }
+
+    /// `URLRequest`s from all of the `URLSessionTask`s executed on behalf of the `Request`. May be different from
+    /// `requests` due to `URLSession` manipulation.
+    public var performedRequests: [URLRequest] { $mutableState.read { $0.tasks.compactMap(\.currentRequest) } }
+
+    // MARK: HTTPURLResponse
+
+    /// `HTTPURLResponse` received from the server, if any. If the `Request` was retried, this is the response of the
+    /// last `URLSessionTask`.
+    public var response: HTTPURLResponse? { lastTask?.response as? HTTPURLResponse }
+
+    // MARK: Tasks
+
+    /// All `URLSessionTask`s created on behalf of the `Request`.
+    public var tasks: [URLSessionTask] { $mutableState.tasks }
+    /// First `URLSessionTask` created on behalf of the `Request`.
+    public var firstTask: URLSessionTask? { tasks.first }
+    /// Last `URLSessionTask` crated on behalf of the `Request`.
+    public var lastTask: URLSessionTask? { tasks.last }
+    /// Current `URLSessionTask` created on behalf of the `Request`.
+    public var task: URLSessionTask? { lastTask }
+
+    // MARK: Metrics
+
+    /// All `URLSessionTaskMetrics` gathered on behalf of the `Request`. Should correspond to the `tasks` created.
+    public var allMetrics: [URLSessionTaskMetrics] { $mutableState.metrics }
+    /// First `URLSessionTaskMetrics` gathered on behalf of the `Request`.
+    public var firstMetrics: URLSessionTaskMetrics? { allMetrics.first }
+    /// Last `URLSessionTaskMetrics` gathered on behalf of the `Request`.
+    public var lastMetrics: URLSessionTaskMetrics? { allMetrics.last }
+    /// Current `URLSessionTaskMetrics` gathered on behalf of the `Request`.
+    public var metrics: URLSessionTaskMetrics? { lastMetrics }
+
+    // MARK: Retry Count
+
+    /// Number of times the `Request` has been retried.
+    public var retryCount: Int { $mutableState.retryCount }
+
+    // MARK: Error
+
+    /// `Error` returned from Alamofire internally, from the network request directly, or any validators executed.
+    public fileprivate(set) var error: AFError? {
+        get { $mutableState.error }
+        set { $mutableState.error = newValue }
+    }
+
+    /// Default initializer for the `Request` superclass.
+    ///
+    /// - Parameters:
+    ///   - id:                 `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
+    ///   - underlyingQueue:    `DispatchQueue` on which all internal `Request` work is performed.
+    ///   - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
+    ///                         `underlyingQueue`, but can be passed another queue from a `Session`.
+    ///   - eventMonitor:       `EventMonitor` called for event callbacks from internal `Request` actions.
+    ///   - interceptor:        `RequestInterceptor` used throughout the request lifecycle.
+    ///   - delegate:           `RequestDelegate` that provides an interface to actions not performed by the `Request`.
+    init(id: UUID = UUID(),
+         underlyingQueue: DispatchQueue,
+         serializationQueue: DispatchQueue,
+         eventMonitor: EventMonitor?,
+         interceptor: RequestInterceptor?,
+         delegate: RequestDelegate) {
+        self.id = id
+        self.underlyingQueue = underlyingQueue
+        self.serializationQueue = serializationQueue
+        self.eventMonitor = eventMonitor
+        self.interceptor = interceptor
+        self.delegate = delegate
+    }
+
+    // MARK: - Internal Event API
+
+    // All API must be called from underlyingQueue.
+
+    /// Called when an initial `URLRequest` has been created on behalf of the instance. If a `RequestAdapter` is active,
+    /// the `URLRequest` will be adapted before being issued.
+    ///
+    /// - Parameter request: The `URLRequest` created.
+    func didCreateInitialURLRequest(_ request: URLRequest) {
+        dispatchPrecondition(condition: .onQueue(underlyingQueue))
+
+        $mutableState.write { $0.requests.append(request) }
+
+        eventMonitor?.request(self, didCreateInitialURLRequest: request)
+    }
+
+    /// Called when initial `URLRequest` creation has failed, typically through a `URLRequestConvertible`.
+    ///
+    /// - Note: Triggers retry.
+    ///
+    /// - Parameter error: `AFError` thrown from the failed creation.
+    func didFailToCreateURLRequest(with error: AFError) {
+        dispatchPrecondition(condition: .onQueue(underlyingQueue))
+
+        self.error = error
+
+        eventMonitor?.request(self, didFailToCreateURLRequestWithError: error)
+
+        callCURLHandlerIfNecessary()
+
+        retryOrFinish(error: error)
+    }
+
+    /// Called when a `RequestAdapter` has successfully adapted a `URLRequest`.
+    ///
+    /// - Parameters:
+    ///   - initialRequest: The `URLRequest` that was adapted.
+    ///   - adaptedRequest: The `URLRequest` returned by the `RequestAdapter`.
+    func didAdaptInitialRequest(_ initialRequest: URLRequest, to adaptedRequest: URLRequest) {
+        dispatchPrecondition(condition: .onQueue(underlyingQueue))
+
+        $mutableState.write { $0.requests.append(adaptedRequest) }
+
+        eventMonitor?.request(self, didAdaptInitialRequest: initialRequest, to: adaptedRequest)
+    }
+
+    /// Called when a `RequestAdapter` fails to adapt a `URLRequest`.
+    ///
+    /// - Note: Triggers retry.
+    ///
+    /// - Parameters:
+    ///   - request: The `URLRequest` the adapter was called with.
+    ///   - error:   The `AFError` returned by the `RequestAdapter`.
+    func didFailToAdaptURLRequest(_ request: URLRequest, withError error: AFError) {
+        dispatchPrecondition(condition: .onQueue(underlyingQueue))
+
+        self.error = error
+
+        eventMonitor?.request(self, didFailToAdaptURLRequest: request, withError: error)
+
+        callCURLHandlerIfNecessary()
+
+        retryOrFinish(error: error)
+    }
+
+    /// Final `URLRequest` has been created for the instance.
+    ///
+    /// - Parameter request: The `URLRequest` created.
+    func didCreateURLRequest(_ request: URLRequest) {
+        dispatchPrecondition(condition: .onQueue(underlyingQueue))
+
+        $mutableState.read { state in
+            state.urlRequestHandler?.queue.async { state.urlRequestHandler?.handler(request) }
+        }
+
+        eventMonitor?.request(self, didCreateURLRequest: request)
+
+        callCURLHandlerIfNecessary()
+    }
+
+    /// Asynchronously calls any stored `cURLHandler` and then removes it from `mutableState`.
+    private func callCURLHandlerIfNecessary() {
+        $mutableState.write { mutableState in
+            guard let cURLHandler = mutableState.cURLHandler else { return }
+
+            cURLHandler.queue.async { cURLHandler.handler(self.cURLDescription()) }
+
+            mutableState.cURLHandler = nil
+        }
+    }
+
+    /// Called when a `URLSessionTask` is created on behalf of the instance.
+    ///
+    /// - Parameter task: The `URLSessionTask` created.
+    func didCreateTask(_ task: URLSessionTask) {
+        dispatchPrecondition(condition: .onQueue(underlyingQueue))
+
+        $mutableState.write { state in
+            state.tasks.append(task)
+
+            guard let urlSessionTaskHandler = state.urlSessionTaskHandler else { return }
+
+            urlSessionTaskHandler.queue.async { urlSessionTaskHandler.handler(task) }
+        }
+
+        eventMonitor?.request(self, didCreateTask: task)
+    }
+
+    /// Called when resumption is completed.
+    func didResume() {
+        dispatchPrecondition(condition: .onQueue(underlyingQueue))
+
+        eventMonitor?.requestDidResume(self)
+    }
+
+    /// Called when a `URLSessionTask` is resumed on behalf of the instance.
+    ///
+    /// - Parameter task: The `URLSessionTask` resumed.
+    func didResumeTask(_ task: URLSessionTask) {
+        dispatchPrecondition(condition: .onQueue(underlyingQueue))
+
+        eventMonitor?.request(self, didResumeTask: task)
+    }
+
+    /// Called when suspension is completed.
+    func didSuspend() {
+        dispatchPrecondition(condition: .onQueue(underlyingQueue))
+
+        eventMonitor?.requestDidSuspend(self)
+    }
+
+    /// Called when a `URLSessionTask` is suspended on behalf of the instance.
+    ///
+    /// - Parameter task: The `URLSessionTask` suspended.
+    func didSuspendTask(_ task: URLSessionTask) {
+        dispatchPrecondition(condition: .onQueue(underlyingQueue))
+
+        eventMonitor?.request(self, didSuspendTask: task)
+    }
+
+    /// Called when cancellation is completed, sets `error` to `AFError.explicitlyCancelled`.
+    func didCancel() {
+        dispatchPrecondition(condition: .onQueue(underlyingQueue))
+
+        error = error ?? AFError.explicitlyCancelled
+
+        eventMonitor?.requestDidCancel(self)
+    }
+
+    /// Called when a `URLSessionTask` is cancelled on behalf of the instance.
+    ///
+    /// - Parameter task: The `URLSessionTask` cancelled.
+    func didCancelTask(_ task: URLSessionTask) {
+        dispatchPrecondition(condition: .onQueue(underlyingQueue))
+
+        eventMonitor?.request(self, didCancelTask: task)
+    }
+
+    /// Called when a `URLSessionTaskMetrics` value is gathered on behalf of the instance.
+    ///
+    /// - Parameter metrics: The `URLSessionTaskMetrics` gathered.
+    func didGatherMetrics(_ metrics: URLSessionTaskMetrics) {
+        dispatchPrecondition(condition: .onQueue(underlyingQueue))
+
+        $mutableState.write { $0.metrics.append(metrics) }
+
+        eventMonitor?.request(self, didGatherMetrics: metrics)
+    }
+
+    /// Called when a `URLSessionTask` fails before it is finished, typically during certificate pinning.
+    ///
+    /// - Parameters:
+    ///   - task:  The `URLSessionTask` which failed.
+    ///   - error: The early failure `AFError`.
+    func didFailTask(_ task: URLSessionTask, earlyWithError error: AFError) {
+        dispatchPrecondition(condition: .onQueue(underlyingQueue))
+
+        self.error = error
+
+        // Task will still complete, so didCompleteTask(_:with:) will handle retry.
+        eventMonitor?.request(self, didFailTask: task, earlyWithError: error)
+    }
+
+    /// Called when a `URLSessionTask` completes. All tasks will eventually call this method.
+    ///
+    /// - Note: Response validation is synchronously triggered in this step.
+    ///
+    /// - Parameters:
+    ///   - task:  The `URLSessionTask` which completed.
+    ///   - error: The `AFError` `task` may have completed with. If `error` has already been set on the instance, this
+    ///            value is ignored.
+    func didCompleteTask(_ task: URLSessionTask, with error: AFError?) {
+        dispatchPrecondition(condition: .onQueue(underlyingQueue))
+
+        self.error = self.error ?? error
+
+        validators.forEach { $0() }
+
+        eventMonitor?.request(self, didCompleteTask: task, with: error)
+
+        retryOrFinish(error: self.error)
+    }
+
+    /// Called when the `RequestDelegate` is going to retry this `Request`. Calls `reset()`.
+    func prepareForRetry() {
+        dispatchPrecondition(condition: .onQueue(underlyingQueue))
+
+        $mutableState.write { $0.retryCount += 1 }
+
+        reset()
+
+        eventMonitor?.requestIsRetrying(self)
+    }
+
+    /// Called to determine whether retry will be triggered for the particular error, or whether the instance should
+    /// call `finish()`.
+    ///
+    /// - Parameter error: The possible `AFError` which may trigger retry.
+    func retryOrFinish(error: AFError?) {
+        dispatchPrecondition(condition: .onQueue(underlyingQueue))
+
+        guard !isCancelled, let error = error, let delegate = delegate else { finish(); return }
+
+        delegate.retryResult(for: self, dueTo: error) { retryResult in
+            switch retryResult {
+            case .doNotRetry:
+                self.finish()
+            case let .doNotRetryWithError(retryError):
+                self.finish(error: retryError.asAFError(orFailWith: "Received retryError was not already AFError"))
+            case .retry, .retryWithDelay:
+                delegate.retryRequest(self, withDelay: retryResult.delay)
+            }
+        }
+    }
+
+    /// Finishes this `Request` and starts the response serializers.
+    ///
+    /// - Parameter error: The possible `Error` with which the instance will finish.
+    func finish(error: AFError? = nil) {
+        dispatchPrecondition(condition: .onQueue(underlyingQueue))
+
+        guard !$mutableState.isFinishing else { return }
+
+        $mutableState.isFinishing = true
+
+        if let error = error { self.error = error }
+
+        // Start response handlers
+        processNextResponseSerializer()
+
+        eventMonitor?.requestDidFinish(self)
+    }
+
+    /// Appends the response serialization closure to the instance.
+    ///
+    ///  - Note: This method will also `resume` the instance if `delegate.startImmediately` returns `true`.
+    ///
+    /// - Parameter closure: The closure containing the response serialization call.
+    func appendResponseSerializer(_ closure: @escaping () -> Void) {
+        $mutableState.write { mutableState in
+            mutableState.responseSerializers.append(closure)
+
+            if mutableState.state == .finished {
+                mutableState.state = .resumed
+            }
+
+            if mutableState.responseSerializerProcessingFinished {
+                underlyingQueue.async { self.processNextResponseSerializer() }
+            }
+
+            if mutableState.state.canTransitionTo(.resumed) {
+                underlyingQueue.async { if self.delegate?.startImmediately == true { self.resume() } }
+            }
+        }
+    }
+
+    /// Returns the next response serializer closure to execute if there's one left.
+    ///
+    /// - Returns: The next response serialization closure, if there is one.
+    func nextResponseSerializer() -> (() -> Void)? {
+        var responseSerializer: (() -> Void)?
+
+        $mutableState.write { mutableState in
+            let responseSerializerIndex = mutableState.responseSerializerCompletions.count
+
+            if responseSerializerIndex < mutableState.responseSerializers.count {
+                responseSerializer = mutableState.responseSerializers[responseSerializerIndex]
+            }
+        }
+
+        return responseSerializer
+    }
+
+    /// Processes the next response serializer and calls all completions if response serialization is complete.
+    func processNextResponseSerializer() {
+        guard let responseSerializer = nextResponseSerializer() else {
+            // Execute all response serializer completions and clear them
+            var completions: [() -> Void] = []
+
+            $mutableState.write { mutableState in
+                completions = mutableState.responseSerializerCompletions
+
+                // Clear out all response serializers and response serializer completions in mutable state since the
+                // request is complete. It's important to do this prior to calling the completion closures in case
+                // the completions call back into the request triggering a re-processing of the response serializers.
+                // An example of how this can happen is by calling cancel inside a response completion closure.
+                mutableState.responseSerializers.removeAll()
+                mutableState.responseSerializerCompletions.removeAll()
+
+                if mutableState.state.canTransitionTo(.finished) {
+                    mutableState.state = .finished
+                }
+
+                mutableState.responseSerializerProcessingFinished = true
+                mutableState.isFinishing = false
+            }
+
+            completions.forEach { $0() }
+
+            // Cleanup the request
+            cleanup()
+
+            return
+        }
+
+        serializationQueue.async { responseSerializer() }
+    }
+
+    /// Notifies the `Request` that the response serializer is complete.
+    ///
+    /// - Parameter completion: The completion handler provided with the response serializer, called when all serializers
+    ///                         are complete.
+    func responseSerializerDidComplete(completion: @escaping () -> Void) {
+        $mutableState.write { $0.responseSerializerCompletions.append(completion) }
+        processNextResponseSerializer()
+    }
+
+    /// Resets all task and response serializer related state for retry.
+    func reset() {
+        error = nil
+
+        uploadProgress.totalUnitCount = 0
+        uploadProgress.completedUnitCount = 0
+        downloadProgress.totalUnitCount = 0
+        downloadProgress.completedUnitCount = 0
+
+        $mutableState.write { state in
+            state.isFinishing = false
+            state.responseSerializerCompletions = []
+        }
+    }
+
+    /// Called when updating the upload progress.
+    ///
+    /// - Parameters:
+    ///   - totalBytesSent: Total bytes sent so far.
+    ///   - totalBytesExpectedToSend: Total bytes expected to send.
+    func updateUploadProgress(totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
+        uploadProgress.totalUnitCount = totalBytesExpectedToSend
+        uploadProgress.completedUnitCount = totalBytesSent
+
+        uploadProgressHandler?.queue.async { self.uploadProgressHandler?.handler(self.uploadProgress) }
+    }
+
+    /// Perform a closure on the current `state` while locked.
+    ///
+    /// - Parameter perform: The closure to perform.
+    func withState(perform: (State) -> Void) {
+        $mutableState.withState(perform: perform)
+    }
+
+    // MARK: Task Creation
+
+    /// Called when creating a `URLSessionTask` for this `Request`. Subclasses must override.
+    ///
+    /// - Parameters:
+    ///   - request: `URLRequest` to use to create the `URLSessionTask`.
+    ///   - session: `URLSession` which creates the `URLSessionTask`.
+    ///
+    /// - Returns:   The `URLSessionTask` created.
+    func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
+        fatalError("Subclasses must override.")
+    }
+
+    // MARK: - Public API
+
+    // These APIs are callable from any queue.
+
+    // MARK: State
+
+    /// Cancels the instance. Once cancelled, a `Request` can no longer be resumed or suspended.
+    ///
+    /// - Returns: The instance.
+    @discardableResult
+    public func cancel() -> Self {
+        $mutableState.write { mutableState in
+            guard mutableState.state.canTransitionTo(.cancelled) else { return }
+
+            mutableState.state = .cancelled
+
+            underlyingQueue.async { self.didCancel() }
+
+            guard let task = mutableState.tasks.last, task.state != .completed else {
+                underlyingQueue.async { self.finish() }
+                return
+            }
+
+            // Resume to ensure metrics are gathered.
+            task.resume()
+            task.cancel()
+            underlyingQueue.async { self.didCancelTask(task) }
+        }
+
+        return self
+    }
+
+    /// Suspends the instance.
+    ///
+    /// - Returns: The instance.
+    @discardableResult
+    public func suspend() -> Self {
+        $mutableState.write { mutableState in
+            guard mutableState.state.canTransitionTo(.suspended) else { return }
+
+            mutableState.state = .suspended
+
+            underlyingQueue.async { self.didSuspend() }
+
+            guard let task = mutableState.tasks.last, task.state != .completed else { return }
+
+            task.suspend()
+            underlyingQueue.async { self.didSuspendTask(task) }
+        }
+
+        return self
+    }
+
+    /// Resumes the instance.
+    ///
+    /// - Returns: The instance.
+    @discardableResult
+    public func resume() -> Self {
+        $mutableState.write { mutableState in
+            guard mutableState.state.canTransitionTo(.resumed) else { return }
+
+            mutableState.state = .resumed
+
+            underlyingQueue.async { self.didResume() }
+
+            guard let task = mutableState.tasks.last, task.state != .completed else { return }
+
+            task.resume()
+            underlyingQueue.async { self.didResumeTask(task) }
+        }
+
+        return self
+    }
+
+    // MARK: - Closure API
+
+    /// Associates a credential using the provided values with the instance.
+    ///
+    /// - Parameters:
+    ///   - username:    The username.
+    ///   - password:    The password.
+    ///   - persistence: The `URLCredential.Persistence` for the created `URLCredential`. `.forSession` by default.
+    ///
+    /// - Returns:       The instance.
+    @discardableResult
+    public func authenticate(username: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self {
+        let credential = URLCredential(user: username, password: password, persistence: persistence)
+
+        return authenticate(with: credential)
+    }
+
+    /// Associates the provided credential with the instance.
+    ///
+    /// - Parameter credential: The `URLCredential`.
+    ///
+    /// - Returns:              The instance.
+    @discardableResult
+    public func authenticate(with credential: URLCredential) -> Self {
+        $mutableState.credential = credential
+
+        return self
+    }
+
+    /// Sets a closure to be called periodically during the lifecycle of the instance as data is read from the server.
+    ///
+    /// - Note: Only the last closure provided is used.
+    ///
+    /// - Parameters:
+    ///   - queue:   The `DispatchQueue` to execute the closure on. `.main` by default.
+    ///   - closure: The closure to be executed periodically as data is read from the server.
+    ///
+    /// - Returns:   The instance.
+    @discardableResult
+    public func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
+        $mutableState.downloadProgressHandler = (handler: closure, queue: queue)
+
+        return self
+    }
+
+    /// Sets a closure to be called periodically during the lifecycle of the instance as data is sent to the server.
+    ///
+    /// - Note: Only the last closure provided is used.
+    ///
+    /// - Parameters:
+    ///   - queue:   The `DispatchQueue` to execute the closure on. `.main` by default.
+    ///   - closure: The closure to be executed periodically as data is sent to the server.
+    ///
+    /// - Returns:   The instance.
+    @discardableResult
+    public func uploadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
+        $mutableState.uploadProgressHandler = (handler: closure, queue: queue)
+
+        return self
+    }
+
+    // MARK: Redirects
+
+    /// Sets the redirect handler for the instance which will be used if a redirect response is encountered.
+    ///
+    /// - Note: Attempting to set the redirect handler more than once is a logic error and will crash.
+    ///
+    /// - Parameter handler: The `RedirectHandler`.
+    ///
+    /// - Returns:           The instance.
+    @discardableResult
+    public func redirect(using handler: RedirectHandler) -> Self {
+        $mutableState.write { mutableState in
+            precondition(mutableState.redirectHandler == nil, "Redirect handler has already been set.")
+            mutableState.redirectHandler = handler
+        }
+
+        return self
+    }
+
+    // MARK: Cached Responses
+
+    /// Sets the cached response handler for the `Request` which will be used when attempting to cache a response.
+    ///
+    /// - Note: Attempting to set the cache handler more than once is a logic error and will crash.
+    ///
+    /// - Parameter handler: The `CachedResponseHandler`.
+    ///
+    /// - Returns:           The instance.
+    @discardableResult
+    public func cacheResponse(using handler: CachedResponseHandler) -> Self {
+        $mutableState.write { mutableState in
+            precondition(mutableState.cachedResponseHandler == nil, "Cached response handler has already been set.")
+            mutableState.cachedResponseHandler = handler
+        }
+
+        return self
+    }
+
+    // MARK: - Lifetime APIs
+
+    /// Sets a handler to be called when the cURL description of the request is available.
+    ///
+    /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called.
+    ///
+    /// - Parameters:
+    ///   - queue:   `DispatchQueue` on which `handler` will be called.
+    ///   - handler: Closure to be called when the cURL description is available.
+    ///
+    /// - Returns:           The instance.
+    @discardableResult
+    public func cURLDescription(on queue: DispatchQueue, calling handler: @escaping (String) -> Void) -> Self {
+        $mutableState.write { mutableState in
+            if mutableState.requests.last != nil {
+                queue.async { handler(self.cURLDescription()) }
+            } else {
+                mutableState.cURLHandler = (queue, handler)
+            }
+        }
+
+        return self
+    }
+
+    /// Sets a handler to be called when the cURL description of the request is available.
+    ///
+    /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called.
+    ///
+    /// - Parameter handler: Closure to be called when the cURL description is available. Called on the instance's
+    ///                      `underlyingQueue` by default.
+    ///
+    /// - Returns:           The instance.
+    @discardableResult
+    public func cURLDescription(calling handler: @escaping (String) -> Void) -> Self {
+        $mutableState.write { mutableState in
+            if mutableState.requests.last != nil {
+                underlyingQueue.async { handler(self.cURLDescription()) }
+            } else {
+                mutableState.cURLHandler = (underlyingQueue, handler)
+            }
+        }
+
+        return self
+    }
+
+    /// Sets a closure to called whenever Alamofire creates a `URLRequest` for this instance.
+    ///
+    /// - Note: This closure will be called multiple times if the instance adapts incoming `URLRequest`s or is retried.
+    ///
+    /// - Parameters:
+    ///   - queue:   `DispatchQueue` on which `handler` will be called. `.main` by default.
+    ///   - handler: Closure to be called when a `URLRequest` is available.
+    ///
+    /// - Returns:   The instance.
+    @discardableResult
+    public func onURLRequestCreation(on queue: DispatchQueue = .main, perform handler: @escaping (URLRequest) -> Void) -> Self {
+        $mutableState.write { state in
+            if let request = state.requests.last {
+                queue.async { handler(request) }
+            }
+
+            state.urlRequestHandler = (queue, handler)
+        }
+
+        return self
+    }
+
+    /// Sets a closure to be called whenever the instance creates a `URLSessionTask`.
+    ///
+    /// - Note: This API should only be used to provide `URLSessionTask`s to existing API, like `NSFileProvider`. It
+    ///         **SHOULD NOT** be used to interact with tasks directly, as that may be break Alamofire features.
+    ///         Additionally, this closure may be called multiple times if the instance is retried.
+    ///
+    /// - Parameters:
+    ///   - queue:   `DispatchQueue` on which `handler` will be called. `.main` by default.
+    ///   - handler: Closure to be called when the `URLSessionTask` is available.
+    ///
+    /// - Returns:   The instance.
+    @discardableResult
+    public func onURLSessionTaskCreation(on queue: DispatchQueue = .main, perform handler: @escaping (URLSessionTask) -> Void) -> Self {
+        $mutableState.write { state in
+            if let task = state.tasks.last {
+                queue.async { handler(task) }
+            }
+
+            state.urlSessionTaskHandler = (queue, handler)
+        }
+
+        return self
+    }
+
+    // MARK: Cleanup
+
+    /// Adds a `finishHandler` closure to be called when the request completes.
+    ///
+    /// - Parameter closure: Closure to be called when the request finishes.
+    func onFinish(perform finishHandler: @escaping () -> Void) {
+        guard !isFinished else { finishHandler(); return }
+
+        $mutableState.write { state in
+            state.finishHandlers.append(finishHandler)
+        }
+    }
+
+    /// Final cleanup step executed when the instance finishes response serialization.
+    func cleanup() {
+        delegate?.cleanup(after: self)
+        let handlers = $mutableState.finishHandlers
+        handlers.forEach { $0() }
+        $mutableState.write { state in
+            state.finishHandlers.removeAll()
+        }
+    }
+}
+
+// MARK: - Protocol Conformances
+
+extension Request: Equatable {
+    public static func ==(lhs: Request, rhs: Request) -> Bool {
+        lhs.id == rhs.id
+    }
+}
+
+extension Request: Hashable {
+    public func hash(into hasher: inout Hasher) {
+        hasher.combine(id)
+    }
+}
+
+extension Request: CustomStringConvertible {
+    /// A textual representation of this instance, including the `HTTPMethod` and `URL` if the `URLRequest` has been
+    /// created, as well as the response status code, if a response has been received.
+    public var description: String {
+        guard let request = performedRequests.last ?? lastRequest,
+              let url = request.url,
+              let method = request.httpMethod else { return "No request created yet." }
+
+        let requestDescription = "\(method) \(url.absoluteString)"
+
+        return response.map { "\(requestDescription) (\($0.statusCode))" } ?? requestDescription
+    }
+}
+
+extension Request {
+    /// cURL representation of the instance.
+    ///
+    /// - Returns: The cURL equivalent of the instance.
+    public func cURLDescription() -> String {
+        guard
+            let request = lastRequest,
+            let url = request.url,
+            let host = url.host,
+            let method = request.httpMethod else { return "$ curl command could not be created" }
+
+        var components = ["$ curl -v"]
+
+        components.append("-X \(method)")
+
+        if let credentialStorage = delegate?.sessionConfiguration.urlCredentialStorage {
+            let protectionSpace = URLProtectionSpace(host: host,
+                                                     port: url.port ?? 0,
+                                                     protocol: url.scheme,
+                                                     realm: host,
+                                                     authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
+
+            if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
+                for credential in credentials {
+                    guard let user = credential.user, let password = credential.password else { continue }
+                    components.append("-u \(user):\(password)")
+                }
+            } else {
+                if let credential = credential, let user = credential.user, let password = credential.password {
+                    components.append("-u \(user):\(password)")
+                }
+            }
+        }
+
+        if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies {
+            if
+                let cookieStorage = configuration.httpCookieStorage,
+                let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty {
+                let allCookies = cookies.map { "\($0.name)=\($0.value)" }.joined(separator: ";")
+
+                components.append("-b \"\(allCookies)\"")
+            }
+        }
+
+        var headers = HTTPHeaders()
+
+        if let sessionHeaders = delegate?.sessionConfiguration.headers {
+            for header in sessionHeaders where header.name != "Cookie" {
+                headers[header.name] = header.value
+            }
+        }
+
+        for header in request.headers where header.name != "Cookie" {
+            headers[header.name] = header.value
+        }
+
+        for header in headers {
+            let escapedValue = header.value.replacingOccurrences(of: "\"", with: "\\\"")
+            components.append("-H \"\(header.name): \(escapedValue)\"")
+        }
+
+        if let httpBodyData = request.httpBody {
+            let httpBody = String(decoding: httpBodyData, as: UTF8.self)
+            var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
+            escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
+
+            components.append("-d \"\(escapedBody)\"")
+        }
+
+        components.append("\"\(url.absoluteString)\"")
+
+        return components.joined(separator: " \\\n\t")
+    }
+}
+
+/// Protocol abstraction for `Request`'s communication back to the `SessionDelegate`.
+public protocol RequestDelegate: AnyObject {
+    /// `URLSessionConfiguration` used to create the underlying `URLSessionTask`s.
+    var sessionConfiguration: URLSessionConfiguration { get }
+
+    /// Determines whether the `Request` should automatically call `resume()` when adding the first response handler.
+    var startImmediately: Bool { get }
+
+    /// Notifies the delegate the `Request` has reached a point where it needs cleanup.
+    ///
+    /// - Parameter request: The `Request` to cleanup after.
+    func cleanup(after request: Request)
+
+    /// Asynchronously ask the delegate whether a `Request` will be retried.
+    ///
+    /// - Parameters:
+    ///   - request:    `Request` which failed.
+    ///   - error:      `Error` which produced the failure.
+    ///   - completion: Closure taking the `RetryResult` for evaluation.
+    func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void)
+
+    /// Asynchronously retry the `Request`.
+    ///
+    /// - Parameters:
+    ///   - request:   `Request` which will be retried.
+    ///   - timeDelay: `TimeInterval` after which the retry will be triggered.
+    func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?)
+}
+
+// MARK: - Subclasses
+
+// MARK: - DataRequest
+
+/// `Request` subclass which handles in-memory `Data` download using `URLSessionDataTask`.
+public class DataRequest: Request {
+    /// `URLRequestConvertible` value used to create `URLRequest`s for this instance.
+    public let convertible: URLRequestConvertible
+    /// `Data` read from the server so far.
+    public var data: Data? { mutableData }
+
+    /// Protected storage for the `Data` read by the instance.
+    @Protected
+    private var mutableData: Data? = nil
+
+    /// Creates a `DataRequest` using the provided parameters.
+    ///
+    /// - Parameters:
+    ///   - id:                 `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
+    ///   - convertible:        `URLRequestConvertible` value used to create `URLRequest`s for this instance.
+    ///   - underlyingQueue:    `DispatchQueue` on which all internal `Request` work is performed.
+    ///   - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
+    ///                         `underlyingQueue`, but can be passed another queue from a `Session`.
+    ///   - eventMonitor:       `EventMonitor` called for event callbacks from internal `Request` actions.
+    ///   - interceptor:        `RequestInterceptor` used throughout the request lifecycle.
+    ///   - delegate:           `RequestDelegate` that provides an interface to actions not performed by the `Request`.
+    init(id: UUID = UUID(),
+         convertible: URLRequestConvertible,
+         underlyingQueue: DispatchQueue,
+         serializationQueue: DispatchQueue,
+         eventMonitor: EventMonitor?,
+         interceptor: RequestInterceptor?,
+         delegate: RequestDelegate) {
+        self.convertible = convertible
+
+        super.init(id: id,
+                   underlyingQueue: underlyingQueue,
+                   serializationQueue: serializationQueue,
+                   eventMonitor: eventMonitor,
+                   interceptor: interceptor,
+                   delegate: delegate)
+    }
+
+    override func reset() {
+        super.reset()
+
+        mutableData = nil
+    }
+
+    /// Called when `Data` is received by this instance.
+    ///
+    /// - Note: Also calls `updateDownloadProgress`.
+    ///
+    /// - Parameter data: The `Data` received.
+    func didReceive(data: Data) {
+        if self.data == nil {
+            mutableData = data
+        } else {
+            $mutableData.write { $0?.append(data) }
+        }
+
+        updateDownloadProgress()
+    }
+
+    override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
+        let copiedRequest = request
+        return session.dataTask(with: copiedRequest)
+    }
+
+    /// Called to update the `downloadProgress` of the instance.
+    func updateDownloadProgress() {
+        let totalBytesReceived = Int64(data?.count ?? 0)
+        let totalBytesExpected = task?.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
+
+        downloadProgress.totalUnitCount = totalBytesExpected
+        downloadProgress.completedUnitCount = totalBytesReceived
+
+        downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
+    }
+
+    /// Validates the request, using the specified closure.
+    ///
+    /// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
+    ///
+    /// - Parameter validation: `Validation` closure used to validate the response.
+    ///
+    /// - Returns:              The instance.
+    @discardableResult
+    public func validate(_ validation: @escaping Validation) -> Self {
+        let validator: () -> Void = { [unowned self] in
+            guard self.error == nil, let response = self.response else { return }
+
+            let result = validation(self.request, response, self.data)
+
+            if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) }
+
+            self.eventMonitor?.request(self,
+                                       didValidateRequest: self.request,
+                                       response: response,
+                                       data: self.data,
+                                       withResult: result)
+        }
+
+        $validators.write { $0.append(validator) }
+
+        return self
+    }
+}
+
+// MARK: - DataStreamRequest
+
+/// `Request` subclass which streams HTTP response `Data` through a `Handler` closure.
+public final class DataStreamRequest: Request {
+    /// Closure type handling `DataStreamRequest.Stream` values.
+    public typealias Handler<Success, Failure: Error> = (Stream<Success, Failure>) throws -> Void
+
+    /// Type encapsulating an `Event` as it flows through the stream, as well as a `CancellationToken` which can be used
+    /// to stop the stream at any time.
+    public struct Stream<Success, Failure: Error> {
+        /// Latest `Event` from the stream.
+        public let event: Event<Success, Failure>
+        /// Token used to cancel the stream.
+        public let token: CancellationToken
+
+        /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`.
+        public func cancel() {
+            token.cancel()
+        }
+    }
+
+    /// Type representing an event flowing through the stream. Contains either the `Result` of processing streamed
+    /// `Data` or the completion of the stream.
+    public enum Event<Success, Failure: Error> {
+        /// Output produced every time the instance receives additional `Data`. The associated value contains the
+        /// `Result` of processing the incoming `Data`.
+        case stream(Result<Success, Failure>)
+        /// Output produced when the instance has completed, whether due to stream end, cancellation, or an error.
+        /// Associated `Completion` value contains the final state.
+        case complete(Completion)
+    }
+
+    /// Value containing the state of a `DataStreamRequest` when the stream was completed.
+    public struct Completion {
+        /// Last `URLRequest` issued by the instance.
+        public let request: URLRequest?
+        /// Last `HTTPURLResponse` received by the instance.
+        public let response: HTTPURLResponse?
+        /// Last `URLSessionTaskMetrics` produced for the instance.
+        public let metrics: URLSessionTaskMetrics?
+        /// `AFError` produced for the instance, if any.
+        public let error: AFError?
+    }
+
+    /// Type used to cancel an ongoing stream.
+    public struct CancellationToken {
+        weak var request: DataStreamRequest?
+
+        init(_ request: DataStreamRequest) {
+            self.request = request
+        }
+
+        /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`.
+        public func cancel() {
+            request?.cancel()
+        }
+    }
+
+    /// `URLRequestConvertible` value used to create `URLRequest`s for this instance.
+    public let convertible: URLRequestConvertible
+    /// Whether or not the instance will be cancelled if stream parsing encounters an error.
+    public let automaticallyCancelOnStreamError: Bool
+
+    /// Internal mutable state specific to this type.
+    struct StreamMutableState {
+        /// `OutputStream` bound to the `InputStream` produced by `asInputStream`, if it has been called.
+        var outputStream: OutputStream?
+        /// Stream closures called as `Data` is received.
+        var streams: [(_ data: Data) -> Void] = []
+        /// Number of currently executing streams. Used to ensure completions are only fired after all streams are
+        /// enqueued.
+        var numberOfExecutingStreams = 0
+        /// Completion calls enqueued while streams are still executing.
+        var enqueuedCompletionEvents: [() -> Void] = []
+    }
+
+    @Protected
+    var streamMutableState = StreamMutableState()
+
+    /// Creates a `DataStreamRequest` using the provided parameters.
+    ///
+    /// - Parameters:
+    ///   - id:                               `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()`
+    ///                                        by default.
+    ///   - convertible:                      `URLRequestConvertible` value used to create `URLRequest`s for this
+    ///                                        instance.
+    ///   - automaticallyCancelOnStreamError: `Bool` indicating whether the instance will be cancelled when an `Error`
+    ///                                       is thrown while serializing stream `Data`.
+    ///   - underlyingQueue:                  `DispatchQueue` on which all internal `Request` work is performed.
+    ///   - serializationQueue:               `DispatchQueue` on which all serialization work is performed. By default
+    ///                                       targets
+    ///                                       `underlyingQueue`, but can be passed another queue from a `Session`.
+    ///   - eventMonitor:                     `EventMonitor` called for event callbacks from internal `Request` actions.
+    ///   - interceptor:                      `RequestInterceptor` used throughout the request lifecycle.
+    ///   - delegate:                         `RequestDelegate` that provides an interface to actions not performed by
+    ///                                       the `Request`.
+    init(id: UUID = UUID(),
+         convertible: URLRequestConvertible,
+         automaticallyCancelOnStreamError: Bool,
+         underlyingQueue: DispatchQueue,
+         serializationQueue: DispatchQueue,
+         eventMonitor: EventMonitor?,
+         interceptor: RequestInterceptor?,
+         delegate: RequestDelegate) {
+        self.convertible = convertible
+        self.automaticallyCancelOnStreamError = automaticallyCancelOnStreamError
+
+        super.init(id: id,
+                   underlyingQueue: underlyingQueue,
+                   serializationQueue: serializationQueue,
+                   eventMonitor: eventMonitor,
+                   interceptor: interceptor,
+                   delegate: delegate)
+    }
+
+    override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
+        let copiedRequest = request
+        return session.dataTask(with: copiedRequest)
+    }
+
+    override func finish(error: AFError? = nil) {
+        $streamMutableState.write { state in
+            state.outputStream?.close()
+        }
+
+        super.finish(error: error)
+    }
+
+    func didReceive(data: Data) {
+        $streamMutableState.write { state in
+            #if !(os(Linux) || os(Windows))
+            if let stream = state.outputStream {
+                underlyingQueue.async {
+                    var bytes = Array(data)
+                    stream.write(&bytes, maxLength: bytes.count)
+                }
+            }
+            #endif
+            state.numberOfExecutingStreams += state.streams.count
+            let localState = state
+            underlyingQueue.async { localState.streams.forEach { $0(data) } }
+        }
+    }
+
+    /// Validates the `URLRequest` and `HTTPURLResponse` received for the instance using the provided `Validation` closure.
+    ///
+    /// - Parameter validation: `Validation` closure used to validate the request and response.
+    ///
+    /// - Returns:              The `DataStreamRequest`.
+    @discardableResult
+    public func validate(_ validation: @escaping Validation) -> Self {
+        let validator: () -> Void = { [unowned self] in
+            guard self.error == nil, let response = self.response else { return }
+
+            let result = validation(self.request, response)
+
+            if case let .failure(error) = result {
+                self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error)))
+            }
+
+            self.eventMonitor?.request(self,
+                                       didValidateRequest: self.request,
+                                       response: response,
+                                       withResult: result)
+        }
+
+        $validators.write { $0.append(validator) }
+
+        return self
+    }
+
+    #if !(os(Linux) || os(Windows))
+    /// Produces an `InputStream` that receives the `Data` received by the instance.
+    ///
+    /// - Note: The `InputStream` produced by this method must have `open()` called before being able to read `Data`.
+    ///         Additionally, this method will automatically call `resume()` on the instance, regardless of whether or
+    ///         not the creating session has `startRequestsImmediately` set to `true`.
+    ///
+    /// - Parameter bufferSize: Size, in bytes, of the buffer between the `OutputStream` and `InputStream`.
+    ///
+    /// - Returns:              The `InputStream` bound to the internal `OutboundStream`.
+    public func asInputStream(bufferSize: Int = 1024) -> InputStream? {
+        defer { resume() }
+
+        var inputStream: InputStream?
+        $streamMutableState.write { state in
+            Foundation.Stream.getBoundStreams(withBufferSize: bufferSize,
+                                              inputStream: &inputStream,
+                                              outputStream: &state.outputStream)
+            state.outputStream?.open()
+        }
+
+        return inputStream
+    }
+    #endif
+
+    func capturingError(from closure: () throws -> Void) {
+        do {
+            try closure()
+        } catch {
+            self.error = error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error)))
+            cancel()
+        }
+    }
+
+    func appendStreamCompletion<Success, Failure>(on queue: DispatchQueue,
+                                                  stream: @escaping Handler<Success, Failure>) {
+        appendResponseSerializer {
+            self.underlyingQueue.async {
+                self.responseSerializerDidComplete {
+                    self.$streamMutableState.write { state in
+                        guard state.numberOfExecutingStreams == 0 else {
+                            state.enqueuedCompletionEvents.append {
+                                self.enqueueCompletion(on: queue, stream: stream)
+                            }
+
+                            return
+                        }
+
+                        self.enqueueCompletion(on: queue, stream: stream)
+                    }
+                }
+            }
+        }
+    }
+
+    func enqueueCompletion<Success, Failure>(on queue: DispatchQueue,
+                                             stream: @escaping Handler<Success, Failure>) {
+        queue.async {
+            do {
+                let completion = Completion(request: self.request,
+                                            response: self.response,
+                                            metrics: self.metrics,
+                                            error: self.error)
+                try stream(.init(event: .complete(completion), token: .init(self)))
+            } catch {
+                // Ignore error, as errors on Completion can't be handled anyway.
+            }
+        }
+    }
+}
+
+extension DataStreamRequest.Stream {
+    /// Incoming `Result` values from `Event.stream`.
+    public var result: Result<Success, Failure>? {
+        guard case let .stream(result) = event else { return nil }
+
+        return result
+    }
+
+    /// `Success` value of the instance, if any.
+    public var value: Success? {
+        guard case let .success(value) = result else { return nil }
+
+        return value
+    }
+
+    /// `Failure` value of the instance, if any.
+    public var error: Failure? {
+        guard case let .failure(error) = result else { return nil }
+
+        return error
+    }
+
+    /// `Completion` value of the instance, if any.
+    public var completion: DataStreamRequest.Completion? {
+        guard case let .complete(completion) = event else { return nil }
+
+        return completion
+    }
+}
+
+// MARK: - DownloadRequest
+
+/// `Request` subclass which downloads `Data` to a file on disk using `URLSessionDownloadTask`.
+public class DownloadRequest: Request {
+    /// A set of options to be executed prior to moving a downloaded file from the temporary `URL` to the destination
+    /// `URL`.
+    public struct Options: OptionSet {
+        /// Specifies that intermediate directories for the destination URL should be created.
+        public static let createIntermediateDirectories = Options(rawValue: 1 << 0)
+        /// Specifies that any previous file at the destination `URL` should be removed.
+        public static let removePreviousFile = Options(rawValue: 1 << 1)
+
+        public let rawValue: Int
+
+        public init(rawValue: Int) {
+            self.rawValue = rawValue
+        }
+    }
+
+    // MARK: Destination
+
+    /// A closure executed once a `DownloadRequest` has successfully completed in order to determine where to move the
+    /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
+    /// and the `HTTPURLResponse`, and returns two values: the file URL where the temporary file should be moved and
+    /// the options defining how the file should be moved.
+    ///
+    /// - Note: Downloads from a local `file://` `URL`s do not use the `Destination` closure, as those downloads do not
+    ///         return an `HTTPURLResponse`. Instead the file is merely moved within the temporary directory.
+    public typealias Destination = (_ temporaryURL: URL,
+                                    _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options)
+
+    /// Creates a download file destination closure which uses the default file manager to move the temporary file to a
+    /// file URL in the first available directory with the specified search path directory and search path domain mask.
+    ///
+    /// - Parameters:
+    ///   - directory: The search path directory. `.documentDirectory` by default.
+    ///   - domain:    The search path domain mask. `.userDomainMask` by default.
+    ///   - options:   `DownloadRequest.Options` used when moving the downloaded file to its destination. None by
+    ///                default.
+    /// - Returns: The `Destination` closure.
+    public class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory,
+                                                   in domain: FileManager.SearchPathDomainMask = .userDomainMask,
+                                                   options: Options = []) -> Destination {
+        { temporaryURL, response in
+            let directoryURLs = FileManager.default.urls(for: directory, in: domain)
+            let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL
+
+            return (url, options)
+        }
+    }
+
+    /// Default `Destination` used by Alamofire to ensure all downloads persist. This `Destination` prepends
+    /// `Alamofire_` to the automatically generated download name and moves it within the temporary directory. Files
+    /// with this destination must be additionally moved if they should survive the system reclamation of temporary
+    /// space.
+    static let defaultDestination: Destination = { url, _ in
+        (defaultDestinationURL(url), [])
+    }
+
+    /// Default `URL` creation closure. Creates a `URL` in the temporary directory with `Alamofire_` prepended to the
+    /// provided file name.
+    static let defaultDestinationURL: (URL) -> URL = { url in
+        let filename = "Alamofire_\(url.lastPathComponent)"
+        let destination = url.deletingLastPathComponent().appendingPathComponent(filename)
+
+        return destination
+    }
+
+    // MARK: Downloadable
+
+    /// Type describing the source used to create the underlying `URLSessionDownloadTask`.
+    public enum Downloadable {
+        /// Download should be started from the `URLRequest` produced by the associated `URLRequestConvertible` value.
+        case request(URLRequestConvertible)
+        /// Download should be started from the associated resume `Data` value.
+        case resumeData(Data)
+    }
+
+    // MARK: Mutable State
+
+    /// Type containing all mutable state for `DownloadRequest` instances.
+    private struct DownloadRequestMutableState {
+        /// Possible resume `Data` produced when cancelling the instance.
+        var resumeData: Data?
+        /// `URL` to which `Data` is being downloaded.
+        var fileURL: URL?
+    }
+
+    /// Protected mutable state specific to `DownloadRequest`.
+    @Protected
+    private var mutableDownloadState = DownloadRequestMutableState()
+
+    /// If the download is resumable and is eventually cancelled or fails, this value may be used to resume the download
+    /// using the `download(resumingWith data:)` API.
+    ///
+    /// - Note: For more information about `resumeData`, see [Apple's documentation](https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel).
+    public var resumeData: Data? {
+        #if !(os(Linux) || os(Windows))
+        return $mutableDownloadState.resumeData ?? error?.downloadResumeData
+        #else
+        return $mutableDownloadState.resumeData
+        #endif
+    }
+
+    /// If the download is successful, the `URL` where the file was downloaded.
+    public var fileURL: URL? { $mutableDownloadState.fileURL }
+
+    // MARK: Initial State
+
+    /// `Downloadable` value used for this instance.
+    public let downloadable: Downloadable
+    /// The `Destination` to which the downloaded file is moved.
+    let destination: Destination
+
+    /// Creates a `DownloadRequest` using the provided parameters.
+    ///
+    /// - Parameters:
+    ///   - id:                 `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
+    ///   - downloadable:       `Downloadable` value used to create `URLSessionDownloadTasks` for the instance.
+    ///   - underlyingQueue:    `DispatchQueue` on which all internal `Request` work is performed.
+    ///   - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
+    ///                         `underlyingQueue`, but can be passed another queue from a `Session`.
+    ///   - eventMonitor:       `EventMonitor` called for event callbacks from internal `Request` actions.
+    ///   - interceptor:        `RequestInterceptor` used throughout the request lifecycle.
+    ///   - delegate:           `RequestDelegate` that provides an interface to actions not performed by the `Request`
+    ///   - destination:        `Destination` closure used to move the downloaded file to its final location.
+    init(id: UUID = UUID(),
+         downloadable: Downloadable,
+         underlyingQueue: DispatchQueue,
+         serializationQueue: DispatchQueue,
+         eventMonitor: EventMonitor?,
+         interceptor: RequestInterceptor?,
+         delegate: RequestDelegate,
+         destination: @escaping Destination) {
+        self.downloadable = downloadable
+        self.destination = destination
+
+        super.init(id: id,
+                   underlyingQueue: underlyingQueue,
+                   serializationQueue: serializationQueue,
+                   eventMonitor: eventMonitor,
+                   interceptor: interceptor,
+                   delegate: delegate)
+    }
+
+    override func reset() {
+        super.reset()
+
+        $mutableDownloadState.write {
+            $0.resumeData = nil
+            $0.fileURL = nil
+        }
+    }
+
+    /// Called when a download has finished.
+    ///
+    /// - Parameters:
+    ///   - task:   `URLSessionTask` that finished the download.
+    ///   - result: `Result` of the automatic move to `destination`.
+    func didFinishDownloading(using task: URLSessionTask, with result: Result<URL, AFError>) {
+        eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result)
+
+        switch result {
+        case let .success(url): $mutableDownloadState.fileURL = url
+        case let .failure(error): self.error = error
+        }
+    }
+
+    /// Updates the `downloadProgress` using the provided values.
+    ///
+    /// - Parameters:
+    ///   - bytesWritten:              Total bytes written so far.
+    ///   - totalBytesExpectedToWrite: Total bytes expected to write.
+    func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
+        downloadProgress.totalUnitCount = totalBytesExpectedToWrite
+        downloadProgress.completedUnitCount += bytesWritten
+
+        downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
+    }
+
+    override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
+        session.downloadTask(with: request)
+    }
+
+    /// Creates a `URLSessionTask` from the provided resume data.
+    ///
+    /// - Parameters:
+    ///   - data:    `Data` used to resume the download.
+    ///   - session: `URLSession` used to create the `URLSessionTask`.
+    ///
+    /// - Returns:   The `URLSessionTask` created.
+    public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask {
+        session.downloadTask(withResumeData: data)
+    }
+
+    /// Cancels the instance. Once cancelled, a `DownloadRequest` can no longer be resumed or suspended.
+    ///
+    /// - Note: This method will NOT produce resume data. If you wish to cancel and produce resume data, use
+    ///         `cancel(producingResumeData:)` or `cancel(byProducingResumeData:)`.
+    ///
+    /// - Returns: The instance.
+    @discardableResult
+    override public func cancel() -> Self {
+        cancel(producingResumeData: false)
+    }
+
+    /// Cancels the instance, optionally producing resume data. Once cancelled, a `DownloadRequest` can no longer be
+    /// resumed or suspended.
+    ///
+    /// - Note: If `producingResumeData` is `true`, the `resumeData` property will be populated with any resume data, if
+    ///         available.
+    ///
+    /// - Returns: The instance.
+    @discardableResult
+    public func cancel(producingResumeData shouldProduceResumeData: Bool) -> Self {
+        cancel(optionallyProducingResumeData: shouldProduceResumeData ? { _ in } : nil)
+    }
+
+    /// Cancels the instance while producing resume data. Once cancelled, a `DownloadRequest` can no longer be resumed
+    /// or suspended.
+    ///
+    /// - Note: The resume data passed to the completion handler will also be available on the instance's `resumeData`
+    ///         property.
+    ///
+    /// - Parameter completionHandler: The completion handler that is called when the download has been successfully
+    ///                                cancelled. It is not guaranteed to be called on a particular queue, so you may
+    ///                                want use an appropriate queue to perform your work.
+    ///
+    /// - Returns:                     The instance.
+    @discardableResult
+    public func cancel(byProducingResumeData completionHandler: @escaping (_ data: Data?) -> Void) -> Self {
+        cancel(optionallyProducingResumeData: completionHandler)
+    }
+
+    /// Internal implementation of cancellation that optionally takes a resume data handler. If no handler is passed,
+    /// cancellation is performed without producing resume data.
+    ///
+    /// - Parameter completionHandler: Optional resume data handler.
+    ///
+    /// - Returns:                     The instance.
+    private func cancel(optionallyProducingResumeData completionHandler: ((_ resumeData: Data?) -> Void)?) -> Self {
+        $mutableState.write { mutableState in
+            guard mutableState.state.canTransitionTo(.cancelled) else { return }
+
+            mutableState.state = .cancelled
+
+            underlyingQueue.async { self.didCancel() }
+
+            guard let task = mutableState.tasks.last as? URLSessionDownloadTask, task.state != .completed else {
+                underlyingQueue.async { self.finish() }
+                return
+            }
+
+            if let completionHandler = completionHandler {
+                // Resume to ensure metrics are gathered.
+                task.resume()
+                task.cancel { resumeData in
+                    self.$mutableDownloadState.resumeData = resumeData
+                    self.underlyingQueue.async { self.didCancelTask(task) }
+                    completionHandler(resumeData)
+                }
+            } else {
+                // Resume to ensure metrics are gathered.
+                task.resume()
+                task.cancel()
+                self.underlyingQueue.async { self.didCancelTask(task) }
+            }
+        }
+
+        return self
+    }
+
+    /// Validates the request, using the specified closure.
+    ///
+    /// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
+    ///
+    /// - Parameter validation: `Validation` closure to validate the response.
+    ///
+    /// - Returns:              The instance.
+    @discardableResult
+    public func validate(_ validation: @escaping Validation) -> Self {
+        let validator: () -> Void = { [unowned self] in
+            guard self.error == nil, let response = self.response else { return }
+
+            let result = validation(self.request, response, self.fileURL)
+
+            if case let .failure(error) = result {
+                self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error)))
+            }
+
+            self.eventMonitor?.request(self,
+                                       didValidateRequest: self.request,
+                                       response: response,
+                                       fileURL: self.fileURL,
+                                       withResult: result)
+        }
+
+        $validators.write { $0.append(validator) }
+
+        return self
+    }
+}
+
+// MARK: - UploadRequest
+
+/// `DataRequest` subclass which handles `Data` upload from memory, file, or stream using `URLSessionUploadTask`.
+public class UploadRequest: DataRequest {
+    /// Type describing the origin of the upload, whether `Data`, file, or stream.
+    public enum Uploadable {
+        /// Upload from the provided `Data` value.
+        case data(Data)
+        /// Upload from the provided file `URL`, as well as a `Bool` determining whether the source file should be
+        /// automatically removed once uploaded.
+        case file(URL, shouldRemove: Bool)
+        /// Upload from the provided `InputStream`.
+        case stream(InputStream)
+    }
+
+    // MARK: Initial State
+
+    /// The `UploadableConvertible` value used to produce the `Uploadable` value for this instance.
+    public let upload: UploadableConvertible
+
+    /// `FileManager` used to perform cleanup tasks, including the removal of multipart form encoded payloads written
+    /// to disk.
+    public let fileManager: FileManager
+
+    // MARK: Mutable State
+
+    /// `Uploadable` value used by the instance.
+    public var uploadable: Uploadable?
+
+    /// Creates an `UploadRequest` using the provided parameters.
+    ///
+    /// - Parameters:
+    ///   - id:                 `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
+    ///   - convertible:        `UploadConvertible` value used to determine the type of upload to be performed.
+    ///   - underlyingQueue:    `DispatchQueue` on which all internal `Request` work is performed.
+    ///   - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
+    ///                         `underlyingQueue`, but can be passed another queue from a `Session`.
+    ///   - eventMonitor:       `EventMonitor` called for event callbacks from internal `Request` actions.
+    ///   - interceptor:        `RequestInterceptor` used throughout the request lifecycle.
+    ///   - fileManager:        `FileManager` used to perform cleanup tasks, including the removal of multipart form
+    ///                         encoded payloads written to disk.
+    ///   - delegate:           `RequestDelegate` that provides an interface to actions not performed by the `Request`.
+    init(id: UUID = UUID(),
+         convertible: UploadConvertible,
+         underlyingQueue: DispatchQueue,
+         serializationQueue: DispatchQueue,
+         eventMonitor: EventMonitor?,
+         interceptor: RequestInterceptor?,
+         fileManager: FileManager,
+         delegate: RequestDelegate) {
+        upload = convertible
+        self.fileManager = fileManager
+
+        super.init(id: id,
+                   convertible: convertible,
+                   underlyingQueue: underlyingQueue,
+                   serializationQueue: serializationQueue,
+                   eventMonitor: eventMonitor,
+                   interceptor: interceptor,
+                   delegate: delegate)
+    }
+
+    /// Called when the `Uploadable` value has been created from the `UploadConvertible`.
+    ///
+    /// - Parameter uploadable: The `Uploadable` that was created.
+    func didCreateUploadable(_ uploadable: Uploadable) {
+        self.uploadable = uploadable
+
+        eventMonitor?.request(self, didCreateUploadable: uploadable)
+    }
+
+    /// Called when the `Uploadable` value could not be created.
+    ///
+    /// - Parameter error: `AFError` produced by the failure.
+    func didFailToCreateUploadable(with error: AFError) {
+        self.error = error
+
+        eventMonitor?.request(self, didFailToCreateUploadableWithError: error)
+
+        retryOrFinish(error: error)
+    }
+
+    override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
+        guard let uploadable = uploadable else {
+            fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.")
+        }
+
+        switch uploadable {
+        case let .data(data): return session.uploadTask(with: request, from: data)
+        case let .file(url, _): return session.uploadTask(with: request, fromFile: url)
+        case .stream: return session.uploadTask(withStreamedRequest: request)
+        }
+    }
+
+    override func reset() {
+        // Uploadable must be recreated on every retry.
+        uploadable = nil
+
+        super.reset()
+    }
+
+    /// Produces the `InputStream` from `uploadable`, if it can.
+    ///
+    /// - Note: Calling this method with a non-`.stream` `Uploadable` is a logic error and will crash.
+    ///
+    /// - Returns: The `InputStream`.
+    func inputStream() -> InputStream {
+        guard let uploadable = uploadable else {
+            fatalError("Attempting to access the input stream but the uploadable doesn't exist.")
+        }
+
+        guard case let .stream(stream) = uploadable else {
+            fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.")
+        }
+
+        eventMonitor?.request(self, didProvideInputStream: stream)
+
+        return stream
+    }
+
+    override public func cleanup() {
+        defer { super.cleanup() }
+
+        guard
+            let uploadable = uploadable,
+            case let .file(url, shouldRemove) = uploadable,
+            shouldRemove
+        else { return }
+
+        try? fileManager.removeItem(at: url)
+    }
+}
+
+/// A type that can produce an `UploadRequest.Uploadable` value.
+public protocol UploadableConvertible {
+    /// Produces an `UploadRequest.Uploadable` value from the instance.
+    ///
+    /// - Returns: The `UploadRequest.Uploadable`.
+    /// - Throws:  Any `Error` produced during creation.
+    func createUploadable() throws -> UploadRequest.Uploadable
+}
+
+extension UploadRequest.Uploadable: UploadableConvertible {
+    public func createUploadable() throws -> UploadRequest.Uploadable {
+        self
+    }
+}
+
+/// A type that can be converted to an upload, whether from an `UploadRequest.Uploadable` or `URLRequestConvertible`.
+public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible {}

+ 357 - 0
Pods/Alamofire/Source/RequestInterceptor.swift

@@ -0,0 +1,357 @@
+//
+//  RequestInterceptor.swift
+//
+//  Copyright (c) 2019 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
+
+/// Stores all state associated with a `URLRequest` being adapted.
+public struct RequestAdapterState {
+    /// The `UUID` of the `Request` associated with the `URLRequest` to adapt.
+    public let requestID: UUID
+
+    /// The `Session` associated with the `URLRequest` to adapt.
+    public let session: Session
+}
+
+// MARK: -
+
+/// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary.
+public protocol RequestAdapter {
+    /// Inspects and adapts the specified `URLRequest` in some manner and calls the completion handler with the Result.
+    ///
+    /// - Parameters:
+    ///   - urlRequest: The `URLRequest` to adapt.
+    ///   - session:    The `Session` that will execute the `URLRequest`.
+    ///   - completion: The completion handler that must be called when adaptation is complete.
+    func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void)
+
+    /// Inspects and adapts the specified `URLRequest` in some manner and calls the completion handler with the Result.
+    ///
+    /// - Parameters:
+    ///   - urlRequest: The `URLRequest` to adapt.
+    ///   - state:      The `RequestAdapterState` associated with the `URLRequest`.
+    ///   - completion: The completion handler that must be called when adaptation is complete.
+    func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping (Result<URLRequest, Error>) -> Void)
+}
+
+extension RequestAdapter {
+    public func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping (Result<URLRequest, Error>) -> Void) {
+        adapt(urlRequest, for: state.session, completion: completion)
+    }
+}
+
+// MARK: -
+
+/// Outcome of determination whether retry is necessary.
+public enum RetryResult {
+    /// Retry should be attempted immediately.
+    case retry
+    /// Retry should be attempted after the associated `TimeInterval`.
+    case retryWithDelay(TimeInterval)
+    /// Do not retry.
+    case doNotRetry
+    /// Do not retry due to the associated `Error`.
+    case doNotRetryWithError(Error)
+}
+
+extension RetryResult {
+    var retryRequired: Bool {
+        switch self {
+        case .retry, .retryWithDelay: return true
+        default: return false
+        }
+    }
+
+    var delay: TimeInterval? {
+        switch self {
+        case let .retryWithDelay(delay): return delay
+        default: return nil
+        }
+    }
+
+    var error: Error? {
+        guard case let .doNotRetryWithError(error) = self else { return nil }
+        return error
+    }
+}
+
+/// A type that determines whether a request should be retried after being executed by the specified session manager
+/// and encountering an error.
+public protocol RequestRetrier {
+    /// Determines whether the `Request` should be retried by calling the `completion` closure.
+    ///
+    /// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs
+    /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly
+    /// cleaned up after.
+    ///
+    /// - Parameters:
+    ///   - request:    `Request` that failed due to the provided `Error`.
+    ///   - session:    `Session` that produced the `Request`.
+    ///   - error:      `Error` encountered while executing the `Request`.
+    ///   - completion: Completion closure to be executed when a retry decision has been determined.
+    func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void)
+}
+
+// MARK: -
+
+/// Type that provides both `RequestAdapter` and `RequestRetrier` functionality.
+public protocol RequestInterceptor: RequestAdapter, RequestRetrier {}
+
+extension RequestInterceptor {
+    public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
+        completion(.success(urlRequest))
+    }
+
+    public func retry(_ request: Request,
+                      for session: Session,
+                      dueTo error: Error,
+                      completion: @escaping (RetryResult) -> Void) {
+        completion(.doNotRetry)
+    }
+}
+
+/// `RequestAdapter` closure definition.
+public typealias AdaptHandler = (URLRequest, Session, _ completion: @escaping (Result<URLRequest, Error>) -> Void) -> Void
+/// `RequestRetrier` closure definition.
+public typealias RetryHandler = (Request, Session, Error, _ completion: @escaping (RetryResult) -> Void) -> Void
+
+// MARK: -
+
+/// Closure-based `RequestAdapter`.
+open class Adapter: RequestInterceptor {
+    private let adaptHandler: AdaptHandler
+
+    /// Creates an instance using the provided closure.
+    ///
+    /// - Parameter adaptHandler: `AdaptHandler` closure to be executed when handling request adaptation.
+    public init(_ adaptHandler: @escaping AdaptHandler) {
+        self.adaptHandler = adaptHandler
+    }
+
+    open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
+        adaptHandler(urlRequest, session, completion)
+    }
+
+    open func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping (Result<URLRequest, Error>) -> Void) {
+        adaptHandler(urlRequest, state.session, completion)
+    }
+}
+
+#if swift(>=5.5)
+extension RequestAdapter where Self == Adapter {
+    /// Creates an `Adapter` using the provided `AdaptHandler` closure.
+    ///
+    /// - Parameter closure: `AdaptHandler` to use to adapt the request.
+    /// - Returns:           The `Adapter`.
+    public static func adapter(using closure: @escaping AdaptHandler) -> Adapter {
+        Adapter(closure)
+    }
+}
+#endif
+
+// MARK: -
+
+/// Closure-based `RequestRetrier`.
+open class Retrier: RequestInterceptor {
+    private let retryHandler: RetryHandler
+
+    /// Creates an instance using the provided closure.
+    ///
+    /// - Parameter retryHandler: `RetryHandler` closure to be executed when handling request retry.
+    public init(_ retryHandler: @escaping RetryHandler) {
+        self.retryHandler = retryHandler
+    }
+
+    open func retry(_ request: Request,
+                    for session: Session,
+                    dueTo error: Error,
+                    completion: @escaping (RetryResult) -> Void) {
+        retryHandler(request, session, error, completion)
+    }
+}
+
+#if swift(>=5.5)
+extension RequestRetrier where Self == Retrier {
+    /// Creates a `Retrier` using the provided `RetryHandler` closure.
+    ///
+    /// - Parameter closure: `RetryHandler` to use to retry the request.
+    /// - Returns:           The `Retrier`.
+    public static func retrier(using closure: @escaping RetryHandler) -> Retrier {
+        Retrier(closure)
+    }
+}
+#endif
+
+// MARK: -
+
+/// `RequestInterceptor` which can use multiple `RequestAdapter` and `RequestRetrier` values.
+open class Interceptor: RequestInterceptor {
+    /// All `RequestAdapter`s associated with the instance. These adapters will be run until one fails.
+    public let adapters: [RequestAdapter]
+    /// All `RequestRetrier`s associated with the instance. These retriers will be run one at a time until one triggers retry.
+    public let retriers: [RequestRetrier]
+
+    /// Creates an instance from `AdaptHandler` and `RetryHandler` closures.
+    ///
+    /// - Parameters:
+    ///   - adaptHandler: `AdaptHandler` closure to be used.
+    ///   - retryHandler: `RetryHandler` closure to be used.
+    public init(adaptHandler: @escaping AdaptHandler, retryHandler: @escaping RetryHandler) {
+        adapters = [Adapter(adaptHandler)]
+        retriers = [Retrier(retryHandler)]
+    }
+
+    /// Creates an instance from `RequestAdapter` and `RequestRetrier` values.
+    ///
+    /// - Parameters:
+    ///   - adapter: `RequestAdapter` value to be used.
+    ///   - retrier: `RequestRetrier` value to be used.
+    public init(adapter: RequestAdapter, retrier: RequestRetrier) {
+        adapters = [adapter]
+        retriers = [retrier]
+    }
+
+    /// Creates an instance from the arrays of `RequestAdapter` and `RequestRetrier` values.
+    ///
+    /// - Parameters:
+    ///   - adapters:     `RequestAdapter` values to be used.
+    ///   - retriers:     `RequestRetrier` values to be used.
+    ///   - interceptors: `RequestInterceptor`s to be used.
+    public init(adapters: [RequestAdapter] = [], retriers: [RequestRetrier] = [], interceptors: [RequestInterceptor] = []) {
+        self.adapters = adapters + interceptors
+        self.retriers = retriers + interceptors
+    }
+
+    open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
+        adapt(urlRequest, for: session, using: adapters, completion: completion)
+    }
+
+    private func adapt(_ urlRequest: URLRequest,
+                       for session: Session,
+                       using adapters: [RequestAdapter],
+                       completion: @escaping (Result<URLRequest, Error>) -> Void) {
+        var pendingAdapters = adapters
+
+        guard !pendingAdapters.isEmpty else { completion(.success(urlRequest)); return }
+
+        let adapter = pendingAdapters.removeFirst()
+
+        adapter.adapt(urlRequest, for: session) { result in
+            switch result {
+            case let .success(urlRequest):
+                self.adapt(urlRequest, for: session, using: pendingAdapters, completion: completion)
+            case .failure:
+                completion(result)
+            }
+        }
+    }
+
+    open func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping (Result<URLRequest, Error>) -> Void) {
+        adapt(urlRequest, using: state, adapters: adapters, completion: completion)
+    }
+
+    private func adapt(_ urlRequest: URLRequest,
+                       using state: RequestAdapterState,
+                       adapters: [RequestAdapter],
+                       completion: @escaping (Result<URLRequest, Error>) -> Void) {
+        var pendingAdapters = adapters
+
+        guard !pendingAdapters.isEmpty else { completion(.success(urlRequest)); return }
+
+        let adapter = pendingAdapters.removeFirst()
+
+        adapter.adapt(urlRequest, using: state) { result in
+            switch result {
+            case let .success(urlRequest):
+                self.adapt(urlRequest, using: state, adapters: pendingAdapters, completion: completion)
+            case .failure:
+                completion(result)
+            }
+        }
+    }
+
+    open func retry(_ request: Request,
+                    for session: Session,
+                    dueTo error: Error,
+                    completion: @escaping (RetryResult) -> Void) {
+        retry(request, for: session, dueTo: error, using: retriers, completion: completion)
+    }
+
+    private func retry(_ request: Request,
+                       for session: Session,
+                       dueTo error: Error,
+                       using retriers: [RequestRetrier],
+                       completion: @escaping (RetryResult) -> Void) {
+        var pendingRetriers = retriers
+
+        guard !pendingRetriers.isEmpty else { completion(.doNotRetry); return }
+
+        let retrier = pendingRetriers.removeFirst()
+
+        retrier.retry(request, for: session, dueTo: error) { result in
+            switch result {
+            case .retry, .retryWithDelay, .doNotRetryWithError:
+                completion(result)
+            case .doNotRetry:
+                // Only continue to the next retrier if retry was not triggered and no error was encountered
+                self.retry(request, for: session, dueTo: error, using: pendingRetriers, completion: completion)
+            }
+        }
+    }
+}
+
+#if swift(>=5.5)
+extension RequestInterceptor where Self == Interceptor {
+    /// Creates an `Interceptor` using the provided `AdaptHandler` and `RetryHandler` closures.
+    ///
+    /// - Parameters:
+    ///   - adapter: `AdapterHandler`to use to adapt the request.
+    ///   - retrier: `RetryHandler` to use to retry the request.
+    /// - Returns:   The `Interceptor`.
+    public static func interceptor(adapter: @escaping AdaptHandler, retrier: @escaping RetryHandler) -> Interceptor {
+        Interceptor(adaptHandler: adapter, retryHandler: retrier)
+    }
+
+    /// Creates an `Interceptor` using the provided `RequestAdapter` and `RequestRetrier` instances.
+    /// - Parameters:
+    ///   - adapter: `RequestAdapter` to use to adapt the request
+    ///   - retrier: `RequestRetrier` to use to retry the request.
+    /// - Returns:   The `Interceptor`.
+    public static func interceptor(adapter: RequestAdapter, retrier: RequestRetrier) -> Interceptor {
+        Interceptor(adapter: adapter, retrier: retrier)
+    }
+
+    /// Creates an `Interceptor` using the provided `RequestAdapter`s, `RequestRetrier`s, and `RequestInterceptor`s.
+    /// - Parameters:
+    ///   - adapters:     `RequestAdapter`s to use to adapt the request. These adapters will be run until one fails.
+    ///   - retriers:     `RequestRetrier`s to use to retry the request. These retriers will be run one at a time until
+    ///                   a retry is triggered.
+    ///   - interceptors: `RequestInterceptor`s to use to intercept the request.
+    /// - Returns:        The `Interceptor`.
+    public static func interceptor(adapters: [RequestAdapter] = [],
+                                   retriers: [RequestRetrier] = [],
+                                   interceptors: [RequestInterceptor] = []) -> Interceptor {
+        Interceptor(adapters: adapters, retriers: retriers, interceptors: interceptors)
+    }
+}
+#endif

+ 149 - 0
Pods/Alamofire/Source/RequestTaskMap.swift

@@ -0,0 +1,149 @@
+//
+//  RequestTaskMap.swift
+//
+//  Copyright (c) 2014-2018 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
+
+/// A type that maintains a two way, one to one map of `URLSessionTask`s to `Request`s.
+struct RequestTaskMap {
+    private typealias Events = (completed: Bool, metricsGathered: Bool)
+
+    private var tasksToRequests: [URLSessionTask: Request]
+    private var requestsToTasks: [Request: URLSessionTask]
+    private var taskEvents: [URLSessionTask: Events]
+
+    var requests: [Request] {
+        Array(tasksToRequests.values)
+    }
+
+    init(tasksToRequests: [URLSessionTask: Request] = [:],
+         requestsToTasks: [Request: URLSessionTask] = [:],
+         taskEvents: [URLSessionTask: (completed: Bool, metricsGathered: Bool)] = [:]) {
+        self.tasksToRequests = tasksToRequests
+        self.requestsToTasks = requestsToTasks
+        self.taskEvents = taskEvents
+    }
+
+    subscript(_ request: Request) -> URLSessionTask? {
+        get { requestsToTasks[request] }
+        set {
+            guard let newValue = newValue else {
+                guard let task = requestsToTasks[request] else {
+                    fatalError("RequestTaskMap consistency error: no task corresponding to request found.")
+                }
+
+                requestsToTasks.removeValue(forKey: request)
+                tasksToRequests.removeValue(forKey: task)
+                taskEvents.removeValue(forKey: task)
+
+                return
+            }
+
+            requestsToTasks[request] = newValue
+            tasksToRequests[newValue] = request
+            taskEvents[newValue] = (completed: false, metricsGathered: false)
+        }
+    }
+
+    subscript(_ task: URLSessionTask) -> Request? {
+        get { tasksToRequests[task] }
+        set {
+            guard let newValue = newValue else {
+                guard let request = tasksToRequests[task] else {
+                    fatalError("RequestTaskMap consistency error: no request corresponding to task found.")
+                }
+
+                tasksToRequests.removeValue(forKey: task)
+                requestsToTasks.removeValue(forKey: request)
+                taskEvents.removeValue(forKey: task)
+
+                return
+            }
+
+            tasksToRequests[task] = newValue
+            requestsToTasks[newValue] = task
+            taskEvents[task] = (completed: false, metricsGathered: false)
+        }
+    }
+
+    var count: Int {
+        precondition(tasksToRequests.count == requestsToTasks.count,
+                     "RequestTaskMap.count invalid, requests.count: \(tasksToRequests.count) != tasks.count: \(requestsToTasks.count)")
+
+        return tasksToRequests.count
+    }
+
+    var eventCount: Int {
+        precondition(taskEvents.count == count, "RequestTaskMap.eventCount invalid, count: \(count) != taskEvents.count: \(taskEvents.count)")
+
+        return taskEvents.count
+    }
+
+    var isEmpty: Bool {
+        precondition(tasksToRequests.isEmpty == requestsToTasks.isEmpty,
+                     "RequestTaskMap.isEmpty invalid, requests.isEmpty: \(tasksToRequests.isEmpty) != tasks.isEmpty: \(requestsToTasks.isEmpty)")
+
+        return tasksToRequests.isEmpty
+    }
+
+    var isEventsEmpty: Bool {
+        precondition(taskEvents.isEmpty == isEmpty, "RequestTaskMap.isEventsEmpty invalid, isEmpty: \(isEmpty) != taskEvents.isEmpty: \(taskEvents.isEmpty)")
+
+        return taskEvents.isEmpty
+    }
+
+    mutating func disassociateIfNecessaryAfterGatheringMetricsForTask(_ task: URLSessionTask) -> Bool {
+        guard let events = taskEvents[task] else {
+            fatalError("RequestTaskMap consistency error: no events corresponding to task found.")
+        }
+
+        switch (events.completed, events.metricsGathered) {
+        case (_, true): fatalError("RequestTaskMap consistency error: duplicate metricsGatheredForTask call.")
+        case (false, false): taskEvents[task] = (completed: false, metricsGathered: true); return false
+        case (true, false): self[task] = nil; return true
+        }
+    }
+
+    mutating func disassociateIfNecessaryAfterCompletingTask(_ task: URLSessionTask) -> Bool {
+        guard let events = taskEvents[task] else {
+            fatalError("RequestTaskMap consistency error: no events corresponding to task found.")
+        }
+
+        switch (events.completed, events.metricsGathered) {
+        case (true, _): fatalError("RequestTaskMap consistency error: duplicate completionReceivedForTask call.")
+        #if os(Linux) // Linux doesn't gather metrics, so unconditionally remove the reference and return true.
+        default: self[task] = nil; return true
+        #else
+        case (false, false):
+            if #available(macOS 10.12, iOS 10, watchOS 7, tvOS 10, *) {
+                taskEvents[task] = (completed: true, metricsGathered: false); return false
+            } else {
+                // watchOS < 7 doesn't gather metrics, so unconditionally remove the reference and return true.
+                self[task] = nil; return true
+            }
+        case (false, true):
+            self[task] = nil; return true
+        #endif
+        }
+    }
+}

+ 453 - 0
Pods/Alamofire/Source/Response.swift

@@ -0,0 +1,453 @@
+//
+//  Response.swift
+//
+//  Copyright (c) 2014-2018 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
+
+/// Default type of `DataResponse` returned by Alamofire, with an `AFError` `Failure` type.
+public typealias AFDataResponse<Success> = DataResponse<Success, AFError>
+/// Default type of `DownloadResponse` returned by Alamofire, with an `AFError` `Failure` type.
+public typealias AFDownloadResponse<Success> = DownloadResponse<Success, AFError>
+
+/// Type used to store all values associated with a serialized response of a `DataRequest` or `UploadRequest`.
+public struct DataResponse<Success, Failure: Error> {
+    /// The URL request sent to the server.
+    public let request: URLRequest?
+
+    /// The server's response to the URL request.
+    public let response: HTTPURLResponse?
+
+    /// The data returned by the server.
+    public let data: Data?
+
+    /// The final metrics of the response.
+    ///
+    /// - Note: Due to `FB7624529`, collection of `URLSessionTaskMetrics` on watchOS is currently disabled.`
+    ///
+    public let metrics: URLSessionTaskMetrics?
+
+    /// The time taken to serialize the response.
+    public let serializationDuration: TimeInterval
+
+    /// The result of response serialization.
+    public let result: Result<Success, Failure>
+
+    /// Returns the associated value of the result if it is a success, `nil` otherwise.
+    public var value: Success? { result.success }
+
+    /// Returns the associated error value if the result if it is a failure, `nil` otherwise.
+    public var error: Failure? { result.failure }
+
+    /// Creates a `DataResponse` instance with the specified parameters derived from the response serialization.
+    ///
+    /// - Parameters:
+    ///   - request:               The `URLRequest` sent to the server.
+    ///   - response:              The `HTTPURLResponse` from the server.
+    ///   - data:                  The `Data` returned by the server.
+    ///   - metrics:               The `URLSessionTaskMetrics` of the `DataRequest` or `UploadRequest`.
+    ///   - serializationDuration: The duration taken by serialization.
+    ///   - result:                The `Result` of response serialization.
+    public init(request: URLRequest?,
+                response: HTTPURLResponse?,
+                data: Data?,
+                metrics: URLSessionTaskMetrics?,
+                serializationDuration: TimeInterval,
+                result: Result<Success, Failure>) {
+        self.request = request
+        self.response = response
+        self.data = data
+        self.metrics = metrics
+        self.serializationDuration = serializationDuration
+        self.result = result
+    }
+}
+
+// MARK: -
+
+extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible {
+    /// The textual representation used when written to an output stream, which includes whether the result was a
+    /// success or failure.
+    public var description: String {
+        "\(result)"
+    }
+
+    /// The debug textual representation used when written to an output stream, which includes (if available) a summary
+    /// of the `URLRequest`, the request's headers and body (if decodable as a `String` below 100KB); the
+    /// `HTTPURLResponse`'s status code, headers, and body; the duration of the network and serialization actions; and
+    /// the `Result` of serialization.
+    public var debugDescription: String {
+        guard let urlRequest = request else { return "[Request]: None\n[Result]: \(result)" }
+
+        let requestDescription = DebugDescription.description(of: urlRequest)
+
+        let responseDescription = response.map { response in
+            let responseBodyDescription = DebugDescription.description(for: data, headers: response.headers)
+
+            return """
+            \(DebugDescription.description(of: response))
+                \(responseBodyDescription.indentingNewlines())
+            """
+        } ?? "[Response]: None"
+
+        let networkDuration = metrics.map { "\($0.taskInterval.duration)s" } ?? "None"
+
+        return """
+        \(requestDescription)
+        \(responseDescription)
+        [Network Duration]: \(networkDuration)
+        [Serialization Duration]: \(serializationDuration)s
+        [Result]: \(result)
+        """
+    }
+}
+
+// MARK: -
+
+extension DataResponse {
+    /// Evaluates the specified closure when the result of this `DataResponse` is a success, passing the unwrapped
+    /// result value as a parameter.
+    ///
+    /// Use the `map` method with a closure that does not throw. For example:
+    ///
+    ///     let possibleData: DataResponse<Data> = ...
+    ///     let possibleInt = possibleData.map { $0.count }
+    ///
+    /// - parameter transform: A closure that takes the success value of the instance's result.
+    ///
+    /// - returns: A `DataResponse` whose result wraps the value returned by the given closure. If this instance's
+    ///            result is a failure, returns a response wrapping the same failure.
+    public func map<NewSuccess>(_ transform: (Success) -> NewSuccess) -> DataResponse<NewSuccess, Failure> {
+        DataResponse<NewSuccess, Failure>(request: request,
+                                          response: response,
+                                          data: data,
+                                          metrics: metrics,
+                                          serializationDuration: serializationDuration,
+                                          result: result.map(transform))
+    }
+
+    /// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result
+    /// value as a parameter.
+    ///
+    /// Use the `tryMap` method with a closure that may throw an error. For example:
+    ///
+    ///     let possibleData: DataResponse<Data> = ...
+    ///     let possibleObject = possibleData.tryMap {
+    ///         try JSONSerialization.jsonObject(with: $0)
+    ///     }
+    ///
+    /// - parameter transform: A closure that takes the success value of the instance's result.
+    ///
+    /// - returns: A success or failure `DataResponse` depending on the result of the given closure. If this instance's
+    ///            result is a failure, returns the same failure.
+    public func tryMap<NewSuccess>(_ transform: (Success) throws -> NewSuccess) -> DataResponse<NewSuccess, Error> {
+        DataResponse<NewSuccess, Error>(request: request,
+                                        response: response,
+                                        data: data,
+                                        metrics: metrics,
+                                        serializationDuration: serializationDuration,
+                                        result: result.tryMap(transform))
+    }
+
+    /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter.
+    ///
+    /// Use the `mapError` function with a closure that does not throw. For example:
+    ///
+    ///     let possibleData: DataResponse<Data> = ...
+    ///     let withMyError = possibleData.mapError { MyError.error($0) }
+    ///
+    /// - Parameter transform: A closure that takes the error of the instance.
+    ///
+    /// - Returns: A `DataResponse` instance containing the result of the transform.
+    public func mapError<NewFailure: Error>(_ transform: (Failure) -> NewFailure) -> DataResponse<Success, NewFailure> {
+        DataResponse<Success, NewFailure>(request: request,
+                                          response: response,
+                                          data: data,
+                                          metrics: metrics,
+                                          serializationDuration: serializationDuration,
+                                          result: result.mapError(transform))
+    }
+
+    /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter.
+    ///
+    /// Use the `tryMapError` function with a closure that may throw an error. For example:
+    ///
+    ///     let possibleData: DataResponse<Data> = ...
+    ///     let possibleObject = possibleData.tryMapError {
+    ///         try someFailableFunction(taking: $0)
+    ///     }
+    ///
+    /// - Parameter transform: A throwing closure that takes the error of the instance.
+    ///
+    /// - Returns: A `DataResponse` instance containing the result of the transform.
+    public func tryMapError<NewFailure: Error>(_ transform: (Failure) throws -> NewFailure) -> DataResponse<Success, Error> {
+        DataResponse<Success, Error>(request: request,
+                                     response: response,
+                                     data: data,
+                                     metrics: metrics,
+                                     serializationDuration: serializationDuration,
+                                     result: result.tryMapError(transform))
+    }
+}
+
+// MARK: -
+
+/// Used to store all data associated with a serialized response of a download request.
+public struct DownloadResponse<Success, Failure: Error> {
+    /// The URL request sent to the server.
+    public let request: URLRequest?
+
+    /// The server's response to the URL request.
+    public let response: HTTPURLResponse?
+
+    /// The final destination URL of the data returned from the server after it is moved.
+    public let fileURL: URL?
+
+    /// The resume data generated if the request was cancelled.
+    public let resumeData: Data?
+
+    /// The final metrics of the response.
+    ///
+    /// - Note: Due to `FB7624529`, collection of `URLSessionTaskMetrics` on watchOS is currently disabled.`
+    ///
+    public let metrics: URLSessionTaskMetrics?
+
+    /// The time taken to serialize the response.
+    public let serializationDuration: TimeInterval
+
+    /// The result of response serialization.
+    public let result: Result<Success, Failure>
+
+    /// Returns the associated value of the result if it is a success, `nil` otherwise.
+    public var value: Success? { result.success }
+
+    /// Returns the associated error value if the result if it is a failure, `nil` otherwise.
+    public var error: Failure? { result.failure }
+
+    /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization.
+    ///
+    /// - Parameters:
+    ///   - request:               The `URLRequest` sent to the server.
+    ///   - response:              The `HTTPURLResponse` from the server.
+    ///   - fileURL:               The final destination URL of the data returned from the server after it is moved.
+    ///   - resumeData:            The resume `Data` generated if the request was cancelled.
+    ///   - metrics:               The `URLSessionTaskMetrics` of the `DownloadRequest`.
+    ///   - serializationDuration: The duration taken by serialization.
+    ///   - result:                The `Result` of response serialization.
+    public init(request: URLRequest?,
+                response: HTTPURLResponse?,
+                fileURL: URL?,
+                resumeData: Data?,
+                metrics: URLSessionTaskMetrics?,
+                serializationDuration: TimeInterval,
+                result: Result<Success, Failure>) {
+        self.request = request
+        self.response = response
+        self.fileURL = fileURL
+        self.resumeData = resumeData
+        self.metrics = metrics
+        self.serializationDuration = serializationDuration
+        self.result = result
+    }
+}
+
+// MARK: -
+
+extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible {
+    /// The textual representation used when written to an output stream, which includes whether the result was a
+    /// success or failure.
+    public var description: String {
+        "\(result)"
+    }
+
+    /// The debug textual representation used when written to an output stream, which includes the URL request, the URL
+    /// response, the temporary and destination URLs, the resume data, the durations of the network and serialization
+    /// actions, and the response serialization result.
+    public var debugDescription: String {
+        guard let urlRequest = request else { return "[Request]: None\n[Result]: \(result)" }
+
+        let requestDescription = DebugDescription.description(of: urlRequest)
+        let responseDescription = response.map(DebugDescription.description(of:)) ?? "[Response]: None"
+        let networkDuration = metrics.map { "\($0.taskInterval.duration)s" } ?? "None"
+        let resumeDataDescription = resumeData.map { "\($0)" } ?? "None"
+
+        return """
+        \(requestDescription)
+        \(responseDescription)
+        [File URL]: \(fileURL?.path ?? "None")
+        [Resume Data]: \(resumeDataDescription)
+        [Network Duration]: \(networkDuration)
+        [Serialization Duration]: \(serializationDuration)s
+        [Result]: \(result)
+        """
+    }
+}
+
+// MARK: -
+
+extension DownloadResponse {
+    /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped
+    /// result value as a parameter.
+    ///
+    /// Use the `map` method with a closure that does not throw. For example:
+    ///
+    ///     let possibleData: DownloadResponse<Data> = ...
+    ///     let possibleInt = possibleData.map { $0.count }
+    ///
+    /// - parameter transform: A closure that takes the success value of the instance's result.
+    ///
+    /// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's
+    ///            result is a failure, returns a response wrapping the same failure.
+    public func map<NewSuccess>(_ transform: (Success) -> NewSuccess) -> DownloadResponse<NewSuccess, Failure> {
+        DownloadResponse<NewSuccess, Failure>(request: request,
+                                              response: response,
+                                              fileURL: fileURL,
+                                              resumeData: resumeData,
+                                              metrics: metrics,
+                                              serializationDuration: serializationDuration,
+                                              result: result.map(transform))
+    }
+
+    /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped
+    /// result value as a parameter.
+    ///
+    /// Use the `tryMap` method with a closure that may throw an error. For example:
+    ///
+    ///     let possibleData: DownloadResponse<Data> = ...
+    ///     let possibleObject = possibleData.tryMap {
+    ///         try JSONSerialization.jsonObject(with: $0)
+    ///     }
+    ///
+    /// - parameter transform: A closure that takes the success value of the instance's result.
+    ///
+    /// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this
+    /// instance's result is a failure, returns the same failure.
+    public func tryMap<NewSuccess>(_ transform: (Success) throws -> NewSuccess) -> DownloadResponse<NewSuccess, Error> {
+        DownloadResponse<NewSuccess, Error>(request: request,
+                                            response: response,
+                                            fileURL: fileURL,
+                                            resumeData: resumeData,
+                                            metrics: metrics,
+                                            serializationDuration: serializationDuration,
+                                            result: result.tryMap(transform))
+    }
+
+    /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter.
+    ///
+    /// Use the `mapError` function with a closure that does not throw. For example:
+    ///
+    ///     let possibleData: DownloadResponse<Data> = ...
+    ///     let withMyError = possibleData.mapError { MyError.error($0) }
+    ///
+    /// - Parameter transform: A closure that takes the error of the instance.
+    ///
+    /// - Returns: A `DownloadResponse` instance containing the result of the transform.
+    public func mapError<NewFailure: Error>(_ transform: (Failure) -> NewFailure) -> DownloadResponse<Success, NewFailure> {
+        DownloadResponse<Success, NewFailure>(request: request,
+                                              response: response,
+                                              fileURL: fileURL,
+                                              resumeData: resumeData,
+                                              metrics: metrics,
+                                              serializationDuration: serializationDuration,
+                                              result: result.mapError(transform))
+    }
+
+    /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter.
+    ///
+    /// Use the `tryMapError` function with a closure that may throw an error. For example:
+    ///
+    ///     let possibleData: DownloadResponse<Data> = ...
+    ///     let possibleObject = possibleData.tryMapError {
+    ///         try someFailableFunction(taking: $0)
+    ///     }
+    ///
+    /// - Parameter transform: A throwing closure that takes the error of the instance.
+    ///
+    /// - Returns: A `DownloadResponse` instance containing the result of the transform.
+    public func tryMapError<NewFailure: Error>(_ transform: (Failure) throws -> NewFailure) -> DownloadResponse<Success, Error> {
+        DownloadResponse<Success, Error>(request: request,
+                                         response: response,
+                                         fileURL: fileURL,
+                                         resumeData: resumeData,
+                                         metrics: metrics,
+                                         serializationDuration: serializationDuration,
+                                         result: result.tryMapError(transform))
+    }
+}
+
+private enum DebugDescription {
+    static func description(of request: URLRequest) -> String {
+        let requestSummary = "\(request.httpMethod!) \(request)"
+        let requestHeadersDescription = DebugDescription.description(for: request.headers)
+        let requestBodyDescription = DebugDescription.description(for: request.httpBody, headers: request.headers)
+
+        return """
+        [Request]: \(requestSummary)
+            \(requestHeadersDescription.indentingNewlines())
+            \(requestBodyDescription.indentingNewlines())
+        """
+    }
+
+    static func description(of response: HTTPURLResponse) -> String {
+        """
+        [Response]:
+            [Status Code]: \(response.statusCode)
+            \(DebugDescription.description(for: response.headers).indentingNewlines())
+        """
+    }
+
+    static func description(for headers: HTTPHeaders) -> String {
+        guard !headers.isEmpty else { return "[Headers]: None" }
+
+        let headerDescription = "\(headers.sorted())".indentingNewlines()
+        return """
+        [Headers]:
+            \(headerDescription)
+        """
+    }
+
+    static func description(for data: Data?,
+                            headers: HTTPHeaders,
+                            allowingPrintableTypes printableTypes: [String] = ["json", "xml", "text"],
+                            maximumLength: Int = 100_000) -> String {
+        guard let data = data, !data.isEmpty else { return "[Body]: None" }
+
+        guard
+            data.count <= maximumLength,
+            printableTypes.compactMap({ headers["Content-Type"]?.contains($0) }).contains(true)
+        else { return "[Body]: \(data.count) bytes" }
+
+        return """
+        [Body]:
+            \(String(decoding: data, as: UTF8.self)
+            .trimmingCharacters(in: .whitespacesAndNewlines)
+            .indentingNewlines())
+        """
+    }
+}
+
+extension String {
+    fileprivate func indentingNewlines(by spaceCount: Int = 4) -> String {
+        let spaces = String(repeating: " ", count: spaceCount)
+        return replacingOccurrences(of: "\n", with: "\n\(spaces)")
+    }
+}

+ 1282 - 0
Pods/Alamofire/Source/ResponseSerialization.swift

@@ -0,0 +1,1282 @@
+//
+//  ResponseSerialization.swift
+//
+//  Copyright (c) 2014-2018 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
+
+// MARK: Protocols
+
+/// The type to which all data response serializers must conform in order to serialize a response.
+public protocol DataResponseSerializerProtocol {
+    /// The type of serialized object to be created.
+    associatedtype SerializedObject
+
+    /// Serialize the response `Data` into the provided type..
+    ///
+    /// - Parameters:
+    ///   - request:  `URLRequest` which was used to perform the request, if any.
+    ///   - response: `HTTPURLResponse` received from the server, if any.
+    ///   - data:     `Data` returned from the server, if any.
+    ///   - error:    `Error` produced by Alamofire or the underlying `URLSession` during the request.
+    ///
+    /// - Returns:    The `SerializedObject`.
+    /// - Throws:     Any `Error` produced during serialization.
+    func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> SerializedObject
+}
+
+/// The type to which all download response serializers must conform in order to serialize a response.
+public protocol DownloadResponseSerializerProtocol {
+    /// The type of serialized object to be created.
+    associatedtype SerializedObject
+
+    /// Serialize the downloaded response `Data` from disk into the provided type..
+    ///
+    /// - Parameters:
+    ///   - request:  `URLRequest` which was used to perform the request, if any.
+    ///   - response: `HTTPURLResponse` received from the server, if any.
+    ///   - fileURL:  File `URL` to which the response data was downloaded.
+    ///   - error:    `Error` produced by Alamofire or the underlying `URLSession` during the request.
+    ///
+    /// - Returns:    The `SerializedObject`.
+    /// - Throws:     Any `Error` produced during serialization.
+    func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> SerializedObject
+}
+
+/// A serializer that can handle both data and download responses.
+public protocol ResponseSerializer: DataResponseSerializerProtocol & DownloadResponseSerializerProtocol {
+    /// `DataPreprocessor` used to prepare incoming `Data` for serialization.
+    var dataPreprocessor: DataPreprocessor { get }
+    /// `HTTPMethod`s for which empty response bodies are considered appropriate.
+    var emptyRequestMethods: Set<HTTPMethod> { get }
+    /// HTTP response codes for which empty response bodies are considered appropriate.
+    var emptyResponseCodes: Set<Int> { get }
+}
+
+/// Type used to preprocess `Data` before it handled by a serializer.
+public protocol DataPreprocessor {
+    /// Process           `Data` before it's handled by a serializer.
+    /// - Parameter data: The raw `Data` to process.
+    func preprocess(_ data: Data) throws -> Data
+}
+
+/// `DataPreprocessor` that returns passed `Data` without any transform.
+public struct PassthroughPreprocessor: DataPreprocessor {
+    public init() {}
+
+    public func preprocess(_ data: Data) throws -> Data { data }
+}
+
+/// `DataPreprocessor` that trims Google's typical `)]}',\n` XSSI JSON header.
+public struct GoogleXSSIPreprocessor: DataPreprocessor {
+    public init() {}
+
+    public func preprocess(_ data: Data) throws -> Data {
+        (data.prefix(6) == Data(")]}',\n".utf8)) ? data.dropFirst(6) : data
+    }
+}
+
+#if swift(>=5.5)
+extension DataPreprocessor where Self == PassthroughPreprocessor {
+    /// Provides a `PassthroughPreprocessor` instance.
+    public static var passthrough: PassthroughPreprocessor { PassthroughPreprocessor() }
+}
+
+extension DataPreprocessor where Self == GoogleXSSIPreprocessor {
+    /// Provides a `GoogleXSSIPreprocessor` instance.
+    public static var googleXSSI: GoogleXSSIPreprocessor { GoogleXSSIPreprocessor() }
+}
+#endif
+
+extension ResponseSerializer {
+    /// Default `DataPreprocessor`. `PassthroughPreprocessor` by default.
+    public static var defaultDataPreprocessor: DataPreprocessor { PassthroughPreprocessor() }
+    /// Default `HTTPMethod`s for which empty response bodies are considered appropriate. `[.head]` by default.
+    public static var defaultEmptyRequestMethods: Set<HTTPMethod> { [.head] }
+    /// HTTP response codes for which empty response bodies are considered appropriate. `[204, 205]` by default.
+    public static var defaultEmptyResponseCodes: Set<Int> { [204, 205] }
+
+    public var dataPreprocessor: DataPreprocessor { Self.defaultDataPreprocessor }
+    public var emptyRequestMethods: Set<HTTPMethod> { Self.defaultEmptyRequestMethods }
+    public var emptyResponseCodes: Set<Int> { Self.defaultEmptyResponseCodes }
+
+    /// Determines whether the `request` allows empty response bodies, if `request` exists.
+    ///
+    /// - Parameter request: `URLRequest` to evaluate.
+    ///
+    /// - Returns:           `Bool` representing the outcome of the evaluation, or `nil` if `request` was `nil`.
+    public func requestAllowsEmptyResponseData(_ request: URLRequest?) -> Bool? {
+        request.flatMap(\.httpMethod)
+            .flatMap(HTTPMethod.init)
+            .map { emptyRequestMethods.contains($0) }
+    }
+
+    /// Determines whether the `response` allows empty response bodies, if `response` exists`.
+    ///
+    /// - Parameter response: `HTTPURLResponse` to evaluate.
+    ///
+    /// - Returns:            `Bool` representing the outcome of the evaluation, or `nil` if `response` was `nil`.
+    public func responseAllowsEmptyResponseData(_ response: HTTPURLResponse?) -> Bool? {
+        response.map(\.statusCode)
+            .map { emptyResponseCodes.contains($0) }
+    }
+
+    /// Determines whether `request` and `response` allow empty response bodies.
+    ///
+    /// - Parameters:
+    ///   - request:  `URLRequest` to evaluate.
+    ///   - response: `HTTPURLResponse` to evaluate.
+    ///
+    /// - Returns:    `true` if `request` or `response` allow empty bodies, `false` otherwise.
+    public func emptyResponseAllowed(forRequest request: URLRequest?, response: HTTPURLResponse?) -> Bool {
+        (requestAllowsEmptyResponseData(request) == true) || (responseAllowsEmptyResponseData(response) == true)
+    }
+}
+
+/// By default, any serializer declared to conform to both types will get file serialization for free, as it just feeds
+/// the data read from disk into the data response serializer.
+extension DownloadResponseSerializerProtocol where Self: DataResponseSerializerProtocol {
+    public func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> Self.SerializedObject {
+        guard error == nil else { throw error! }
+
+        guard let fileURL = fileURL else {
+            throw AFError.responseSerializationFailed(reason: .inputFileNil)
+        }
+
+        let data: Data
+        do {
+            data = try Data(contentsOf: fileURL)
+        } catch {
+            throw AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))
+        }
+
+        do {
+            return try serialize(request: request, response: response, data: data, error: error)
+        } catch {
+            throw error
+        }
+    }
+}
+
+// MARK: - Default
+
+extension DataRequest {
+    /// Adds a handler to be called once the request has finished.
+    ///
+    /// - Parameters:
+    ///   - queue:             The queue on which the completion handler is dispatched. `.main` by default.
+    ///   - completionHandler: The code to be executed once the request has finished.
+    ///
+    /// - Returns:             The request.
+    @discardableResult
+    public func response(queue: DispatchQueue = .main, completionHandler: @escaping (AFDataResponse<Data?>) -> Void) -> Self {
+        appendResponseSerializer {
+            // Start work that should be on the serialization queue.
+            let result = AFResult<Data?>(value: self.data, error: self.error)
+            // End work that should be on the serialization queue.
+
+            self.underlyingQueue.async {
+                let response = DataResponse(request: self.request,
+                                            response: self.response,
+                                            data: self.data,
+                                            metrics: self.metrics,
+                                            serializationDuration: 0,
+                                            result: result)
+
+                self.eventMonitor?.request(self, didParseResponse: response)
+
+                self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
+            }
+        }
+
+        return self
+    }
+
+    private func _response<Serializer: DataResponseSerializerProtocol>(queue: DispatchQueue = .main,
+                                                                       responseSerializer: Serializer,
+                                                                       completionHandler: @escaping (AFDataResponse<Serializer.SerializedObject>) -> Void)
+        -> Self {
+        appendResponseSerializer {
+            // Start work that should be on the serialization queue.
+            let start = ProcessInfo.processInfo.systemUptime
+            let result: AFResult<Serializer.SerializedObject> = Result {
+                try responseSerializer.serialize(request: self.request,
+                                                 response: self.response,
+                                                 data: self.data,
+                                                 error: self.error)
+            }.mapError { error in
+                error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error)))
+            }
+
+            let end = ProcessInfo.processInfo.systemUptime
+            // End work that should be on the serialization queue.
+
+            self.underlyingQueue.async {
+                let response = DataResponse(request: self.request,
+                                            response: self.response,
+                                            data: self.data,
+                                            metrics: self.metrics,
+                                            serializationDuration: end - start,
+                                            result: result)
+
+                self.eventMonitor?.request(self, didParseResponse: response)
+
+                guard !self.isCancelled, let serializerError = result.failure, let delegate = self.delegate else {
+                    self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
+                    return
+                }
+
+                delegate.retryResult(for: self, dueTo: serializerError) { retryResult in
+                    var didComplete: (() -> Void)?
+
+                    defer {
+                        if let didComplete = didComplete {
+                            self.responseSerializerDidComplete { queue.async { didComplete() } }
+                        }
+                    }
+
+                    switch retryResult {
+                    case .doNotRetry:
+                        didComplete = { completionHandler(response) }
+
+                    case let .doNotRetryWithError(retryError):
+                        let result: AFResult<Serializer.SerializedObject> = .failure(retryError.asAFError(orFailWith: "Received retryError was not already AFError"))
+
+                        let response = DataResponse(request: self.request,
+                                                    response: self.response,
+                                                    data: self.data,
+                                                    metrics: self.metrics,
+                                                    serializationDuration: end - start,
+                                                    result: result)
+
+                        didComplete = { completionHandler(response) }
+
+                    case .retry, .retryWithDelay:
+                        delegate.retryRequest(self, withDelay: retryResult.delay)
+                    }
+                }
+            }
+        }
+
+        return self
+    }
+
+    /// Adds a handler to be called once the request has finished.
+    ///
+    /// - Parameters:
+    ///   - queue:              The queue on which the completion handler is dispatched. `.main` by default
+    ///   - responseSerializer: The response serializer responsible for serializing the request, response, and data.
+    ///   - completionHandler:  The code to be executed once the request has finished.
+    ///
+    /// - Returns:              The request.
+    @discardableResult
+    public func response<Serializer: DataResponseSerializerProtocol>(queue: DispatchQueue = .main,
+                                                                     responseSerializer: Serializer,
+                                                                     completionHandler: @escaping (AFDataResponse<Serializer.SerializedObject>) -> Void)
+        -> Self {
+        _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
+    }
+
+    /// Adds a handler to be called once the request has finished.
+    ///
+    /// - Parameters:
+    ///   - queue:              The queue on which the completion handler is dispatched. `.main` by default
+    ///   - responseSerializer: The response serializer responsible for serializing the request, response, and data.
+    ///   - completionHandler:  The code to be executed once the request has finished.
+    ///
+    /// - Returns:              The request.
+    @discardableResult
+    public func response<Serializer: ResponseSerializer>(queue: DispatchQueue = .main,
+                                                         responseSerializer: Serializer,
+                                                         completionHandler: @escaping (AFDataResponse<Serializer.SerializedObject>) -> Void)
+        -> Self {
+        _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
+    }
+}
+
+extension DownloadRequest {
+    /// Adds a handler to be called once the request has finished.
+    ///
+    /// - Parameters:
+    ///   - queue:             The queue on which the completion handler is dispatched. `.main` by default.
+    ///   - completionHandler: The code to be executed once the request has finished.
+    ///
+    /// - Returns:             The request.
+    @discardableResult
+    public func response(queue: DispatchQueue = .main,
+                         completionHandler: @escaping (AFDownloadResponse<URL?>) -> Void)
+        -> Self {
+        appendResponseSerializer {
+            // Start work that should be on the serialization queue.
+            let result = AFResult<URL?>(value: self.fileURL, error: self.error)
+            // End work that should be on the serialization queue.
+
+            self.underlyingQueue.async {
+                let response = DownloadResponse(request: self.request,
+                                                response: self.response,
+                                                fileURL: self.fileURL,
+                                                resumeData: self.resumeData,
+                                                metrics: self.metrics,
+                                                serializationDuration: 0,
+                                                result: result)
+
+                self.eventMonitor?.request(self, didParseResponse: response)
+
+                self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
+            }
+        }
+
+        return self
+    }
+
+    private func _response<Serializer: DownloadResponseSerializerProtocol>(queue: DispatchQueue = .main,
+                                                                           responseSerializer: Serializer,
+                                                                           completionHandler: @escaping (AFDownloadResponse<Serializer.SerializedObject>) -> Void)
+        -> Self {
+        appendResponseSerializer {
+            // Start work that should be on the serialization queue.
+            let start = ProcessInfo.processInfo.systemUptime
+            let result: AFResult<Serializer.SerializedObject> = Result {
+                try responseSerializer.serializeDownload(request: self.request,
+                                                         response: self.response,
+                                                         fileURL: self.fileURL,
+                                                         error: self.error)
+            }.mapError { error in
+                error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error)))
+            }
+            let end = ProcessInfo.processInfo.systemUptime
+            // End work that should be on the serialization queue.
+
+            self.underlyingQueue.async {
+                let response = DownloadResponse(request: self.request,
+                                                response: self.response,
+                                                fileURL: self.fileURL,
+                                                resumeData: self.resumeData,
+                                                metrics: self.metrics,
+                                                serializationDuration: end - start,
+                                                result: result)
+
+                self.eventMonitor?.request(self, didParseResponse: response)
+
+                guard let serializerError = result.failure, let delegate = self.delegate else {
+                    self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
+                    return
+                }
+
+                delegate.retryResult(for: self, dueTo: serializerError) { retryResult in
+                    var didComplete: (() -> Void)?
+
+                    defer {
+                        if let didComplete = didComplete {
+                            self.responseSerializerDidComplete { queue.async { didComplete() } }
+                        }
+                    }
+
+                    switch retryResult {
+                    case .doNotRetry:
+                        didComplete = { completionHandler(response) }
+
+                    case let .doNotRetryWithError(retryError):
+                        let result: AFResult<Serializer.SerializedObject> = .failure(retryError.asAFError(orFailWith: "Received retryError was not already AFError"))
+
+                        let response = DownloadResponse(request: self.request,
+                                                        response: self.response,
+                                                        fileURL: self.fileURL,
+                                                        resumeData: self.resumeData,
+                                                        metrics: self.metrics,
+                                                        serializationDuration: end - start,
+                                                        result: result)
+
+                        didComplete = { completionHandler(response) }
+
+                    case .retry, .retryWithDelay:
+                        delegate.retryRequest(self, withDelay: retryResult.delay)
+                    }
+                }
+            }
+        }
+
+        return self
+    }
+
+    /// Adds a handler to be called once the request has finished.
+    ///
+    /// - Parameters:
+    ///   - queue:              The queue on which the completion handler is dispatched. `.main` by default.
+    ///   - responseSerializer: The response serializer responsible for serializing the request, response, and data
+    ///                         contained in the destination `URL`.
+    ///   - completionHandler:  The code to be executed once the request has finished.
+    ///
+    /// - Returns:              The request.
+    @discardableResult
+    public func response<Serializer: DownloadResponseSerializerProtocol>(queue: DispatchQueue = .main,
+                                                                         responseSerializer: Serializer,
+                                                                         completionHandler: @escaping (AFDownloadResponse<Serializer.SerializedObject>) -> Void)
+        -> Self {
+        _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
+    }
+
+    /// Adds a handler to be called once the request has finished.
+    ///
+    /// - Parameters:
+    ///   - queue:              The queue on which the completion handler is dispatched. `.main` by default.
+    ///   - responseSerializer: The response serializer responsible for serializing the request, response, and data
+    ///                         contained in the destination `URL`.
+    ///   - completionHandler:  The code to be executed once the request has finished.
+    ///
+    /// - Returns:              The request.
+    @discardableResult
+    public func response<Serializer: ResponseSerializer>(queue: DispatchQueue = .main,
+                                                         responseSerializer: Serializer,
+                                                         completionHandler: @escaping (AFDownloadResponse<Serializer.SerializedObject>) -> Void)
+        -> Self {
+        _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
+    }
+}
+
+// MARK: - URL
+
+/// A `DownloadResponseSerializerProtocol` that performs only `Error` checking and ensures that a downloaded `fileURL`
+/// is present.
+public struct URLResponseSerializer: DownloadResponseSerializerProtocol {
+    /// Creates an instance.
+    public init() {}
+
+    public func serializeDownload(request: URLRequest?,
+                                  response: HTTPURLResponse?,
+                                  fileURL: URL?,
+                                  error: Error?) throws -> URL {
+        guard error == nil else { throw error! }
+
+        guard let url = fileURL else {
+            throw AFError.responseSerializationFailed(reason: .inputFileNil)
+        }
+
+        return url
+    }
+}
+
+#if swift(>=5.5)
+extension DownloadResponseSerializerProtocol where Self == URLResponseSerializer {
+    /// Provides a `URLResponseSerializer` instance.
+    public static var url: URLResponseSerializer { URLResponseSerializer() }
+}
+#endif
+
+extension DownloadRequest {
+    /// Adds a handler using a `URLResponseSerializer` to be called once the request is finished.
+    ///
+    /// - Parameters:
+    ///   - queue:             The queue on which the completion handler is called. `.main` by default.
+    ///   - completionHandler: A closure to be executed once the request has finished.
+    ///
+    /// - Returns:             The request.
+    @discardableResult
+    public func responseURL(queue: DispatchQueue = .main,
+                            completionHandler: @escaping (AFDownloadResponse<URL>) -> Void) -> Self {
+        response(queue: queue, responseSerializer: URLResponseSerializer(), completionHandler: completionHandler)
+    }
+}
+
+// MARK: - Data
+
+/// A `ResponseSerializer` that performs minimal response checking and returns any response `Data` as-is. By default, a
+/// request returning `nil` or no data is considered an error. However, if the request has an `HTTPMethod` or the
+/// response has an  HTTP status code valid for empty responses, then an empty `Data` value is returned.
+public final class DataResponseSerializer: ResponseSerializer {
+    public let dataPreprocessor: DataPreprocessor
+    public let emptyResponseCodes: Set<Int>
+    public let emptyRequestMethods: Set<HTTPMethod>
+
+    /// Creates a `DataResponseSerializer` using the provided parameters.
+    ///
+    /// - Parameters:
+    ///   - dataPreprocessor:    `DataPreprocessor` used to prepare the received `Data` for serialization.
+    ///   - emptyResponseCodes:  The HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
+    ///   - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default.
+    public init(dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
+                emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
+                emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods) {
+        self.dataPreprocessor = dataPreprocessor
+        self.emptyResponseCodes = emptyResponseCodes
+        self.emptyRequestMethods = emptyRequestMethods
+    }
+
+    public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Data {
+        guard error == nil else { throw error! }
+
+        guard var data = data, !data.isEmpty else {
+            guard emptyResponseAllowed(forRequest: request, response: response) else {
+                throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
+            }
+
+            return Data()
+        }
+
+        data = try dataPreprocessor.preprocess(data)
+
+        return data
+    }
+}
+
+#if swift(>=5.5)
+extension ResponseSerializer where Self == DataResponseSerializer {
+    /// Provides a default `DataResponseSerializer` instance.
+    public static var data: DataResponseSerializer { DataResponseSerializer() }
+
+    /// Creates a `DataResponseSerializer` using the provided parameters.
+    ///
+    /// - Parameters:
+    ///   - dataPreprocessor:    `DataPreprocessor` used to prepare the received `Data` for serialization.
+    ///   - emptyResponseCodes:  The HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
+    ///   - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default.
+    ///
+    /// - Returns:               The `DataResponseSerializer`.
+    public static func data(dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
+                            emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
+                            emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods) -> DataResponseSerializer {
+        DataResponseSerializer(dataPreprocessor: dataPreprocessor,
+                               emptyResponseCodes: emptyResponseCodes,
+                               emptyRequestMethods: emptyRequestMethods)
+    }
+}
+#endif
+
+extension DataRequest {
+    /// Adds a handler using a `DataResponseSerializer` to be called once the request has finished.
+    ///
+    /// - Parameters:
+    ///   - queue:               The queue on which the completion handler is called. `.main` by default.
+    ///   - dataPreprocessor:    `DataPreprocessor` which processes the received `Data` before calling the
+    ///                          `completionHandler`. `PassthroughPreprocessor()` by default.
+    ///   - emptyResponseCodes:  HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
+    ///   - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
+    ///   - completionHandler:   A closure to be executed once the request has finished.
+    ///
+    /// - Returns:               The request.
+    @discardableResult
+    public func responseData(queue: DispatchQueue = .main,
+                             dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
+                             emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
+                             emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods,
+                             completionHandler: @escaping (AFDataResponse<Data>) -> Void) -> Self {
+        response(queue: queue,
+                 responseSerializer: DataResponseSerializer(dataPreprocessor: dataPreprocessor,
+                                                            emptyResponseCodes: emptyResponseCodes,
+                                                            emptyRequestMethods: emptyRequestMethods),
+                 completionHandler: completionHandler)
+    }
+}
+
+extension DownloadRequest {
+    /// Adds a handler using a `DataResponseSerializer` to be called once the request has finished.
+    ///
+    /// - Parameters:
+    ///   - queue:               The queue on which the completion handler is called. `.main` by default.
+    ///   - dataPreprocessor:    `DataPreprocessor` which processes the received `Data` before calling the
+    ///                          `completionHandler`. `PassthroughPreprocessor()` by default.
+    ///   - emptyResponseCodes:  HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
+    ///   - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
+    ///   - completionHandler:   A closure to be executed once the request has finished.
+    ///
+    /// - Returns:               The request.
+    @discardableResult
+    public func responseData(queue: DispatchQueue = .main,
+                             dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
+                             emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
+                             emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods,
+                             completionHandler: @escaping (AFDownloadResponse<Data>) -> Void) -> Self {
+        response(queue: queue,
+                 responseSerializer: DataResponseSerializer(dataPreprocessor: dataPreprocessor,
+                                                            emptyResponseCodes: emptyResponseCodes,
+                                                            emptyRequestMethods: emptyRequestMethods),
+                 completionHandler: completionHandler)
+    }
+}
+
+// MARK: - String
+
+/// A `ResponseSerializer` that decodes the response data as a `String`. By default, a request returning `nil` or no
+/// data is considered an error. However, if the request has an `HTTPMethod` or the response has an  HTTP status code
+/// valid for empty responses, then an empty `String` is returned.
+public final class StringResponseSerializer: ResponseSerializer {
+    public let dataPreprocessor: DataPreprocessor
+    /// Optional string encoding used to validate the response.
+    public let encoding: String.Encoding?
+    public let emptyResponseCodes: Set<Int>
+    public let emptyRequestMethods: Set<HTTPMethod>
+
+    /// Creates an instance with the provided values.
+    ///
+    /// - Parameters:
+    ///   - dataPreprocessor:    `DataPreprocessor` used to prepare the received `Data` for serialization.
+    ///   - encoding:            A string encoding. Defaults to `nil`, in which case the encoding will be determined
+    ///                          from the server response, falling back to the default HTTP character set, `ISO-8859-1`.
+    ///   - emptyResponseCodes:  The HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
+    ///   - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default.
+    public init(dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
+                encoding: String.Encoding? = nil,
+                emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
+                emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods) {
+        self.dataPreprocessor = dataPreprocessor
+        self.encoding = encoding
+        self.emptyResponseCodes = emptyResponseCodes
+        self.emptyRequestMethods = emptyRequestMethods
+    }
+
+    public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> String {
+        guard error == nil else { throw error! }
+
+        guard var data = data, !data.isEmpty else {
+            guard emptyResponseAllowed(forRequest: request, response: response) else {
+                throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
+            }
+
+            return ""
+        }
+
+        data = try dataPreprocessor.preprocess(data)
+
+        var convertedEncoding = encoding
+
+        if let encodingName = response?.textEncodingName, convertedEncoding == nil {
+            convertedEncoding = String.Encoding(ianaCharsetName: encodingName)
+        }
+
+        let actualEncoding = convertedEncoding ?? .isoLatin1
+
+        guard let string = String(data: data, encoding: actualEncoding) else {
+            throw AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding))
+        }
+
+        return string
+    }
+}
+
+#if swift(>=5.5)
+extension ResponseSerializer where Self == StringResponseSerializer {
+    /// Provides a default `StringResponseSerializer` instance.
+    public static var string: StringResponseSerializer { StringResponseSerializer() }
+
+    /// Creates a `StringResponseSerializer` with the provided values.
+    ///
+    /// - Parameters:
+    ///   - dataPreprocessor:    `DataPreprocessor` used to prepare the received `Data` for serialization.
+    ///   - encoding:            A string encoding. Defaults to `nil`, in which case the encoding will be determined
+    ///                          from the server response, falling back to the default HTTP character set, `ISO-8859-1`.
+    ///   - emptyResponseCodes:  The HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
+    ///   - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default.
+    ///
+    /// - Returns:               The `StringResponseSerializer`.
+    public static func string(dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
+                              encoding: String.Encoding? = nil,
+                              emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
+                              emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods) -> StringResponseSerializer {
+        StringResponseSerializer(dataPreprocessor: dataPreprocessor,
+                                 encoding: encoding,
+                                 emptyResponseCodes: emptyResponseCodes,
+                                 emptyRequestMethods: emptyRequestMethods)
+    }
+}
+#endif
+
+extension DataRequest {
+    /// Adds a handler using a `StringResponseSerializer` to be called once the request has finished.
+    ///
+    /// - Parameters:
+    ///   - queue:               The queue on which the completion handler is dispatched. `.main` by default.
+    ///   - dataPreprocessor:    `DataPreprocessor` which processes the received `Data` before calling the
+    ///                          `completionHandler`. `PassthroughPreprocessor()` by default.
+    ///   - encoding:            The string encoding. Defaults to `nil`, in which case the encoding will be determined
+    ///                          from the server response, falling back to the default HTTP character set, `ISO-8859-1`.
+    ///   - emptyResponseCodes:  HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
+    ///   - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
+    ///   - completionHandler:   A closure to be executed once the request has finished.
+    ///
+    /// - Returns:               The request.
+    @discardableResult
+    public func responseString(queue: DispatchQueue = .main,
+                               dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
+                               encoding: String.Encoding? = nil,
+                               emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
+                               emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods,
+                               completionHandler: @escaping (AFDataResponse<String>) -> Void) -> Self {
+        response(queue: queue,
+                 responseSerializer: StringResponseSerializer(dataPreprocessor: dataPreprocessor,
+                                                              encoding: encoding,
+                                                              emptyResponseCodes: emptyResponseCodes,
+                                                              emptyRequestMethods: emptyRequestMethods),
+                 completionHandler: completionHandler)
+    }
+}
+
+extension DownloadRequest {
+    /// Adds a handler using a `StringResponseSerializer` to be called once the request has finished.
+    ///
+    /// - Parameters:
+    ///   - queue:               The queue on which the completion handler is dispatched. `.main` by default.
+    ///   - dataPreprocessor:    `DataPreprocessor` which processes the received `Data` before calling the
+    ///                          `completionHandler`. `PassthroughPreprocessor()` by default.
+    ///   - encoding:            The string encoding. Defaults to `nil`, in which case the encoding will be determined
+    ///                          from the server response, falling back to the default HTTP character set, `ISO-8859-1`.
+    ///   - emptyResponseCodes:  HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
+    ///   - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
+    ///   - completionHandler:   A closure to be executed once the request has finished.
+    ///
+    /// - Returns:               The request.
+    @discardableResult
+    public func responseString(queue: DispatchQueue = .main,
+                               dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
+                               encoding: String.Encoding? = nil,
+                               emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
+                               emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods,
+                               completionHandler: @escaping (AFDownloadResponse<String>) -> Void) -> Self {
+        response(queue: queue,
+                 responseSerializer: StringResponseSerializer(dataPreprocessor: dataPreprocessor,
+                                                              encoding: encoding,
+                                                              emptyResponseCodes: emptyResponseCodes,
+                                                              emptyRequestMethods: emptyRequestMethods),
+                 completionHandler: completionHandler)
+    }
+}
+
+// MARK: - JSON
+
+/// A `ResponseSerializer` that decodes the response data using `JSONSerialization`. By default, a request returning
+/// `nil` or no data is considered an error. However, if the request has an `HTTPMethod` or the response has an
+/// HTTP status code valid for empty responses, then an `NSNull` value is returned.
+@available(*, deprecated, message: "JSONResponseSerializer deprecated and will be removed in Alamofire 6. Use DecodableResponseSerializer instead.")
+public final class JSONResponseSerializer: ResponseSerializer {
+    public let dataPreprocessor: DataPreprocessor
+    public let emptyResponseCodes: Set<Int>
+    public let emptyRequestMethods: Set<HTTPMethod>
+    /// `JSONSerialization.ReadingOptions` used when serializing a response.
+    public let options: JSONSerialization.ReadingOptions
+
+    /// Creates an instance with the provided values.
+    ///
+    /// - Parameters:
+    ///   - dataPreprocessor:    `DataPreprocessor` used to prepare the received `Data` for serialization.
+    ///   - emptyResponseCodes:  The HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
+    ///   - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default.
+    ///   - options:             The options to use. `.allowFragments` by default.
+    public init(dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor,
+                emptyResponseCodes: Set<Int> = JSONResponseSerializer.defaultEmptyResponseCodes,
+                emptyRequestMethods: Set<HTTPMethod> = JSONResponseSerializer.defaultEmptyRequestMethods,
+                options: JSONSerialization.ReadingOptions = .allowFragments) {
+        self.dataPreprocessor = dataPreprocessor
+        self.emptyResponseCodes = emptyResponseCodes
+        self.emptyRequestMethods = emptyRequestMethods
+        self.options = options
+    }
+
+    public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Any {
+        guard error == nil else { throw error! }
+
+        guard var data = data, !data.isEmpty else {
+            guard emptyResponseAllowed(forRequest: request, response: response) else {
+                throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
+            }
+
+            return NSNull()
+        }
+
+        data = try dataPreprocessor.preprocess(data)
+
+        do {
+            return try JSONSerialization.jsonObject(with: data, options: options)
+        } catch {
+            throw AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error))
+        }
+    }
+}
+
+extension DataRequest {
+    /// Adds a handler using a `JSONResponseSerializer` to be called once the request has finished.
+    ///
+    /// - Parameters:
+    ///   - queue:               The queue on which the completion handler is dispatched. `.main` by default.
+    ///   - dataPreprocessor:    `DataPreprocessor` which processes the received `Data` before calling the
+    ///                          `completionHandler`. `PassthroughPreprocessor()` by default.
+    ///   - emptyResponseCodes:  HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
+    ///   - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
+    ///   - options:             `JSONSerialization.ReadingOptions` used when parsing the response. `.allowFragments`
+    ///                          by default.
+    ///   - completionHandler:   A closure to be executed once the request has finished.
+    ///
+    /// - Returns:               The request.
+    @available(*, deprecated, message: "responseJSON deprecated and will be removed in Alamofire 6. Use responseDecodable instead.")
+    @discardableResult
+    public func responseJSON(queue: DispatchQueue = .main,
+                             dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor,
+                             emptyResponseCodes: Set<Int> = JSONResponseSerializer.defaultEmptyResponseCodes,
+                             emptyRequestMethods: Set<HTTPMethod> = JSONResponseSerializer.defaultEmptyRequestMethods,
+                             options: JSONSerialization.ReadingOptions = .allowFragments,
+                             completionHandler: @escaping (AFDataResponse<Any>) -> Void) -> Self {
+        response(queue: queue,
+                 responseSerializer: JSONResponseSerializer(dataPreprocessor: dataPreprocessor,
+                                                            emptyResponseCodes: emptyResponseCodes,
+                                                            emptyRequestMethods: emptyRequestMethods,
+                                                            options: options),
+                 completionHandler: completionHandler)
+    }
+}
+
+extension DownloadRequest {
+    /// Adds a handler using a `JSONResponseSerializer` to be called once the request has finished.
+    ///
+    /// - Parameters:
+    ///   - queue:               The queue on which the completion handler is dispatched. `.main` by default.
+    ///   - dataPreprocessor:    `DataPreprocessor` which processes the received `Data` before calling the
+    ///                          `completionHandler`. `PassthroughPreprocessor()` by default.
+    ///   - emptyResponseCodes:  HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
+    ///   - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
+    ///   - options:             `JSONSerialization.ReadingOptions` used when parsing the response. `.allowFragments`
+    ///                          by default.
+    ///   - completionHandler:   A closure to be executed once the request has finished.
+    ///
+    /// - Returns:               The request.
+    @available(*, deprecated, message: "responseJSON deprecated and will be removed in Alamofire 6. Use responseDecodable instead.")
+    @discardableResult
+    public func responseJSON(queue: DispatchQueue = .main,
+                             dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor,
+                             emptyResponseCodes: Set<Int> = JSONResponseSerializer.defaultEmptyResponseCodes,
+                             emptyRequestMethods: Set<HTTPMethod> = JSONResponseSerializer.defaultEmptyRequestMethods,
+                             options: JSONSerialization.ReadingOptions = .allowFragments,
+                             completionHandler: @escaping (AFDownloadResponse<Any>) -> Void) -> Self {
+        response(queue: queue,
+                 responseSerializer: JSONResponseSerializer(dataPreprocessor: dataPreprocessor,
+                                                            emptyResponseCodes: emptyResponseCodes,
+                                                            emptyRequestMethods: emptyRequestMethods,
+                                                            options: options),
+                 completionHandler: completionHandler)
+    }
+}
+
+// MARK: - Empty
+
+/// Protocol representing an empty response. Use `T.emptyValue()` to get an instance.
+public protocol EmptyResponse {
+    /// Empty value for the conforming type.
+    ///
+    /// - Returns: Value of `Self` to use for empty values.
+    static func emptyValue() -> Self
+}
+
+/// Type representing an empty value. Use `Empty.value` to get the static instance.
+public struct Empty: Codable {
+    /// Static `Empty` instance used for all `Empty` responses.
+    public static let value = Empty()
+}
+
+extension Empty: EmptyResponse {
+    public static func emptyValue() -> Empty {
+        value
+    }
+}
+
+// MARK: - DataDecoder Protocol
+
+/// Any type which can decode `Data` into a `Decodable` type.
+public protocol DataDecoder {
+    /// Decode `Data` into the provided type.
+    ///
+    /// - Parameters:
+    ///   - type:  The `Type` to be decoded.
+    ///   - data:  The `Data` to be decoded.
+    ///
+    /// - Returns: The decoded value of type `D`.
+    /// - Throws:  Any error that occurs during decode.
+    func decode<D: Decodable>(_ type: D.Type, from data: Data) throws -> D
+}
+
+/// `JSONDecoder` automatically conforms to `DataDecoder`.
+extension JSONDecoder: DataDecoder {}
+/// `PropertyListDecoder` automatically conforms to `DataDecoder`.
+extension PropertyListDecoder: DataDecoder {}
+
+// MARK: - Decodable
+
+/// A `ResponseSerializer` that decodes the response data as a generic value using any type that conforms to
+/// `DataDecoder`. By default, this is an instance of `JSONDecoder`. Additionally, a request returning `nil` or no data
+/// is considered an error. However, if the request has an `HTTPMethod` or the response has an HTTP status code valid
+/// for empty responses then an empty value will be returned. If the decoded type conforms to `EmptyResponse`, the
+/// type's `emptyValue()` will be returned. If the decoded type is `Empty`, the `.value` instance is returned. If the
+/// decoded type *does not* conform to `EmptyResponse` and isn't `Empty`, an error will be produced.
+public final class DecodableResponseSerializer<T: Decodable>: ResponseSerializer {
+    public let dataPreprocessor: DataPreprocessor
+    /// The `DataDecoder` instance used to decode responses.
+    public let decoder: DataDecoder
+    public let emptyResponseCodes: Set<Int>
+    public let emptyRequestMethods: Set<HTTPMethod>
+
+    /// Creates an instance using the values provided.
+    ///
+    /// - Parameters:
+    ///   - dataPreprocessor:    `DataPreprocessor` used to prepare the received `Data` for serialization.
+    ///   - decoder:             The `DataDecoder`. `JSONDecoder()` by default.
+    ///   - emptyResponseCodes:  The HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
+    ///   - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default.
+    public init(dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor,
+                decoder: DataDecoder = JSONDecoder(),
+                emptyResponseCodes: Set<Int> = DecodableResponseSerializer.defaultEmptyResponseCodes,
+                emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer.defaultEmptyRequestMethods) {
+        self.dataPreprocessor = dataPreprocessor
+        self.decoder = decoder
+        self.emptyResponseCodes = emptyResponseCodes
+        self.emptyRequestMethods = emptyRequestMethods
+    }
+
+    public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> T {
+        guard error == nil else { throw error! }
+
+        guard var data = data, !data.isEmpty else {
+            guard emptyResponseAllowed(forRequest: request, response: response) else {
+                throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
+            }
+
+            guard let emptyResponseType = T.self as? EmptyResponse.Type, let emptyValue = emptyResponseType.emptyValue() as? T else {
+                throw AFError.responseSerializationFailed(reason: .invalidEmptyResponse(type: "\(T.self)"))
+            }
+
+            return emptyValue
+        }
+
+        data = try dataPreprocessor.preprocess(data)
+
+        do {
+            return try decoder.decode(T.self, from: data)
+        } catch {
+            throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error))
+        }
+    }
+}
+
+#if swift(>=5.5)
+extension ResponseSerializer {
+    /// Creates a `DecodableResponseSerializer` using the values provided.
+    ///
+    /// - Parameters:
+    ///   - type:                `Decodable` type to decode from response data.
+    ///   - dataPreprocessor:    `DataPreprocessor` used to prepare the received `Data` for serialization.
+    ///   - decoder:             The `DataDecoder`. `JSONDecoder()` by default.
+    ///   - emptyResponseCodes:  The HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
+    ///   - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default.
+    ///
+    /// - Returns:               The `DecodableResponseSerializer`.
+    public static func decodable<T: Decodable>(of type: T.Type,
+                                               dataPreprocessor: DataPreprocessor = DecodableResponseSerializer<T>.defaultDataPreprocessor,
+                                               decoder: DataDecoder = JSONDecoder(),
+                                               emptyResponseCodes: Set<Int> = DecodableResponseSerializer<T>.defaultEmptyResponseCodes,
+                                               emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer<T>.defaultEmptyRequestMethods) -> DecodableResponseSerializer<T> where Self == DecodableResponseSerializer<T> {
+        DecodableResponseSerializer<T>(dataPreprocessor: dataPreprocessor,
+                                       decoder: decoder,
+                                       emptyResponseCodes: emptyResponseCodes,
+                                       emptyRequestMethods: emptyRequestMethods)
+    }
+}
+#endif
+
+extension DataRequest {
+    /// Adds a handler using a `DecodableResponseSerializer` to be called once the request has finished.
+    ///
+    /// - Parameters:
+    ///   - type:                `Decodable` type to decode from response data.
+    ///   - queue:               The queue on which the completion handler is dispatched. `.main` by default.
+    ///   - dataPreprocessor:    `DataPreprocessor` which processes the received `Data` before calling the
+    ///                          `completionHandler`. `PassthroughPreprocessor()` by default.
+    ///   - decoder:             `DataDecoder` to use to decode the response. `JSONDecoder()` by default.
+    ///   - emptyResponseCodes:  HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
+    ///   - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
+    ///   - completionHandler:   A closure to be executed once the request has finished.
+    ///
+    /// - Returns:               The request.
+    @discardableResult
+    public func responseDecodable<T: Decodable>(of type: T.Type = T.self,
+                                                queue: DispatchQueue = .main,
+                                                dataPreprocessor: DataPreprocessor = DecodableResponseSerializer<T>.defaultDataPreprocessor,
+                                                decoder: DataDecoder = JSONDecoder(),
+                                                emptyResponseCodes: Set<Int> = DecodableResponseSerializer<T>.defaultEmptyResponseCodes,
+                                                emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer<T>.defaultEmptyRequestMethods,
+                                                completionHandler: @escaping (AFDataResponse<T>) -> Void) -> Self {
+        response(queue: queue,
+                 responseSerializer: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor,
+                                                                 decoder: decoder,
+                                                                 emptyResponseCodes: emptyResponseCodes,
+                                                                 emptyRequestMethods: emptyRequestMethods),
+                 completionHandler: completionHandler)
+    }
+}
+
+extension DownloadRequest {
+    /// Adds a handler using a `DecodableResponseSerializer` to be called once the request has finished.
+    ///
+    /// - Parameters:
+    ///   - type:                `Decodable` type to decode from response data.
+    ///   - queue:               The queue on which the completion handler is dispatched. `.main` by default.
+    ///   - dataPreprocessor:    `DataPreprocessor` which processes the received `Data` before calling the
+    ///                          `completionHandler`. `PassthroughPreprocessor()` by default.
+    ///   - decoder:             `DataDecoder` to use to decode the response. `JSONDecoder()` by default.
+    ///   - emptyResponseCodes:  HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
+    ///   - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
+    ///   - completionHandler:   A closure to be executed once the request has finished.
+    ///
+    /// - Returns:               The request.
+    @discardableResult
+    public func responseDecodable<T: Decodable>(of type: T.Type = T.self,
+                                                queue: DispatchQueue = .main,
+                                                dataPreprocessor: DataPreprocessor = DecodableResponseSerializer<T>.defaultDataPreprocessor,
+                                                decoder: DataDecoder = JSONDecoder(),
+                                                emptyResponseCodes: Set<Int> = DecodableResponseSerializer<T>.defaultEmptyResponseCodes,
+                                                emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer<T>.defaultEmptyRequestMethods,
+                                                completionHandler: @escaping (AFDownloadResponse<T>) -> Void) -> Self {
+        response(queue: queue,
+                 responseSerializer: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor,
+                                                                 decoder: decoder,
+                                                                 emptyResponseCodes: emptyResponseCodes,
+                                                                 emptyRequestMethods: emptyRequestMethods),
+                 completionHandler: completionHandler)
+    }
+}
+
+// MARK: - DataStreamRequest
+
+/// A type which can serialize incoming `Data`.
+public protocol DataStreamSerializer {
+    /// Type produced from the serialized `Data`.
+    associatedtype SerializedObject
+
+    /// Serializes incoming `Data` into a `SerializedObject` value.
+    ///
+    /// - Parameter data: `Data` to be serialized.
+    ///
+    /// - Throws: Any error produced during serialization.
+    func serialize(_ data: Data) throws -> SerializedObject
+}
+
+/// `DataStreamSerializer` which uses the provided `DataPreprocessor` and `DataDecoder` to serialize the incoming `Data`.
+public struct DecodableStreamSerializer<T: Decodable>: DataStreamSerializer {
+    /// `DataDecoder` used to decode incoming `Data`.
+    public let decoder: DataDecoder
+    /// `DataPreprocessor` incoming `Data` is passed through before being passed to the `DataDecoder`.
+    public let dataPreprocessor: DataPreprocessor
+
+    /// Creates an instance with the provided `DataDecoder` and `DataPreprocessor`.
+    /// - Parameters:
+    ///   - decoder: `        DataDecoder` used to decode incoming `Data`. `JSONDecoder()` by default.
+    ///   - dataPreprocessor: `DataPreprocessor` used to process incoming `Data` before it's passed through the
+    ///                       `decoder`. `PassthroughPreprocessor()` by default.
+    public init(decoder: DataDecoder = JSONDecoder(), dataPreprocessor: DataPreprocessor = PassthroughPreprocessor()) {
+        self.decoder = decoder
+        self.dataPreprocessor = dataPreprocessor
+    }
+
+    public func serialize(_ data: Data) throws -> T {
+        let processedData = try dataPreprocessor.preprocess(data)
+        do {
+            return try decoder.decode(T.self, from: processedData)
+        } catch {
+            throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error))
+        }
+    }
+}
+
+/// `DataStreamSerializer` which performs no serialization on incoming `Data`.
+public struct PassthroughStreamSerializer: DataStreamSerializer {
+    /// Creates an instance.
+    public init() {}
+
+    public func serialize(_ data: Data) throws -> Data { data }
+}
+
+/// `DataStreamSerializer` which serializes incoming stream `Data` into `UTF8`-decoded `String` values.
+public struct StringStreamSerializer: DataStreamSerializer {
+    /// Creates an instance.
+    public init() {}
+
+    public func serialize(_ data: Data) throws -> String {
+        String(decoding: data, as: UTF8.self)
+    }
+}
+
+#if swift(>=5.5)
+extension DataStreamSerializer {
+    /// Creates a `DecodableStreamSerializer` instance with the provided `DataDecoder` and `DataPreprocessor`.
+    ///
+    /// - Parameters:
+    ///   - type:             `Decodable` type to decode from stream data.
+    ///   - decoder: `        DataDecoder` used to decode incoming `Data`. `JSONDecoder()` by default.
+    ///   - dataPreprocessor: `DataPreprocessor` used to process incoming `Data` before it's passed through the
+    ///                       `decoder`. `PassthroughPreprocessor()` by default.
+    public static func decodable<T: Decodable>(of type: T.Type,
+                                               decoder: DataDecoder = JSONDecoder(),
+                                               dataPreprocessor: DataPreprocessor = PassthroughPreprocessor()) -> Self where Self == DecodableStreamSerializer<T> {
+        DecodableStreamSerializer<T>(decoder: decoder, dataPreprocessor: dataPreprocessor)
+    }
+}
+
+extension DataStreamSerializer where Self == PassthroughStreamSerializer {
+    /// Provides a `PassthroughStreamSerializer` instance.
+    public static var passthrough: PassthroughStreamSerializer { PassthroughStreamSerializer() }
+}
+
+extension DataStreamSerializer where Self == StringStreamSerializer {
+    /// Provides a `StringStreamSerializer` instance.
+    public static var string: StringStreamSerializer { StringStreamSerializer() }
+}
+#endif
+
+extension DataStreamRequest {
+    /// Adds a `StreamHandler` which performs no parsing on incoming `Data`.
+    ///
+    /// - Parameters:
+    ///   - queue:  `DispatchQueue` on which to perform `StreamHandler` closure.
+    ///   - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times.
+    ///
+    /// - Returns:  The `DataStreamRequest`.
+    @discardableResult
+    public func responseStream(on queue: DispatchQueue = .main, stream: @escaping Handler<Data, Never>) -> Self {
+        let parser = { [unowned self] (data: Data) in
+            queue.async {
+                self.capturingError {
+                    try stream(.init(event: .stream(.success(data)), token: .init(self)))
+                }
+
+                self.updateAndCompleteIfPossible()
+            }
+        }
+
+        $streamMutableState.write { $0.streams.append(parser) }
+        appendStreamCompletion(on: queue, stream: stream)
+
+        return self
+    }
+
+    /// Adds a `StreamHandler` which uses the provided `DataStreamSerializer` to process incoming `Data`.
+    ///
+    /// - Parameters:
+    ///   - serializer: `DataStreamSerializer` used to process incoming `Data`. Its work is done on the `serializationQueue`.
+    ///   - queue:      `DispatchQueue` on which to perform `StreamHandler` closure.
+    ///   - stream:     `StreamHandler` closure called as `Data` is received. May be called multiple times.
+    ///
+    /// - Returns:      The `DataStreamRequest`.
+    @discardableResult
+    public func responseStream<Serializer: DataStreamSerializer>(using serializer: Serializer,
+                                                                 on queue: DispatchQueue = .main,
+                                                                 stream: @escaping Handler<Serializer.SerializedObject, AFError>) -> Self {
+        let parser = { [unowned self] (data: Data) in
+            self.serializationQueue.async {
+                // Start work on serialization queue.
+                let result = Result { try serializer.serialize(data) }
+                    .mapError { $0.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: $0))) }
+                // End work on serialization queue.
+                self.underlyingQueue.async {
+                    self.eventMonitor?.request(self, didParseStream: result)
+
+                    if result.isFailure, self.automaticallyCancelOnStreamError {
+                        self.cancel()
+                    }
+
+                    queue.async {
+                        self.capturingError {
+                            try stream(.init(event: .stream(result), token: .init(self)))
+                        }
+
+                        self.updateAndCompleteIfPossible()
+                    }
+                }
+            }
+        }
+
+        $streamMutableState.write { $0.streams.append(parser) }
+        appendStreamCompletion(on: queue, stream: stream)
+
+        return self
+    }
+
+    /// Adds a `StreamHandler` which parses incoming `Data` as a UTF8 `String`.
+    ///
+    /// - Parameters:
+    ///   - queue:      `DispatchQueue` on which to perform `StreamHandler` closure.
+    ///   - stream:     `StreamHandler` closure called as `Data` is received. May be called multiple times.
+    ///
+    /// - Returns:  The `DataStreamRequest`.
+    @discardableResult
+    public func responseStreamString(on queue: DispatchQueue = .main,
+                                     stream: @escaping Handler<String, Never>) -> Self {
+        let parser = { [unowned self] (data: Data) in
+            self.serializationQueue.async {
+                // Start work on serialization queue.
+                let string = String(decoding: data, as: UTF8.self)
+                // End work on serialization queue.
+                self.underlyingQueue.async {
+                    self.eventMonitor?.request(self, didParseStream: .success(string))
+
+                    queue.async {
+                        self.capturingError {
+                            try stream(.init(event: .stream(.success(string)), token: .init(self)))
+                        }
+
+                        self.updateAndCompleteIfPossible()
+                    }
+                }
+            }
+        }
+
+        $streamMutableState.write { $0.streams.append(parser) }
+        appendStreamCompletion(on: queue, stream: stream)
+
+        return self
+    }
+
+    private func updateAndCompleteIfPossible() {
+        $streamMutableState.write { state in
+            state.numberOfExecutingStreams -= 1
+
+            guard state.numberOfExecutingStreams == 0, !state.enqueuedCompletionEvents.isEmpty else { return }
+
+            let completionEvents = state.enqueuedCompletionEvents
+            self.underlyingQueue.async { completionEvents.forEach { $0() } }
+            state.enqueuedCompletionEvents.removeAll()
+        }
+    }
+
+    /// Adds a `StreamHandler` which parses incoming `Data` using the provided `DataDecoder`.
+    ///
+    /// - Parameters:
+    ///   - type:         `Decodable` type to parse incoming `Data` into.
+    ///   - queue:        `DispatchQueue` on which to perform `StreamHandler` closure.
+    ///   - decoder:      `DataDecoder` used to decode the incoming `Data`.
+    ///   - preprocessor: `DataPreprocessor` used to process the incoming `Data` before it's passed to the `decoder`.
+    ///   - stream:       `StreamHandler` closure called as `Data` is received. May be called multiple times.
+    ///
+    /// - Returns: The `DataStreamRequest`.
+    @discardableResult
+    public func responseStreamDecodable<T: Decodable>(of type: T.Type = T.self,
+                                                      on queue: DispatchQueue = .main,
+                                                      using decoder: DataDecoder = JSONDecoder(),
+                                                      preprocessor: DataPreprocessor = PassthroughPreprocessor(),
+                                                      stream: @escaping Handler<T, AFError>) -> Self {
+        responseStream(using: DecodableStreamSerializer<T>(decoder: decoder, dataPreprocessor: preprocessor),
+                       stream: stream)
+    }
+}

+ 120 - 0
Pods/Alamofire/Source/Result+Alamofire.swift

@@ -0,0 +1,120 @@
+//
+//  Result+Alamofire.swift
+//
+//  Copyright (c) 2019 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
+
+/// Default type of `Result` returned by Alamofire, with an `AFError` `Failure` type.
+public typealias AFResult<Success> = Result<Success, AFError>
+
+// MARK: - Internal APIs
+
+extension Result {
+    /// Returns whether the instance is `.success`.
+    var isSuccess: Bool {
+        guard case .success = self else { return false }
+        return true
+    }
+
+    /// Returns whether the instance is `.failure`.
+    var isFailure: Bool {
+        !isSuccess
+    }
+
+    /// Returns the associated value if the result is a success, `nil` otherwise.
+    var success: Success? {
+        guard case let .success(value) = self else { return nil }
+        return value
+    }
+
+    /// Returns the associated error value if the result is a failure, `nil` otherwise.
+    var failure: Failure? {
+        guard case let .failure(error) = self else { return nil }
+        return error
+    }
+
+    /// Initializes a `Result` from value or error. Returns `.failure` if the error is non-nil, `.success` otherwise.
+    ///
+    /// - Parameters:
+    ///   - value: A value.
+    ///   - error: An `Error`.
+    init(value: Success, error: Failure?) {
+        if let error = error {
+            self = .failure(error)
+        } else {
+            self = .success(value)
+        }
+    }
+
+    /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter.
+    ///
+    /// Use the `tryMap` method with a closure that may throw an error. For example:
+    ///
+    ///     let possibleData: Result<Data, Error> = .success(Data(...))
+    ///     let possibleObject = possibleData.tryMap {
+    ///         try JSONSerialization.jsonObject(with: $0)
+    ///     }
+    ///
+    /// - parameter transform: A closure that takes the success value of the instance.
+    ///
+    /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the
+    ///            same failure.
+    func tryMap<NewSuccess>(_ transform: (Success) throws -> NewSuccess) -> Result<NewSuccess, Error> {
+        switch self {
+        case let .success(value):
+            do {
+                return try .success(transform(value))
+            } catch {
+                return .failure(error)
+            }
+        case let .failure(error):
+            return .failure(error)
+        }
+    }
+
+    /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter.
+    ///
+    /// Use the `tryMapError` function with a closure that may throw an error. For example:
+    ///
+    ///     let possibleData: Result<Data, Error> = .success(Data(...))
+    ///     let possibleObject = possibleData.tryMapError {
+    ///         try someFailableFunction(taking: $0)
+    ///     }
+    ///
+    /// - Parameter transform: A throwing closure that takes the error of the instance.
+    ///
+    /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns
+    ///            the same success.
+    func tryMapError<NewFailure: Error>(_ transform: (Failure) throws -> NewFailure) -> Result<Success, Error> {
+        switch self {
+        case let .failure(error):
+            do {
+                return try .failure(transform(error))
+            } catch {
+                return .failure(error)
+            }
+        case let .success(value):
+            return .success(value)
+        }
+    }
+}

+ 434 - 0
Pods/Alamofire/Source/RetryPolicy.swift

@@ -0,0 +1,434 @@
+//
+//  RetryPolicy.swift
+//
+//  Copyright (c) 2019-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.
+//
+
+import Foundation
+
+/// A retry policy that retries requests using an exponential backoff for allowed HTTP methods and HTTP status codes
+/// as well as certain types of networking errors.
+open class RetryPolicy: RequestInterceptor {
+    /// The default retry limit for retry policies.
+    public static let defaultRetryLimit: UInt = 2
+
+    /// The default exponential backoff base for retry policies (must be a minimum of 2).
+    public static let defaultExponentialBackoffBase: UInt = 2
+
+    /// The default exponential backoff scale for retry policies.
+    public static let defaultExponentialBackoffScale: Double = 0.5
+
+    /// The default HTTP methods to retry.
+    /// See [RFC 2616 - Section 9.1.2](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html) for more information.
+    public static let defaultRetryableHTTPMethods: Set<HTTPMethod> = [.delete, // [Delete](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.7) - not always idempotent
+                                                                      .get, // [GET](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3) - generally idempotent
+                                                                      .head, // [HEAD](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4) - generally idempotent
+                                                                      .options, // [OPTIONS](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.2) - inherently idempotent
+                                                                      .put, // [PUT](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6) - not always idempotent
+                                                                      .trace // [TRACE](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.8) - inherently idempotent
+    ]
+
+    /// The default HTTP status codes to retry.
+    /// See [RFC 2616 - Section 10](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10) for more information.
+    public static let defaultRetryableHTTPStatusCodes: Set<Int> = [408, // [Request Timeout](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.9)
+                                                                   500, // [Internal Server Error](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.1)
+                                                                   502, // [Bad Gateway](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.3)
+                                                                   503, // [Service Unavailable](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.4)
+                                                                   504 // [Gateway Timeout](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.5)
+    ]
+
+    /// The default URL error codes to retry.
+    public static let defaultRetryableURLErrorCodes: Set<URLError.Code> = [// [Security] App Transport Security disallowed a connection because there is no secure network connection.
+        //   - [Disabled] ATS settings do not change at runtime.
+        // .appTransportSecurityRequiresSecureConnection,
+
+        // [System] An app or app extension attempted to connect to a background session that is already connected to a
+        // process.
+        //   - [Enabled] The other process could release the background session.
+        .backgroundSessionInUseByAnotherProcess,
+
+        // [System] The shared container identifier of the URL session configuration is needed but has not been set.
+        //   - [Disabled] Cannot change at runtime.
+        // .backgroundSessionRequiresSharedContainer,
+
+        // [System] The app is suspended or exits while a background data task is processing.
+        //   - [Enabled] App can be foregrounded or launched to recover.
+        .backgroundSessionWasDisconnected,
+
+        // [Network] The URL Loading system received bad data from the server.
+        //   - [Enabled] Server could return valid data when retrying.
+        .badServerResponse,
+
+        // [Resource] A malformed URL prevented a URL request from being initiated.
+        //   - [Disabled] URL was most likely constructed incorrectly.
+        // .badURL,
+
+        // [System] A connection was attempted while a phone call is active on a network that does not support
+        // simultaneous phone and data communication (EDGE or GPRS).
+        //   - [Enabled] Phone call could be ended to allow request to recover.
+        .callIsActive,
+
+        // [Client] An asynchronous load has been canceled.
+        //   - [Disabled] Request was cancelled by the client.
+        // .cancelled,
+
+        // [File System] A download task couldn’t close the downloaded file on disk.
+        //   - [Disabled] File system error is unlikely to recover with retry.
+        // .cannotCloseFile,
+
+        // [Network] An attempt to connect to a host failed.
+        //   - [Enabled] Server or DNS lookup could recover during retry.
+        .cannotConnectToHost,
+
+        // [File System] A download task couldn’t create the downloaded file on disk because of an I/O failure.
+        //   - [Disabled] File system error is unlikely to recover with retry.
+        // .cannotCreateFile,
+
+        // [Data] Content data received during a connection request had an unknown content encoding.
+        //   - [Disabled] Server is unlikely to modify the content encoding during a retry.
+        // .cannotDecodeContentData,
+
+        // [Data] Content data received during a connection request could not be decoded for a known content encoding.
+        //   - [Disabled] Server is unlikely to modify the content encoding during a retry.
+        // .cannotDecodeRawData,
+
+        // [Network] The host name for a URL could not be resolved.
+        //   - [Enabled] Server or DNS lookup could recover during retry.
+        .cannotFindHost,
+
+        // [Network] A request to load an item only from the cache could not be satisfied.
+        //   - [Enabled] Cache could be populated during a retry.
+        .cannotLoadFromNetwork,
+
+        // [File System] A download task was unable to move a downloaded file on disk.
+        //   - [Disabled] File system error is unlikely to recover with retry.
+        // .cannotMoveFile,
+
+        // [File System] A download task was unable to open the downloaded file on disk.
+        //   - [Disabled] File system error is unlikely to recover with retry.
+        // .cannotOpenFile,
+
+        // [Data] A task could not parse a response.
+        //   - [Disabled] Invalid response is unlikely to recover with retry.
+        // .cannotParseResponse,
+
+        // [File System] A download task was unable to remove a downloaded file from disk.
+        //   - [Disabled] File system error is unlikely to recover with retry.
+        // .cannotRemoveFile,
+
+        // [File System] A download task was unable to write to the downloaded file on disk.
+        //   - [Disabled] File system error is unlikely to recover with retry.
+        // .cannotWriteToFile,
+
+        // [Security] A client certificate was rejected.
+        //   - [Disabled] Client certificate is unlikely to change with retry.
+        // .clientCertificateRejected,
+
+        // [Security] A client certificate was required to authenticate an SSL connection during a request.
+        //   - [Disabled] Client certificate is unlikely to be provided with retry.
+        // .clientCertificateRequired,
+
+        // [Data] The length of the resource data exceeds the maximum allowed.
+        //   - [Disabled] Resource will likely still exceed the length maximum on retry.
+        // .dataLengthExceedsMaximum,
+
+        // [System] The cellular network disallowed a connection.
+        //   - [Enabled] WiFi connection could be established during retry.
+        .dataNotAllowed,
+
+        // [Network] The host address could not be found via DNS lookup.
+        //   - [Enabled] DNS lookup could succeed during retry.
+        .dnsLookupFailed,
+
+        // [Data] A download task failed to decode an encoded file during the download.
+        //   - [Enabled] Server could correct the decoding issue with retry.
+        .downloadDecodingFailedMidStream,
+
+        // [Data] A download task failed to decode an encoded file after downloading.
+        //   - [Enabled] Server could correct the decoding issue with retry.
+        .downloadDecodingFailedToComplete,
+
+        // [File System] A file does not exist.
+        //   - [Disabled] File system error is unlikely to recover with retry.
+        // .fileDoesNotExist,
+
+        // [File System] A request for an FTP file resulted in the server responding that the file is not a plain file,
+        // but a directory.
+        //   - [Disabled] FTP directory is not likely to change to a file during a retry.
+        // .fileIsDirectory,
+
+        // [Network] A redirect loop has been detected or the threshold for number of allowable redirects has been
+        // exceeded (currently 16).
+        //   - [Disabled] The redirect loop is unlikely to be resolved within the retry window.
+        // .httpTooManyRedirects,
+
+        // [System] The attempted connection required activating a data context while roaming, but international roaming
+        // is disabled.
+        //   - [Enabled] WiFi connection could be established during retry.
+        .internationalRoamingOff,
+
+        // [Connectivity] A client or server connection was severed in the middle of an in-progress load.
+        //   - [Enabled] A network connection could be established during retry.
+        .networkConnectionLost,
+
+        // [File System] A resource couldn’t be read because of insufficient permissions.
+        //   - [Disabled] Permissions are unlikely to be granted during retry.
+        // .noPermissionsToReadFile,
+
+        // [Connectivity] A network resource was requested, but an internet connection has not been established and
+        // cannot be established automatically.
+        //   - [Enabled] A network connection could be established during retry.
+        .notConnectedToInternet,
+
+        // [Resource] A redirect was specified by way of server response code, but the server did not accompany this
+        // code with a redirect URL.
+        //   - [Disabled] The redirect URL is unlikely to be supplied during a retry.
+        // .redirectToNonExistentLocation,
+
+        // [Client] A body stream is needed but the client did not provide one.
+        //   - [Disabled] The client will be unlikely to supply a body stream during retry.
+        // .requestBodyStreamExhausted,
+
+        // [Resource] A requested resource couldn’t be retrieved.
+        //   - [Disabled] The resource is unlikely to become available during the retry window.
+        // .resourceUnavailable,
+
+        // [Security] An attempt to establish a secure connection failed for reasons that can’t be expressed more
+        // specifically.
+        //   - [Enabled] The secure connection could be established during a retry given the lack of specificity
+        //     provided by the error.
+        .secureConnectionFailed,
+
+        // [Security] A server certificate had a date which indicates it has expired, or is not yet valid.
+        //   - [Enabled] The server certificate could become valid within the retry window.
+        .serverCertificateHasBadDate,
+
+        // [Security] A server certificate was not signed by any root server.
+        //   - [Disabled] The server certificate is unlikely to change during the retry window.
+        // .serverCertificateHasUnknownRoot,
+
+        // [Security] A server certificate is not yet valid.
+        //   - [Enabled] The server certificate could become valid within the retry window.
+        .serverCertificateNotYetValid,
+
+        // [Security] A server certificate was signed by a root server that isn’t trusted.
+        //   - [Disabled] The server certificate is unlikely to become trusted within the retry window.
+        // .serverCertificateUntrusted,
+
+        // [Network] An asynchronous operation timed out.
+        //   - [Enabled] The request timed out for an unknown reason and should be retried.
+        .timedOut
+
+        // [System] The URL Loading System encountered an error that it can’t interpret.
+        //   - [Disabled] The error could not be interpreted and is unlikely to be recovered from during a retry.
+        // .unknown,
+
+        // [Resource] A properly formed URL couldn’t be handled by the framework.
+        //   - [Disabled] The URL is unlikely to change during a retry.
+        // .unsupportedURL,
+
+        // [Client] Authentication is required to access a resource.
+        //   - [Disabled] The user authentication is unlikely to be provided by retrying.
+        // .userAuthenticationRequired,
+
+        // [Client] An asynchronous request for authentication has been canceled by the user.
+        //   - [Disabled] The user cancelled authentication and explicitly took action to not retry.
+        // .userCancelledAuthentication,
+
+        // [Resource] A server reported that a URL has a non-zero content length, but terminated the network connection
+        // gracefully without sending any data.
+        //   - [Disabled] The server is unlikely to provide data during the retry window.
+        // .zeroByteResource,
+    ]
+
+    /// The total number of times the request is allowed to be retried.
+    public let retryLimit: UInt
+
+    /// The base of the exponential backoff policy (should always be greater than or equal to 2).
+    public let exponentialBackoffBase: UInt
+
+    /// The scale of the exponential backoff.
+    public let exponentialBackoffScale: Double
+
+    /// The HTTP methods that are allowed to be retried.
+    public let retryableHTTPMethods: Set<HTTPMethod>
+
+    /// The HTTP status codes that are automatically retried by the policy.
+    public let retryableHTTPStatusCodes: Set<Int>
+
+    /// The URL error codes that are automatically retried by the policy.
+    public let retryableURLErrorCodes: Set<URLError.Code>
+
+    /// Creates a `RetryPolicy` from the specified parameters.
+    ///
+    /// - Parameters:
+    ///   - retryLimit:               The total number of times the request is allowed to be retried. `2` by default.
+    ///   - exponentialBackoffBase:   The base of the exponential backoff policy. `2` by default.
+    ///   - exponentialBackoffScale:  The scale of the exponential backoff. `0.5` by default.
+    ///   - retryableHTTPMethods:     The HTTP methods that are allowed to be retried.
+    ///                               `RetryPolicy.defaultRetryableHTTPMethods` by default.
+    ///   - retryableHTTPStatusCodes: The HTTP status codes that are automatically retried by the policy.
+    ///                               `RetryPolicy.defaultRetryableHTTPStatusCodes` by default.
+    ///   - retryableURLErrorCodes:   The URL error codes that are automatically retried by the policy.
+    ///                               `RetryPolicy.defaultRetryableURLErrorCodes` by default.
+    public init(retryLimit: UInt = RetryPolicy.defaultRetryLimit,
+                exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase,
+                exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale,
+                retryableHTTPMethods: Set<HTTPMethod> = RetryPolicy.defaultRetryableHTTPMethods,
+                retryableHTTPStatusCodes: Set<Int> = RetryPolicy.defaultRetryableHTTPStatusCodes,
+                retryableURLErrorCodes: Set<URLError.Code> = RetryPolicy.defaultRetryableURLErrorCodes) {
+        precondition(exponentialBackoffBase >= 2, "The `exponentialBackoffBase` must be a minimum of 2.")
+
+        self.retryLimit = retryLimit
+        self.exponentialBackoffBase = exponentialBackoffBase
+        self.exponentialBackoffScale = exponentialBackoffScale
+        self.retryableHTTPMethods = retryableHTTPMethods
+        self.retryableHTTPStatusCodes = retryableHTTPStatusCodes
+        self.retryableURLErrorCodes = retryableURLErrorCodes
+    }
+
+    open func retry(_ request: Request,
+                    for session: Session,
+                    dueTo error: Error,
+                    completion: @escaping (RetryResult) -> Void) {
+        if request.retryCount < retryLimit, shouldRetry(request: request, dueTo: error) {
+            completion(.retryWithDelay(pow(Double(exponentialBackoffBase), Double(request.retryCount)) * exponentialBackoffScale))
+        } else {
+            completion(.doNotRetry)
+        }
+    }
+
+    /// Determines whether or not to retry the provided `Request`.
+    ///
+    /// - Parameters:
+    ///     - request: `Request` that failed due to the provided `Error`.
+    ///     - error:   `Error` encountered while executing the `Request`.
+    ///
+    /// - Returns:     `Bool` determining whether or not to retry the `Request`.
+    open func shouldRetry(request: Request, dueTo error: Error) -> Bool {
+        guard let httpMethod = request.request?.method, retryableHTTPMethods.contains(httpMethod) else { return false }
+
+        if let statusCode = request.response?.statusCode, retryableHTTPStatusCodes.contains(statusCode) {
+            return true
+        } else {
+            let errorCode = (error as? URLError)?.code
+            let afErrorCode = (error.asAFError?.underlyingError as? URLError)?.code
+
+            guard let code = errorCode ?? afErrorCode else { return false }
+
+            return retryableURLErrorCodes.contains(code)
+        }
+    }
+}
+
+#if swift(>=5.5)
+extension RequestInterceptor where Self == RetryPolicy {
+    /// Provides a default `RetryPolicy` instance.
+    public static var retryPolicy: RetryPolicy { RetryPolicy() }
+
+    /// Creates an `RetryPolicy` from the specified parameters.
+    ///
+    /// - Parameters:
+    ///   - retryLimit:               The total number of times the request is allowed to be retried. `2` by default.
+    ///   - exponentialBackoffBase:   The base of the exponential backoff policy. `2` by default.
+    ///   - exponentialBackoffScale:  The scale of the exponential backoff. `0.5` by default.
+    ///   - retryableHTTPMethods:     The HTTP methods that are allowed to be retried.
+    ///                               `RetryPolicy.defaultRetryableHTTPMethods` by default.
+    ///   - retryableHTTPStatusCodes: The HTTP status codes that are automatically retried by the policy.
+    ///                               `RetryPolicy.defaultRetryableHTTPStatusCodes` by default.
+    ///   - retryableURLErrorCodes:   The URL error codes that are automatically retried by the policy.
+    ///                               `RetryPolicy.defaultRetryableURLErrorCodes` by default.
+    ///
+    /// - Returns:                    The `RetryPolicy`
+    public static func retryPolicy(retryLimit: UInt = RetryPolicy.defaultRetryLimit,
+                                   exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase,
+                                   exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale,
+                                   retryableHTTPMethods: Set<HTTPMethod> = RetryPolicy.defaultRetryableHTTPMethods,
+                                   retryableHTTPStatusCodes: Set<Int> = RetryPolicy.defaultRetryableHTTPStatusCodes,
+                                   retryableURLErrorCodes: Set<URLError.Code> = RetryPolicy.defaultRetryableURLErrorCodes) -> RetryPolicy {
+        RetryPolicy(retryLimit: retryLimit,
+                    exponentialBackoffBase: exponentialBackoffBase,
+                    exponentialBackoffScale: exponentialBackoffScale,
+                    retryableHTTPMethods: retryableHTTPMethods,
+                    retryableHTTPStatusCodes: retryableHTTPStatusCodes,
+                    retryableURLErrorCodes: retryableURLErrorCodes)
+    }
+}
+#endif
+
+// MARK: -
+
+/// A retry policy that automatically retries idempotent requests for network connection lost errors. For more
+/// information about retrying network connection lost errors, please refer to Apple's
+/// [technical document](https://developer.apple.com/library/content/qa/qa1941/_index.html).
+open class ConnectionLostRetryPolicy: RetryPolicy {
+    /// Creates a `ConnectionLostRetryPolicy` instance from the specified parameters.
+    ///
+    /// - Parameters:
+    ///   - retryLimit:              The total number of times the request is allowed to be retried.
+    ///                              `RetryPolicy.defaultRetryLimit` by default.
+    ///   - exponentialBackoffBase:  The base of the exponential backoff policy.
+    ///                              `RetryPolicy.defaultExponentialBackoffBase` by default.
+    ///   - exponentialBackoffScale: The scale of the exponential backoff.
+    ///                              `RetryPolicy.defaultExponentialBackoffScale` by default.
+    ///   - retryableHTTPMethods:    The idempotent http methods to retry.
+    ///                              `RetryPolicy.defaultRetryableHTTPMethods` by default.
+    public init(retryLimit: UInt = RetryPolicy.defaultRetryLimit,
+                exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase,
+                exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale,
+                retryableHTTPMethods: Set<HTTPMethod> = RetryPolicy.defaultRetryableHTTPMethods) {
+        super.init(retryLimit: retryLimit,
+                   exponentialBackoffBase: exponentialBackoffBase,
+                   exponentialBackoffScale: exponentialBackoffScale,
+                   retryableHTTPMethods: retryableHTTPMethods,
+                   retryableHTTPStatusCodes: [],
+                   retryableURLErrorCodes: [.networkConnectionLost])
+    }
+}
+
+#if swift(>=5.5)
+extension RequestInterceptor where Self == ConnectionLostRetryPolicy {
+    /// Provides a default `ConnectionLostRetryPolicy` instance.
+    public static var connectionLostRetryPolicy: ConnectionLostRetryPolicy { ConnectionLostRetryPolicy() }
+
+    /// Creates a `ConnectionLostRetryPolicy` instance from the specified parameters.
+    ///
+    /// - Parameters:
+    ///   - retryLimit:              The total number of times the request is allowed to be retried.
+    ///                              `RetryPolicy.defaultRetryLimit` by default.
+    ///   - exponentialBackoffBase:  The base of the exponential backoff policy.
+    ///                              `RetryPolicy.defaultExponentialBackoffBase` by default.
+    ///   - exponentialBackoffScale: The scale of the exponential backoff.
+    ///                              `RetryPolicy.defaultExponentialBackoffScale` by default.
+    ///   - retryableHTTPMethods:    The idempotent http methods to retry.
+    ///
+    /// - Returns:                   The `ConnectionLostRetryPolicy`.
+    public static func connectionLostRetryPolicy(retryLimit: UInt = RetryPolicy.defaultRetryLimit,
+                                                 exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase,
+                                                 exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale,
+                                                 retryableHTTPMethods: Set<HTTPMethod> = RetryPolicy.defaultRetryableHTTPMethods) -> ConnectionLostRetryPolicy {
+        ConnectionLostRetryPolicy(retryLimit: retryLimit,
+                                  exponentialBackoffBase: exponentialBackoffBase,
+                                  exponentialBackoffScale: exponentialBackoffScale,
+                                  retryableHTTPMethods: retryableHTTPMethods)
+    }
+}
+#endif

+ 743 - 0
Pods/Alamofire/Source/ServerTrustEvaluation.swift

@@ -0,0 +1,743 @@
+//
+//  ServerTrustPolicy.swift
+//
+//  Copyright (c) 2014-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
+
+/// Responsible for managing the mapping of `ServerTrustEvaluating` values to given hosts.
+open class ServerTrustManager {
+    /// Determines whether all hosts for this `ServerTrustManager` must be evaluated. `true` by default.
+    public let allHostsMustBeEvaluated: Bool
+
+    /// The dictionary of policies mapped to a particular host.
+    public let evaluators: [String: ServerTrustEvaluating]
+
+    /// Initializes the `ServerTrustManager` instance with the given evaluators.
+    ///
+    /// Since different servers and web services can have different leaf certificates, intermediate and even root
+    /// certificates, it is important to have the flexibility to specify evaluation policies on a per host basis. This
+    /// allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key
+    /// pinning for host3 and disabling evaluation for host4.
+    ///
+    /// - Parameters:
+    ///   - allHostsMustBeEvaluated: The value determining whether all hosts for this instance must be evaluated. `true`
+    ///                              by default.
+    ///   - evaluators:              A dictionary of evaluators mapped to hosts.
+    public init(allHostsMustBeEvaluated: Bool = true, evaluators: [String: ServerTrustEvaluating]) {
+        self.allHostsMustBeEvaluated = allHostsMustBeEvaluated
+        self.evaluators = evaluators
+    }
+
+    #if !(os(Linux) || os(Windows))
+    /// Returns the `ServerTrustEvaluating` value for the given host, if one is set.
+    ///
+    /// By default, this method will return the policy that perfectly matches the given host. Subclasses could override
+    /// this method and implement more complex mapping implementations such as wildcards.
+    ///
+    /// - Parameter host: The host to use when searching for a matching policy.
+    ///
+    /// - Returns:        The `ServerTrustEvaluating` value for the given host if found, `nil` otherwise.
+    /// - Throws:         `AFError.serverTrustEvaluationFailed` if `allHostsMustBeEvaluated` is `true` and no matching
+    ///                   evaluators are found.
+    open func serverTrustEvaluator(forHost host: String) throws -> ServerTrustEvaluating? {
+        guard let evaluator = evaluators[host] else {
+            if allHostsMustBeEvaluated {
+                throw AFError.serverTrustEvaluationFailed(reason: .noRequiredEvaluator(host: host))
+            }
+
+            return nil
+        }
+
+        return evaluator
+    }
+    #endif
+}
+
+/// A protocol describing the API used to evaluate server trusts.
+public protocol ServerTrustEvaluating {
+    #if os(Linux) || os(Windows)
+    // Implement this once Linux/Windows has API for evaluating server trusts.
+    #else
+    /// Evaluates the given `SecTrust` value for the given `host`.
+    ///
+    /// - Parameters:
+    ///   - trust: The `SecTrust` value to evaluate.
+    ///   - host:  The host for which to evaluate the `SecTrust` value.
+    ///
+    /// - Returns: A `Bool` indicating whether the evaluator considers the `SecTrust` value valid for `host`.
+    func evaluate(_ trust: SecTrust, forHost host: String) throws
+    #endif
+}
+
+// MARK: - Server Trust Evaluators
+
+#if !(os(Linux) || os(Windows))
+/// An evaluator which uses the default server trust evaluation while allowing you to control whether to validate the
+/// host provided by the challenge. Applications are encouraged to always validate the host in production environments
+/// to guarantee the validity of the server's certificate chain.
+public final class DefaultTrustEvaluator: ServerTrustEvaluating {
+    private let validateHost: Bool
+
+    /// Creates a `DefaultTrustEvaluator`.
+    ///
+    /// - Parameter validateHost: Determines whether or not the evaluator should validate the host. `true` by default.
+    public init(validateHost: Bool = true) {
+        self.validateHost = validateHost
+    }
+
+    public func evaluate(_ trust: SecTrust, forHost host: String) throws {
+        if validateHost {
+            try trust.af.performValidation(forHost: host)
+        }
+
+        try trust.af.performDefaultValidation(forHost: host)
+    }
+}
+
+/// An evaluator which Uses the default and revoked server trust evaluations allowing you to control whether to validate
+/// the host provided by the challenge as well as specify the revocation flags for testing for revoked certificates.
+/// Apple platforms did not start testing for revoked certificates automatically until iOS 10.1, macOS 10.12 and tvOS
+/// 10.1 which is demonstrated in our TLS tests. Applications are encouraged to always validate the host in production
+/// environments to guarantee the validity of the server's certificate chain.
+public final class RevocationTrustEvaluator: ServerTrustEvaluating {
+    /// Represents the options to be use when evaluating the status of a certificate.
+    /// Only Revocation Policy Constants are valid, and can be found in [Apple's documentation](https://developer.apple.com/documentation/security/certificate_key_and_trust_services/policies/1563600-revocation_policy_constants).
+    public struct Options: OptionSet {
+        /// Perform revocation checking using the CRL (Certification Revocation List) method.
+        public static let crl = Options(rawValue: kSecRevocationCRLMethod)
+        /// Consult only locally cached replies; do not use network access.
+        public static let networkAccessDisabled = Options(rawValue: kSecRevocationNetworkAccessDisabled)
+        /// Perform revocation checking using OCSP (Online Certificate Status Protocol).
+        public static let ocsp = Options(rawValue: kSecRevocationOCSPMethod)
+        /// Prefer CRL revocation checking over OCSP; by default, OCSP is preferred.
+        public static let preferCRL = Options(rawValue: kSecRevocationPreferCRL)
+        /// Require a positive response to pass the policy. If the flag is not set, revocation checking is done on a
+        /// "best attempt" basis, where failure to reach the server is not considered fatal.
+        public static let requirePositiveResponse = Options(rawValue: kSecRevocationRequirePositiveResponse)
+        /// Perform either OCSP or CRL checking. The checking is performed according to the method(s) specified in the
+        /// certificate and the value of `preferCRL`.
+        public static let any = Options(rawValue: kSecRevocationUseAnyAvailableMethod)
+
+        /// The raw value of the option.
+        public let rawValue: CFOptionFlags
+
+        /// Creates an `Options` value with the given `CFOptionFlags`.
+        ///
+        /// - Parameter rawValue: The `CFOptionFlags` value to initialize with.
+        public init(rawValue: CFOptionFlags) {
+            self.rawValue = rawValue
+        }
+    }
+
+    private let performDefaultValidation: Bool
+    private let validateHost: Bool
+    private let options: Options
+
+    /// Creates a `RevocationTrustEvaluator` using the provided parameters.
+    ///
+    /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use
+    ///         `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates.
+    ///
+    /// - Parameters:
+    ///   - performDefaultValidation: Determines whether default validation should be performed in addition to
+    ///                               evaluating the pinned certificates. `true` by default.
+    ///   - validateHost:             Determines whether or not the evaluator should validate the host, in addition to
+    ///                               performing the default evaluation, even if `performDefaultValidation` is `false`.
+    ///                               `true` by default.
+    ///   - options:                  The `Options` to use to check the revocation status of the certificate. `.any` by
+    ///                               default.
+    public init(performDefaultValidation: Bool = true, validateHost: Bool = true, options: Options = .any) {
+        self.performDefaultValidation = performDefaultValidation
+        self.validateHost = validateHost
+        self.options = options
+    }
+
+    public func evaluate(_ trust: SecTrust, forHost host: String) throws {
+        if performDefaultValidation {
+            try trust.af.performDefaultValidation(forHost: host)
+        }
+
+        if validateHost {
+            try trust.af.performValidation(forHost: host)
+        }
+
+        if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) {
+            try trust.af.evaluate(afterApplying: SecPolicy.af.revocation(options: options))
+        } else {
+            try trust.af.validate(policy: SecPolicy.af.revocation(options: options)) { status, result in
+                AFError.serverTrustEvaluationFailed(reason: .revocationCheckFailed(output: .init(host, trust, status, result), options: options))
+            }
+        }
+    }
+}
+
+#if swift(>=5.5)
+extension ServerTrustEvaluating where Self == RevocationTrustEvaluator {
+    /// Provides a default `RevocationTrustEvaluator` instance.
+    public static var revocationChecking: RevocationTrustEvaluator { RevocationTrustEvaluator() }
+
+    /// Creates a `RevocationTrustEvaluator` using the provided parameters.
+    ///
+    /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use
+    ///         `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates.
+    ///
+    /// - Parameters:
+    ///   - performDefaultValidation: Determines whether default validation should be performed in addition to
+    ///                               evaluating the pinned certificates. `true` by default.
+    ///   - validateHost:             Determines whether or not the evaluator should validate the host, in addition
+    ///                               to performing the default evaluation, even if `performDefaultValidation` is
+    ///                               `false`. `true` by default.
+    ///   - options:                  The `Options` to use to check the revocation status of the certificate. `.any`
+    ///                               by default.
+    /// - Returns:                    The `RevocationTrustEvaluator`.
+    public static func revocationChecking(performDefaultValidation: Bool = true,
+                                          validateHost: Bool = true,
+                                          options: RevocationTrustEvaluator.Options = .any) -> RevocationTrustEvaluator {
+        RevocationTrustEvaluator(performDefaultValidation: performDefaultValidation,
+                                 validateHost: validateHost,
+                                 options: options)
+    }
+}
+#endif
+
+/// Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned
+/// certificates match one of the server certificates. By validating both the certificate chain and host, certificate
+/// pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks.
+/// Applications are encouraged to always validate the host and require a valid certificate chain in production
+/// environments.
+public final class PinnedCertificatesTrustEvaluator: ServerTrustEvaluating {
+    private let certificates: [SecCertificate]
+    private let acceptSelfSignedCertificates: Bool
+    private let performDefaultValidation: Bool
+    private let validateHost: Bool
+
+    /// Creates a `PinnedCertificatesTrustEvaluator` from the provided parameters.
+    ///
+    /// - Parameters:
+    ///   - certificates:                 The certificates to use to evaluate the trust. All `cer`, `crt`, and `der`
+    ///                                   certificates in `Bundle.main` by default.
+    ///   - acceptSelfSignedCertificates: Adds the provided certificates as anchors for the trust evaluation, allowing
+    ///                                   self-signed certificates to pass. `false` by default. THIS SETTING SHOULD BE
+    ///                                   FALSE IN PRODUCTION!
+    ///   - performDefaultValidation:     Determines whether default validation should be performed in addition to
+    ///                                   evaluating the pinned certificates. `true` by default.
+    ///   - validateHost:                 Determines whether or not the evaluator should validate the host, in addition
+    ///                                   to performing the default evaluation, even if `performDefaultValidation` is
+    ///                                   `false`. `true` by default.
+    public init(certificates: [SecCertificate] = Bundle.main.af.certificates,
+                acceptSelfSignedCertificates: Bool = false,
+                performDefaultValidation: Bool = true,
+                validateHost: Bool = true) {
+        self.certificates = certificates
+        self.acceptSelfSignedCertificates = acceptSelfSignedCertificates
+        self.performDefaultValidation = performDefaultValidation
+        self.validateHost = validateHost
+    }
+
+    public func evaluate(_ trust: SecTrust, forHost host: String) throws {
+        guard !certificates.isEmpty else {
+            throw AFError.serverTrustEvaluationFailed(reason: .noCertificatesFound)
+        }
+
+        if acceptSelfSignedCertificates {
+            try trust.af.setAnchorCertificates(certificates)
+        }
+
+        if performDefaultValidation {
+            try trust.af.performDefaultValidation(forHost: host)
+        }
+
+        if validateHost {
+            try trust.af.performValidation(forHost: host)
+        }
+
+        let serverCertificatesData = Set(trust.af.certificateData)
+        let pinnedCertificatesData = Set(certificates.af.data)
+        let pinnedCertificatesInServerData = !serverCertificatesData.isDisjoint(with: pinnedCertificatesData)
+        if !pinnedCertificatesInServerData {
+            throw AFError.serverTrustEvaluationFailed(reason: .certificatePinningFailed(host: host,
+                                                                                        trust: trust,
+                                                                                        pinnedCertificates: certificates,
+                                                                                        serverCertificates: trust.af.certificates))
+        }
+    }
+}
+
+#if swift(>=5.5)
+extension ServerTrustEvaluating where Self == PinnedCertificatesTrustEvaluator {
+    /// Provides a default `PinnedCertificatesTrustEvaluator` instance.
+    public static var pinnedCertificates: PinnedCertificatesTrustEvaluator { PinnedCertificatesTrustEvaluator() }
+
+    /// Creates a `PinnedCertificatesTrustEvaluator` using the provided parameters.
+    ///
+    /// - Parameters:
+    ///   - certificates:                 The certificates to use to evaluate the trust. All `cer`, `crt`, and `der`
+    ///                                   certificates in `Bundle.main` by default.
+    ///   - acceptSelfSignedCertificates: Adds the provided certificates as anchors for the trust evaluation, allowing
+    ///                                   self-signed certificates to pass. `false` by default. THIS SETTING SHOULD BE
+    ///                                   FALSE IN PRODUCTION!
+    ///   - performDefaultValidation:     Determines whether default validation should be performed in addition to
+    ///                                   evaluating the pinned certificates. `true` by default.
+    ///   - validateHost:                 Determines whether or not the evaluator should validate the host, in addition
+    ///                                   to performing the default evaluation, even if `performDefaultValidation` is
+    ///                                   `false`. `true` by default.
+    public static func pinnedCertificates(certificates: [SecCertificate] = Bundle.main.af.certificates,
+                                          acceptSelfSignedCertificates: Bool = false,
+                                          performDefaultValidation: Bool = true,
+                                          validateHost: Bool = true) -> PinnedCertificatesTrustEvaluator {
+        PinnedCertificatesTrustEvaluator(certificates: certificates,
+                                         acceptSelfSignedCertificates: acceptSelfSignedCertificates,
+                                         performDefaultValidation: performDefaultValidation,
+                                         validateHost: validateHost)
+    }
+}
+#endif
+
+/// Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned
+/// public keys match one of the server certificate public keys. By validating both the certificate chain and host,
+/// public key pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks.
+/// Applications are encouraged to always validate the host and require a valid certificate chain in production
+/// environments.
+public final class PublicKeysTrustEvaluator: ServerTrustEvaluating {
+    private let keys: [SecKey]
+    private let performDefaultValidation: Bool
+    private let validateHost: Bool
+
+    /// Creates a `PublicKeysTrustEvaluator` from the provided parameters.
+    ///
+    /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use
+    ///         `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates.
+    ///
+    /// - Parameters:
+    ///   - keys:                     The `SecKey`s to use to validate public keys. Defaults to the public keys of all
+    ///                               certificates included in the main bundle.
+    ///   - performDefaultValidation: Determines whether default validation should be performed in addition to
+    ///                               evaluating the pinned certificates. `true` by default.
+    ///   - validateHost:             Determines whether or not the evaluator should validate the host, in addition to
+    ///                               performing the default evaluation, even if `performDefaultValidation` is `false`.
+    ///                               `true` by default.
+    public init(keys: [SecKey] = Bundle.main.af.publicKeys,
+                performDefaultValidation: Bool = true,
+                validateHost: Bool = true) {
+        self.keys = keys
+        self.performDefaultValidation = performDefaultValidation
+        self.validateHost = validateHost
+    }
+
+    public func evaluate(_ trust: SecTrust, forHost host: String) throws {
+        guard !keys.isEmpty else {
+            throw AFError.serverTrustEvaluationFailed(reason: .noPublicKeysFound)
+        }
+
+        if performDefaultValidation {
+            try trust.af.performDefaultValidation(forHost: host)
+        }
+
+        if validateHost {
+            try trust.af.performValidation(forHost: host)
+        }
+
+        let pinnedKeysInServerKeys: Bool = {
+            for serverPublicKey in trust.af.publicKeys {
+                for pinnedPublicKey in keys {
+                    if serverPublicKey == pinnedPublicKey {
+                        return true
+                    }
+                }
+            }
+            return false
+        }()
+
+        if !pinnedKeysInServerKeys {
+            throw AFError.serverTrustEvaluationFailed(reason: .publicKeyPinningFailed(host: host,
+                                                                                      trust: trust,
+                                                                                      pinnedKeys: keys,
+                                                                                      serverKeys: trust.af.publicKeys))
+        }
+    }
+}
+
+#if swift(>=5.5)
+extension ServerTrustEvaluating where Self == PublicKeysTrustEvaluator {
+    /// Provides a default `PublicKeysTrustEvaluator` instance.
+    public static var publicKeys: PublicKeysTrustEvaluator { PublicKeysTrustEvaluator() }
+
+    /// Creates a `PublicKeysTrustEvaluator` from the provided parameters.
+    ///
+    /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use
+    ///         `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates.
+    ///
+    /// - Parameters:
+    ///   - keys:                     The `SecKey`s to use to validate public keys. Defaults to the public keys of all
+    ///                               certificates included in the main bundle.
+    ///   - performDefaultValidation: Determines whether default validation should be performed in addition to
+    ///                               evaluating the pinned certificates. `true` by default.
+    ///   - validateHost:             Determines whether or not the evaluator should validate the host, in addition to
+    ///                               performing the default evaluation, even if `performDefaultValidation` is `false`.
+    ///                               `true` by default.
+    public static func publicKeys(keys: [SecKey] = Bundle.main.af.publicKeys,
+                                  performDefaultValidation: Bool = true,
+                                  validateHost: Bool = true) -> PublicKeysTrustEvaluator {
+        PublicKeysTrustEvaluator(keys: keys, performDefaultValidation: performDefaultValidation, validateHost: validateHost)
+    }
+}
+#endif
+
+/// Uses the provided evaluators to validate the server trust. The trust is only considered valid if all of the
+/// evaluators consider it valid.
+public final class CompositeTrustEvaluator: ServerTrustEvaluating {
+    private let evaluators: [ServerTrustEvaluating]
+
+    /// Creates a `CompositeTrustEvaluator` from the provided evaluators.
+    ///
+    /// - Parameter evaluators: The `ServerTrustEvaluating` values used to evaluate the server trust.
+    public init(evaluators: [ServerTrustEvaluating]) {
+        self.evaluators = evaluators
+    }
+
+    public func evaluate(_ trust: SecTrust, forHost host: String) throws {
+        try evaluators.evaluate(trust, forHost: host)
+    }
+}
+
+#if swift(>=5.5)
+extension ServerTrustEvaluating where Self == CompositeTrustEvaluator {
+    /// Creates a `CompositeTrustEvaluator` from the provided evaluators.
+    ///
+    /// - Parameter evaluators: The `ServerTrustEvaluating` values used to evaluate the server trust.
+    public static func composite(evaluators: [ServerTrustEvaluating]) -> CompositeTrustEvaluator {
+        CompositeTrustEvaluator(evaluators: evaluators)
+    }
+}
+#endif
+
+/// Disables all evaluation which in turn will always consider any server trust as valid.
+///
+/// - Note: Instead of disabling server trust evaluation, it's a better idea to configure systems to properly trust test
+///         certificates, as outlined in [this Apple tech note](https://developer.apple.com/library/archive/qa/qa1948/_index.html).
+///
+/// **THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION!**
+@available(*, deprecated, renamed: "DisabledTrustEvaluator", message: "DisabledEvaluator has been renamed DisabledTrustEvaluator.")
+public typealias DisabledEvaluator = DisabledTrustEvaluator
+
+/// Disables all evaluation which in turn will always consider any server trust as valid.
+///
+///
+/// - Note: Instead of disabling server trust evaluation, it's a better idea to configure systems to properly trust test
+///         certificates, as outlined in [this Apple tech note](https://developer.apple.com/library/archive/qa/qa1948/_index.html).
+///
+/// **THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION!**
+public final class DisabledTrustEvaluator: ServerTrustEvaluating {
+    /// Creates an instance.
+    public init() {}
+
+    public func evaluate(_ trust: SecTrust, forHost host: String) throws {}
+}
+
+// MARK: - Extensions
+
+extension Array where Element == ServerTrustEvaluating {
+    #if os(Linux) || os(Windows)
+    // Add this same convenience method for Linux/Windows.
+    #else
+    /// Evaluates the given `SecTrust` value for the given `host`.
+    ///
+    /// - Parameters:
+    ///   - trust: The `SecTrust` value to evaluate.
+    ///   - host:  The host for which to evaluate the `SecTrust` value.
+    ///
+    /// - Returns: Whether or not the evaluator considers the `SecTrust` value valid for `host`.
+    public func evaluate(_ trust: SecTrust, forHost host: String) throws {
+        for evaluator in self {
+            try evaluator.evaluate(trust, forHost: host)
+        }
+    }
+    #endif
+}
+
+extension Bundle: AlamofireExtended {}
+extension AlamofireExtension where ExtendedType: Bundle {
+    /// Returns all valid `cer`, `crt`, and `der` certificates in the bundle.
+    public var certificates: [SecCertificate] {
+        paths(forResourcesOfTypes: [".cer", ".CER", ".crt", ".CRT", ".der", ".DER"]).compactMap { path in
+            guard
+                let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData,
+                let certificate = SecCertificateCreateWithData(nil, certificateData) else { return nil }
+
+            return certificate
+        }
+    }
+
+    /// Returns all public keys for the valid certificates in the bundle.
+    public var publicKeys: [SecKey] {
+        certificates.af.publicKeys
+    }
+
+    /// Returns all pathnames for the resources identified by the provided file extensions.
+    ///
+    /// - Parameter types: The filename extensions locate.
+    ///
+    /// - Returns:         All pathnames for the given filename extensions.
+    public func paths(forResourcesOfTypes types: [String]) -> [String] {
+        Array(Set(types.flatMap { type.paths(forResourcesOfType: $0, inDirectory: nil) }))
+    }
+}
+
+extension SecTrust: AlamofireExtended {}
+extension AlamofireExtension where ExtendedType == SecTrust {
+    /// Evaluates `self` after applying the `SecPolicy` value provided.
+    ///
+    /// - Parameter policy: The `SecPolicy` to apply to `self` before evaluation.
+    ///
+    /// - Throws:           Any `Error` from applying the `SecPolicy` or from evaluation.
+    @available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *)
+    public func evaluate(afterApplying policy: SecPolicy) throws {
+        try apply(policy: policy).af.evaluate()
+    }
+
+    /// Attempts to validate `self` using the `SecPolicy` provided and transforming any error produced using the closure passed.
+    ///
+    /// - Parameters:
+    ///   - policy:        The `SecPolicy` used to evaluate `self`.
+    ///   - errorProducer: The closure used transform the failed `OSStatus` and `SecTrustResultType`.
+    /// - Throws:          Any `Error` from applying the `policy`, or the result of `errorProducer` if validation fails.
+    @available(iOS, introduced: 10, deprecated: 12, renamed: "evaluate(afterApplying:)")
+    @available(macOS, introduced: 10.12, deprecated: 10.14, renamed: "evaluate(afterApplying:)")
+    @available(tvOS, introduced: 10, deprecated: 12, renamed: "evaluate(afterApplying:)")
+    @available(watchOS, introduced: 3, deprecated: 5, renamed: "evaluate(afterApplying:)")
+    public func validate(policy: SecPolicy, errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws {
+        try apply(policy: policy).af.validate(errorProducer: errorProducer)
+    }
+
+    /// Applies a `SecPolicy` to `self`, throwing if it fails.
+    ///
+    /// - Parameter policy: The `SecPolicy`.
+    ///
+    /// - Returns: `self`, with the policy applied.
+    /// - Throws: An `AFError.serverTrustEvaluationFailed` instance with a `.policyApplicationFailed` reason.
+    public func apply(policy: SecPolicy) throws -> SecTrust {
+        let status = SecTrustSetPolicies(type, policy)
+
+        guard status.af.isSuccess else {
+            throw AFError.serverTrustEvaluationFailed(reason: .policyApplicationFailed(trust: type,
+                                                                                       policy: policy,
+                                                                                       status: status))
+        }
+
+        return type
+    }
+
+    /// Evaluate `self`, throwing an `Error` if evaluation fails.
+    ///
+    /// - Throws: `AFError.serverTrustEvaluationFailed` with reason `.trustValidationFailed` and associated error from
+    ///           the underlying evaluation.
+    @available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *)
+    public func evaluate() throws {
+        var error: CFError?
+        let evaluationSucceeded = SecTrustEvaluateWithError(type, &error)
+
+        if !evaluationSucceeded {
+            throw AFError.serverTrustEvaluationFailed(reason: .trustEvaluationFailed(error: error))
+        }
+    }
+
+    /// Validate `self`, passing any failure values through `errorProducer`.
+    ///
+    /// - Parameter errorProducer: The closure used to transform the failed `OSStatus` and `SecTrustResultType` into an
+    ///                            `Error`.
+    /// - Throws:                  The `Error` produced by the `errorProducer` closure.
+    @available(iOS, introduced: 10, deprecated: 12, renamed: "evaluate()")
+    @available(macOS, introduced: 10.12, deprecated: 10.14, renamed: "evaluate()")
+    @available(tvOS, introduced: 10, deprecated: 12, renamed: "evaluate()")
+    @available(watchOS, introduced: 3, deprecated: 5, renamed: "evaluate()")
+    public func validate(errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws {
+        var result = SecTrustResultType.invalid
+        let status = SecTrustEvaluate(type, &result)
+
+        guard status.af.isSuccess && result.af.isSuccess else {
+            throw errorProducer(status, result)
+        }
+    }
+
+    /// Sets a custom certificate chain on `self`, allowing full validation of a self-signed certificate and its chain.
+    ///
+    /// - Parameter certificates: The `SecCertificate`s to add to the chain.
+    /// - Throws:                 Any error produced when applying the new certificate chain.
+    public func setAnchorCertificates(_ certificates: [SecCertificate]) throws {
+        // Add additional anchor certificates.
+        let status = SecTrustSetAnchorCertificates(type, certificates as CFArray)
+        guard status.af.isSuccess else {
+            throw AFError.serverTrustEvaluationFailed(reason: .settingAnchorCertificatesFailed(status: status,
+                                                                                               certificates: certificates))
+        }
+
+        // Trust only the set anchor certs.
+        let onlyStatus = SecTrustSetAnchorCertificatesOnly(type, true)
+        guard onlyStatus.af.isSuccess else {
+            throw AFError.serverTrustEvaluationFailed(reason: .settingAnchorCertificatesFailed(status: onlyStatus,
+                                                                                               certificates: certificates))
+        }
+    }
+
+    /// The public keys contained in `self`.
+    public var publicKeys: [SecKey] {
+        certificates.af.publicKeys
+    }
+
+    #if swift(>=5.5.1) // Xcode 13.1 / 2021 SDKs.
+    /// The `SecCertificate`s contained in `self`.
+    public var certificates: [SecCertificate] {
+        if #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) {
+            return (SecTrustCopyCertificateChain(type) as? [SecCertificate]) ?? []
+        } else {
+            return (0..<SecTrustGetCertificateCount(type)).compactMap { index in
+                SecTrustGetCertificateAtIndex(type, index)
+            }
+        }
+    }
+    #else
+    /// The `SecCertificate`s contained in `self`.
+    public var certificates: [SecCertificate] {
+        (0..<SecTrustGetCertificateCount(type)).compactMap { index in
+            SecTrustGetCertificateAtIndex(type, index)
+        }
+    }
+    #endif
+
+    /// The `Data` values for all certificates contained in `self`.
+    public var certificateData: [Data] {
+        certificates.af.data
+    }
+
+    /// Validates `self` after applying `SecPolicy.af.default`. This evaluation does not validate the hostname.
+    ///
+    /// - Parameter host: The hostname, used only in the error output if validation fails.
+    /// - Throws: An `AFError.serverTrustEvaluationFailed` instance with a `.defaultEvaluationFailed` reason.
+    public func performDefaultValidation(forHost host: String) throws {
+        if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) {
+            try evaluate(afterApplying: SecPolicy.af.default)
+        } else {
+            try validate(policy: SecPolicy.af.default) { status, result in
+                AFError.serverTrustEvaluationFailed(reason: .defaultEvaluationFailed(output: .init(host, type, status, result)))
+            }
+        }
+    }
+
+    /// Validates `self` after applying `SecPolicy.af.hostname(host)`, which performs the default validation as well as
+    /// hostname validation.
+    ///
+    /// - Parameter host: The hostname to use in the validation.
+    /// - Throws:         An `AFError.serverTrustEvaluationFailed` instance with a `.defaultEvaluationFailed` reason.
+    public func performValidation(forHost host: String) throws {
+        if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) {
+            try evaluate(afterApplying: SecPolicy.af.hostname(host))
+        } else {
+            try validate(policy: SecPolicy.af.hostname(host)) { status, result in
+                AFError.serverTrustEvaluationFailed(reason: .hostValidationFailed(output: .init(host, type, status, result)))
+            }
+        }
+    }
+}
+
+extension SecPolicy: AlamofireExtended {}
+extension AlamofireExtension where ExtendedType == SecPolicy {
+    /// Creates a `SecPolicy` instance which will validate server certificates but not require a host name match.
+    public static let `default` = SecPolicyCreateSSL(true, nil)
+
+    /// Creates a `SecPolicy` instance which will validate server certificates and much match the provided hostname.
+    ///
+    /// - Parameter hostname: The hostname to validate against.
+    ///
+    /// - Returns:            The `SecPolicy`.
+    public static func hostname(_ hostname: String) -> SecPolicy {
+        SecPolicyCreateSSL(true, hostname as CFString)
+    }
+
+    /// Creates a `SecPolicy` which checks the revocation of certificates.
+    ///
+    /// - Parameter options: The `RevocationTrustEvaluator.Options` for evaluation.
+    ///
+    /// - Returns:           The `SecPolicy`.
+    /// - Throws:            An `AFError.serverTrustEvaluationFailed` error with reason `.revocationPolicyCreationFailed`
+    ///                      if the policy cannot be created.
+    public static func revocation(options: RevocationTrustEvaluator.Options) throws -> SecPolicy {
+        guard let policy = SecPolicyCreateRevocation(options.rawValue) else {
+            throw AFError.serverTrustEvaluationFailed(reason: .revocationPolicyCreationFailed)
+        }
+
+        return policy
+    }
+}
+
+extension Array: AlamofireExtended {}
+extension AlamofireExtension where ExtendedType == [SecCertificate] {
+    /// All `Data` values for the contained `SecCertificate`s.
+    public var data: [Data] {
+        type.map { SecCertificateCopyData($0) as Data }
+    }
+
+    /// All public `SecKey` values for the contained `SecCertificate`s.
+    public var publicKeys: [SecKey] {
+        type.compactMap(\.af.publicKey)
+    }
+}
+
+extension SecCertificate: AlamofireExtended {}
+extension AlamofireExtension where ExtendedType == SecCertificate {
+    /// The public key for `self`, if it can be extracted.
+    ///
+    /// - Note: On 2020 OSes and newer, only RSA and ECDSA keys are supported.
+    ///
+    public var publicKey: SecKey? {
+        let policy = SecPolicyCreateBasicX509()
+        var trust: SecTrust?
+        let trustCreationStatus = SecTrustCreateWithCertificates(type, policy, &trust)
+
+        guard let createdTrust = trust, trustCreationStatus == errSecSuccess else { return nil }
+
+        #if swift(>=5.3.1) // SecTrustCopyKey not visible in Xcode <= 12.1, despite being a 2020 API.
+        if #available(iOS 14, macOS 11, tvOS 14, watchOS 7, *) {
+            return SecTrustCopyKey(createdTrust)
+        } else {
+            return SecTrustCopyPublicKey(createdTrust)
+        }
+        #else
+        return SecTrustCopyPublicKey(createdTrust)
+        #endif
+    }
+}
+
+extension OSStatus: AlamofireExtended {}
+extension AlamofireExtension where ExtendedType == OSStatus {
+    /// Returns whether `self` is `errSecSuccess`.
+    public var isSuccess: Bool { type == errSecSuccess }
+}
+
+extension SecTrustResultType: AlamofireExtended {}
+extension AlamofireExtension where ExtendedType == SecTrustResultType {
+    /// Returns whether `self is `.unspecified` or `.proceed`.
+    public var isSuccess: Bool {
+        type == .unspecified || type == .proceed
+    }
+}
+#endif

+ 1264 - 0
Pods/Alamofire/Source/Session.swift

@@ -0,0 +1,1264 @@
+//
+//  Session.swift
+//
+//  Copyright (c) 2014-2018 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
+
+/// `Session` creates and manages Alamofire's `Request` types during their lifetimes. It also provides common
+/// functionality for all `Request`s, including queuing, interception, trust management, redirect handling, and response
+/// cache handling.
+open class Session {
+    /// Shared singleton instance used by all `AF.request` APIs. Cannot be modified.
+    public static let `default` = Session()
+
+    /// Underlying `URLSession` used to create `URLSessionTasks` for this instance, and for which this instance's
+    /// `delegate` handles `URLSessionDelegate` callbacks.
+    ///
+    /// - Note: This instance should **NOT** be used to interact with the underlying `URLSessionTask`s. Doing so will
+    ///         break internal Alamofire logic that tracks those tasks.
+    ///
+    public let session: URLSession
+    /// Instance's `SessionDelegate`, which handles the `URLSessionDelegate` methods and `Request` interaction.
+    public let delegate: SessionDelegate
+    /// Root `DispatchQueue` for all internal callbacks and state update. **MUST** be a serial queue.
+    public let rootQueue: DispatchQueue
+    /// Value determining whether this instance automatically calls `resume()` on all created `Request`s.
+    public let startRequestsImmediately: Bool
+    /// `DispatchQueue` on which `URLRequest`s are created asynchronously. By default this queue uses `rootQueue` as its
+    /// `target`, but a separate queue can be used if request creation is determined to be a bottleneck. Always profile
+    /// and test before introducing an additional queue.
+    public let requestQueue: DispatchQueue
+    /// `DispatchQueue` passed to all `Request`s on which they perform their response serialization. By default this
+    /// queue uses `rootQueue` as its `target` but a separate queue can be used if response serialization is determined
+    /// to be a bottleneck. Always profile and test before introducing an additional queue.
+    public let serializationQueue: DispatchQueue
+    /// `RequestInterceptor` used for all `Request` created by the instance. `RequestInterceptor`s can also be set on a
+    /// per-`Request` basis, in which case the `Request`'s interceptor takes precedence over this value.
+    public let interceptor: RequestInterceptor?
+    /// `ServerTrustManager` instance used to evaluate all trust challenges and provide certificate and key pinning.
+    public let serverTrustManager: ServerTrustManager?
+    /// `RedirectHandler` instance used to provide customization for request redirection.
+    public let redirectHandler: RedirectHandler?
+    /// `CachedResponseHandler` instance used to provide customization of cached response handling.
+    public let cachedResponseHandler: CachedResponseHandler?
+    /// `CompositeEventMonitor` used to compose Alamofire's `defaultEventMonitors` and any passed `EventMonitor`s.
+    public let eventMonitor: CompositeEventMonitor
+    /// `EventMonitor`s included in all instances. `[AlamofireNotifications()]` by default.
+    public let defaultEventMonitors: [EventMonitor] = [AlamofireNotifications()]
+
+    /// Internal map between `Request`s and any `URLSessionTasks` that may be in flight for them.
+    var requestTaskMap = RequestTaskMap()
+    /// `Set` of currently active `Request`s.
+    var activeRequests: Set<Request> = []
+    /// Completion events awaiting `URLSessionTaskMetrics`.
+    var waitingCompletions: [URLSessionTask: () -> Void] = [:]
+
+    /// Creates a `Session` from a `URLSession` and other parameters.
+    ///
+    /// - Note: When passing a `URLSession`, you must create the `URLSession` with a specific `delegateQueue` value and
+    ///         pass the `delegateQueue`'s `underlyingQueue` as the `rootQueue` parameter of this initializer.
+    ///
+    /// - Parameters:
+    ///   - session:                  Underlying `URLSession` for this instance.
+    ///   - delegate:                 `SessionDelegate` that handles `session`'s delegate callbacks as well as `Request`
+    ///                               interaction.
+    ///   - rootQueue:                Root `DispatchQueue` for all internal callbacks and state updates. **MUST** be a
+    ///                               serial queue.
+    ///   - startRequestsImmediately: Determines whether this instance will automatically start all `Request`s. `true`
+    ///                               by default. If set to `false`, all `Request`s created must have `.resume()` called.
+    ///                               on them for them to start.
+    ///   - requestQueue:             `DispatchQueue` on which to perform `URLRequest` creation. By default this queue
+    ///                               will use the `rootQueue` as its `target`. A separate queue can be used if it's
+    ///                               determined request creation is a bottleneck, but that should only be done after
+    ///                               careful testing and profiling. `nil` by default.
+    ///   - serializationQueue:       `DispatchQueue` on which to perform all response serialization. By default this
+    ///                               queue will use the `rootQueue` as its `target`. A separate queue can be used if
+    ///                               it's determined response serialization is a bottleneck, but that should only be
+    ///                               done after careful testing and profiling. `nil` by default.
+    ///   - interceptor:              `RequestInterceptor` to be used for all `Request`s created by this instance. `nil`
+    ///                               by default.
+    ///   - serverTrustManager:       `ServerTrustManager` to be used for all trust evaluations by this instance. `nil`
+    ///                               by default.
+    ///   - redirectHandler:          `RedirectHandler` to be used by all `Request`s created by this instance. `nil` by
+    ///                               default.
+    ///   - cachedResponseHandler:    `CachedResponseHandler` to be used by all `Request`s created by this instance.
+    ///                               `nil` by default.
+    ///   - eventMonitors:            Additional `EventMonitor`s used by the instance. Alamofire always adds a
+    ///                               `AlamofireNotifications` `EventMonitor` to the array passed here. `[]` by default.
+    public init(session: URLSession,
+                delegate: SessionDelegate,
+                rootQueue: DispatchQueue,
+                startRequestsImmediately: Bool = true,
+                requestQueue: DispatchQueue? = nil,
+                serializationQueue: DispatchQueue? = nil,
+                interceptor: RequestInterceptor? = nil,
+                serverTrustManager: ServerTrustManager? = nil,
+                redirectHandler: RedirectHandler? = nil,
+                cachedResponseHandler: CachedResponseHandler? = nil,
+                eventMonitors: [EventMonitor] = []) {
+        precondition(session.configuration.identifier == nil,
+                     "Alamofire does not support background URLSessionConfigurations.")
+        precondition(session.delegateQueue.underlyingQueue === rootQueue,
+                     "Session(session:) initializer must be passed the DispatchQueue used as the delegateQueue's underlyingQueue as rootQueue.")
+
+        self.session = session
+        self.delegate = delegate
+        self.rootQueue = rootQueue
+        self.startRequestsImmediately = startRequestsImmediately
+        self.requestQueue = requestQueue ?? DispatchQueue(label: "\(rootQueue.label).requestQueue", target: rootQueue)
+        self.serializationQueue = serializationQueue ?? DispatchQueue(label: "\(rootQueue.label).serializationQueue", target: rootQueue)
+        self.interceptor = interceptor
+        self.serverTrustManager = serverTrustManager
+        self.redirectHandler = redirectHandler
+        self.cachedResponseHandler = cachedResponseHandler
+        eventMonitor = CompositeEventMonitor(monitors: defaultEventMonitors + eventMonitors)
+        delegate.eventMonitor = eventMonitor
+        delegate.stateProvider = self
+    }
+
+    /// Creates a `Session` from a `URLSessionConfiguration`.
+    ///
+    /// - Note: This initializer lets Alamofire handle the creation of the underlying `URLSession` and its
+    ///         `delegateQueue`, and is the recommended initializer for most uses.
+    ///
+    /// - Parameters:
+    ///   - configuration:            `URLSessionConfiguration` to be used to create the underlying `URLSession`. Changes
+    ///                               to this value after being passed to this initializer will have no effect.
+    ///                               `URLSessionConfiguration.af.default` by default.
+    ///   - delegate:                 `SessionDelegate` that handles `session`'s delegate callbacks as well as `Request`
+    ///                               interaction. `SessionDelegate()` by default.
+    ///   - rootQueue:                Root `DispatchQueue` for all internal callbacks and state updates. **MUST** be a
+    ///                               serial queue. `DispatchQueue(label: "org.alamofire.session.rootQueue")` by default.
+    ///   - startRequestsImmediately: Determines whether this instance will automatically start all `Request`s. `true`
+    ///                               by default. If set to `false`, all `Request`s created must have `.resume()` called.
+    ///                               on them for them to start.
+    ///   - requestQueue:             `DispatchQueue` on which to perform `URLRequest` creation. By default this queue
+    ///                               will use the `rootQueue` as its `target`. A separate queue can be used if it's
+    ///                               determined request creation is a bottleneck, but that should only be done after
+    ///                               careful testing and profiling. `nil` by default.
+    ///   - serializationQueue:       `DispatchQueue` on which to perform all response serialization. By default this
+    ///                               queue will use the `rootQueue` as its `target`. A separate queue can be used if
+    ///                               it's determined response serialization is a bottleneck, but that should only be
+    ///                               done after careful testing and profiling. `nil` by default.
+    ///   - interceptor:              `RequestInterceptor` to be used for all `Request`s created by this instance. `nil`
+    ///                               by default.
+    ///   - serverTrustManager:       `ServerTrustManager` to be used for all trust evaluations by this instance. `nil`
+    ///                               by default.
+    ///   - redirectHandler:          `RedirectHandler` to be used by all `Request`s created by this instance. `nil` by
+    ///                               default.
+    ///   - cachedResponseHandler:    `CachedResponseHandler` to be used by all `Request`s created by this instance.
+    ///                               `nil` by default.
+    ///   - eventMonitors:            Additional `EventMonitor`s used by the instance. Alamofire always adds a
+    ///                               `AlamofireNotifications` `EventMonitor` to the array passed here. `[]` by default.
+    public convenience init(configuration: URLSessionConfiguration = URLSessionConfiguration.af.default,
+                            delegate: SessionDelegate = SessionDelegate(),
+                            rootQueue: DispatchQueue = DispatchQueue(label: "org.alamofire.session.rootQueue"),
+                            startRequestsImmediately: Bool = true,
+                            requestQueue: DispatchQueue? = nil,
+                            serializationQueue: DispatchQueue? = nil,
+                            interceptor: RequestInterceptor? = nil,
+                            serverTrustManager: ServerTrustManager? = nil,
+                            redirectHandler: RedirectHandler? = nil,
+                            cachedResponseHandler: CachedResponseHandler? = nil,
+                            eventMonitors: [EventMonitor] = []) {
+        precondition(configuration.identifier == nil, "Alamofire does not support background URLSessionConfigurations.")
+
+        // Retarget the incoming rootQueue for safety, unless it's the main queue, which we know is safe.
+        let serialRootQueue = (rootQueue === DispatchQueue.main) ? rootQueue : DispatchQueue(label: rootQueue.label,
+                                                                                             target: rootQueue)
+        let delegateQueue = OperationQueue(maxConcurrentOperationCount: 1, underlyingQueue: serialRootQueue, name: "\(serialRootQueue.label).sessionDelegate")
+        let session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: delegateQueue)
+
+        self.init(session: session,
+                  delegate: delegate,
+                  rootQueue: serialRootQueue,
+                  startRequestsImmediately: startRequestsImmediately,
+                  requestQueue: requestQueue,
+                  serializationQueue: serializationQueue,
+                  interceptor: interceptor,
+                  serverTrustManager: serverTrustManager,
+                  redirectHandler: redirectHandler,
+                  cachedResponseHandler: cachedResponseHandler,
+                  eventMonitors: eventMonitors)
+    }
+
+    deinit {
+        finishRequestsForDeinit()
+        session.invalidateAndCancel()
+    }
+
+    // MARK: - All Requests API
+
+    /// Perform an action on all active `Request`s.
+    ///
+    /// - Note: The provided `action` closure is performed asynchronously, meaning that some `Request`s may complete and
+    ///         be unavailable by time it runs. Additionally, this action is performed on the instances's `rootQueue`,
+    ///         so care should be taken that actions are fast. Once the work on the `Request`s is complete, any
+    ///         additional work should be performed on another queue.
+    ///
+    /// - Parameters:
+    ///   - action:     Closure to perform with all `Request`s.
+    public func withAllRequests(perform action: @escaping (Set<Request>) -> Void) {
+        rootQueue.async {
+            action(self.activeRequests)
+        }
+    }
+
+    /// Cancel all active `Request`s, optionally calling a completion handler when complete.
+    ///
+    /// - Note: This is an asynchronous operation and does not block the creation of future `Request`s. Cancelled
+    ///         `Request`s may not cancel immediately due internal work, and may not cancel at all if they are close to
+    ///         completion when cancelled.
+    ///
+    /// - Parameters:
+    ///   - queue:      `DispatchQueue` on which the completion handler is run. `.main` by default.
+    ///   - completion: Closure to be called when all `Request`s have been cancelled.
+    public func cancelAllRequests(completingOnQueue queue: DispatchQueue = .main, completion: (() -> Void)? = nil) {
+        withAllRequests { requests in
+            requests.forEach { $0.cancel() }
+            queue.async {
+                completion?()
+            }
+        }
+    }
+
+    // MARK: - DataRequest
+
+    /// Closure which provides a `URLRequest` for mutation.
+    public typealias RequestModifier = (inout URLRequest) throws -> Void
+
+    struct RequestConvertible: URLRequestConvertible {
+        let url: URLConvertible
+        let method: HTTPMethod
+        let parameters: Parameters?
+        let encoding: ParameterEncoding
+        let headers: HTTPHeaders?
+        let requestModifier: RequestModifier?
+
+        func asURLRequest() throws -> URLRequest {
+            var request = try URLRequest(url: url, method: method, headers: headers)
+            try requestModifier?(&request)
+
+            return try encoding.encode(request, with: parameters)
+        }
+    }
+
+    /// Creates a `DataRequest` from a `URLRequest` created using the passed components and a `RequestInterceptor`.
+    ///
+    /// - Parameters:
+    ///   - convertible:     `URLConvertible` value to be used as the `URLRequest`'s `URL`.
+    ///   - method:          `HTTPMethod` for the `URLRequest`. `.get` by default.
+    ///   - parameters:      `Parameters` (a.k.a. `[String: Any]`) value to be encoded into the `URLRequest`. `nil` by
+    ///                      default.
+    ///   - encoding:        `ParameterEncoding` to be used to encode the `parameters` value into the `URLRequest`.
+    ///                      `URLEncoding.default` by default.
+    ///   - headers:         `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
+    ///   - interceptor:     `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
+    ///   - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided
+    ///                      parameters. `nil` by default.
+    ///
+    /// - Returns:       The created `DataRequest`.
+    open func request(_ convertible: URLConvertible,
+                      method: HTTPMethod = .get,
+                      parameters: Parameters? = nil,
+                      encoding: ParameterEncoding = URLEncoding.default,
+                      headers: HTTPHeaders? = nil,
+                      interceptor: RequestInterceptor? = nil,
+                      requestModifier: RequestModifier? = nil) -> DataRequest {
+        let convertible = RequestConvertible(url: convertible,
+                                             method: method,
+                                             parameters: parameters,
+                                             encoding: encoding,
+                                             headers: headers,
+                                             requestModifier: requestModifier)
+
+        return request(convertible, interceptor: interceptor)
+    }
+
+    struct RequestEncodableConvertible<Parameters: Encodable>: URLRequestConvertible {
+        let url: URLConvertible
+        let method: HTTPMethod
+        let parameters: Parameters?
+        let encoder: ParameterEncoder
+        let headers: HTTPHeaders?
+        let requestModifier: RequestModifier?
+
+        func asURLRequest() throws -> URLRequest {
+            var request = try URLRequest(url: url, method: method, headers: headers)
+            try requestModifier?(&request)
+
+            return try parameters.map { try encoder.encode($0, into: request) } ?? request
+        }
+    }
+
+    /// Creates a `DataRequest` from a `URLRequest` created using the passed components, `Encodable` parameters, and a
+    /// `RequestInterceptor`.
+    ///
+    /// - Parameters:
+    ///   - convertible:     `URLConvertible` value to be used as the `URLRequest`'s `URL`.
+    ///   - method:          `HTTPMethod` for the `URLRequest`. `.get` by default.
+    ///   - parameters:      `Encodable` value to be encoded into the `URLRequest`. `nil` by default.
+    ///   - encoder:         `ParameterEncoder` to be used to encode the `parameters` value into the `URLRequest`.
+    ///                      `URLEncodedFormParameterEncoder.default` by default.
+    ///   - headers:         `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
+    ///   - interceptor:     `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
+    ///   - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from
+    ///                      the provided parameters. `nil` by default.
+    ///
+    /// - Returns:           The created `DataRequest`.
+    open func request<Parameters: Encodable>(_ convertible: URLConvertible,
+                                             method: HTTPMethod = .get,
+                                             parameters: Parameters? = nil,
+                                             encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default,
+                                             headers: HTTPHeaders? = nil,
+                                             interceptor: RequestInterceptor? = nil,
+                                             requestModifier: RequestModifier? = nil) -> DataRequest {
+        let convertible = RequestEncodableConvertible(url: convertible,
+                                                      method: method,
+                                                      parameters: parameters,
+                                                      encoder: encoder,
+                                                      headers: headers,
+                                                      requestModifier: requestModifier)
+
+        return request(convertible, interceptor: interceptor)
+    }
+
+    /// Creates a `DataRequest` from a `URLRequestConvertible` value and a `RequestInterceptor`.
+    ///
+    /// - Parameters:
+    ///   - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
+    ///   - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
+    ///
+    /// - Returns:       The created `DataRequest`.
+    open func request(_ convertible: URLRequestConvertible, interceptor: RequestInterceptor? = nil) -> DataRequest {
+        let request = DataRequest(convertible: convertible,
+                                  underlyingQueue: rootQueue,
+                                  serializationQueue: serializationQueue,
+                                  eventMonitor: eventMonitor,
+                                  interceptor: interceptor,
+                                  delegate: self)
+
+        perform(request)
+
+        return request
+    }
+
+    // MARK: - DataStreamRequest
+
+    /// Creates a `DataStreamRequest` from the passed components, `Encodable` parameters, and `RequestInterceptor`.
+    ///
+    /// - Parameters:
+    ///   - convertible:                      `URLConvertible` value to be used as the `URLRequest`'s `URL`.
+    ///   - method:                           `HTTPMethod` for the `URLRequest`. `.get` by default.
+    ///   - parameters:                       `Encodable` value to be encoded into the `URLRequest`. `nil` by default.
+    ///   - encoder:                          `ParameterEncoder` to be used to encode the `parameters` value into the
+    ///                                       `URLRequest`.
+    ///                                       `URLEncodedFormParameterEncoder.default` by default.
+    ///   - headers:                          `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
+    ///   - automaticallyCancelOnStreamError: `Bool` indicating whether the instance should be canceled when an `Error`
+    ///                                       is thrown while serializing stream `Data`. `false` by default.
+    ///   - interceptor:                      `RequestInterceptor` value to be used by the returned `DataRequest`. `nil`
+    ///                                       by default.
+    ///   - requestModifier:                  `RequestModifier` which will be applied to the `URLRequest` created from
+    ///                                       the provided parameters. `nil` by default.
+    ///
+    /// - Returns:       The created `DataStream` request.
+    open func streamRequest<Parameters: Encodable>(_ convertible: URLConvertible,
+                                                   method: HTTPMethod = .get,
+                                                   parameters: Parameters? = nil,
+                                                   encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default,
+                                                   headers: HTTPHeaders? = nil,
+                                                   automaticallyCancelOnStreamError: Bool = false,
+                                                   interceptor: RequestInterceptor? = nil,
+                                                   requestModifier: RequestModifier? = nil) -> DataStreamRequest {
+        let convertible = RequestEncodableConvertible(url: convertible,
+                                                      method: method,
+                                                      parameters: parameters,
+                                                      encoder: encoder,
+                                                      headers: headers,
+                                                      requestModifier: requestModifier)
+
+        return streamRequest(convertible,
+                             automaticallyCancelOnStreamError: automaticallyCancelOnStreamError,
+                             interceptor: interceptor)
+    }
+
+    /// Creates a `DataStreamRequest` from the passed components and `RequestInterceptor`.
+    ///
+    /// - Parameters:
+    ///   - convertible:                      `URLConvertible` value to be used as the `URLRequest`'s `URL`.
+    ///   - method:                           `HTTPMethod` for the `URLRequest`. `.get` by default.
+    ///   - headers:                          `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
+    ///   - automaticallyCancelOnStreamError: `Bool` indicating whether the instance should be canceled when an `Error`
+    ///                                       is thrown while serializing stream `Data`. `false` by default.
+    ///   - interceptor:                      `RequestInterceptor` value to be used by the returned `DataRequest`. `nil`
+    ///                                       by default.
+    ///   - requestModifier:                  `RequestModifier` which will be applied to the `URLRequest` created from
+    ///                                       the provided parameters. `nil` by default.
+    ///
+    /// - Returns:       The created `DataStream` request.
+    open func streamRequest(_ convertible: URLConvertible,
+                            method: HTTPMethod = .get,
+                            headers: HTTPHeaders? = nil,
+                            automaticallyCancelOnStreamError: Bool = false,
+                            interceptor: RequestInterceptor? = nil,
+                            requestModifier: RequestModifier? = nil) -> DataStreamRequest {
+        let convertible = RequestEncodableConvertible(url: convertible,
+                                                      method: method,
+                                                      parameters: Empty?.none,
+                                                      encoder: URLEncodedFormParameterEncoder.default,
+                                                      headers: headers,
+                                                      requestModifier: requestModifier)
+
+        return streamRequest(convertible,
+                             automaticallyCancelOnStreamError: automaticallyCancelOnStreamError,
+                             interceptor: interceptor)
+    }
+
+    /// Creates a `DataStreamRequest` from the passed `URLRequestConvertible` value and `RequestInterceptor`.
+    ///
+    /// - Parameters:
+    ///   - convertible:                      `URLRequestConvertible` value to be used to create the `URLRequest`.
+    ///   - automaticallyCancelOnStreamError: `Bool` indicating whether the instance should be canceled when an `Error`
+    ///                                       is thrown while serializing stream `Data`. `false` by default.
+    ///   - interceptor:                      `RequestInterceptor` value to be used by the returned `DataRequest`. `nil`
+    ///                                        by default.
+    ///
+    /// - Returns:       The created `DataStreamRequest`.
+    open func streamRequest(_ convertible: URLRequestConvertible,
+                            automaticallyCancelOnStreamError: Bool = false,
+                            interceptor: RequestInterceptor? = nil) -> DataStreamRequest {
+        let request = DataStreamRequest(convertible: convertible,
+                                        automaticallyCancelOnStreamError: automaticallyCancelOnStreamError,
+                                        underlyingQueue: rootQueue,
+                                        serializationQueue: serializationQueue,
+                                        eventMonitor: eventMonitor,
+                                        interceptor: interceptor,
+                                        delegate: self)
+
+        perform(request)
+
+        return request
+    }
+
+    // MARK: - DownloadRequest
+
+    /// Creates a `DownloadRequest` using a `URLRequest` created using the passed components, `RequestInterceptor`, and
+    /// `Destination`.
+    ///
+    /// - Parameters:
+    ///   - convertible:     `URLConvertible` value to be used as the `URLRequest`'s `URL`.
+    ///   - method:          `HTTPMethod` for the `URLRequest`. `.get` by default.
+    ///   - parameters:      `Parameters` (a.k.a. `[String: Any]`) value to be encoded into the `URLRequest`. `nil` by
+    ///                      default.
+    ///   - encoding:        `ParameterEncoding` to be used to encode the `parameters` value into the `URLRequest`.
+    ///                      Defaults to `URLEncoding.default`.
+    ///   - headers:         `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
+    ///   - interceptor:     `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
+    ///   - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided
+    ///                      parameters. `nil` by default.
+    ///   - destination:     `DownloadRequest.Destination` closure used to determine how and where the downloaded file
+    ///                      should be moved. `nil` by default.
+    ///
+    /// - Returns:           The created `DownloadRequest`.
+    open func download(_ convertible: URLConvertible,
+                       method: HTTPMethod = .get,
+                       parameters: Parameters? = nil,
+                       encoding: ParameterEncoding = URLEncoding.default,
+                       headers: HTTPHeaders? = nil,
+                       interceptor: RequestInterceptor? = nil,
+                       requestModifier: RequestModifier? = nil,
+                       to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
+        let convertible = RequestConvertible(url: convertible,
+                                             method: method,
+                                             parameters: parameters,
+                                             encoding: encoding,
+                                             headers: headers,
+                                             requestModifier: requestModifier)
+
+        return download(convertible, interceptor: interceptor, to: destination)
+    }
+
+    /// Creates a `DownloadRequest` from a `URLRequest` created using the passed components, `Encodable` parameters, and
+    /// a `RequestInterceptor`.
+    ///
+    /// - Parameters:
+    ///   - convertible:     `URLConvertible` value to be used as the `URLRequest`'s `URL`.
+    ///   - method:          `HTTPMethod` for the `URLRequest`. `.get` by default.
+    ///   - parameters:      Value conforming to `Encodable` to be encoded into the `URLRequest`. `nil` by default.
+    ///   - encoder:         `ParameterEncoder` to be used to encode the `parameters` value into the `URLRequest`.
+    ///                      Defaults to `URLEncodedFormParameterEncoder.default`.
+    ///   - headers:         `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
+    ///   - interceptor:     `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
+    ///   - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided
+    ///                      parameters. `nil` by default.
+    ///   - destination:     `DownloadRequest.Destination` closure used to determine how and where the downloaded file
+    ///                      should be moved. `nil` by default.
+    ///
+    /// - Returns:           The created `DownloadRequest`.
+    open func download<Parameters: Encodable>(_ convertible: URLConvertible,
+                                              method: HTTPMethod = .get,
+                                              parameters: Parameters? = nil,
+                                              encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default,
+                                              headers: HTTPHeaders? = nil,
+                                              interceptor: RequestInterceptor? = nil,
+                                              requestModifier: RequestModifier? = nil,
+                                              to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
+        let convertible = RequestEncodableConvertible(url: convertible,
+                                                      method: method,
+                                                      parameters: parameters,
+                                                      encoder: encoder,
+                                                      headers: headers,
+                                                      requestModifier: requestModifier)
+
+        return download(convertible, interceptor: interceptor, to: destination)
+    }
+
+    /// Creates a `DownloadRequest` from a `URLRequestConvertible` value, a `RequestInterceptor`, and a `Destination`.
+    ///
+    /// - Parameters:
+    ///   - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
+    ///   - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
+    ///   - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file
+    ///                  should be moved. `nil` by default.
+    ///
+    /// - Returns:       The created `DownloadRequest`.
+    open func download(_ convertible: URLRequestConvertible,
+                       interceptor: RequestInterceptor? = nil,
+                       to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
+        let request = DownloadRequest(downloadable: .request(convertible),
+                                      underlyingQueue: rootQueue,
+                                      serializationQueue: serializationQueue,
+                                      eventMonitor: eventMonitor,
+                                      interceptor: interceptor,
+                                      delegate: self,
+                                      destination: destination ?? DownloadRequest.defaultDestination)
+
+        perform(request)
+
+        return request
+    }
+
+    /// Creates a `DownloadRequest` from the `resumeData` produced from a previously cancelled `DownloadRequest`, as
+    /// well as a `RequestInterceptor`, and a `Destination`.
+    ///
+    /// - Note: If `destination` is not specified, the download will be moved to a temporary location determined by
+    ///         Alamofire. The file will not be deleted until the system purges the temporary files.
+    ///
+    /// - Note: On some versions of all Apple platforms (iOS 10 - 10.2, macOS 10.12 - 10.12.2, tvOS 10 - 10.1, watchOS 3 - 3.1.1),
+    /// `resumeData` is broken on background URL session configurations. There's an underlying bug in the `resumeData`
+    /// generation logic where the data is written incorrectly and will always fail to resume the download. For more
+    /// information about the bug and possible workarounds, please refer to the [this Stack Overflow post](http://stackoverflow.com/a/39347461/1342462).
+    ///
+    /// - Parameters:
+    ///   - data:        The resume data from a previously cancelled `DownloadRequest` or `URLSessionDownloadTask`.
+    ///   - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
+    ///   - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file
+    ///                  should be moved. `nil` by default.
+    ///
+    /// - Returns:       The created `DownloadRequest`.
+    open func download(resumingWith data: Data,
+                       interceptor: RequestInterceptor? = nil,
+                       to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
+        let request = DownloadRequest(downloadable: .resumeData(data),
+                                      underlyingQueue: rootQueue,
+                                      serializationQueue: serializationQueue,
+                                      eventMonitor: eventMonitor,
+                                      interceptor: interceptor,
+                                      delegate: self,
+                                      destination: destination ?? DownloadRequest.defaultDestination)
+
+        perform(request)
+
+        return request
+    }
+
+    // MARK: - UploadRequest
+
+    struct ParameterlessRequestConvertible: URLRequestConvertible {
+        let url: URLConvertible
+        let method: HTTPMethod
+        let headers: HTTPHeaders?
+        let requestModifier: RequestModifier?
+
+        func asURLRequest() throws -> URLRequest {
+            var request = try URLRequest(url: url, method: method, headers: headers)
+            try requestModifier?(&request)
+
+            return request
+        }
+    }
+
+    struct Upload: UploadConvertible {
+        let request: URLRequestConvertible
+        let uploadable: UploadableConvertible
+
+        func createUploadable() throws -> UploadRequest.Uploadable {
+            try uploadable.createUploadable()
+        }
+
+        func asURLRequest() throws -> URLRequest {
+            try request.asURLRequest()
+        }
+    }
+
+    // MARK: Data
+
+    /// Creates an `UploadRequest` for the given `Data`, `URLRequest` components, and `RequestInterceptor`.
+    ///
+    /// - Parameters:
+    ///   - data:            The `Data` to upload.
+    ///   - convertible:     `URLConvertible` value to be used as the `URLRequest`'s `URL`.
+    ///   - method:          `HTTPMethod` for the `URLRequest`. `.post` by default.
+    ///   - headers:         `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
+    ///   - interceptor:     `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
+    ///   - fileManager:     `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
+    ///                      default.
+    ///   - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided
+    ///                      parameters. `nil` by default.
+    ///
+    /// - Returns:           The created `UploadRequest`.
+    open func upload(_ data: Data,
+                     to convertible: URLConvertible,
+                     method: HTTPMethod = .post,
+                     headers: HTTPHeaders? = nil,
+                     interceptor: RequestInterceptor? = nil,
+                     fileManager: FileManager = .default,
+                     requestModifier: RequestModifier? = nil) -> UploadRequest {
+        let convertible = ParameterlessRequestConvertible(url: convertible,
+                                                          method: method,
+                                                          headers: headers,
+                                                          requestModifier: requestModifier)
+
+        return upload(data, with: convertible, interceptor: interceptor, fileManager: fileManager)
+    }
+
+    /// Creates an `UploadRequest` for the given `Data` using the `URLRequestConvertible` value and `RequestInterceptor`.
+    ///
+    /// - Parameters:
+    ///   - data:        The `Data` to upload.
+    ///   - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
+    ///   - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
+    ///   - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
+    ///                  default.
+    ///
+    /// - Returns:       The created `UploadRequest`.
+    open func upload(_ data: Data,
+                     with convertible: URLRequestConvertible,
+                     interceptor: RequestInterceptor? = nil,
+                     fileManager: FileManager = .default) -> UploadRequest {
+        upload(.data(data), with: convertible, interceptor: interceptor, fileManager: fileManager)
+    }
+
+    // MARK: File
+
+    /// Creates an `UploadRequest` for the file at the given file `URL`, using a `URLRequest` from the provided
+    /// components and `RequestInterceptor`.
+    ///
+    /// - Parameters:
+    ///   - fileURL:         The `URL` of the file to upload.
+    ///   - convertible:     `URLConvertible` value to be used as the `URLRequest`'s `URL`.
+    ///   - method:          `HTTPMethod` for the `URLRequest`. `.post` by default.
+    ///   - headers:         `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
+    ///   - interceptor:     `RequestInterceptor` value to be used by the returned `UploadRequest`. `nil` by default.
+    ///   - fileManager:     `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
+    ///                      default.
+    ///   - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided
+    ///                      parameters. `nil` by default.
+    ///
+    /// - Returns:           The created `UploadRequest`.
+    open func upload(_ fileURL: URL,
+                     to convertible: URLConvertible,
+                     method: HTTPMethod = .post,
+                     headers: HTTPHeaders? = nil,
+                     interceptor: RequestInterceptor? = nil,
+                     fileManager: FileManager = .default,
+                     requestModifier: RequestModifier? = nil) -> UploadRequest {
+        let convertible = ParameterlessRequestConvertible(url: convertible,
+                                                          method: method,
+                                                          headers: headers,
+                                                          requestModifier: requestModifier)
+
+        return upload(fileURL, with: convertible, interceptor: interceptor, fileManager: fileManager)
+    }
+
+    /// Creates an `UploadRequest` for the file at the given file `URL` using the `URLRequestConvertible` value and
+    /// `RequestInterceptor`.
+    ///
+    /// - Parameters:
+    ///   - fileURL:     The `URL` of the file to upload.
+    ///   - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
+    ///   - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
+    ///   - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
+    ///                  default.
+    ///
+    /// - Returns:       The created `UploadRequest`.
+    open func upload(_ fileURL: URL,
+                     with convertible: URLRequestConvertible,
+                     interceptor: RequestInterceptor? = nil,
+                     fileManager: FileManager = .default) -> UploadRequest {
+        upload(.file(fileURL, shouldRemove: false), with: convertible, interceptor: interceptor, fileManager: fileManager)
+    }
+
+    // MARK: InputStream
+
+    /// Creates an `UploadRequest` from the `InputStream` provided using a `URLRequest` from the provided components and
+    /// `RequestInterceptor`.
+    ///
+    /// - Parameters:
+    ///   - stream:          The `InputStream` that provides the data to upload.
+    ///   - convertible:     `URLConvertible` value to be used as the `URLRequest`'s `URL`.
+    ///   - method:          `HTTPMethod` for the `URLRequest`. `.post` by default.
+    ///   - headers:         `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
+    ///   - interceptor:     `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
+    ///   - fileManager:     `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
+    ///                      default.
+    ///   - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided
+    ///                      parameters. `nil` by default.
+    ///
+    /// - Returns:           The created `UploadRequest`.
+    open func upload(_ stream: InputStream,
+                     to convertible: URLConvertible,
+                     method: HTTPMethod = .post,
+                     headers: HTTPHeaders? = nil,
+                     interceptor: RequestInterceptor? = nil,
+                     fileManager: FileManager = .default,
+                     requestModifier: RequestModifier? = nil) -> UploadRequest {
+        let convertible = ParameterlessRequestConvertible(url: convertible,
+                                                          method: method,
+                                                          headers: headers,
+                                                          requestModifier: requestModifier)
+
+        return upload(stream, with: convertible, interceptor: interceptor, fileManager: fileManager)
+    }
+
+    /// Creates an `UploadRequest` from the provided `InputStream` using the `URLRequestConvertible` value and
+    /// `RequestInterceptor`.
+    ///
+    /// - Parameters:
+    ///   - stream:      The `InputStream` that provides the data to upload.
+    ///   - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
+    ///   - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
+    ///   - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
+    ///                  default.
+    ///
+    /// - Returns:       The created `UploadRequest`.
+    open func upload(_ stream: InputStream,
+                     with convertible: URLRequestConvertible,
+                     interceptor: RequestInterceptor? = nil,
+                     fileManager: FileManager = .default) -> UploadRequest {
+        upload(.stream(stream), with: convertible, interceptor: interceptor, fileManager: fileManager)
+    }
+
+    // MARK: MultipartFormData
+
+    /// Creates an `UploadRequest` for the multipart form data built using a closure and sent using the provided
+    /// `URLRequest` components and `RequestInterceptor`.
+    ///
+    /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative
+    /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
+    /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
+    /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
+    /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
+    /// used for larger payloads such as video content.
+    ///
+    /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
+    /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
+    /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
+    /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
+    /// technique was used.
+    ///
+    /// - Parameters:
+    ///   - multipartFormData:      `MultipartFormData` building closure.
+    ///   - url:                    `URLConvertible` value to be used as the `URLRequest`'s `URL`.
+    ///   - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or
+    ///                              onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by
+    ///                              default.
+    ///   - method:                  `HTTPMethod` for the `URLRequest`. `.post` by default.
+    ///   - headers:                 `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
+    ///   - interceptor:             `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
+    ///   - fileManager:             `FileManager` to be used if the form data exceeds the memory threshold and is
+    ///                              written to disk before being uploaded. `.default` instance by default.
+    ///   - requestModifier:         `RequestModifier` which will be applied to the `URLRequest` created from the
+    ///                              provided parameters. `nil` by default.
+    ///
+    /// - Returns:                   The created `UploadRequest`.
+    open func upload(multipartFormData: @escaping (MultipartFormData) -> Void,
+                     to url: URLConvertible,
+                     usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
+                     method: HTTPMethod = .post,
+                     headers: HTTPHeaders? = nil,
+                     interceptor: RequestInterceptor? = nil,
+                     fileManager: FileManager = .default,
+                     requestModifier: RequestModifier? = nil) -> UploadRequest {
+        let convertible = ParameterlessRequestConvertible(url: url,
+                                                          method: method,
+                                                          headers: headers,
+                                                          requestModifier: requestModifier)
+
+        let formData = MultipartFormData(fileManager: fileManager)
+        multipartFormData(formData)
+
+        return upload(multipartFormData: formData,
+                      with: convertible,
+                      usingThreshold: encodingMemoryThreshold,
+                      interceptor: interceptor,
+                      fileManager: fileManager)
+    }
+
+    /// Creates an `UploadRequest` using a `MultipartFormData` building closure, the provided `URLRequestConvertible`
+    /// value, and a `RequestInterceptor`.
+    ///
+    /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative
+    /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
+    /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
+    /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
+    /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
+    /// used for larger payloads such as video content.
+    ///
+    /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
+    /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
+    /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
+    /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
+    /// technique was used.
+    ///
+    /// - Parameters:
+    ///   - multipartFormData:       `MultipartFormData` building closure.
+    ///   - request:                 `URLRequestConvertible` value to be used to create the `URLRequest`.
+    ///   - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or
+    ///                              onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by
+    ///                              default.
+    ///   - interceptor:             `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
+    ///   - fileManager:             `FileManager` to be used if the form data exceeds the memory threshold and is
+    ///                              written to disk before being uploaded. `.default` instance by default.
+    ///
+    /// - Returns:                   The created `UploadRequest`.
+    open func upload(multipartFormData: @escaping (MultipartFormData) -> Void,
+                     with request: URLRequestConvertible,
+                     usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
+                     interceptor: RequestInterceptor? = nil,
+                     fileManager: FileManager = .default) -> UploadRequest {
+        let formData = MultipartFormData(fileManager: fileManager)
+        multipartFormData(formData)
+
+        return upload(multipartFormData: formData,
+                      with: request,
+                      usingThreshold: encodingMemoryThreshold,
+                      interceptor: interceptor,
+                      fileManager: fileManager)
+    }
+
+    /// Creates an `UploadRequest` for the prebuilt `MultipartFormData` value using the provided `URLRequest` components
+    /// and `RequestInterceptor`.
+    ///
+    /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative
+    /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
+    /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
+    /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
+    /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
+    /// used for larger payloads such as video content.
+    ///
+    /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
+    /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
+    /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
+    /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
+    /// technique was used.
+    ///
+    /// - Parameters:
+    ///   - multipartFormData:       `MultipartFormData` instance to upload.
+    ///   - url:                     `URLConvertible` value to be used as the `URLRequest`'s `URL`.
+    ///   - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or
+    ///                              onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by
+    ///                              default.
+    ///   - method:                  `HTTPMethod` for the `URLRequest`. `.post` by default.
+    ///   - headers:                 `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
+    ///   - interceptor:             `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
+    ///   - fileManager:             `FileManager` to be used if the form data exceeds the memory threshold and is
+    ///                              written to disk before being uploaded. `.default` instance by default.
+    ///   - requestModifier:         `RequestModifier` which will be applied to the `URLRequest` created from the
+    ///                              provided parameters. `nil` by default.
+    ///
+    /// - Returns:                   The created `UploadRequest`.
+    open func upload(multipartFormData: MultipartFormData,
+                     to url: URLConvertible,
+                     usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
+                     method: HTTPMethod = .post,
+                     headers: HTTPHeaders? = nil,
+                     interceptor: RequestInterceptor? = nil,
+                     fileManager: FileManager = .default,
+                     requestModifier: RequestModifier? = nil) -> UploadRequest {
+        let convertible = ParameterlessRequestConvertible(url: url,
+                                                          method: method,
+                                                          headers: headers,
+                                                          requestModifier: requestModifier)
+
+        let multipartUpload = MultipartUpload(encodingMemoryThreshold: encodingMemoryThreshold,
+                                              request: convertible,
+                                              multipartFormData: multipartFormData)
+
+        return upload(multipartUpload, interceptor: interceptor, fileManager: fileManager)
+    }
+
+    /// Creates an `UploadRequest` for the prebuilt `MultipartFormData` value using the providing `URLRequestConvertible`
+    /// value and `RequestInterceptor`.
+    ///
+    /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative
+    /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
+    /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
+    /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
+    /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
+    /// used for larger payloads such as video content.
+    ///
+    /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
+    /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
+    /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
+    /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
+    /// technique was used.
+    ///
+    /// - Parameters:
+    ///   - multipartFormData:       `MultipartFormData` instance to upload.
+    ///   - request:                 `URLRequestConvertible` value to be used to create the `URLRequest`.
+    ///   - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or
+    ///                              onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by
+    ///                              default.
+    ///   - interceptor:             `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
+    ///   - fileManager:             `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
+    ///                              default.
+    ///
+    /// - Returns:                   The created `UploadRequest`.
+    open func upload(multipartFormData: MultipartFormData,
+                     with request: URLRequestConvertible,
+                     usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
+                     interceptor: RequestInterceptor? = nil,
+                     fileManager: FileManager = .default) -> UploadRequest {
+        let multipartUpload = MultipartUpload(encodingMemoryThreshold: encodingMemoryThreshold,
+                                              request: request,
+                                              multipartFormData: multipartFormData)
+
+        return upload(multipartUpload, interceptor: interceptor, fileManager: fileManager)
+    }
+
+    // MARK: - Internal API
+
+    // MARK: Uploadable
+
+    func upload(_ uploadable: UploadRequest.Uploadable,
+                with convertible: URLRequestConvertible,
+                interceptor: RequestInterceptor?,
+                fileManager: FileManager) -> UploadRequest {
+        let uploadable = Upload(request: convertible, uploadable: uploadable)
+
+        return upload(uploadable, interceptor: interceptor, fileManager: fileManager)
+    }
+
+    func upload(_ upload: UploadConvertible, interceptor: RequestInterceptor?, fileManager: FileManager) -> UploadRequest {
+        let request = UploadRequest(convertible: upload,
+                                    underlyingQueue: rootQueue,
+                                    serializationQueue: serializationQueue,
+                                    eventMonitor: eventMonitor,
+                                    interceptor: interceptor,
+                                    fileManager: fileManager,
+                                    delegate: self)
+
+        perform(request)
+
+        return request
+    }
+
+    // MARK: Perform
+
+    /// Starts performing the provided `Request`.
+    ///
+    /// - Parameter request: The `Request` to perform.
+    func perform(_ request: Request) {
+        rootQueue.async {
+            guard !request.isCancelled else { return }
+
+            self.activeRequests.insert(request)
+
+            self.requestQueue.async {
+                // Leaf types must come first, otherwise they will cast as their superclass.
+                switch request {
+                case let r as UploadRequest: self.performUploadRequest(r) // UploadRequest must come before DataRequest due to subtype relationship.
+                case let r as DataRequest: self.performDataRequest(r)
+                case let r as DownloadRequest: self.performDownloadRequest(r)
+                case let r as DataStreamRequest: self.performDataStreamRequest(r)
+                default: fatalError("Attempted to perform unsupported Request subclass: \(type(of: request))")
+                }
+            }
+        }
+    }
+
+    func performDataRequest(_ request: DataRequest) {
+        dispatchPrecondition(condition: .onQueue(requestQueue))
+
+        performSetupOperations(for: request, convertible: request.convertible)
+    }
+
+    func performDataStreamRequest(_ request: DataStreamRequest) {
+        dispatchPrecondition(condition: .onQueue(requestQueue))
+
+        performSetupOperations(for: request, convertible: request.convertible)
+    }
+
+    func performUploadRequest(_ request: UploadRequest) {
+        dispatchPrecondition(condition: .onQueue(requestQueue))
+
+        performSetupOperations(for: request, convertible: request.convertible) {
+            do {
+                let uploadable = try request.upload.createUploadable()
+                self.rootQueue.async { request.didCreateUploadable(uploadable) }
+                return true
+            } catch {
+                self.rootQueue.async { request.didFailToCreateUploadable(with: error.asAFError(or: .createUploadableFailed(error: error))) }
+                return false
+            }
+        }
+    }
+
+    func performDownloadRequest(_ request: DownloadRequest) {
+        dispatchPrecondition(condition: .onQueue(requestQueue))
+
+        switch request.downloadable {
+        case let .request(convertible):
+            performSetupOperations(for: request, convertible: convertible)
+        case let .resumeData(resumeData):
+            rootQueue.async { self.didReceiveResumeData(resumeData, for: request) }
+        }
+    }
+
+    func performSetupOperations(for request: Request,
+                                convertible: URLRequestConvertible,
+                                shouldCreateTask: @escaping () -> Bool = { true }) {
+        dispatchPrecondition(condition: .onQueue(requestQueue))
+
+        let initialRequest: URLRequest
+
+        do {
+            initialRequest = try convertible.asURLRequest()
+            try initialRequest.validate()
+        } catch {
+            rootQueue.async { request.didFailToCreateURLRequest(with: error.asAFError(or: .createURLRequestFailed(error: error))) }
+            return
+        }
+
+        rootQueue.async { request.didCreateInitialURLRequest(initialRequest) }
+
+        guard !request.isCancelled else { return }
+
+        guard let adapter = adapter(for: request) else {
+            guard shouldCreateTask() else { return }
+            rootQueue.async { self.didCreateURLRequest(initialRequest, for: request) }
+            return
+        }
+
+        let adapterState = RequestAdapterState(requestID: request.id, session: self)
+
+        adapter.adapt(initialRequest, using: adapterState) { result in
+            do {
+                let adaptedRequest = try result.get()
+                try adaptedRequest.validate()
+
+                self.rootQueue.async { request.didAdaptInitialRequest(initialRequest, to: adaptedRequest) }
+
+                guard shouldCreateTask() else { return }
+
+                self.rootQueue.async { self.didCreateURLRequest(adaptedRequest, for: request) }
+            } catch {
+                self.rootQueue.async { request.didFailToAdaptURLRequest(initialRequest, withError: .requestAdaptationFailed(error: error)) }
+            }
+        }
+    }
+
+    // MARK: - Task Handling
+
+    func didCreateURLRequest(_ urlRequest: URLRequest, for request: Request) {
+        dispatchPrecondition(condition: .onQueue(rootQueue))
+
+        request.didCreateURLRequest(urlRequest)
+
+        guard !request.isCancelled else { return }
+
+        let task = request.task(for: urlRequest, using: session)
+        requestTaskMap[request] = task
+        request.didCreateTask(task)
+
+        updateStatesForTask(task, request: request)
+    }
+
+    func didReceiveResumeData(_ data: Data, for request: DownloadRequest) {
+        dispatchPrecondition(condition: .onQueue(rootQueue))
+
+        guard !request.isCancelled else { return }
+
+        let task = request.task(forResumeData: data, using: session)
+        requestTaskMap[request] = task
+        request.didCreateTask(task)
+
+        updateStatesForTask(task, request: request)
+    }
+
+    func updateStatesForTask(_ task: URLSessionTask, request: Request) {
+        dispatchPrecondition(condition: .onQueue(rootQueue))
+
+        request.withState { state in
+            switch state {
+            case .initialized, .finished:
+                // Do nothing.
+                break
+            case .resumed:
+                task.resume()
+                rootQueue.async { request.didResumeTask(task) }
+            case .suspended:
+                task.suspend()
+                rootQueue.async { request.didSuspendTask(task) }
+            case .cancelled:
+                // Resume to ensure metrics are gathered.
+                task.resume()
+                task.cancel()
+                rootQueue.async { request.didCancelTask(task) }
+            }
+        }
+    }
+
+    // MARK: - Adapters and Retriers
+
+    func adapter(for request: Request) -> RequestAdapter? {
+        if let requestInterceptor = request.interceptor, let sessionInterceptor = interceptor {
+            return Interceptor(adapters: [requestInterceptor, sessionInterceptor])
+        } else {
+            return request.interceptor ?? interceptor
+        }
+    }
+
+    func retrier(for request: Request) -> RequestRetrier? {
+        if let requestInterceptor = request.interceptor, let sessionInterceptor = interceptor {
+            return Interceptor(retriers: [requestInterceptor, sessionInterceptor])
+        } else {
+            return request.interceptor ?? interceptor
+        }
+    }
+
+    // MARK: - Invalidation
+
+    func finishRequestsForDeinit() {
+        requestTaskMap.requests.forEach { request in
+            rootQueue.async {
+                request.finish(error: AFError.sessionDeinitialized)
+            }
+        }
+    }
+}
+
+// MARK: - RequestDelegate
+
+extension Session: RequestDelegate {
+    public var sessionConfiguration: URLSessionConfiguration {
+        session.configuration
+    }
+
+    public var startImmediately: Bool { startRequestsImmediately }
+
+    public func cleanup(after request: Request) {
+        activeRequests.remove(request)
+    }
+
+    public func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void) {
+        guard let retrier = retrier(for: request) else {
+            rootQueue.async { completion(.doNotRetry) }
+            return
+        }
+
+        retrier.retry(request, for: self, dueTo: error) { retryResult in
+            self.rootQueue.async {
+                guard let retryResultError = retryResult.error else { completion(retryResult); return }
+
+                let retryError = AFError.requestRetryFailed(retryError: retryResultError, originalError: error)
+                completion(.doNotRetryWithError(retryError))
+            }
+        }
+    }
+
+    public func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?) {
+        rootQueue.async {
+            let retry: () -> Void = {
+                guard !request.isCancelled else { return }
+
+                request.prepareForRetry()
+                self.perform(request)
+            }
+
+            if let retryDelay = timeDelay {
+                self.rootQueue.after(retryDelay) { retry() }
+            } else {
+                retry()
+            }
+        }
+    }
+}
+
+// MARK: - SessionStateProvider
+
+extension Session: SessionStateProvider {
+    func request(for task: URLSessionTask) -> Request? {
+        dispatchPrecondition(condition: .onQueue(rootQueue))
+
+        return requestTaskMap[task]
+    }
+
+    func didGatherMetricsForTask(_ task: URLSessionTask) {
+        dispatchPrecondition(condition: .onQueue(rootQueue))
+
+        let didDisassociate = requestTaskMap.disassociateIfNecessaryAfterGatheringMetricsForTask(task)
+
+        if didDisassociate {
+            waitingCompletions[task]?()
+            waitingCompletions[task] = nil
+        }
+    }
+
+    func didCompleteTask(_ task: URLSessionTask, completion: @escaping () -> Void) {
+        dispatchPrecondition(condition: .onQueue(rootQueue))
+
+        let didDisassociate = requestTaskMap.disassociateIfNecessaryAfterCompletingTask(task)
+
+        if didDisassociate {
+            completion()
+        } else {
+            waitingCompletions[task] = completion
+        }
+    }
+
+    func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential? {
+        dispatchPrecondition(condition: .onQueue(rootQueue))
+
+        return requestTaskMap[task]?.credential ??
+            session.configuration.urlCredentialStorage?.defaultCredential(for: protectionSpace)
+    }
+
+    func cancelRequestsForSessionInvalidation(with error: Error?) {
+        dispatchPrecondition(condition: .onQueue(rootQueue))
+
+        requestTaskMap.requests.forEach { $0.finish(error: AFError.sessionInvalidated(error: error)) }
+    }
+}

+ 336 - 0
Pods/Alamofire/Source/SessionDelegate.swift

@@ -0,0 +1,336 @@
+//
+//  SessionDelegate.swift
+//
+//  Copyright (c) 2014-2018 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
+
+/// Class which implements the various `URLSessionDelegate` methods to connect various Alamofire features.
+open class SessionDelegate: NSObject {
+    private let fileManager: FileManager
+
+    weak var stateProvider: SessionStateProvider?
+    var eventMonitor: EventMonitor?
+
+    /// Creates an instance from the given `FileManager`.
+    ///
+    /// - Parameter fileManager: `FileManager` to use for underlying file management, such as moving downloaded files.
+    ///                          `.default` by default.
+    public init(fileManager: FileManager = .default) {
+        self.fileManager = fileManager
+    }
+
+    /// Internal method to find and cast requests while maintaining some integrity checking.
+    ///
+    /// - Parameters:
+    ///   - task: The `URLSessionTask` for which to find the associated `Request`.
+    ///   - type: The `Request` subclass type to cast any `Request` associate with `task`.
+    func request<R: Request>(for task: URLSessionTask, as type: R.Type) -> R? {
+        guard let provider = stateProvider else {
+            assertionFailure("StateProvider is nil.")
+            return nil
+        }
+
+        return provider.request(for: task) as? R
+    }
+}
+
+/// Type which provides various `Session` state values.
+protocol SessionStateProvider: AnyObject {
+    var serverTrustManager: ServerTrustManager? { get }
+    var redirectHandler: RedirectHandler? { get }
+    var cachedResponseHandler: CachedResponseHandler? { get }
+
+    func request(for task: URLSessionTask) -> Request?
+    func didGatherMetricsForTask(_ task: URLSessionTask)
+    func didCompleteTask(_ task: URLSessionTask, completion: @escaping () -> Void)
+    func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential?
+    func cancelRequestsForSessionInvalidation(with error: Error?)
+}
+
+// MARK: URLSessionDelegate
+
+extension SessionDelegate: URLSessionDelegate {
+    open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
+        eventMonitor?.urlSession(session, didBecomeInvalidWithError: error)
+
+        stateProvider?.cancelRequestsForSessionInvalidation(with: error)
+    }
+}
+
+// MARK: URLSessionTaskDelegate
+
+extension SessionDelegate: URLSessionTaskDelegate {
+    /// Result of a `URLAuthenticationChallenge` evaluation.
+    typealias ChallengeEvaluation = (disposition: URLSession.AuthChallengeDisposition, credential: URLCredential?, error: AFError?)
+
+    open func urlSession(_ session: URLSession,
+                         task: URLSessionTask,
+                         didReceive challenge: URLAuthenticationChallenge,
+                         completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
+        eventMonitor?.urlSession(session, task: task, didReceive: challenge)
+
+        let evaluation: ChallengeEvaluation
+        switch challenge.protectionSpace.authenticationMethod {
+        case NSURLAuthenticationMethodHTTPBasic, NSURLAuthenticationMethodHTTPDigest, NSURLAuthenticationMethodNTLM,
+             NSURLAuthenticationMethodNegotiate:
+            evaluation = attemptCredentialAuthentication(for: challenge, belongingTo: task)
+        #if !(os(Linux) || os(Windows))
+        case NSURLAuthenticationMethodServerTrust:
+            evaluation = attemptServerTrustAuthentication(with: challenge)
+        case NSURLAuthenticationMethodClientCertificate:
+            evaluation = attemptCredentialAuthentication(for: challenge, belongingTo: task)
+        #endif
+        default:
+            evaluation = (.performDefaultHandling, nil, nil)
+        }
+
+        if let error = evaluation.error {
+            stateProvider?.request(for: task)?.didFailTask(task, earlyWithError: error)
+        }
+
+        completionHandler(evaluation.disposition, evaluation.credential)
+    }
+
+    #if !(os(Linux) || os(Windows))
+    /// Evaluates the server trust `URLAuthenticationChallenge` received.
+    ///
+    /// - Parameter challenge: The `URLAuthenticationChallenge`.
+    ///
+    /// - Returns:             The `ChallengeEvaluation`.
+    func attemptServerTrustAuthentication(with challenge: URLAuthenticationChallenge) -> ChallengeEvaluation {
+        let host = challenge.protectionSpace.host
+
+        guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
+              let trust = challenge.protectionSpace.serverTrust
+        else {
+            return (.performDefaultHandling, nil, nil)
+        }
+
+        do {
+            guard let evaluator = try stateProvider?.serverTrustManager?.serverTrustEvaluator(forHost: host) else {
+                return (.performDefaultHandling, nil, nil)
+            }
+
+            try evaluator.evaluate(trust, forHost: host)
+
+            return (.useCredential, URLCredential(trust: trust), nil)
+        } catch {
+            return (.cancelAuthenticationChallenge, nil, error.asAFError(or: .serverTrustEvaluationFailed(reason: .customEvaluationFailed(error: error))))
+        }
+    }
+    #endif
+
+    /// Evaluates the credential-based authentication `URLAuthenticationChallenge` received for `task`.
+    ///
+    /// - Parameters:
+    ///   - challenge: The `URLAuthenticationChallenge`.
+    ///   - task:      The `URLSessionTask` which received the challenge.
+    ///
+    /// - Returns:     The `ChallengeEvaluation`.
+    func attemptCredentialAuthentication(for challenge: URLAuthenticationChallenge,
+                                         belongingTo task: URLSessionTask) -> ChallengeEvaluation {
+        guard challenge.previousFailureCount == 0 else {
+            return (.rejectProtectionSpace, nil, nil)
+        }
+
+        guard let credential = stateProvider?.credential(for: task, in: challenge.protectionSpace) else {
+            return (.performDefaultHandling, nil, nil)
+        }
+
+        return (.useCredential, credential, nil)
+    }
+
+    open func urlSession(_ session: URLSession,
+                         task: URLSessionTask,
+                         didSendBodyData bytesSent: Int64,
+                         totalBytesSent: Int64,
+                         totalBytesExpectedToSend: Int64) {
+        eventMonitor?.urlSession(session,
+                                 task: task,
+                                 didSendBodyData: bytesSent,
+                                 totalBytesSent: totalBytesSent,
+                                 totalBytesExpectedToSend: totalBytesExpectedToSend)
+
+        stateProvider?.request(for: task)?.updateUploadProgress(totalBytesSent: totalBytesSent,
+                                                                totalBytesExpectedToSend: totalBytesExpectedToSend)
+    }
+
+    open func urlSession(_ session: URLSession,
+                         task: URLSessionTask,
+                         needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) {
+        eventMonitor?.urlSession(session, taskNeedsNewBodyStream: task)
+
+        guard let request = request(for: task, as: UploadRequest.self) else {
+            assertionFailure("needNewBodyStream did not find UploadRequest.")
+            completionHandler(nil)
+            return
+        }
+
+        completionHandler(request.inputStream())
+    }
+
+    open func urlSession(_ session: URLSession,
+                         task: URLSessionTask,
+                         willPerformHTTPRedirection response: HTTPURLResponse,
+                         newRequest request: URLRequest,
+                         completionHandler: @escaping (URLRequest?) -> Void) {
+        eventMonitor?.urlSession(session, task: task, willPerformHTTPRedirection: response, newRequest: request)
+
+        if let redirectHandler = stateProvider?.request(for: task)?.redirectHandler ?? stateProvider?.redirectHandler {
+            redirectHandler.task(task, willBeRedirectedTo: request, for: response, completion: completionHandler)
+        } else {
+            completionHandler(request)
+        }
+    }
+
+    open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
+        eventMonitor?.urlSession(session, task: task, didFinishCollecting: metrics)
+
+        stateProvider?.request(for: task)?.didGatherMetrics(metrics)
+
+        stateProvider?.didGatherMetricsForTask(task)
+    }
+
+    open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
+        eventMonitor?.urlSession(session, task: task, didCompleteWithError: error)
+
+        let request = stateProvider?.request(for: task)
+
+        stateProvider?.didCompleteTask(task) {
+            request?.didCompleteTask(task, with: error.map { $0.asAFError(or: .sessionTaskFailed(error: $0)) })
+        }
+    }
+
+    @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
+    open func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {
+        eventMonitor?.urlSession(session, taskIsWaitingForConnectivity: task)
+    }
+}
+
+// MARK: URLSessionDataDelegate
+
+extension SessionDelegate: URLSessionDataDelegate {
+    open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
+        eventMonitor?.urlSession(session, dataTask: dataTask, didReceive: data)
+
+        if let request = request(for: dataTask, as: DataRequest.self) {
+            request.didReceive(data: data)
+        } else if let request = request(for: dataTask, as: DataStreamRequest.self) {
+            request.didReceive(data: data)
+        } else {
+            assertionFailure("dataTask did not find DataRequest or DataStreamRequest in didReceive")
+            return
+        }
+    }
+
+    open func urlSession(_ session: URLSession,
+                         dataTask: URLSessionDataTask,
+                         willCacheResponse proposedResponse: CachedURLResponse,
+                         completionHandler: @escaping (CachedURLResponse?) -> Void) {
+        eventMonitor?.urlSession(session, dataTask: dataTask, willCacheResponse: proposedResponse)
+
+        if let handler = stateProvider?.request(for: dataTask)?.cachedResponseHandler ?? stateProvider?.cachedResponseHandler {
+            handler.dataTask(dataTask, willCacheResponse: proposedResponse, completion: completionHandler)
+        } else {
+            completionHandler(proposedResponse)
+        }
+    }
+}
+
+// MARK: URLSessionDownloadDelegate
+
+extension SessionDelegate: URLSessionDownloadDelegate {
+    open func urlSession(_ session: URLSession,
+                         downloadTask: URLSessionDownloadTask,
+                         didResumeAtOffset fileOffset: Int64,
+                         expectedTotalBytes: Int64) {
+        eventMonitor?.urlSession(session,
+                                 downloadTask: downloadTask,
+                                 didResumeAtOffset: fileOffset,
+                                 expectedTotalBytes: expectedTotalBytes)
+        guard let downloadRequest = request(for: downloadTask, as: DownloadRequest.self) else {
+            assertionFailure("downloadTask did not find DownloadRequest.")
+            return
+        }
+
+        downloadRequest.updateDownloadProgress(bytesWritten: fileOffset,
+                                               totalBytesExpectedToWrite: expectedTotalBytes)
+    }
+
+    open func urlSession(_ session: URLSession,
+                         downloadTask: URLSessionDownloadTask,
+                         didWriteData bytesWritten: Int64,
+                         totalBytesWritten: Int64,
+                         totalBytesExpectedToWrite: Int64) {
+        eventMonitor?.urlSession(session,
+                                 downloadTask: downloadTask,
+                                 didWriteData: bytesWritten,
+                                 totalBytesWritten: totalBytesWritten,
+                                 totalBytesExpectedToWrite: totalBytesExpectedToWrite)
+        guard let downloadRequest = request(for: downloadTask, as: DownloadRequest.self) else {
+            assertionFailure("downloadTask did not find DownloadRequest.")
+            return
+        }
+
+        downloadRequest.updateDownloadProgress(bytesWritten: bytesWritten,
+                                               totalBytesExpectedToWrite: totalBytesExpectedToWrite)
+    }
+
+    open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
+        eventMonitor?.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location)
+
+        guard let request = request(for: downloadTask, as: DownloadRequest.self) else {
+            assertionFailure("downloadTask did not find DownloadRequest.")
+            return
+        }
+
+        let (destination, options): (URL, DownloadRequest.Options)
+        if let response = request.response {
+            (destination, options) = request.destination(location, response)
+        } else {
+            // If there's no response this is likely a local file download, so generate the temporary URL directly.
+            (destination, options) = (DownloadRequest.defaultDestinationURL(location), [])
+        }
+
+        eventMonitor?.request(request, didCreateDestinationURL: destination)
+
+        do {
+            if options.contains(.removePreviousFile), fileManager.fileExists(atPath: destination.path) {
+                try fileManager.removeItem(at: destination)
+            }
+
+            if options.contains(.createIntermediateDirectories) {
+                let directory = destination.deletingLastPathComponent()
+                try fileManager.createDirectory(at: directory, withIntermediateDirectories: true)
+            }
+
+            try fileManager.moveItem(at: location, to: destination)
+
+            request.didFinishDownloading(using: downloadTask, with: .success(destination))
+        } catch {
+            request.didFinishDownloading(using: downloadTask, with: .failure(.downloadedFileMoveFailed(error: error,
+                                                                                                       source: location,
+                                                                                                       destination: destination)))
+        }
+    }
+}

+ 55 - 0
Pods/Alamofire/Source/StringEncoding+Alamofire.swift

@@ -0,0 +1,55 @@
+//
+//  StringEncoding+Alamofire.swift
+//
+//  Copyright (c) 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.
+//
+
+import Foundation
+
+extension String.Encoding {
+    /// Creates an encoding from the IANA charset name.
+    ///
+    /// - Notes: These mappings match those [provided by CoreFoundation](https://opensource.apple.com/source/CF/CF-476.18/CFStringUtilities.c.auto.html)
+    ///
+    /// - Parameter name: IANA charset name.
+    init?(ianaCharsetName name: String) {
+        switch name.lowercased() {
+        case "utf-8":
+            self = .utf8
+        case "iso-8859-1":
+            self = .isoLatin1
+        case "unicode-1-1", "iso-10646-ucs-2", "utf-16":
+            self = .utf16
+        case "utf-16be":
+            self = .utf16BigEndian
+        case "utf-16le":
+            self = .utf16LittleEndian
+        case "utf-32":
+            self = .utf32
+        case "utf-32be":
+            self = .utf32BigEndian
+        case "utf-32le":
+            self = .utf32LittleEndian
+        default:
+            return nil
+        }
+    }
+}

+ 105 - 0
Pods/Alamofire/Source/URLConvertible+URLRequestConvertible.swift

@@ -0,0 +1,105 @@
+//
+//  URLConvertible+URLRequestConvertible.swift
+//
+//  Copyright (c) 2014-2018 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
+
+/// Types adopting the `URLConvertible` protocol can be used to construct `URL`s, which can then be used to construct
+/// `URLRequests`.
+public protocol URLConvertible {
+    /// Returns a `URL` from the conforming instance or throws.
+    ///
+    /// - Returns: The `URL` created from the instance.
+    /// - Throws:  Any error thrown while creating the `URL`.
+    func asURL() throws -> URL
+}
+
+extension String: URLConvertible {
+    /// Returns a `URL` if `self` can be used to initialize a `URL` instance, otherwise throws.
+    ///
+    /// - Returns: The `URL` initialized with `self`.
+    /// - Throws:  An `AFError.invalidURL` instance.
+    public func asURL() throws -> URL {
+        guard let url = URL(string: self) else { throw AFError.invalidURL(url: self) }
+
+        return url
+    }
+}
+
+extension URL: URLConvertible {
+    /// Returns `self`.
+    public func asURL() throws -> URL { self }
+}
+
+extension URLComponents: URLConvertible {
+    /// Returns a `URL` if the `self`'s `url` is not nil, otherwise throws.
+    ///
+    /// - Returns: The `URL` from the `url` property.
+    /// - Throws:  An `AFError.invalidURL` instance.
+    public func asURL() throws -> URL {
+        guard let url = url else { throw AFError.invalidURL(url: self) }
+
+        return url
+    }
+}
+
+// MARK: -
+
+/// Types adopting the `URLRequestConvertible` protocol can be used to safely construct `URLRequest`s.
+public protocol URLRequestConvertible {
+    /// Returns a `URLRequest` or throws if an `Error` was encountered.
+    ///
+    /// - Returns: A `URLRequest`.
+    /// - Throws:  Any error thrown while constructing the `URLRequest`.
+    func asURLRequest() throws -> URLRequest
+}
+
+extension URLRequestConvertible {
+    /// The `URLRequest` returned by discarding any `Error` encountered.
+    public var urlRequest: URLRequest? { try? asURLRequest() }
+}
+
+extension URLRequest: URLRequestConvertible {
+    /// Returns `self`.
+    public func asURLRequest() throws -> URLRequest { self }
+}
+
+// MARK: -
+
+extension URLRequest {
+    /// Creates an instance with the specified `url`, `method`, and `headers`.
+    ///
+    /// - Parameters:
+    ///   - url:     The `URLConvertible` value.
+    ///   - method:  The `HTTPMethod`.
+    ///   - headers: The `HTTPHeaders`, `nil` by default.
+    /// - Throws:    Any error thrown while converting the `URLConvertible` to a `URL`.
+    public init(url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws {
+        let url = try url.asURL()
+
+        self.init(url: url)
+
+        httpMethod = method.rawValue
+        allHTTPHeaderFields = headers?.dictionary
+    }
+}

+ 982 - 0
Pods/Alamofire/Source/URLEncodedFormEncoder.swift

@@ -0,0 +1,982 @@
+//
+//  URLEncodedFormEncoder.swift
+//
+//  Copyright (c) 2019 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
+
+/// An object that encodes instances into URL-encoded query strings.
+///
+/// There is no published specification for how to encode collection types. By default, the convention of appending
+/// `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for
+/// nested dictionary values (`foo[bar]=baz`) is used. Optionally, `ArrayEncoding` can be used to omit the
+/// square brackets appended to array keys.
+///
+/// `BoolEncoding` can be used to configure how `Bool` values are encoded. The default behavior is to encode
+/// `true` as 1 and `false` as 0.
+///
+/// `DateEncoding` can be used to configure how `Date` values are encoded. By default, the `.deferredToDate`
+/// strategy is used, which formats dates from their structure.
+///
+/// `SpaceEncoding` can be used to configure how spaces are encoded. Modern encodings use percent replacement (`%20`),
+/// while older encodings may expect spaces to be replaced with `+`.
+///
+/// This type is largely based on Vapor's [`url-encoded-form`](https://github.com/vapor/url-encoded-form) project.
+public final class URLEncodedFormEncoder {
+    /// Encoding to use for `Array` values.
+    public enum ArrayEncoding {
+        /// An empty set of square brackets ("[]") are appended to the key for every value. This is the default encoding.
+        case brackets
+        /// No brackets are appended to the key and the key is encoded as is.
+        case noBrackets
+        /// Brackets containing the item index are appended. This matches the jQuery and Node.js behavior.
+        case indexInBrackets
+
+        /// Encodes the key according to the encoding.
+        ///
+        /// - Parameters:
+        ///     - key:      The `key` to encode.
+        ///     - index:   When this enum instance is `.indexInBrackets`, the `index` to encode.
+        ///
+        /// - Returns:          The encoded key.
+        func encode(_ key: String, atIndex index: Int) -> String {
+            switch self {
+            case .brackets: return "\(key)[]"
+            case .noBrackets: return key
+            case .indexInBrackets: return "\(key)[\(index)]"
+            }
+        }
+    }
+
+    /// Encoding to use for `Bool` values.
+    public enum BoolEncoding {
+        /// Encodes `true` as `1`, `false` as `0`.
+        case numeric
+        /// Encodes `true` as "true", `false` as "false". This is the default encoding.
+        case literal
+
+        /// Encodes the given `Bool` as a `String`.
+        ///
+        /// - Parameter value: The `Bool` to encode.
+        ///
+        /// - Returns:         The encoded `String`.
+        func encode(_ value: Bool) -> String {
+            switch self {
+            case .numeric: return value ? "1" : "0"
+            case .literal: return value ? "true" : "false"
+            }
+        }
+    }
+
+    /// Encoding to use for `Data` values.
+    public enum DataEncoding {
+        /// Defers encoding to the `Data` type.
+        case deferredToData
+        /// Encodes `Data` as a Base64-encoded string. This is the default encoding.
+        case base64
+        /// Encode the `Data` as a custom value encoded by the given closure.
+        case custom((Data) throws -> String)
+
+        /// Encodes `Data` according to the encoding.
+        ///
+        /// - Parameter data: The `Data` to encode.
+        ///
+        /// - Returns:        The encoded `String`, or `nil` if the `Data` should be encoded according to its
+        ///                   `Encodable` implementation.
+        func encode(_ data: Data) throws -> String? {
+            switch self {
+            case .deferredToData: return nil
+            case .base64: return data.base64EncodedString()
+            case let .custom(encoding): return try encoding(data)
+            }
+        }
+    }
+
+    /// Encoding to use for `Date` values.
+    public enum DateEncoding {
+        /// ISO8601 and RFC3339 formatter.
+        private static let iso8601Formatter: ISO8601DateFormatter = {
+            let formatter = ISO8601DateFormatter()
+            formatter.formatOptions = .withInternetDateTime
+            return formatter
+        }()
+
+        /// Defers encoding to the `Date` type. This is the default encoding.
+        case deferredToDate
+        /// Encodes `Date`s as seconds since midnight UTC on January 1, 1970.
+        case secondsSince1970
+        /// Encodes `Date`s as milliseconds since midnight UTC on January 1, 1970.
+        case millisecondsSince1970
+        /// Encodes `Date`s according to the ISO8601 and RFC3339 standards.
+        case iso8601
+        /// Encodes `Date`s using the given `DateFormatter`.
+        case formatted(DateFormatter)
+        /// Encodes `Date`s using the given closure.
+        case custom((Date) throws -> String)
+
+        /// Encodes the date according to the encoding.
+        ///
+        /// - Parameter date: The `Date` to encode.
+        ///
+        /// - Returns:        The encoded `String`, or `nil` if the `Date` should be encoded according to its
+        ///                   `Encodable` implementation.
+        func encode(_ date: Date) throws -> String? {
+            switch self {
+            case .deferredToDate:
+                return nil
+            case .secondsSince1970:
+                return String(date.timeIntervalSince1970)
+            case .millisecondsSince1970:
+                return String(date.timeIntervalSince1970 * 1000.0)
+            case .iso8601:
+                return DateEncoding.iso8601Formatter.string(from: date)
+            case let .formatted(formatter):
+                return formatter.string(from: date)
+            case let .custom(closure):
+                return try closure(date)
+            }
+        }
+    }
+
+    /// Encoding to use for keys.
+    ///
+    /// This type is derived from [`JSONEncoder`'s `KeyEncodingStrategy`](https://github.com/apple/swift/blob/6aa313b8dd5f05135f7f878eccc1db6f9fbe34ff/stdlib/public/Darwin/Foundation/JSONEncoder.swift#L128)
+    /// and [`XMLEncoder`s `KeyEncodingStrategy`](https://github.com/MaxDesiatov/XMLCoder/blob/master/Sources/XMLCoder/Encoder/XMLEncoder.swift#L102).
+    public enum KeyEncoding {
+        /// Use the keys specified by each type. This is the default encoding.
+        case useDefaultKeys
+        /// Convert from "camelCaseKeys" to "snake_case_keys" before writing a key.
+        ///
+        /// Capital characters are determined by testing membership in
+        /// `CharacterSet.uppercaseLetters` and `CharacterSet.lowercaseLetters`
+        /// (Unicode General Categories Lu and Lt).
+        /// The conversion to lower case uses `Locale.system`, also known as
+        /// the ICU "root" locale. This means the result is consistent
+        /// regardless of the current user's locale and language preferences.
+        ///
+        /// Converting from camel case to snake case:
+        /// 1. Splits words at the boundary of lower-case to upper-case
+        /// 2. Inserts `_` between words
+        /// 3. Lowercases the entire string
+        /// 4. Preserves starting and ending `_`.
+        ///
+        /// For example, `oneTwoThree` becomes `one_two_three`. `_oneTwoThree_` becomes `_one_two_three_`.
+        ///
+        /// - Note: Using a key encoding strategy has a nominal performance cost, as each string key has to be converted.
+        case convertToSnakeCase
+        /// Same as convertToSnakeCase, but using `-` instead of `_`.
+        /// For example `oneTwoThree` becomes `one-two-three`.
+        case convertToKebabCase
+        /// Capitalize the first letter only.
+        /// For example `oneTwoThree` becomes  `OneTwoThree`.
+        case capitalized
+        /// Uppercase all letters.
+        /// For example `oneTwoThree` becomes  `ONETWOTHREE`.
+        case uppercased
+        /// Lowercase all letters.
+        /// For example `oneTwoThree` becomes  `onetwothree`.
+        case lowercased
+        /// A custom encoding using the provided closure.
+        case custom((String) -> String)
+
+        func encode(_ key: String) -> String {
+            switch self {
+            case .useDefaultKeys: return key
+            case .convertToSnakeCase: return convertToSnakeCase(key)
+            case .convertToKebabCase: return convertToKebabCase(key)
+            case .capitalized: return String(key.prefix(1).uppercased() + key.dropFirst())
+            case .uppercased: return key.uppercased()
+            case .lowercased: return key.lowercased()
+            case let .custom(encoding): return encoding(key)
+            }
+        }
+
+        private func convertToSnakeCase(_ key: String) -> String {
+            convert(key, usingSeparator: "_")
+        }
+
+        private func convertToKebabCase(_ key: String) -> String {
+            convert(key, usingSeparator: "-")
+        }
+
+        private func convert(_ key: String, usingSeparator separator: String) -> String {
+            guard !key.isEmpty else { return key }
+
+            var words: [Range<String.Index>] = []
+            // The general idea of this algorithm is to split words on
+            // transition from lower to upper case, then on transition of >1
+            // upper case characters to lowercase
+            //
+            // myProperty -> my_property
+            // myURLProperty -> my_url_property
+            //
+            // It is assumed, per Swift naming conventions, that the first character of the key is lowercase.
+            var wordStart = key.startIndex
+            var searchRange = key.index(after: wordStart)..<key.endIndex
+
+            // Find next uppercase character
+            while let upperCaseRange = key.rangeOfCharacter(from: CharacterSet.uppercaseLetters, options: [], range: searchRange) {
+                let untilUpperCase = wordStart..<upperCaseRange.lowerBound
+                words.append(untilUpperCase)
+
+                // Find next lowercase character
+                searchRange = upperCaseRange.lowerBound..<searchRange.upperBound
+                guard let lowerCaseRange = key.rangeOfCharacter(from: CharacterSet.lowercaseLetters, options: [], range: searchRange) else {
+                    // There are no more lower case letters. Just end here.
+                    wordStart = searchRange.lowerBound
+                    break
+                }
+
+                // Is the next lowercase letter more than 1 after the uppercase?
+                // If so, we encountered a group of uppercase letters that we
+                // should treat as its own word
+                let nextCharacterAfterCapital = key.index(after: upperCaseRange.lowerBound)
+                if lowerCaseRange.lowerBound == nextCharacterAfterCapital {
+                    // The next character after capital is a lower case character and therefore not a word boundary.
+                    // Continue searching for the next upper case for the boundary.
+                    wordStart = upperCaseRange.lowerBound
+                } else {
+                    // There was a range of >1 capital letters. Turn those into a word, stopping at the capital before the lower case character.
+                    let beforeLowerIndex = key.index(before: lowerCaseRange.lowerBound)
+                    words.append(upperCaseRange.lowerBound..<beforeLowerIndex)
+
+                    // Next word starts at the capital before the lowercase we just found
+                    wordStart = beforeLowerIndex
+                }
+                searchRange = lowerCaseRange.upperBound..<searchRange.upperBound
+            }
+            words.append(wordStart..<searchRange.upperBound)
+            let result = words.map { range in
+                key[range].lowercased()
+            }.joined(separator: separator)
+
+            return result
+        }
+    }
+
+    /// Encoding to use for spaces.
+    public enum SpaceEncoding {
+        /// Encodes spaces according to normal percent escaping rules (%20).
+        case percentEscaped
+        /// Encodes spaces as `+`,
+        case plusReplaced
+
+        /// Encodes the string according to the encoding.
+        ///
+        /// - Parameter string: The `String` to encode.
+        ///
+        /// - Returns:          The encoded `String`.
+        func encode(_ string: String) -> String {
+            switch self {
+            case .percentEscaped: return string.replacingOccurrences(of: " ", with: "%20")
+            case .plusReplaced: return string.replacingOccurrences(of: " ", with: "+")
+            }
+        }
+    }
+
+    /// `URLEncodedFormEncoder` error.
+    public enum Error: Swift.Error {
+        /// An invalid root object was created by the encoder. Only keyed values are valid.
+        case invalidRootObject(String)
+
+        var localizedDescription: String {
+            switch self {
+            case let .invalidRootObject(object):
+                return "URLEncodedFormEncoder requires keyed root object. Received \(object) instead."
+            }
+        }
+    }
+
+    /// Whether or not to sort the encoded key value pairs.
+    ///
+    /// - Note: This setting ensures a consistent ordering for all encodings of the same parameters. When set to `false`,
+    ///         encoded `Dictionary` values may have a different encoded order each time they're encoded due to
+    ///       ` Dictionary`'s random storage order, but `Encodable` types will maintain their encoded order.
+    public let alphabetizeKeyValuePairs: Bool
+    /// The `ArrayEncoding` to use.
+    public let arrayEncoding: ArrayEncoding
+    /// The `BoolEncoding` to use.
+    public let boolEncoding: BoolEncoding
+    /// THe `DataEncoding` to use.
+    public let dataEncoding: DataEncoding
+    /// The `DateEncoding` to use.
+    public let dateEncoding: DateEncoding
+    /// The `KeyEncoding` to use.
+    public let keyEncoding: KeyEncoding
+    /// The `SpaceEncoding` to use.
+    public let spaceEncoding: SpaceEncoding
+    /// The `CharacterSet` of allowed (non-escaped) characters.
+    public var allowedCharacters: CharacterSet
+
+    /// Creates an instance from the supplied parameters.
+    ///
+    /// - Parameters:
+    ///   - alphabetizeKeyValuePairs: Whether or not to sort the encoded key value pairs. `true` by default.
+    ///   - arrayEncoding:            The `ArrayEncoding` to use. `.brackets` by default.
+    ///   - boolEncoding:             The `BoolEncoding` to use. `.numeric` by default.
+    ///   - dataEncoding:             The `DataEncoding` to use. `.base64` by default.
+    ///   - dateEncoding:             The `DateEncoding` to use. `.deferredToDate` by default.
+    ///   - keyEncoding:              The `KeyEncoding` to use. `.useDefaultKeys` by default.
+    ///   - spaceEncoding:            The `SpaceEncoding` to use. `.percentEscaped` by default.
+    ///   - allowedCharacters:        The `CharacterSet` of allowed (non-escaped) characters. `.afURLQueryAllowed` by
+    ///                               default.
+    public init(alphabetizeKeyValuePairs: Bool = true,
+                arrayEncoding: ArrayEncoding = .brackets,
+                boolEncoding: BoolEncoding = .numeric,
+                dataEncoding: DataEncoding = .base64,
+                dateEncoding: DateEncoding = .deferredToDate,
+                keyEncoding: KeyEncoding = .useDefaultKeys,
+                spaceEncoding: SpaceEncoding = .percentEscaped,
+                allowedCharacters: CharacterSet = .afURLQueryAllowed) {
+        self.alphabetizeKeyValuePairs = alphabetizeKeyValuePairs
+        self.arrayEncoding = arrayEncoding
+        self.boolEncoding = boolEncoding
+        self.dataEncoding = dataEncoding
+        self.dateEncoding = dateEncoding
+        self.keyEncoding = keyEncoding
+        self.spaceEncoding = spaceEncoding
+        self.allowedCharacters = allowedCharacters
+    }
+
+    func encode(_ value: Encodable) throws -> URLEncodedFormComponent {
+        let context = URLEncodedFormContext(.object([]))
+        let encoder = _URLEncodedFormEncoder(context: context,
+                                             boolEncoding: boolEncoding,
+                                             dataEncoding: dataEncoding,
+                                             dateEncoding: dateEncoding)
+        try value.encode(to: encoder)
+
+        return context.component
+    }
+
+    /// Encodes the `value` as a URL form encoded `String`.
+    ///
+    /// - Parameter value: The `Encodable` value.`
+    ///
+    /// - Returns:         The encoded `String`.
+    /// - Throws:          An `Error` or `EncodingError` instance if encoding fails.
+    public func encode(_ value: Encodable) throws -> String {
+        let component: URLEncodedFormComponent = try encode(value)
+
+        guard case let .object(object) = component else {
+            throw Error.invalidRootObject("\(component)")
+        }
+
+        let serializer = URLEncodedFormSerializer(alphabetizeKeyValuePairs: alphabetizeKeyValuePairs,
+                                                  arrayEncoding: arrayEncoding,
+                                                  keyEncoding: keyEncoding,
+                                                  spaceEncoding: spaceEncoding,
+                                                  allowedCharacters: allowedCharacters)
+        let query = serializer.serialize(object)
+
+        return query
+    }
+
+    /// Encodes the value as `Data`. This is performed by first creating an encoded `String` and then returning the
+    /// `.utf8` data.
+    ///
+    /// - Parameter value: The `Encodable` value.
+    ///
+    /// - Returns:         The encoded `Data`.
+    ///
+    /// - Throws:          An `Error` or `EncodingError` instance if encoding fails.
+    public func encode(_ value: Encodable) throws -> Data {
+        let string: String = try encode(value)
+
+        return Data(string.utf8)
+    }
+}
+
+final class _URLEncodedFormEncoder {
+    var codingPath: [CodingKey]
+    // Returns an empty dictionary, as this encoder doesn't support userInfo.
+    var userInfo: [CodingUserInfoKey: Any] { [:] }
+
+    let context: URLEncodedFormContext
+
+    private let boolEncoding: URLEncodedFormEncoder.BoolEncoding
+    private let dataEncoding: URLEncodedFormEncoder.DataEncoding
+    private let dateEncoding: URLEncodedFormEncoder.DateEncoding
+
+    init(context: URLEncodedFormContext,
+         codingPath: [CodingKey] = [],
+         boolEncoding: URLEncodedFormEncoder.BoolEncoding,
+         dataEncoding: URLEncodedFormEncoder.DataEncoding,
+         dateEncoding: URLEncodedFormEncoder.DateEncoding) {
+        self.context = context
+        self.codingPath = codingPath
+        self.boolEncoding = boolEncoding
+        self.dataEncoding = dataEncoding
+        self.dateEncoding = dateEncoding
+    }
+}
+
+extension _URLEncodedFormEncoder: Encoder {
+    func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key: CodingKey {
+        let container = _URLEncodedFormEncoder.KeyedContainer<Key>(context: context,
+                                                                   codingPath: codingPath,
+                                                                   boolEncoding: boolEncoding,
+                                                                   dataEncoding: dataEncoding,
+                                                                   dateEncoding: dateEncoding)
+        return KeyedEncodingContainer(container)
+    }
+
+    func unkeyedContainer() -> UnkeyedEncodingContainer {
+        _URLEncodedFormEncoder.UnkeyedContainer(context: context,
+                                                codingPath: codingPath,
+                                                boolEncoding: boolEncoding,
+                                                dataEncoding: dataEncoding,
+                                                dateEncoding: dateEncoding)
+    }
+
+    func singleValueContainer() -> SingleValueEncodingContainer {
+        _URLEncodedFormEncoder.SingleValueContainer(context: context,
+                                                    codingPath: codingPath,
+                                                    boolEncoding: boolEncoding,
+                                                    dataEncoding: dataEncoding,
+                                                    dateEncoding: dateEncoding)
+    }
+}
+
+final class URLEncodedFormContext {
+    var component: URLEncodedFormComponent
+
+    init(_ component: URLEncodedFormComponent) {
+        self.component = component
+    }
+}
+
+enum URLEncodedFormComponent {
+    typealias Object = [(key: String, value: URLEncodedFormComponent)]
+
+    case string(String)
+    case array([URLEncodedFormComponent])
+    case object(Object)
+
+    /// Converts self to an `[URLEncodedFormData]` or returns `nil` if not convertible.
+    var array: [URLEncodedFormComponent]? {
+        switch self {
+        case let .array(array): return array
+        default: return nil
+        }
+    }
+
+    /// Converts self to an `Object` or returns `nil` if not convertible.
+    var object: Object? {
+        switch self {
+        case let .object(object): return object
+        default: return nil
+        }
+    }
+
+    /// Sets self to the supplied value at a given path.
+    ///
+    ///     data.set(to: "hello", at: ["path", "to", "value"])
+    ///
+    /// - parameters:
+    ///     - value: Value of `Self` to set at the supplied path.
+    ///     - path: `CodingKey` path to update with the supplied value.
+    public mutating func set(to value: URLEncodedFormComponent, at path: [CodingKey]) {
+        set(&self, to: value, at: path)
+    }
+
+    /// Recursive backing method to `set(to:at:)`.
+    private func set(_ context: inout URLEncodedFormComponent, to value: URLEncodedFormComponent, at path: [CodingKey]) {
+        guard !path.isEmpty else {
+            context = value
+            return
+        }
+
+        let end = path[0]
+        var child: URLEncodedFormComponent
+        switch path.count {
+        case 1:
+            child = value
+        case 2...:
+            if let index = end.intValue {
+                let array = context.array ?? []
+                if array.count > index {
+                    child = array[index]
+                } else {
+                    child = .array([])
+                }
+                set(&child, to: value, at: Array(path[1...]))
+            } else {
+                child = context.object?.first { $0.key == end.stringValue }?.value ?? .object(.init())
+                set(&child, to: value, at: Array(path[1...]))
+            }
+        default: fatalError("Unreachable")
+        }
+
+        if let index = end.intValue {
+            if var array = context.array {
+                if array.count > index {
+                    array[index] = child
+                } else {
+                    array.append(child)
+                }
+                context = .array(array)
+            } else {
+                context = .array([child])
+            }
+        } else {
+            if var object = context.object {
+                if let index = object.firstIndex(where: { $0.key == end.stringValue }) {
+                    object[index] = (key: end.stringValue, value: child)
+                } else {
+                    object.append((key: end.stringValue, value: child))
+                }
+                context = .object(object)
+            } else {
+                context = .object([(key: end.stringValue, value: child)])
+            }
+        }
+    }
+}
+
+struct AnyCodingKey: CodingKey, Hashable {
+    let stringValue: String
+    let intValue: Int?
+
+    init?(stringValue: String) {
+        self.stringValue = stringValue
+        intValue = nil
+    }
+
+    init?(intValue: Int) {
+        stringValue = "\(intValue)"
+        self.intValue = intValue
+    }
+
+    init<Key>(_ base: Key) where Key: CodingKey {
+        if let intValue = base.intValue {
+            self.init(intValue: intValue)!
+        } else {
+            self.init(stringValue: base.stringValue)!
+        }
+    }
+}
+
+extension _URLEncodedFormEncoder {
+    final class KeyedContainer<Key> where Key: CodingKey {
+        var codingPath: [CodingKey]
+
+        private let context: URLEncodedFormContext
+        private let boolEncoding: URLEncodedFormEncoder.BoolEncoding
+        private let dataEncoding: URLEncodedFormEncoder.DataEncoding
+        private let dateEncoding: URLEncodedFormEncoder.DateEncoding
+
+        init(context: URLEncodedFormContext,
+             codingPath: [CodingKey],
+             boolEncoding: URLEncodedFormEncoder.BoolEncoding,
+             dataEncoding: URLEncodedFormEncoder.DataEncoding,
+             dateEncoding: URLEncodedFormEncoder.DateEncoding) {
+            self.context = context
+            self.codingPath = codingPath
+            self.boolEncoding = boolEncoding
+            self.dataEncoding = dataEncoding
+            self.dateEncoding = dateEncoding
+        }
+
+        private func nestedCodingPath(for key: CodingKey) -> [CodingKey] {
+            codingPath + [key]
+        }
+    }
+}
+
+extension _URLEncodedFormEncoder.KeyedContainer: KeyedEncodingContainerProtocol {
+    func encodeNil(forKey key: Key) throws {
+        let context = EncodingError.Context(codingPath: codingPath,
+                                            debugDescription: "URLEncodedFormEncoder cannot encode nil values.")
+        throw EncodingError.invalidValue("\(key): nil", context)
+    }
+
+    func encode<T>(_ value: T, forKey key: Key) throws where T: Encodable {
+        var container = nestedSingleValueEncoder(for: key)
+        try container.encode(value)
+    }
+
+    func nestedSingleValueEncoder(for key: Key) -> SingleValueEncodingContainer {
+        let container = _URLEncodedFormEncoder.SingleValueContainer(context: context,
+                                                                    codingPath: nestedCodingPath(for: key),
+                                                                    boolEncoding: boolEncoding,
+                                                                    dataEncoding: dataEncoding,
+                                                                    dateEncoding: dateEncoding)
+
+        return container
+    }
+
+    func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {
+        let container = _URLEncodedFormEncoder.UnkeyedContainer(context: context,
+                                                                codingPath: nestedCodingPath(for: key),
+                                                                boolEncoding: boolEncoding,
+                                                                dataEncoding: dataEncoding,
+                                                                dateEncoding: dateEncoding)
+
+        return container
+    }
+
+    func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> where NestedKey: CodingKey {
+        let container = _URLEncodedFormEncoder.KeyedContainer<NestedKey>(context: context,
+                                                                         codingPath: nestedCodingPath(for: key),
+                                                                         boolEncoding: boolEncoding,
+                                                                         dataEncoding: dataEncoding,
+                                                                         dateEncoding: dateEncoding)
+
+        return KeyedEncodingContainer(container)
+    }
+
+    func superEncoder() -> Encoder {
+        _URLEncodedFormEncoder(context: context,
+                               codingPath: codingPath,
+                               boolEncoding: boolEncoding,
+                               dataEncoding: dataEncoding,
+                               dateEncoding: dateEncoding)
+    }
+
+    func superEncoder(forKey key: Key) -> Encoder {
+        _URLEncodedFormEncoder(context: context,
+                               codingPath: nestedCodingPath(for: key),
+                               boolEncoding: boolEncoding,
+                               dataEncoding: dataEncoding,
+                               dateEncoding: dateEncoding)
+    }
+}
+
+extension _URLEncodedFormEncoder {
+    final class SingleValueContainer {
+        var codingPath: [CodingKey]
+
+        private var canEncodeNewValue = true
+
+        private let context: URLEncodedFormContext
+        private let boolEncoding: URLEncodedFormEncoder.BoolEncoding
+        private let dataEncoding: URLEncodedFormEncoder.DataEncoding
+        private let dateEncoding: URLEncodedFormEncoder.DateEncoding
+
+        init(context: URLEncodedFormContext,
+             codingPath: [CodingKey],
+             boolEncoding: URLEncodedFormEncoder.BoolEncoding,
+             dataEncoding: URLEncodedFormEncoder.DataEncoding,
+             dateEncoding: URLEncodedFormEncoder.DateEncoding) {
+            self.context = context
+            self.codingPath = codingPath
+            self.boolEncoding = boolEncoding
+            self.dataEncoding = dataEncoding
+            self.dateEncoding = dateEncoding
+        }
+
+        private func checkCanEncode(value: Any?) throws {
+            guard canEncodeNewValue else {
+                let context = EncodingError.Context(codingPath: codingPath,
+                                                    debugDescription: "Attempt to encode value through single value container when previously value already encoded.")
+                throw EncodingError.invalidValue(value as Any, context)
+            }
+        }
+    }
+}
+
+extension _URLEncodedFormEncoder.SingleValueContainer: SingleValueEncodingContainer {
+    func encodeNil() throws {
+        try checkCanEncode(value: nil)
+        defer { canEncodeNewValue = false }
+
+        let context = EncodingError.Context(codingPath: codingPath,
+                                            debugDescription: "URLEncodedFormEncoder cannot encode nil values.")
+        throw EncodingError.invalidValue("nil", context)
+    }
+
+    func encode(_ value: Bool) throws {
+        try encode(value, as: String(boolEncoding.encode(value)))
+    }
+
+    func encode(_ value: String) throws {
+        try encode(value, as: value)
+    }
+
+    func encode(_ value: Double) throws {
+        try encode(value, as: String(value))
+    }
+
+    func encode(_ value: Float) throws {
+        try encode(value, as: String(value))
+    }
+
+    func encode(_ value: Int) throws {
+        try encode(value, as: String(value))
+    }
+
+    func encode(_ value: Int8) throws {
+        try encode(value, as: String(value))
+    }
+
+    func encode(_ value: Int16) throws {
+        try encode(value, as: String(value))
+    }
+
+    func encode(_ value: Int32) throws {
+        try encode(value, as: String(value))
+    }
+
+    func encode(_ value: Int64) throws {
+        try encode(value, as: String(value))
+    }
+
+    func encode(_ value: UInt) throws {
+        try encode(value, as: String(value))
+    }
+
+    func encode(_ value: UInt8) throws {
+        try encode(value, as: String(value))
+    }
+
+    func encode(_ value: UInt16) throws {
+        try encode(value, as: String(value))
+    }
+
+    func encode(_ value: UInt32) throws {
+        try encode(value, as: String(value))
+    }
+
+    func encode(_ value: UInt64) throws {
+        try encode(value, as: String(value))
+    }
+
+    private func encode<T>(_ value: T, as string: String) throws where T: Encodable {
+        try checkCanEncode(value: value)
+        defer { canEncodeNewValue = false }
+
+        context.component.set(to: .string(string), at: codingPath)
+    }
+
+    func encode<T>(_ value: T) throws where T: Encodable {
+        switch value {
+        case let date as Date:
+            guard let string = try dateEncoding.encode(date) else {
+                try attemptToEncode(value)
+                return
+            }
+
+            try encode(value, as: string)
+        case let data as Data:
+            guard let string = try dataEncoding.encode(data) else {
+                try attemptToEncode(value)
+                return
+            }
+
+            try encode(value, as: string)
+        case let decimal as Decimal:
+            // Decimal's `Encodable` implementation returns an object, not a single value, so override it.
+            try encode(value, as: String(describing: decimal))
+        default:
+            try attemptToEncode(value)
+        }
+    }
+
+    private func attemptToEncode<T>(_ value: T) throws where T: Encodable {
+        try checkCanEncode(value: value)
+        defer { canEncodeNewValue = false }
+
+        let encoder = _URLEncodedFormEncoder(context: context,
+                                             codingPath: codingPath,
+                                             boolEncoding: boolEncoding,
+                                             dataEncoding: dataEncoding,
+                                             dateEncoding: dateEncoding)
+        try value.encode(to: encoder)
+    }
+}
+
+extension _URLEncodedFormEncoder {
+    final class UnkeyedContainer {
+        var codingPath: [CodingKey]
+
+        var count = 0
+        var nestedCodingPath: [CodingKey] {
+            codingPath + [AnyCodingKey(intValue: count)!]
+        }
+
+        private let context: URLEncodedFormContext
+        private let boolEncoding: URLEncodedFormEncoder.BoolEncoding
+        private let dataEncoding: URLEncodedFormEncoder.DataEncoding
+        private let dateEncoding: URLEncodedFormEncoder.DateEncoding
+
+        init(context: URLEncodedFormContext,
+             codingPath: [CodingKey],
+             boolEncoding: URLEncodedFormEncoder.BoolEncoding,
+             dataEncoding: URLEncodedFormEncoder.DataEncoding,
+             dateEncoding: URLEncodedFormEncoder.DateEncoding) {
+            self.context = context
+            self.codingPath = codingPath
+            self.boolEncoding = boolEncoding
+            self.dataEncoding = dataEncoding
+            self.dateEncoding = dateEncoding
+        }
+    }
+}
+
+extension _URLEncodedFormEncoder.UnkeyedContainer: UnkeyedEncodingContainer {
+    func encodeNil() throws {
+        let context = EncodingError.Context(codingPath: codingPath,
+                                            debugDescription: "URLEncodedFormEncoder cannot encode nil values.")
+        throw EncodingError.invalidValue("nil", context)
+    }
+
+    func encode<T>(_ value: T) throws where T: Encodable {
+        var container = nestedSingleValueContainer()
+        try container.encode(value)
+    }
+
+    func nestedSingleValueContainer() -> SingleValueEncodingContainer {
+        defer { count += 1 }
+
+        return _URLEncodedFormEncoder.SingleValueContainer(context: context,
+                                                           codingPath: nestedCodingPath,
+                                                           boolEncoding: boolEncoding,
+                                                           dataEncoding: dataEncoding,
+                                                           dateEncoding: dateEncoding)
+    }
+
+    func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> where NestedKey: CodingKey {
+        defer { count += 1 }
+        let container = _URLEncodedFormEncoder.KeyedContainer<NestedKey>(context: context,
+                                                                         codingPath: nestedCodingPath,
+                                                                         boolEncoding: boolEncoding,
+                                                                         dataEncoding: dataEncoding,
+                                                                         dateEncoding: dateEncoding)
+
+        return KeyedEncodingContainer(container)
+    }
+
+    func nestedUnkeyedContainer() -> UnkeyedEncodingContainer {
+        defer { count += 1 }
+
+        return _URLEncodedFormEncoder.UnkeyedContainer(context: context,
+                                                       codingPath: nestedCodingPath,
+                                                       boolEncoding: boolEncoding,
+                                                       dataEncoding: dataEncoding,
+                                                       dateEncoding: dateEncoding)
+    }
+
+    func superEncoder() -> Encoder {
+        defer { count += 1 }
+
+        return _URLEncodedFormEncoder(context: context,
+                                      codingPath: codingPath,
+                                      boolEncoding: boolEncoding,
+                                      dataEncoding: dataEncoding,
+                                      dateEncoding: dateEncoding)
+    }
+}
+
+final class URLEncodedFormSerializer {
+    private let alphabetizeKeyValuePairs: Bool
+    private let arrayEncoding: URLEncodedFormEncoder.ArrayEncoding
+    private let keyEncoding: URLEncodedFormEncoder.KeyEncoding
+    private let spaceEncoding: URLEncodedFormEncoder.SpaceEncoding
+    private let allowedCharacters: CharacterSet
+
+    init(alphabetizeKeyValuePairs: Bool,
+         arrayEncoding: URLEncodedFormEncoder.ArrayEncoding,
+         keyEncoding: URLEncodedFormEncoder.KeyEncoding,
+         spaceEncoding: URLEncodedFormEncoder.SpaceEncoding,
+         allowedCharacters: CharacterSet) {
+        self.alphabetizeKeyValuePairs = alphabetizeKeyValuePairs
+        self.arrayEncoding = arrayEncoding
+        self.keyEncoding = keyEncoding
+        self.spaceEncoding = spaceEncoding
+        self.allowedCharacters = allowedCharacters
+    }
+
+    func serialize(_ object: URLEncodedFormComponent.Object) -> String {
+        var output: [String] = []
+        for (key, component) in object {
+            let value = serialize(component, forKey: key)
+            output.append(value)
+        }
+        output = alphabetizeKeyValuePairs ? output.sorted() : output
+
+        return output.joinedWithAmpersands()
+    }
+
+    func serialize(_ component: URLEncodedFormComponent, forKey key: String) -> String {
+        switch component {
+        case let .string(string): return "\(escape(keyEncoding.encode(key)))=\(escape(string))"
+        case let .array(array): return serialize(array, forKey: key)
+        case let .object(object): return serialize(object, forKey: key)
+        }
+    }
+
+    func serialize(_ object: URLEncodedFormComponent.Object, forKey key: String) -> String {
+        var segments: [String] = object.map { subKey, value in
+            let keyPath = "[\(subKey)]"
+            return serialize(value, forKey: key + keyPath)
+        }
+        segments = alphabetizeKeyValuePairs ? segments.sorted() : segments
+
+        return segments.joinedWithAmpersands()
+    }
+
+    func serialize(_ array: [URLEncodedFormComponent], forKey key: String) -> String {
+        var segments: [String] = array.enumerated().map { index, component in
+            let keyPath = arrayEncoding.encode(key, atIndex: index)
+            return serialize(component, forKey: keyPath)
+        }
+        segments = alphabetizeKeyValuePairs ? segments.sorted() : segments
+
+        return segments.joinedWithAmpersands()
+    }
+
+    func escape(_ query: String) -> String {
+        var allowedCharactersWithSpace = allowedCharacters
+        allowedCharactersWithSpace.insert(charactersIn: " ")
+        let escapedQuery = query.addingPercentEncoding(withAllowedCharacters: allowedCharactersWithSpace) ?? query
+        let spaceEncodedQuery = spaceEncoding.encode(escapedQuery)
+
+        return spaceEncodedQuery
+    }
+}
+
+extension Array where Element == String {
+    func joinedWithAmpersands() -> String {
+        joined(separator: "&")
+    }
+}
+
+extension CharacterSet {
+    /// Creates a CharacterSet from RFC 3986 allowed characters.
+    ///
+    /// 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.
+    public static let afURLQueryAllowed: CharacterSet = {
+        let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
+        let subDelimitersToEncode = "!$&'()*+,;="
+        let encodableDelimiters = CharacterSet(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
+
+        return CharacterSet.urlQueryAllowed.subtracting(encodableDelimiters)
+    }()
+}

+ 39 - 0
Pods/Alamofire/Source/URLRequest+Alamofire.swift

@@ -0,0 +1,39 @@
+//
+//  URLRequest+Alamofire.swift
+//
+//  Copyright (c) 2019 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
+
+extension URLRequest {
+    /// Returns the `httpMethod` as Alamofire's `HTTPMethod` type.
+    public var method: HTTPMethod? {
+        get { httpMethod.flatMap(HTTPMethod.init) }
+        set { httpMethod = newValue?.rawValue }
+    }
+
+    public func validate() throws {
+        if method == .get, let bodyData = httpBody {
+            throw AFError.urlRequestValidationFailed(reason: .bodyDataInGETRequest(bodyData))
+        }
+    }
+}

+ 46 - 0
Pods/Alamofire/Source/URLSessionConfiguration+Alamofire.swift

@@ -0,0 +1,46 @@
+//
+//  URLSessionConfiguration+Alamofire.swift
+//
+//  Copyright (c) 2014-2018 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
+
+extension URLSessionConfiguration: AlamofireExtended {}
+extension AlamofireExtension where ExtendedType: URLSessionConfiguration {
+    /// Alamofire's default configuration. Same as `URLSessionConfiguration.default` but adds Alamofire default
+    /// `Accept-Language`, `Accept-Encoding`, and `User-Agent` headers.
+    public static var `default`: URLSessionConfiguration {
+        let configuration = URLSessionConfiguration.default
+        configuration.headers = .default
+
+        return configuration
+    }
+
+    /// `.ephemeral` configuration with Alamofire's default `Accept-Language`, `Accept-Encoding`, and `User-Agent`
+    /// headers.
+    public static var ephemeral: URLSessionConfiguration {
+        let configuration = URLSessionConfiguration.ephemeral
+        configuration.headers = .default
+
+        return configuration
+    }
+}

+ 302 - 0
Pods/Alamofire/Source/Validation.swift

@@ -0,0 +1,302 @@
+//
+//  Validation.swift
+//
+//  Copyright (c) 2014-2018 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
+
+extension Request {
+    // MARK: Helper Types
+
+    fileprivate typealias ErrorReason = AFError.ResponseValidationFailureReason
+
+    /// Used to represent whether a validation succeeded or failed.
+    public typealias ValidationResult = Result<Void, Error>
+
+    fileprivate struct MIMEType {
+        let type: String
+        let subtype: String
+
+        var isWildcard: Bool { type == "*" && subtype == "*" }
+
+        init?(_ string: String) {
+            let components: [String] = {
+                let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines)
+                let split = stripped[..<(stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)]
+
+                return split.components(separatedBy: "/")
+            }()
+
+            if let type = components.first, let subtype = components.last {
+                self.type = type
+                self.subtype = subtype
+            } else {
+                return nil
+            }
+        }
+
+        func matches(_ mime: MIMEType) -> Bool {
+            switch (type, subtype) {
+            case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"):
+                return true
+            default:
+                return false
+            }
+        }
+    }
+
+    // MARK: Properties
+
+    fileprivate var acceptableStatusCodes: Range<Int> { 200..<300 }
+
+    fileprivate var acceptableContentTypes: [String] {
+        if let accept = request?.value(forHTTPHeaderField: "Accept") {
+            return accept.components(separatedBy: ",")
+        }
+
+        return ["*/*"]
+    }
+
+    // MARK: Status Code
+
+    fileprivate func validate<S: Sequence>(statusCode acceptableStatusCodes: S,
+                                           response: HTTPURLResponse)
+        -> ValidationResult
+        where S.Iterator.Element == Int {
+        if acceptableStatusCodes.contains(response.statusCode) {
+            return .success(())
+        } else {
+            let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode)
+            return .failure(AFError.responseValidationFailed(reason: reason))
+        }
+    }
+
+    // MARK: Content Type
+
+    fileprivate func validate<S: Sequence>(contentType acceptableContentTypes: S,
+                                           response: HTTPURLResponse,
+                                           data: Data?)
+        -> ValidationResult
+        where S.Iterator.Element == String {
+        guard let data = data, !data.isEmpty else { return .success(()) }
+
+        return validate(contentType: acceptableContentTypes, response: response)
+    }
+
+    fileprivate func validate<S: Sequence>(contentType acceptableContentTypes: S,
+                                           response: HTTPURLResponse)
+        -> ValidationResult
+        where S.Iterator.Element == String {
+        guard
+            let responseContentType = response.mimeType,
+            let responseMIMEType = MIMEType(responseContentType)
+        else {
+            for contentType in acceptableContentTypes {
+                if let mimeType = MIMEType(contentType), mimeType.isWildcard {
+                    return .success(())
+                }
+            }
+
+            let error: AFError = {
+                let reason: ErrorReason = .missingContentType(acceptableContentTypes: acceptableContentTypes.sorted())
+                return AFError.responseValidationFailed(reason: reason)
+            }()
+
+            return .failure(error)
+        }
+
+        for contentType in acceptableContentTypes {
+            if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) {
+                return .success(())
+            }
+        }
+
+        let error: AFError = {
+            let reason: ErrorReason = .unacceptableContentType(acceptableContentTypes: acceptableContentTypes.sorted(),
+                                                               responseContentType: responseContentType)
+
+            return AFError.responseValidationFailed(reason: reason)
+        }()
+
+        return .failure(error)
+    }
+}
+
+// MARK: -
+
+extension DataRequest {
+    /// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the
+    /// request was valid.
+    public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult
+
+    /// Validates that the response has a status code in the specified sequence.
+    ///
+    /// If validation fails, subsequent calls to response handlers will have an associated error.
+    ///
+    /// - Parameter acceptableStatusCodes: `Sequence` of acceptable response status codes.
+    ///
+    /// - Returns:                         The instance.
+    @discardableResult
+    public func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int {
+        validate { [unowned self] _, response, _ in
+            self.validate(statusCode: acceptableStatusCodes, response: response)
+        }
+    }
+
+    /// Validates that the response has a content type in the specified sequence.
+    ///
+    /// If validation fails, subsequent calls to response handlers will have an associated error.
+    ///
+    /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
+    ///
+    /// - returns: The request.
+    @discardableResult
+    public func validate<S: Sequence>(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String {
+        validate { [unowned self] _, response, data in
+            self.validate(contentType: acceptableContentTypes(), response: response, data: data)
+        }
+    }
+
+    /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content
+    /// type matches any specified in the Accept HTTP header field.
+    ///
+    /// If validation fails, subsequent calls to response handlers will have an associated error.
+    ///
+    /// - returns: The request.
+    @discardableResult
+    public func validate() -> Self {
+        let contentTypes: () -> [String] = { [unowned self] in
+            self.acceptableContentTypes
+        }
+        return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes())
+    }
+}
+
+extension DataStreamRequest {
+    /// A closure used to validate a request that takes a `URLRequest` and `HTTPURLResponse` and returns whether the
+    /// request was valid.
+    public typealias Validation = (_ request: URLRequest?, _ response: HTTPURLResponse) -> ValidationResult
+
+    /// Validates that the response has a status code in the specified sequence.
+    ///
+    /// If validation fails, subsequent calls to response handlers will have an associated error.
+    ///
+    /// - Parameter acceptableStatusCodes: `Sequence` of acceptable response status codes.
+    ///
+    /// - Returns:                         The instance.
+    @discardableResult
+    public func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int {
+        validate { [unowned self] _, response in
+            self.validate(statusCode: acceptableStatusCodes, response: response)
+        }
+    }
+
+    /// Validates that the response has a content type in the specified sequence.
+    ///
+    /// If validation fails, subsequent calls to response handlers will have an associated error.
+    ///
+    /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
+    ///
+    /// - returns: The request.
+    @discardableResult
+    public func validate<S: Sequence>(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String {
+        validate { [unowned self] _, response in
+            self.validate(contentType: acceptableContentTypes(), response: response)
+        }
+    }
+
+    /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content
+    /// type matches any specified in the Accept HTTP header field.
+    ///
+    /// If validation fails, subsequent calls to response handlers will have an associated error.
+    ///
+    /// - Returns: The instance.
+    @discardableResult
+    public func validate() -> Self {
+        let contentTypes: () -> [String] = { [unowned self] in
+            self.acceptableContentTypes
+        }
+        return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes())
+    }
+}
+
+// MARK: -
+
+extension DownloadRequest {
+    /// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a
+    /// destination URL, and returns whether the request was valid.
+    public typealias Validation = (_ request: URLRequest?,
+                                   _ response: HTTPURLResponse,
+                                   _ fileURL: URL?)
+        -> ValidationResult
+
+    /// Validates that the response has a status code in the specified sequence.
+    ///
+    /// If validation fails, subsequent calls to response handlers will have an associated error.
+    ///
+    /// - Parameter acceptableStatusCodes: `Sequence` of acceptable response status codes.
+    ///
+    /// - Returns:                         The instance.
+    @discardableResult
+    public func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int {
+        validate { [unowned self] _, response, _ in
+            self.validate(statusCode: acceptableStatusCodes, response: response)
+        }
+    }
+
+    /// Validates that the response has a content type in the specified sequence.
+    ///
+    /// If validation fails, subsequent calls to response handlers will have an associated error.
+    ///
+    /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
+    ///
+    /// - returns: The request.
+    @discardableResult
+    public func validate<S: Sequence>(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String {
+        validate { [unowned self] _, response, fileURL in
+            guard let validFileURL = fileURL else {
+                return .failure(AFError.responseValidationFailed(reason: .dataFileNil))
+            }
+
+            do {
+                let data = try Data(contentsOf: validFileURL)
+                return self.validate(contentType: acceptableContentTypes(), response: response, data: data)
+            } catch {
+                return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL)))
+            }
+        }
+    }
+
+    /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content
+    /// type matches any specified in the Accept HTTP header field.
+    ///
+    /// If validation fails, subsequent calls to response handlers will have an associated error.
+    ///
+    /// - returns: The request.
+    @discardableResult
+    public func validate() -> Self {
+        let contentTypes = { [unowned self] in
+            self.acceptableContentTypes
+        }
+        return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes())
+    }
+}

+ 57 - 0
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/Categories/IQNSArray+Sort.swift

@@ -0,0 +1,57 @@
+//
+//  IQNSArray+Sort.swift
+// https://github.com/hackiftekhar/IQKeyboardManager
+// Copyright (c) 2013-20 Iftekhar Qurashi.
+//
+// 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 - UIKit contains Foundation
+import UIKit
+
+/**
+UIView.subviews sorting category.
+*/
+@available(iOSApplicationExtension, unavailable)
+internal extension Array where Element: UIView {
+
+    /**
+    Returns the array by sorting the UIView's by their tag property.
+    */
+    func sortedArrayByTag() -> [Element] {
+
+        return sorted(by: { (obj1: Element, obj2: Element) -> Bool in
+
+            return (obj1.tag < obj2.tag)
+        })
+    }
+
+    /**
+    Returns the array by sorting the UIView's by their tag property.
+    */
+    func sortedArrayByPosition() -> [Element] {
+
+        return sorted(by: { (obj1: Element, obj2: Element) -> Bool in
+            if obj1.frame.minY != obj2.frame.minY {
+                return obj1.frame.minY < obj2.frame.minY
+            } else {
+                return obj1.frame.minX < obj2.frame.minX
+            }
+        })
+    }
+}

+ 117 - 0
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/Categories/IQUIScrollView+Additions.swift

@@ -0,0 +1,117 @@
+//
+//  IQUIScrollView+Additions.swift
+// https://github.com/hackiftekhar/IQKeyboardManager
+// Copyright (c) 2013-20 Iftekhar Qurashi.
+//
+// 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 - UIKit contains Foundation
+import UIKit
+
+@available(iOSApplicationExtension, unavailable)
+@objc public extension UIScrollView {
+
+    private struct AssociatedKeys {
+        static var shouldIgnoreScrollingAdjustment = "shouldIgnoreScrollingAdjustment"
+        static var shouldIgnoreContentInsetAdjustment = "shouldIgnoreContentInsetAdjustment"
+        static var shouldRestoreScrollViewContentOffset = "shouldRestoreScrollViewContentOffset"
+    }
+
+    /**
+     If YES, then scrollview will ignore scrolling (simply not scroll it) for adjusting textfield position. Default is NO.
+     */
+    var shouldIgnoreScrollingAdjustment: Bool {
+        get {
+            return objc_getAssociatedObject(self, &AssociatedKeys.shouldIgnoreScrollingAdjustment) as? Bool ?? false
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.shouldIgnoreScrollingAdjustment, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+        }
+    }
+
+    /**
+     If YES, then scrollview will ignore content inset adjustment (simply not updating it) when keyboard is shown. Default is NO.
+     */
+    var shouldIgnoreContentInsetAdjustment: Bool {
+        get {
+            return objc_getAssociatedObject(self, &AssociatedKeys.shouldIgnoreContentInsetAdjustment) as? Bool ?? false
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.shouldIgnoreContentInsetAdjustment, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+        }
+    }
+
+    /**
+     To set customized distance from keyboard for textField/textView. Can't be less than zero
+     */
+    var shouldRestoreScrollViewContentOffset: Bool {
+        get {
+            return objc_getAssociatedObject(self, &AssociatedKeys.shouldRestoreScrollViewContentOffset) as? Bool ?? false
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.shouldRestoreScrollViewContentOffset, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+        }
+    }
+}
+
+@available(iOSApplicationExtension, unavailable)
+internal extension UITableView {
+
+    func previousIndexPath(of indexPath: IndexPath) -> IndexPath? {
+        var previousRow = indexPath.row - 1
+        var previousSection = indexPath.section
+
+        //Fixing indexPath
+        if previousRow < 0 {
+            previousSection -= 1
+            if previousSection >= 0 {
+                previousRow = self.numberOfRows(inSection: previousSection) - 1
+            }
+        }
+
+        if previousRow >= 0, previousSection >= 0 {
+            return IndexPath(row: previousRow, section: previousSection)
+        } else {
+            return nil
+        }
+    }
+}
+
+@available(iOSApplicationExtension, unavailable)
+internal extension UICollectionView {
+
+    func previousIndexPath(of indexPath: IndexPath) -> IndexPath? {
+        var previousRow = indexPath.row - 1
+        var previousSection = indexPath.section
+
+        //Fixing indexPath
+        if previousRow < 0 {
+            previousSection -= 1
+            if previousSection >= 0 {
+                previousRow = self.numberOfItems(inSection: previousSection) - 1
+            }
+        }
+
+        if previousRow >= 0, previousSection >= 0 {
+            return IndexPath(item: previousRow, section: previousSection)
+        } else {
+            return nil
+        }
+    }
+}

+ 93 - 0
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/Categories/IQUITextFieldView+Additions.swift

@@ -0,0 +1,93 @@
+//
+//  IQUITextFieldView+Additions.swift
+// https://github.com/hackiftekhar/IQKeyboardManager
+// Copyright (c) 2013-20 Iftekhar Qurashi.
+//
+// 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 - UIKit contains Foundation
+import UIKit
+
+/**
+Uses default keyboard distance for textField.
+*/
+@available(iOSApplicationExtension, unavailable)
+public let kIQUseDefaultKeyboardDistance = CGFloat.greatestFiniteMagnitude
+
+/**
+UIView category for managing UITextField/UITextView
+*/
+@available(iOSApplicationExtension, unavailable)
+@objc public extension UIView {
+
+    private struct AssociatedKeys {
+        static var keyboardDistanceFromTextField = "keyboardDistanceFromTextField"
+        static var ignoreSwitchingByNextPrevious = "ignoreSwitchingByNextPrevious"
+        static var enableMode = "enableMode"
+        static var shouldResignOnTouchOutsideMode = "shouldResignOnTouchOutsideMode"
+    }
+
+    /**
+     To set customized distance from keyboard for textField/textView. Can't be less than zero
+     */
+    var keyboardDistanceFromTextField: CGFloat {
+        get {
+            return objc_getAssociatedObject(self, &AssociatedKeys.keyboardDistanceFromTextField) as? CGFloat ?? kIQUseDefaultKeyboardDistance
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.keyboardDistanceFromTextField, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+        }
+    }
+
+    /**
+     If shouldIgnoreSwitchingByNextPrevious is true then library will ignore this textField/textView while moving to other textField/textView using keyboard toolbar next previous buttons. Default is false
+     */
+    var ignoreSwitchingByNextPrevious: Bool {
+        get {
+            return objc_getAssociatedObject(self, &AssociatedKeys.ignoreSwitchingByNextPrevious) as? Bool ?? false
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.ignoreSwitchingByNextPrevious, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+        }
+    }
+
+    /**
+     Override Enable/disable managing distance between keyboard and textField behaviour for this particular textField.
+     */
+    var enableMode: IQEnableMode {
+        get {
+            return objc_getAssociatedObject(self, &AssociatedKeys.enableMode) as? IQEnableMode ?? .default
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.enableMode, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+        }
+    }
+
+    /**
+     Override resigns Keyboard on touching outside of UITextField/View behaviour for this particular textField.
+     */
+    var shouldResignOnTouchOutsideMode: IQEnableMode {
+        get {
+            return objc_getAssociatedObject(self, &AssociatedKeys.shouldResignOnTouchOutsideMode) as? IQEnableMode ?? .default
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.shouldResignOnTouchOutsideMode, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+        }
+    }
+}

+ 324 - 0
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/Categories/IQUIView+Hierarchy.swift

@@ -0,0 +1,324 @@
+//
+//  IQUIView+Hierarchy.swift
+// https://github.com/hackiftekhar/IQKeyboardManager
+// Copyright (c) 2013-20 Iftekhar Qurashi.
+//
+// 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
+
+/**
+UIView hierarchy category.
+*/
+@available(iOSApplicationExtension, unavailable)
+@objc public extension UIView {
+
+    // MARK: viewControllers
+
+    /**
+    Returns the UIViewController object that manages the receiver.
+    */
+    func viewContainingController() -> UIViewController? {
+
+        var nextResponder: UIResponder? = self
+
+        repeat {
+            nextResponder = nextResponder?.next
+
+            if let viewController = nextResponder as? UIViewController {
+                return viewController
+            }
+
+        } while nextResponder != nil
+
+        return nil
+    }
+
+    /**
+    Returns the topMost UIViewController object in hierarchy.
+    */
+    func topMostController() -> UIViewController? {
+
+        var controllersHierarchy = [UIViewController]()
+
+        if var topController = window?.rootViewController {
+            controllersHierarchy.append(topController)
+
+            while let presented = topController.presentedViewController {
+
+                topController = presented
+
+                controllersHierarchy.append(presented)
+            }
+
+            var matchController: UIResponder? = viewContainingController()
+
+            while let mController = matchController as? UIViewController, controllersHierarchy.contains(mController) == false {
+
+                repeat {
+                    matchController = matchController?.next
+
+                } while matchController != nil && matchController is UIViewController == false
+            }
+
+            return matchController as? UIViewController
+
+        } else {
+            return viewContainingController()
+        }
+    }
+
+    /**
+     Returns the UIViewController object that is actually the parent of this object. Most of the time it's the viewController object which actually contains it, but result may be different if it's viewController is added as childViewController of another viewController.
+     */
+    func parentContainerViewController() -> UIViewController? {
+
+        var matchController = viewContainingController()
+        var parentContainerViewController: UIViewController?
+
+        if var navController = matchController?.navigationController {
+
+            while let parentNav = navController.navigationController {
+                navController = parentNav
+            }
+
+            var parentController: UIViewController = navController
+
+            while let parent = parentController.parent,
+                (parent.isKind(of: UINavigationController.self) == false &&
+                    parent.isKind(of: UITabBarController.self) == false &&
+                    parent.isKind(of: UISplitViewController.self) == false) {
+
+                        parentController = parent
+            }
+
+            if navController == parentController {
+                parentContainerViewController = navController.topViewController
+            } else {
+                parentContainerViewController = parentController
+            }
+        } else if let tabController = matchController?.tabBarController {
+
+            if let navController = tabController.selectedViewController as? UINavigationController {
+                parentContainerViewController = navController.topViewController
+            } else {
+                parentContainerViewController = tabController.selectedViewController
+            }
+        } else {
+            while let parentController = matchController?.parent,
+                (parentController.isKind(of: UINavigationController.self) == false &&
+                    parentController.isKind(of: UITabBarController.self) == false &&
+                    parentController.isKind(of: UISplitViewController.self) == false) {
+
+                        matchController = parentController
+            }
+
+            parentContainerViewController = matchController
+        }
+
+        let finalController = parentContainerViewController?.parentIQContainerViewController() ?? parentContainerViewController
+
+        return finalController
+
+    }
+
+    // MARK: Superviews/Subviews/Siglings
+
+    /**
+    Returns the superView of provided class type.
+
+     
+     @param classType class type of the object which is to be search in above hierarchy and return
+     
+     @param belowView view object in upper hierarchy where method should stop searching and return nil
+*/
+    func superviewOfClassType(_ classType: UIView.Type, belowView: UIView? = nil) -> UIView? {
+
+        var superView = superview
+
+        while let unwrappedSuperView = superView {
+
+            if unwrappedSuperView.isKind(of: classType) {
+
+                //If it's UIScrollView, then validating for special cases
+                if unwrappedSuperView.isKind(of: UIScrollView.self) {
+
+                    let classNameString: String = "\(type(of: unwrappedSuperView.self))"
+
+                    //  If it's not UITableViewWrapperView class, this is internal class which is actually manage in UITableview. The speciality of this class is that it's superview is UITableView.
+                    //  If it's not UITableViewCellScrollView class, this is internal class which is actually manage in UITableviewCell. The speciality of this class is that it's superview is UITableViewCell.
+                    //If it's not _UIQueuingScrollView class, actually we validate for _ prefix which usually used by Apple internal classes
+                    if unwrappedSuperView.superview?.isKind(of: UITableView.self) == false,
+                        unwrappedSuperView.superview?.isKind(of: UITableViewCell.self) == false,
+                        classNameString.hasPrefix("_") == false {
+                        return superView
+                    }
+                } else {
+                    return superView
+                }
+            } else if unwrappedSuperView == belowView {
+                return nil
+            }
+
+            superView = unwrappedSuperView.superview
+        }
+
+        return nil
+    }
+
+    /**
+    Returns all siblings of the receiver which canBecomeFirstResponder.
+    */
+    internal func responderSiblings() -> [UIView] {
+
+        //Array of (UITextField/UITextView's).
+        var tempTextFields = [UIView]()
+
+        //	Getting all siblings
+        if let siblings = superview?.subviews {
+            for textField in siblings {
+                if (textField == self || textField.ignoreSwitchingByNextPrevious == false), textField.IQcanBecomeFirstResponder() {
+                    tempTextFields.append(textField)
+                }
+            }
+        }
+
+        return tempTextFields
+    }
+
+    /**
+    Returns all deep subViews of the receiver which canBecomeFirstResponder.
+    */
+    internal func deepResponderViews() -> [UIView] {
+
+        //Array of (UITextField/UITextView's).
+        var textfields = [UIView]()
+
+        for textField in subviews {
+
+            if (textField == self || textField.ignoreSwitchingByNextPrevious == false), textField.IQcanBecomeFirstResponder() {
+                textfields.append(textField)
+            }
+            //Sometimes there are hidden or disabled views and textField inside them still recorded, so we added some more validations here (Bug ID: #458)
+            //Uncommented else (Bug ID: #625)
+            else if textField.subviews.count != 0, isUserInteractionEnabled, !isHidden, alpha != 0.0 {
+                for deepView in textField.deepResponderViews() {
+                    textfields.append(deepView)
+                }
+            }
+        }
+
+        //subviews are returning in opposite order. Sorting according the frames 'y'.
+        return textfields.sorted(by: { (view1: UIView, view2: UIView) -> Bool in
+
+            let frame1 = view1.convert(view1.bounds, to: self)
+            let frame2 = view2.convert(view2.bounds, to: self)
+
+            if frame1.minY != frame2.minY {
+                return frame1.minY < frame2.minY
+            } else {
+                return frame1.minX < frame2.minX
+            }
+        })
+    }
+
+    private func IQcanBecomeFirstResponder() -> Bool {
+
+        var IQcanBecomeFirstResponder = false
+
+        if self.conforms(to: UITextInput.self) {
+            //  Setting toolbar to keyboard.
+            if let textView = self as? UITextView {
+                IQcanBecomeFirstResponder = textView.isEditable
+            } else if let textField = self as? UITextField {
+                IQcanBecomeFirstResponder = textField.isEnabled
+            }
+        }
+
+        if IQcanBecomeFirstResponder {
+            IQcanBecomeFirstResponder = isUserInteractionEnabled && !isHidden && alpha != 0.0 && !isAlertViewTextField() && textFieldSearchBar() == nil
+        }
+
+        return IQcanBecomeFirstResponder
+    }
+
+    // MARK: Special TextFields
+
+    /**
+     Returns searchBar if receiver object is UISearchBarTextField, otherwise return nil.
+    */
+    internal func textFieldSearchBar() -> UISearchBar? {
+
+        var responder: UIResponder? = self.next
+
+        while let bar = responder {
+
+            if let searchBar = bar as? UISearchBar {
+                return searchBar
+            } else if bar is UIViewController {
+                break
+            }
+
+            responder = bar.next
+        }
+
+        return nil
+    }
+
+    /**
+    Returns YES if the receiver object is UIAlertSheetTextField, otherwise return NO.
+    */
+    internal func isAlertViewTextField() -> Bool {
+
+        var alertViewController: UIResponder? = viewContainingController()
+
+        var isAlertViewTextField = false
+
+        while let controller = alertViewController, !isAlertViewTextField {
+
+            if controller.isKind(of: UIAlertController.self) {
+                isAlertViewTextField = true
+                break
+            }
+
+            alertViewController = controller.next
+        }
+
+        return isAlertViewTextField
+    }
+
+    private func depth() -> Int {
+        var depth: Int = 0
+
+        if let superView = superview {
+            depth = superView.depth()+1
+        }
+
+        return depth
+    }
+
+}
+
+@available(iOSApplicationExtension, unavailable)
+extension NSObject {
+
+    internal func _IQDescription() -> String {
+        return "<\(self) \(Unmanaged.passUnretained(self).toOpaque())>"
+    }
+}

+ 54 - 0
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/Categories/IQUIViewController+Additions.swift

@@ -0,0 +1,54 @@
+//
+//  IQUIViewController+Additions.swift
+// https://github.com/hackiftekhar/IQKeyboardManager
+// Copyright (c) 2013-20 Iftekhar Qurashi.
+//
+// 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
+
+@available(iOSApplicationExtension, unavailable)
+@objc extension UIViewController {
+
+    private struct AssociatedKeys {
+        static var IQLayoutGuideConstraint = "IQLayoutGuideConstraint"
+    }
+
+    /**
+     This method is provided to override by viewController's if the library lifts a viewController which you doesn't want to lift . This may happen if you have implemented side menu feature in your app and the library try to lift the side menu controller. Overriding this method in side menu class to return correct controller should fix the problem.
+    */
+    open func parentIQContainerViewController() -> UIViewController? {
+        return self
+    }
+
+    /**
+    To set customized distance from keyboard for textField/textView. Can't be less than zero
+     
+     @deprecated    Due to change in core-logic of handling distance between textField and keyboard distance, this layout contraint tweak is no longer needed and things will just work out of the box regardless of constraint pinned with safeArea/layoutGuide/superview
+    */
+    @available(*, deprecated, message: "Due to change in core-logic of handling distance between textField and keyboard distance, this layout contraint tweak is no longer needed and things will just work out of the box regardless of constraint pinned with safeArea/layoutGuide/superview.")
+    @IBOutlet public var IQLayoutGuideConstraint: NSLayoutConstraint? {
+        get {
+            return objc_getAssociatedObject(self, &AssociatedKeys.IQLayoutGuideConstraint) as? NSLayoutConstraint
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.IQLayoutGuideConstraint, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+        }
+    }
+}

+ 150 - 0
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/Constants/IQKeyboardManagerConstants.swift

@@ -0,0 +1,150 @@
+//
+//  IQKeyboardManagerConstants.swift
+// https://github.com/hackiftekhar/IQKeyboardManager
+// Copyright (c) 2013-20 Iftekhar Qurashi.
+//
+// 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
+
+// MARK: IQAutoToolbarManageBehaviour
+
+/**
+`IQAutoToolbarBySubviews`
+Creates Toolbar according to subview's hirarchy of Textfield's in view.
+
+`IQAutoToolbarByTag`
+Creates Toolbar according to tag property of TextField's.
+
+`IQAutoToolbarByPosition`
+Creates Toolbar according to the y,x position of textField in it's superview coordinate.
+*/
+@available(iOSApplicationExtension, unavailable)
+@objc public enum IQAutoToolbarManageBehaviour: Int {
+    case bySubviews
+    case byTag
+    case byPosition
+}
+
+/**
+ `IQPreviousNextDisplayModeDefault`
+ Show NextPrevious when there are more than 1 textField otherwise hide.
+ 
+ `IQPreviousNextDisplayModeAlwaysHide`
+ Do not show NextPrevious buttons in any case.
+ 
+ `IQPreviousNextDisplayModeAlwaysShow`
+ Always show nextPrevious buttons, if there are more than 1 textField then both buttons will be visible but will be shown as disabled.
+ */
+@available(iOSApplicationExtension, unavailable)
+@objc public enum IQPreviousNextDisplayMode: Int {
+    case `default`
+    case alwaysHide
+    case alwaysShow
+}
+
+/**
+ `IQEnableModeDefault`
+ Pick default settings.
+ 
+ `IQEnableModeEnabled`
+ setting is enabled.
+ 
+ `IQEnableModeDisabled`
+ setting is disabled.
+ */
+@available(iOSApplicationExtension, unavailable)
+@objc public enum IQEnableMode: Int {
+    case `default`
+    case enabled
+    case disabled
+}
+
+/*
+ /---------------------------------------------------------------------------------------------------\
+ \---------------------------------------------------------------------------------------------------/
+ |                                   iOS Notification Mechanism                                    |
+ /---------------------------------------------------------------------------------------------------\
+ \---------------------------------------------------------------------------------------------------/
+ 
+ ------------------------------------------------------------
+ When UITextField become first responder
+ ------------------------------------------------------------
+ - UITextFieldTextDidBeginEditingNotification (UITextField)
+ - UIKeyboardWillShowNotification
+ - UIKeyboardDidShowNotification
+ 
+ ------------------------------------------------------------
+ When UITextView become first responder
+ ------------------------------------------------------------
+ - UIKeyboardWillShowNotification
+ - UITextViewTextDidBeginEditingNotification (UITextView)
+ - UIKeyboardDidShowNotification
+ 
+ ------------------------------------------------------------
+ When switching focus from UITextField to another UITextField
+ ------------------------------------------------------------
+ - UITextFieldTextDidEndEditingNotification (UITextField1)
+ - UITextFieldTextDidBeginEditingNotification (UITextField2)
+ - UIKeyboardWillShowNotification
+ - UIKeyboardDidShowNotification
+ 
+ ------------------------------------------------------------
+ When switching focus from UITextView to another UITextView
+ ------------------------------------------------------------
+ - UITextViewTextDidEndEditingNotification: (UITextView1)
+ - UIKeyboardWillShowNotification
+ - UITextViewTextDidBeginEditingNotification: (UITextView2)
+ - UIKeyboardDidShowNotification
+ 
+ ------------------------------------------------------------
+ When switching focus from UITextField to UITextView
+ ------------------------------------------------------------
+ - UITextFieldTextDidEndEditingNotification (UITextField)
+ - UIKeyboardWillShowNotification
+ - UITextViewTextDidBeginEditingNotification (UITextView)
+ - UIKeyboardDidShowNotification
+ 
+ ------------------------------------------------------------
+ When switching focus from UITextView to UITextField
+ ------------------------------------------------------------
+ - UITextViewTextDidEndEditingNotification (UITextView)
+ - UITextFieldTextDidBeginEditingNotification (UITextField)
+ - UIKeyboardWillShowNotification
+ - UIKeyboardDidShowNotification
+ 
+ ------------------------------------------------------------
+ When opening/closing UIKeyboard Predictive bar
+ ------------------------------------------------------------
+ - UIKeyboardWillShowNotification
+ - UIKeyboardDidShowNotification
+ 
+ ------------------------------------------------------------
+ On orientation change
+ ------------------------------------------------------------
+ - UIApplicationWillChangeStatusBarOrientationNotification
+ - UIKeyboardWillHideNotification
+ - UIKeyboardDidHideNotification
+ - UIApplicationDidChangeStatusBarOrientationNotification
+ - UIKeyboardWillShowNotification
+ - UIKeyboardDidShowNotification
+ - UIKeyboardWillShowNotification
+ - UIKeyboardDidShowNotification
+ 
+ */

+ 24 - 0
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/Constants/IQKeyboardManagerConstantsInternal.swift

@@ -0,0 +1,24 @@
+//
+//  IQKeyboardManagerConstantsInternal.swift
+// https://github.com/hackiftekhar/IQKeyboardManager
+// Copyright (c) 2013-20 Iftekhar Qurashi.
+//
+// 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

+ 111 - 0
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQKeyboardManager+Debug.swift

@@ -0,0 +1,111 @@
+//
+//  IQKeyboardManager+Debug.swift
+// https://github.com/hackiftekhar/IQKeyboardManager
+// Copyright (c) 2013-20 Iftekhar Qurashi.
+//
+// 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 - UIKit contains Foundation
+import UIKit
+
+// MARK: Debugging & Developer options
+@available(iOSApplicationExtension, unavailable)
+public extension IQKeyboardManager {
+
+    private struct AssociatedKeys {
+        static var enableDebugging = "enableDebugging"
+    }
+
+    @objc var enableDebugging: Bool {
+        get {
+            return objc_getAssociatedObject(self, &AssociatedKeys.enableDebugging) as? Bool ?? false
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.enableDebugging, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+        }
+    }
+
+    /**
+     @warning Use below methods to completely enable/disable notifications registered by library internally.
+     Please keep in mind that library is totally dependent on NSNotification of UITextField, UITextField, Keyboard etc.
+     If you do unregisterAllNotifications then library will not work at all. You should only use below methods if you want to completedly disable all library functions.
+     You should use below methods at your own risk.
+     */
+    @objc func registerAllNotifications() {
+
+        //  Registering for keyboard notification.
+        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
+        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidShow(_:)), name: UIResponder.keyboardDidShowNotification, object: nil)
+        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
+        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidHide(_:)), name: UIResponder.keyboardDidHideNotification, object: nil)
+
+        //  Registering for UITextField notification.
+        registerTextFieldViewClass(UITextField.self, didBeginEditingNotificationName: UITextField.textDidBeginEditingNotification.rawValue, didEndEditingNotificationName: UITextField.textDidEndEditingNotification.rawValue)
+
+        //  Registering for UITextView notification.
+        registerTextFieldViewClass(UITextView.self, didBeginEditingNotificationName: UITextView.textDidBeginEditingNotification.rawValue, didEndEditingNotificationName: UITextView.textDidEndEditingNotification.rawValue)
+
+        //  Registering for orientation changes notification
+        NotificationCenter.default.addObserver(self, selector: #selector(self.willChangeStatusBarOrientation(_:)), name: UIApplication.willChangeStatusBarOrientationNotification, object: UIApplication.shared)
+    }
+
+    @objc func unregisterAllNotifications() {
+
+        //  Unregistering for keyboard notification.
+        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
+        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardDidShowNotification, object: nil)
+        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
+        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardDidHideNotification, object: nil)
+
+        //  Unregistering for UITextField notification.
+        unregisterTextFieldViewClass(UITextField.self, didBeginEditingNotificationName: UITextField.textDidBeginEditingNotification.rawValue, didEndEditingNotificationName: UITextField.textDidEndEditingNotification.rawValue)
+
+        //  Unregistering for UITextView notification.
+        unregisterTextFieldViewClass(UITextView.self, didBeginEditingNotificationName: UITextView.textDidBeginEditingNotification.rawValue, didEndEditingNotificationName: UITextView.textDidEndEditingNotification.rawValue)
+
+        //  Unregistering for orientation changes notification
+        NotificationCenter.default.removeObserver(self, name: UIApplication.willChangeStatusBarOrientationNotification, object: UIApplication.shared)
+    }
+
+    struct Static {
+        static var indentation = 0
+    }
+
+    internal func showLog(_ logString: String, indentation: Int = 0) {
+
+        guard enableDebugging else {
+            return
+        }
+
+        if indentation < 0 {
+            Static.indentation = max(0, Static.indentation + indentation)
+        }
+
+        var preLog = "IQKeyboardManager"
+        for _ in 0 ... Static.indentation {
+            preLog += "|\t"
+        }
+
+        print(preLog + logString)
+
+        if indentation > 0 {
+            Static.indentation += indentation
+        }
+    }
+}

+ 193 - 0
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQKeyboardManager+Internal.swift

@@ -0,0 +1,193 @@
+//
+//  IQKeyboardManager+Internal.swift
+// https://github.com/hackiftekhar/IQKeyboardManager
+// Copyright (c) 2013-20 Iftekhar Qurashi.
+//
+// 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 - UIKit contains Foundation
+import UIKit
+
+@available(iOSApplicationExtension, unavailable)
+internal extension IQKeyboardManager {
+
+    /**    Get all UITextField/UITextView siblings of textFieldView. */
+    func responderViews() -> [UIView]? {
+
+        var superConsideredView: UIView?
+
+        //If find any consider responderView in it's upper hierarchy then will get deepResponderView.
+        for disabledClass in toolbarPreviousNextAllowedClasses {
+            superConsideredView = textFieldView?.superviewOfClassType(disabledClass)
+            if superConsideredView != nil {
+                break
+            }
+        }
+
+        //If there is a superConsideredView in view's hierarchy, then fetching all it's subview that responds. No sorting for superConsideredView, it's by subView position.    (Enhancement ID: #22)
+        if let view = superConsideredView {
+            return view.deepResponderViews()
+        } else {  //Otherwise fetching all the siblings
+
+            guard let textFields = textFieldView?.responderSiblings() else {
+                return nil
+            }
+
+            //Sorting textFields according to behaviour
+            switch toolbarManageBehaviour {
+            //If autoToolbar behaviour is bySubviews, then returning it.
+            case .bySubviews:   return textFields
+
+            //If autoToolbar behaviour is by tag, then sorting it according to tag property.
+            case .byTag:    return textFields.sortedArrayByTag()
+
+            //If autoToolbar behaviour is by tag, then sorting it according to tag property.
+            case .byPosition:    return textFields.sortedArrayByPosition()
+            }
+        }
+    }
+
+    func privateIsEnabled() -> Bool {
+
+        var isEnabled = enable
+
+        let enableMode = textFieldView?.enableMode
+
+        if enableMode == .enabled {
+            isEnabled = true
+        } else if enableMode == .disabled {
+            isEnabled = false
+        } else if var textFieldViewController = textFieldView?.viewContainingController() {
+
+            //If it is searchBar textField embedded in Navigation Bar
+            if textFieldView?.textFieldSearchBar() != nil, let navController = textFieldViewController as? UINavigationController, let topController = navController.topViewController {
+                textFieldViewController = topController
+            }
+
+            //If viewController is kind of enable viewController class, then assuming it's enabled.
+            if !isEnabled, enabledDistanceHandlingClasses.contains(where: { textFieldViewController.isKind(of: $0) }) {
+                isEnabled = true
+            }
+
+            if isEnabled {
+
+                //If viewController is kind of disabled viewController class, then assuming it's disabled.
+                if disabledDistanceHandlingClasses.contains(where: { textFieldViewController.isKind(of: $0) }) {
+                    isEnabled = false
+                }
+
+                //Special Controllers
+                if isEnabled {
+
+                    let classNameString: String = "\(type(of: textFieldViewController.self))"
+
+                    //_UIAlertControllerTextFieldViewController
+                    if classNameString.contains("UIAlertController"), classNameString.hasSuffix("TextFieldViewController") {
+                        isEnabled = false
+                    }
+                }
+            }
+        }
+
+        return isEnabled
+    }
+
+    func privateIsEnableAutoToolbar() -> Bool {
+
+        guard var textFieldViewController = textFieldView?.viewContainingController() else {
+            return enableAutoToolbar
+        }
+
+        //If it is searchBar textField embedded in Navigation Bar
+        if textFieldView?.textFieldSearchBar() != nil, let navController = textFieldViewController as? UINavigationController, let topController = navController.topViewController {
+            textFieldViewController = topController
+        }
+
+        var enableToolbar = enableAutoToolbar
+
+        if !enableToolbar, enabledToolbarClasses.contains(where: { textFieldViewController.isKind(of: $0) }) {
+            enableToolbar = true
+        }
+
+        if enableToolbar {
+
+            //If found any toolbar disabled classes then return.
+            if disabledToolbarClasses.contains(where: { textFieldViewController.isKind(of: $0) }) {
+                enableToolbar = false
+            }
+
+            //Special Controllers
+            if enableToolbar {
+
+                let classNameString: String = "\(type(of: textFieldViewController.self))"
+
+                //_UIAlertControllerTextFieldViewController
+                if classNameString.contains("UIAlertController"), classNameString.hasSuffix("TextFieldViewController") {
+                    enableToolbar = false
+                }
+            }
+        }
+
+        return enableToolbar
+    }
+
+    func privateShouldResignOnTouchOutside() -> Bool {
+
+        var shouldResign = shouldResignOnTouchOutside
+
+        let enableMode = textFieldView?.shouldResignOnTouchOutsideMode
+
+        if enableMode == .enabled {
+            shouldResign = true
+        } else if enableMode == .disabled {
+            shouldResign = false
+        } else if var textFieldViewController = textFieldView?.viewContainingController() {
+
+            //If it is searchBar textField embedded in Navigation Bar
+            if textFieldView?.textFieldSearchBar() != nil, let navController = textFieldViewController as? UINavigationController, let topController = navController.topViewController {
+                textFieldViewController = topController
+            }
+
+            //If viewController is kind of enable viewController class, then assuming shouldResignOnTouchOutside is enabled.
+            if !shouldResign, enabledTouchResignedClasses.contains(where: { textFieldViewController.isKind(of: $0) }) {
+                shouldResign = true
+            }
+
+            if shouldResign {
+
+                //If viewController is kind of disable viewController class, then assuming shouldResignOnTouchOutside is disable.
+                if disabledTouchResignedClasses.contains(where: { textFieldViewController.isKind(of: $0) }) {
+                    shouldResign = false
+                }
+
+                //Special Controllers
+                if shouldResign {
+
+                    let classNameString: String = "\(type(of: textFieldViewController.self))"
+
+                    //_UIAlertControllerTextFieldViewController
+                    if classNameString.contains("UIAlertController"), classNameString.hasSuffix("TextFieldViewController") {
+                        shouldResign = false
+                    }
+                }
+            }
+        }
+        return shouldResign
+    }
+}

+ 77 - 0
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQKeyboardManager+OrientationNotification.swift

@@ -0,0 +1,77 @@
+//
+//  IQKeyboardManager+OrientationNotification.swift
+// https://github.com/hackiftekhar/IQKeyboardManager
+// Copyright (c) 2013-20 Iftekhar Qurashi.
+//
+// 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 - UIKit contains Foundation
+import UIKit
+
+// MARK: UIStatusBar Notification methods
+@available(iOSApplicationExtension, unavailable)
+internal extension IQKeyboardManager {
+
+    /**  UIApplicationWillChangeStatusBarOrientationNotification. Need to set the textView to it's original position. If any frame changes made. (Bug ID: #92)*/
+    @objc func willChangeStatusBarOrientation(_ notification: Notification) {
+
+        let currentStatusBarOrientation: UIInterfaceOrientation
+        #if swift(>=5.1)
+        if #available(iOS 13, *) {
+            currentStatusBarOrientation = keyWindow()?.windowScene?.interfaceOrientation ?? UIInterfaceOrientation.unknown
+        } else {
+            currentStatusBarOrientation = UIApplication.shared.statusBarOrientation
+        }
+        #else
+        currentStatusBarOrientation = UIApplication.shared.statusBarOrientation
+        #endif
+
+        guard let statusBarOrientation = notification.userInfo?[UIApplication.statusBarOrientationUserInfoKey] as? Int, currentStatusBarOrientation.rawValue != statusBarOrientation else {
+            return
+        }
+
+        let startTime = CACurrentMediaTime()
+        showLog("📱>>>>> \(#function) started >>>>>", indentation: 1)
+        showLog("Notification Object:\(notification.object ?? "NULL")")
+
+        //If textViewContentInsetChanged is saved then restore it.
+        if let textView = textFieldView as? UIScrollView, textView.responds(to: #selector(getter: UITextView.isEditable)) {
+
+            if isTextViewContentInsetChanged {
+                self.isTextViewContentInsetChanged = false
+                if textView.contentInset != self.startingTextViewContentInsets {
+                    UIView.animate(withDuration: animationDuration, delay: 0, options: animationCurve, animations: { () -> Void in
+
+                        self.showLog("Restoring textView.contentInset to: \(self.startingTextViewContentInsets)")
+
+                        //Setting textField to it's initial contentInset
+                        textView.contentInset = self.startingTextViewContentInsets
+                        textView.scrollIndicatorInsets = self.startingTextViewScrollIndicatorInsets
+
+                    }, completion: { (_) -> Void in })
+                }
+            }
+        }
+
+        restorePosition()
+
+        let elapsedTime = CACurrentMediaTime() - startTime
+        showLog("📱<<<<< \(#function) ended: \(elapsedTime) seconds <<<<<", indentation: -1)
+    }
+}

+ 717 - 0
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQKeyboardManager+Position.swift

@@ -0,0 +1,717 @@
+//
+//  IQKeyboardManager+Position.swift
+// https://github.com/hackiftekhar/IQKeyboardManager
+// Copyright (c) 2013-20 Iftekhar Qurashi.
+//
+// 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 - UIKit contains Foundation
+import UIKit
+
+@available(iOSApplicationExtension, unavailable)
+public extension IQKeyboardManager {
+
+    private struct AssociatedKeys {
+        static var movedDistance = "movedDistance"
+        static var movedDistanceChanged = "movedDistanceChanged"
+        static var lastScrollView = "lastScrollView"
+        static var startingContentOffset = "startingContentOffset"
+        static var startingScrollIndicatorInsets = "startingScrollIndicatorInsets"
+        static var startingContentInsets = "startingContentInsets"
+        static var startingTextViewContentInsets = "startingTextViewContentInsets"
+        static var startingTextViewScrollIndicatorInsets = "startingTextViewScrollIndicatorInsets"
+        static var isTextViewContentInsetChanged = "isTextViewContentInsetChanged"
+        static var hasPendingAdjustRequest = "hasPendingAdjustRequest"
+    }
+
+    /**
+     moved distance to the top used to maintain distance between keyboard and textField. Most of the time this will be a positive value.
+     */
+    @objc private(set) var movedDistance: CGFloat {
+        get {
+            return objc_getAssociatedObject(self, &AssociatedKeys.movedDistance) as? CGFloat ?? 0.0
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.movedDistance, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+            movedDistanceChanged?(movedDistance)
+        }
+    }
+
+    /**
+    Will be called then movedDistance will be changed
+     */
+    @objc var movedDistanceChanged: ((CGFloat) -> Void)? {
+        get {
+            return objc_getAssociatedObject(self, &AssociatedKeys.movedDistanceChanged) as? ((CGFloat) -> Void)
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.movedDistanceChanged, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+            movedDistanceChanged?(movedDistance)
+        }
+    }
+
+    /** Variable to save lastScrollView that was scrolled. */
+    internal weak var lastScrollView: UIScrollView? {
+        get {
+            return (objc_getAssociatedObject(self, &AssociatedKeys.lastScrollView) as? WeakObjectContainer)?.object as? UIScrollView
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.lastScrollView, WeakObjectContainer(object: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+        }
+    }
+
+    /** LastScrollView's initial contentOffset. */
+    internal var startingContentOffset: CGPoint {
+        get {
+            return objc_getAssociatedObject(self, &AssociatedKeys.startingContentOffset) as? CGPoint ?? IQKeyboardManager.kIQCGPointInvalid
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.startingContentOffset, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+        }
+    }
+
+    /** LastScrollView's initial scrollIndicatorInsets. */
+    internal var startingScrollIndicatorInsets: UIEdgeInsets {
+        get {
+            return objc_getAssociatedObject(self, &AssociatedKeys.startingScrollIndicatorInsets) as? UIEdgeInsets ?? .init()
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.startingScrollIndicatorInsets, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+        }
+    }
+
+    /** LastScrollView's initial contentInsets. */
+    internal var startingContentInsets: UIEdgeInsets {
+        get {
+            return objc_getAssociatedObject(self, &AssociatedKeys.startingContentInsets) as? UIEdgeInsets ?? .init()
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.startingContentInsets, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+        }
+    }
+
+    /** used to adjust contentInset of UITextView. */
+    internal var startingTextViewContentInsets: UIEdgeInsets {
+        get {
+            return objc_getAssociatedObject(self, &AssociatedKeys.startingTextViewContentInsets) as? UIEdgeInsets ?? .init()
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.startingTextViewContentInsets, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+        }
+    }
+
+    /** used to adjust scrollIndicatorInsets of UITextView. */
+    internal var startingTextViewScrollIndicatorInsets: UIEdgeInsets {
+        get {
+            return objc_getAssociatedObject(self, &AssociatedKeys.startingTextViewScrollIndicatorInsets) as? UIEdgeInsets ?? .init()
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.startingTextViewScrollIndicatorInsets, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+        }
+    }
+
+    /** used with textView to detect a textFieldView contentInset is changed or not. (Bug ID: #92)*/
+    internal var isTextViewContentInsetChanged: Bool {
+        get {
+            return objc_getAssociatedObject(self, &AssociatedKeys.isTextViewContentInsetChanged) as? Bool ?? false
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.isTextViewContentInsetChanged, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+        }
+    }
+
+    /** To know if we have any pending request to adjust view position. */
+    private var hasPendingAdjustRequest: Bool {
+        get {
+            return objc_getAssociatedObject(self, &AssociatedKeys.hasPendingAdjustRequest) as? Bool ?? false
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.hasPendingAdjustRequest, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+        }
+    }
+
+    internal func optimizedAdjustPosition() {
+        if !hasPendingAdjustRequest {
+            hasPendingAdjustRequest = true
+            OperationQueue.main.addOperation {
+                self.adjustPosition()
+                self.hasPendingAdjustRequest = false
+            }
+        }
+    }
+
+    /* Adjusting RootViewController's frame according to interface orientation. */
+    private func adjustPosition() {
+
+        //  We are unable to get textField object while keyboard showing on WKWebView's textField.  (Bug ID: #11)
+        guard hasPendingAdjustRequest,
+            let textFieldView = textFieldView,
+            let rootController = textFieldView.parentContainerViewController(),
+            let window = keyWindow(),
+            let textFieldViewRectInWindow = textFieldView.superview?.convert(textFieldView.frame, to: window),
+            let textFieldViewRectInRootSuperview = textFieldView.superview?.convert(textFieldView.frame, to: rootController.view?.superview) else {
+                return
+        }
+
+        let startTime = CACurrentMediaTime()
+        showLog(">>>>> \(#function) started >>>>>", indentation: 1)
+
+        //  Getting RootViewOrigin.
+        var rootViewOrigin = rootController.view.frame.origin
+
+        //Maintain keyboardDistanceFromTextField
+        var specialKeyboardDistanceFromTextField = textFieldView.keyboardDistanceFromTextField
+
+        if let searchBar = textFieldView.textFieldSearchBar() {
+            specialKeyboardDistanceFromTextField = searchBar.keyboardDistanceFromTextField
+        }
+
+        let newKeyboardDistanceFromTextField = (specialKeyboardDistanceFromTextField == kIQUseDefaultKeyboardDistance) ? keyboardDistanceFromTextField : specialKeyboardDistanceFromTextField
+
+        var kbSize = keyboardFrame.size
+
+        do {
+            var kbFrame = keyboardFrame
+
+            kbFrame.origin.y -= newKeyboardDistanceFromTextField
+            kbFrame.size.height += newKeyboardDistanceFromTextField
+
+            //Calculating actual keyboard covered size respect to window, keyboard frame may be different when hardware keyboard is attached (Bug ID: #469) (Bug ID: #381) (Bug ID: #1506)
+            let intersectRect = kbFrame.intersection(window.frame)
+
+            if intersectRect.isNull {
+                kbSize = CGSize(width: kbFrame.size.width, height: 0)
+            } else {
+                kbSize = intersectRect.size
+            }
+        }
+
+        let statusBarHeight: CGFloat
+
+        let navigationBarAreaHeight: CGFloat
+        if let navigationController = rootController.navigationController {
+            navigationBarAreaHeight = navigationController.navigationBar.frame.maxY
+        } else {
+#if swift(>=5.1)
+            if #available(iOS 13, *) {
+                statusBarHeight = window.windowScene?.statusBarManager?.statusBarFrame.height ?? 0
+            } else {
+                statusBarHeight = UIApplication.shared.statusBarFrame.height
+            }
+#else
+            statusBarHeight = UIApplication.shared.statusBarFrame.height
+#endif
+            navigationBarAreaHeight = statusBarHeight
+        }
+
+        let layoutAreaHeight: CGFloat = rootController.view.layoutMargins.bottom
+
+        let isTextView: Bool
+        let isNonScrollableTextView: Bool
+
+        if let textView = textFieldView as? UIScrollView, textFieldView.responds(to: #selector(getter: UITextView.isEditable)) {
+
+            isTextView = true
+            isNonScrollableTextView = !textView.isScrollEnabled
+        } else {
+            isTextView = false
+            isNonScrollableTextView = false
+        }
+
+        let topLayoutGuide: CGFloat = max(navigationBarAreaHeight, layoutAreaHeight) + 5
+
+        let bottomLayoutGuide: CGFloat = (isTextView && !isNonScrollableTextView) ? 0 : rootController.view.layoutMargins.bottom  //Validation of textView for case where there is a tab bar at the bottom or running on iPhone X and textView is at the bottom.
+        let visibleHeight: CGFloat = window.frame.height-kbSize.height
+
+        //  Move positive = textField is hidden.
+        //  Move negative = textField is showing.
+        //  Calculating move position.
+        var move: CGFloat
+
+        //Special case: when the textView is not scrollable, then we'll be scrolling to the bottom part and let hide the top part above
+        if isNonScrollableTextView {
+            move = textFieldViewRectInWindow.maxY - visibleHeight + bottomLayoutGuide
+        } else {
+            move = min(textFieldViewRectInRootSuperview.minY-(topLayoutGuide), textFieldViewRectInWindow.maxY - visibleHeight + bottomLayoutGuide)
+        }
+
+        showLog("Need to move: \(move)")
+
+        var superScrollView: UIScrollView?
+        var superView = textFieldView.superviewOfClassType(UIScrollView.self) as? UIScrollView
+
+        //Getting UIScrollView whose scrolling is enabled.    //  (Bug ID: #285)
+        while let view = superView {
+
+            if view.isScrollEnabled, !view.shouldIgnoreScrollingAdjustment {
+                superScrollView = view
+                break
+            } else {
+                //  Getting it's superScrollView.   //  (Enhancement ID: #21, #24)
+                superView = view.superviewOfClassType(UIScrollView.self) as? UIScrollView
+            }
+        }
+
+        //If there was a lastScrollView.    //  (Bug ID: #34)
+        if let lastScrollView = lastScrollView {
+            //If we can't find current superScrollView, then setting lastScrollView to it's original form.
+            if superScrollView == nil {
+
+                if lastScrollView.contentInset != self.startingContentInsets {
+                    showLog("Restoring contentInset to: \(startingContentInsets)")
+                    UIView.animate(withDuration: animationDuration, delay: 0, options: animationCurve, animations: { () -> Void in
+
+                        lastScrollView.contentInset = self.startingContentInsets
+                        lastScrollView.scrollIndicatorInsets = self.startingScrollIndicatorInsets
+                    })
+                }
+
+                if lastScrollView.shouldRestoreScrollViewContentOffset, !lastScrollView.contentOffset.equalTo(startingContentOffset) {
+                    showLog("Restoring contentOffset to: \(startingContentOffset)")
+
+                    let animatedContentOffset = textFieldView.superviewOfClassType(UIStackView.self, belowView: lastScrollView) != nil  //  (Bug ID: #1365, #1508, #1541)
+
+                    if animatedContentOffset {
+                        lastScrollView.setContentOffset(startingContentOffset, animated: UIView.areAnimationsEnabled)
+                    } else {
+                        lastScrollView.contentOffset = startingContentOffset
+                    }
+                }
+
+                startingContentInsets = UIEdgeInsets()
+                startingScrollIndicatorInsets = UIEdgeInsets()
+                startingContentOffset = CGPoint.zero
+                self.lastScrollView = nil
+            } else if superScrollView != lastScrollView {     //If both scrollView's are different, then reset lastScrollView to it's original frame and setting current scrollView as last scrollView.
+
+                if lastScrollView.contentInset != self.startingContentInsets {
+                    showLog("Restoring contentInset to: \(startingContentInsets)")
+                    UIView.animate(withDuration: animationDuration, delay: 0, options: animationCurve, animations: { () -> Void in
+
+                        lastScrollView.contentInset = self.startingContentInsets
+                        lastScrollView.scrollIndicatorInsets = self.startingScrollIndicatorInsets
+                    })
+                }
+
+                if lastScrollView.shouldRestoreScrollViewContentOffset, !lastScrollView.contentOffset.equalTo(startingContentOffset) {
+                    showLog("Restoring contentOffset to: \(startingContentOffset)")
+
+                    let animatedContentOffset = textFieldView.superviewOfClassType(UIStackView.self, belowView: lastScrollView) != nil  //  (Bug ID: #1365, #1508, #1541)
+
+                    if animatedContentOffset {
+                        lastScrollView.setContentOffset(startingContentOffset, animated: UIView.areAnimationsEnabled)
+                    } else {
+                        lastScrollView.contentOffset = startingContentOffset
+                    }
+                }
+
+                self.lastScrollView = superScrollView
+                if let scrollView = superScrollView {
+                    startingContentInsets = scrollView.contentInset
+                    startingContentOffset = scrollView.contentOffset
+
+                    #if swift(>=5.1)
+                    if #available(iOS 11.1, *) {
+                        startingScrollIndicatorInsets = scrollView.verticalScrollIndicatorInsets
+                    } else {
+                        startingScrollIndicatorInsets = scrollView.scrollIndicatorInsets
+                    }
+                    #else
+                    startingScrollIndicatorInsets = scrollView.scrollIndicatorInsets
+                    #endif
+                }
+
+                showLog("Saving ScrollView New contentInset: \(startingContentInsets) and contentOffset: \(startingContentOffset)")
+            }
+            //Else the case where superScrollView == lastScrollView means we are on same scrollView after switching to different textField. So doing nothing, going ahead
+        } else if let unwrappedSuperScrollView = superScrollView {    //If there was no lastScrollView and we found a current scrollView. then setting it as lastScrollView.
+            lastScrollView = unwrappedSuperScrollView
+            startingContentInsets = unwrappedSuperScrollView.contentInset
+            startingContentOffset = unwrappedSuperScrollView.contentOffset
+
+            #if swift(>=5.1)
+            if #available(iOS 11.1, *) {
+                startingScrollIndicatorInsets = unwrappedSuperScrollView.verticalScrollIndicatorInsets
+            } else {
+                startingScrollIndicatorInsets = unwrappedSuperScrollView.scrollIndicatorInsets
+            }
+            #else
+            startingScrollIndicatorInsets = unwrappedSuperScrollView.scrollIndicatorInsets
+            #endif
+
+            showLog("Saving ScrollView contentInset: \(startingContentInsets) and contentOffset: \(startingContentOffset)")
+        }
+
+        //  Special case for ScrollView.
+        //  If we found lastScrollView then setting it's contentOffset to show textField.
+        if let lastScrollView = lastScrollView {
+            //Saving
+            var lastView = textFieldView
+            var superScrollView = self.lastScrollView
+
+            while let scrollView = superScrollView {
+
+                var shouldContinue = false
+
+                if move > 0 {
+                    shouldContinue =  move > (-scrollView.contentOffset.y - scrollView.contentInset.top)
+
+                } else if let tableView = scrollView.superviewOfClassType(UITableView.self) as? UITableView {
+
+                    shouldContinue = scrollView.contentOffset.y > 0
+
+                    if shouldContinue, let tableCell = textFieldView.superviewOfClassType(UITableViewCell.self) as? UITableViewCell, let indexPath = tableView.indexPath(for: tableCell), let previousIndexPath = tableView.previousIndexPath(of: indexPath) {
+
+                        let previousCellRect = tableView.rectForRow(at: previousIndexPath)
+                        if !previousCellRect.isEmpty {
+                            let previousCellRectInRootSuperview = tableView.convert(previousCellRect, to: rootController.view.superview)
+
+                            move = min(0, previousCellRectInRootSuperview.maxY - topLayoutGuide)
+                        }
+                    }
+                } else if let collectionView = scrollView.superviewOfClassType(UICollectionView.self) as? UICollectionView {
+
+                    shouldContinue = scrollView.contentOffset.y > 0
+
+                    if shouldContinue, let collectionCell = textFieldView.superviewOfClassType(UICollectionViewCell.self) as? UICollectionViewCell, let indexPath = collectionView.indexPath(for: collectionCell), let previousIndexPath = collectionView.previousIndexPath(of: indexPath), let attributes = collectionView.layoutAttributesForItem(at: previousIndexPath) {
+
+                        let previousCellRect = attributes.frame
+                        if !previousCellRect.isEmpty {
+                            let previousCellRectInRootSuperview = collectionView.convert(previousCellRect, to: rootController.view.superview)
+
+                            move = min(0, previousCellRectInRootSuperview.maxY - topLayoutGuide)
+                        }
+                    }
+                } else {
+
+                    if isNonScrollableTextView {
+                        shouldContinue = textFieldViewRectInWindow.maxY < visibleHeight + bottomLayoutGuide
+
+                        if shouldContinue {
+                            move = min(0,  textFieldViewRectInWindow.maxY -  visibleHeight + bottomLayoutGuide)
+                        }
+                    } else {
+                        shouldContinue = textFieldViewRectInRootSuperview.minY < topLayoutGuide
+
+                        if shouldContinue {
+                            move = min(0, textFieldViewRectInRootSuperview.minY - topLayoutGuide)
+                        }
+                    }
+                }
+
+                //Looping in upper hierarchy until we don't found any scrollView in it's upper hirarchy till UIWindow object.
+                if shouldContinue {
+
+                    var tempScrollView = scrollView.superviewOfClassType(UIScrollView.self) as? UIScrollView
+                    var nextScrollView: UIScrollView?
+                    while let view = tempScrollView {
+
+                        if view.isScrollEnabled, !view.shouldIgnoreScrollingAdjustment {
+                            nextScrollView = view
+                            break
+                        } else {
+                            tempScrollView = view.superviewOfClassType(UIScrollView.self) as? UIScrollView
+                        }
+                    }
+
+                    //Getting lastViewRect.
+                    if let lastViewRect = lastView.superview?.convert(lastView.frame, to: scrollView) {
+
+                        //Calculating the expected Y offset from move and scrollView's contentOffset.
+                        var shouldOffsetY = scrollView.contentOffset.y - min(scrollView.contentOffset.y, -move)
+
+                        //Rearranging the expected Y offset according to the view.
+
+                        if isNonScrollableTextView {
+                            shouldOffsetY = min(shouldOffsetY, lastViewRect.maxY - visibleHeight + bottomLayoutGuide)
+                        } else {
+                            shouldOffsetY = min(shouldOffsetY, lastViewRect.minY)
+                        }
+
+                        //[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type
+                        //nextScrollView == nil    If processing scrollView is last scrollView in upper hierarchy (there is no other scrollView upper hierrchy.)
+                        //[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type
+                        //shouldOffsetY >= 0     shouldOffsetY must be greater than in order to keep distance from navigationBar (Bug ID: #92)
+                        if isTextView, !isNonScrollableTextView,
+                            nextScrollView == nil,
+                            shouldOffsetY >= 0 {
+
+                            //  Converting Rectangle according to window bounds.
+                            if let currentTextFieldViewRect = textFieldView.superview?.convert(textFieldView.frame, to: window) {
+
+                                //Calculating expected fix distance which needs to be managed from navigation bar
+                                let expectedFixDistance: CGFloat = currentTextFieldViewRect.minY - topLayoutGuide
+
+                                //Now if expectedOffsetY (superScrollView.contentOffset.y + expectedFixDistance) is lower than current shouldOffsetY, which means we're in a position where navigationBar up and hide, then reducing shouldOffsetY with expectedOffsetY (superScrollView.contentOffset.y + expectedFixDistance)
+                                shouldOffsetY = min(shouldOffsetY, scrollView.contentOffset.y + expectedFixDistance)
+
+                                //Setting move to 0 because now we don't want to move any view anymore (All will be managed by our contentInset logic.
+                                move = 0
+                            } else {
+                                //Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY.
+                                move -= (shouldOffsetY-scrollView.contentOffset.y)
+                            }
+                        } else {
+                            //Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY.
+                            move -= (shouldOffsetY-scrollView.contentOffset.y)
+                        }
+
+                        let newContentOffset = CGPoint(x: scrollView.contentOffset.x, y: shouldOffsetY)
+
+                        if scrollView.contentOffset.equalTo(newContentOffset) == false {
+
+                            showLog("old contentOffset: \(scrollView.contentOffset) new contentOffset: \(newContentOffset)")
+                            self.showLog("Remaining Move: \(move)")
+
+                            //Getting problem while using `setContentOffset:animated:`, So I used animation API.
+                            UIView.animate(withDuration: animationDuration, delay: 0, options: animationCurve, animations: { () -> Void in
+
+                                let animatedContentOffset = textFieldView.superviewOfClassType(UIStackView.self, belowView: scrollView) != nil  //  (Bug ID: #1365, #1508, #1541)
+
+                                if animatedContentOffset {
+                                    scrollView.setContentOffset(newContentOffset, animated: UIView.areAnimationsEnabled)
+                                } else {
+                                    scrollView.contentOffset = newContentOffset
+                                }
+                            }, completion: { _ in
+
+                                if scrollView is UITableView || scrollView is UICollectionView {
+                                    //This will update the next/previous states
+                                    self.addToolbarIfRequired()
+                                }
+                            })
+                        }
+                    }
+
+                    //  Getting next lastView & superScrollView.
+                    lastView = scrollView
+                    superScrollView = nextScrollView
+                } else {
+                    move = 0
+                    break
+                }
+            }
+
+            //Updating contentInset
+            if let lastScrollViewRect = lastScrollView.superview?.convert(lastScrollView.frame, to: window),
+                lastScrollView.shouldIgnoreContentInsetAdjustment == false {
+
+                var bottomInset: CGFloat = (kbSize.height)-(window.frame.height-lastScrollViewRect.maxY)
+                var bottomScrollIndicatorInset = bottomInset - newKeyboardDistanceFromTextField
+
+                // Update the insets so that the scroll vew doesn't shift incorrectly when the offset is near the bottom of the scroll view.
+                bottomInset = max(startingContentInsets.bottom, bottomInset)
+                bottomScrollIndicatorInset = max(startingScrollIndicatorInsets.bottom, bottomScrollIndicatorInset)
+
+                if #available(iOS 11, *) {
+                    bottomInset -= lastScrollView.safeAreaInsets.bottom
+                    bottomScrollIndicatorInset -= lastScrollView.safeAreaInsets.bottom
+                }
+
+                var movedInsets = lastScrollView.contentInset
+                movedInsets.bottom = bottomInset
+
+                if lastScrollView.contentInset != movedInsets {
+                    showLog("old ContentInset: \(lastScrollView.contentInset) new ContentInset: \(movedInsets)")
+
+                    UIView.animate(withDuration: animationDuration, delay: 0, options: animationCurve, animations: { () -> Void in
+                        lastScrollView.contentInset = movedInsets
+
+                        var newScrollIndicatorInset: UIEdgeInsets
+
+                        #if swift(>=5.1)
+                        if #available(iOS 11.1, *) {
+                            newScrollIndicatorInset = lastScrollView.verticalScrollIndicatorInsets
+                        } else {
+                            newScrollIndicatorInset = lastScrollView.scrollIndicatorInsets
+                        }
+                        #else
+                        newScrollIndicatorInset = lastScrollView.scrollIndicatorInsets
+                        #endif
+
+                        newScrollIndicatorInset.bottom = bottomScrollIndicatorInset
+                        lastScrollView.scrollIndicatorInsets = newScrollIndicatorInset
+                    })
+                }
+            }
+        }
+        //Going ahead. No else if.
+
+        //Special case for UITextView(Readjusting textView.contentInset when textView hight is too big to fit on screen)
+        //_lastScrollView       If not having inside any scrollView, (now contentInset manages the full screen textView.
+        //[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type
+        if let textView = textFieldView as? UIScrollView, textView.isScrollEnabled, textFieldView.responds(to: #selector(getter: UITextView.isEditable)) {
+
+            //                CGRect rootSuperViewFrameInWindow = [_rootViewController.view.superview convertRect:_rootViewController.view.superview.bounds toView:keyWindow];
+            //
+            //                CGFloat keyboardOverlapping = CGRectGetMaxY(rootSuperViewFrameInWindow) - keyboardYPosition;
+            //
+            //                CGFloat textViewHeight = MIN(CGRectGetHeight(_textFieldView.frame), (CGRectGetHeight(rootSuperViewFrameInWindow)-topLayoutGuide-keyboardOverlapping));
+
+            let keyboardYPosition = window.frame.height - (kbSize.height-newKeyboardDistanceFromTextField)
+            var rootSuperViewFrameInWindow = window.frame
+            if let rootSuperview = rootController.view.superview {
+                rootSuperViewFrameInWindow = rootSuperview.convert(rootSuperview.bounds, to: window)
+            }
+
+            let keyboardOverlapping = rootSuperViewFrameInWindow.maxY - keyboardYPosition
+
+            let textViewHeight = min(textView.frame.height, rootSuperViewFrameInWindow.height-topLayoutGuide-keyboardOverlapping)
+
+            if textView.frame.size.height-textView.contentInset.bottom>textViewHeight {
+                //_isTextViewContentInsetChanged,  If frame is not change by library in past, then saving user textView properties  (Bug ID: #92)
+                if !self.isTextViewContentInsetChanged {
+                    self.startingTextViewContentInsets = textView.contentInset
+
+                    #if swift(>=5.1)
+                    if #available(iOS 11.1, *) {
+                        self.startingTextViewScrollIndicatorInsets = textView.verticalScrollIndicatorInsets
+                    } else {
+                        self.startingTextViewScrollIndicatorInsets = textView.scrollIndicatorInsets
+                    }
+                    #else
+                    self.startingTextViewScrollIndicatorInsets = textView.scrollIndicatorInsets
+                    #endif
+                }
+
+                self.isTextViewContentInsetChanged = true
+
+                var newContentInset = textView.contentInset
+                newContentInset.bottom = textView.frame.size.height-textViewHeight
+
+                if #available(iOS 11, *) {
+                    newContentInset.bottom -= textView.safeAreaInsets.bottom
+                }
+
+                if textView.contentInset != newContentInset {
+                    self.showLog("\(textFieldView) Old UITextView.contentInset: \(textView.contentInset) New UITextView.contentInset: \(newContentInset)")
+
+                    UIView.animate(withDuration: animationDuration, delay: 0, options: animationCurve, animations: { () -> Void in
+
+                        textView.contentInset = newContentInset
+                        textView.scrollIndicatorInsets = newContentInset
+                    }, completion: { (_) -> Void in })
+                }
+            }
+        }
+
+        //  +Positive or zero.
+        if move >= 0 {
+
+            rootViewOrigin.y = max(rootViewOrigin.y - move, min(0, -(kbSize.height-newKeyboardDistanceFromTextField)))
+
+            if rootController.view.frame.origin.equalTo(rootViewOrigin) == false {
+                showLog("Moving Upward")
+
+                UIView.animate(withDuration: animationDuration, delay: 0, options: animationCurve, animations: { () -> Void in
+
+                    var rect = rootController.view.frame
+                    rect.origin = rootViewOrigin
+                    rootController.view.frame = rect
+
+                    //Animating content if needed (Bug ID: #204)
+                    if self.layoutIfNeededOnUpdate {
+                        //Animating content (Bug ID: #160)
+                        rootController.view.setNeedsLayout()
+                        rootController.view.layoutIfNeeded()
+                    }
+
+                    self.showLog("Set \(rootController) origin to: \(rootViewOrigin)")
+                })
+            }
+
+            movedDistance = (topViewBeginOrigin.y-rootViewOrigin.y)
+        } else {  //  -Negative
+            let disturbDistance: CGFloat = rootViewOrigin.y-topViewBeginOrigin.y
+
+            //  disturbDistance Negative = frame disturbed.
+            //  disturbDistance positive = frame not disturbed.
+            if disturbDistance <= 0 {
+
+                rootViewOrigin.y -= max(move, disturbDistance)
+
+                if rootController.view.frame.origin.equalTo(rootViewOrigin) == false {
+                    showLog("Moving Downward")
+                    //  Setting adjusted rootViewRect
+                    //  Setting adjusted rootViewRect
+
+                    UIView.animate(withDuration: animationDuration, delay: 0, options: animationCurve, animations: { () -> Void in
+
+                        var rect = rootController.view.frame
+                        rect.origin = rootViewOrigin
+                        rootController.view.frame = rect
+
+                        //Animating content if needed (Bug ID: #204)
+                        if self.layoutIfNeededOnUpdate {
+                            //Animating content (Bug ID: #160)
+                            rootController.view.setNeedsLayout()
+                            rootController.view.layoutIfNeeded()
+                        }
+
+                        self.showLog("Set \(rootController) origin to: \(rootViewOrigin)")
+                    })
+                }
+
+                movedDistance = (topViewBeginOrigin.y-rootViewOrigin.y)
+            }
+        }
+
+        let elapsedTime = CACurrentMediaTime() - startTime
+        showLog("<<<<< \(#function) ended: \(elapsedTime) seconds <<<<<", indentation: -1)
+    }
+
+    internal func restorePosition() {
+
+        hasPendingAdjustRequest = false
+
+        //  Setting rootViewController frame to it's original position. //  (Bug ID: #18)
+        guard topViewBeginOrigin.equalTo(IQKeyboardManager.kIQCGPointInvalid) == false, let rootViewController = rootViewController else {
+            return
+        }
+
+        if rootViewController.view.frame.origin.equalTo(self.topViewBeginOrigin) == false {
+            //Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations.
+            UIView.animate(withDuration: animationDuration, delay: 0, options: animationCurve, animations: { () -> Void in
+
+                self.showLog("Restoring \(rootViewController) origin to: \(self.topViewBeginOrigin)")
+
+                //  Setting it's new frame
+                var rect = rootViewController.view.frame
+                rect.origin = self.topViewBeginOrigin
+                rootViewController.view.frame = rect
+
+                //Animating content if needed (Bug ID: #204)
+                if self.layoutIfNeededOnUpdate {
+                    //Animating content (Bug ID: #160)
+                    rootViewController.view.setNeedsLayout()
+                    rootViewController.view.layoutIfNeeded()
+                }
+            })
+        }
+
+        self.movedDistance = 0
+
+        if rootViewController.navigationController?.interactivePopGestureRecognizer?.state == .began {
+            self.rootViewControllerWhilePopGestureRecognizerActive = rootViewController
+            self.topViewBeginOriginWhilePopGestureRecognizerActive = self.topViewBeginOrigin
+        }
+
+        self.rootViewController = nil
+    }
+}

+ 368 - 0
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQKeyboardManager+Toolbar.swift

@@ -0,0 +1,368 @@
+//
+//  IQKeyboardManager+Toolbar.swift
+// https://github.com/hackiftekhar/IQKeyboardManager
+// Copyright (c) 2013-20 Iftekhar Qurashi.
+//
+// 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 - UIKit contains Foundation
+import UIKit
+
+@available(iOSApplicationExtension, unavailable)
+public extension IQKeyboardManager {
+
+    /**
+    Default tag for toolbar with Done button   -1002.
+    */
+    private static let  kIQDoneButtonToolbarTag         =   -1002
+
+    /**
+    Default tag for toolbar with Previous/Next buttons -1005.
+    */
+    private static let  kIQPreviousNextButtonToolbarTag =   -1005
+
+    /** Add toolbar if it is required to add on textFields and it's siblings. */
+    internal func addToolbarIfRequired() {
+
+        //Either there is no inputAccessoryView or if accessoryView is not appropriate for current situation(There is Previous/Next/Done toolbar).
+        guard let siblings = responderViews(), !siblings.isEmpty,
+              let textField = textFieldView, textField.responds(to: #selector(setter: UITextField.inputAccessoryView)),
+              (textField.inputAccessoryView == nil ||
+                textField.inputAccessoryView?.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag ||
+                textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag) else {
+            return
+        }
+
+        let startTime = CACurrentMediaTime()
+        showLog(">>>>> \(#function) started >>>>>", indentation: 1)
+
+        showLog("Found \(siblings.count) responder sibling(s)")
+
+        let rightConfiguration: IQBarButtonItemConfiguration
+
+        if let doneBarButtonItemImage = toolbarDoneBarButtonItemImage {
+            rightConfiguration = IQBarButtonItemConfiguration(image: doneBarButtonItemImage, action: #selector(self.doneAction(_:)))
+        } else if let doneBarButtonItemText = toolbarDoneBarButtonItemText {
+            rightConfiguration = IQBarButtonItemConfiguration(title: doneBarButtonItemText, action: #selector(self.doneAction(_:)))
+        } else {
+            rightConfiguration = IQBarButtonItemConfiguration(barButtonSystemItem: .done, action: #selector(self.doneAction(_:)))
+        }
+        rightConfiguration.accessibilityLabel = toolbarDoneBarButtonItemAccessibilityLabel ?? "Done"
+
+        //    If only one object is found, then adding only Done button.
+        if (siblings.count <= 1 && previousNextDisplayMode == .default) || previousNextDisplayMode == .alwaysHide {
+
+            textField.addKeyboardToolbarWithTarget(target: self, titleText: (shouldShowToolbarPlaceholder ? textField.drawingToolbarPlaceholder: nil), rightBarButtonConfiguration: rightConfiguration, previousBarButtonConfiguration: nil, nextBarButtonConfiguration: nil)
+
+            textField.inputAccessoryView?.tag = IQKeyboardManager.kIQDoneButtonToolbarTag //  (Bug ID: #78)
+
+        } else if previousNextDisplayMode == .default || previousNextDisplayMode == .alwaysShow {
+
+            let prevConfiguration: IQBarButtonItemConfiguration
+
+            if let doneBarButtonItemImage = toolbarPreviousBarButtonItemImage {
+                prevConfiguration = IQBarButtonItemConfiguration(image: doneBarButtonItemImage, action: #selector(self.previousAction(_:)))
+            } else if let doneBarButtonItemText = toolbarPreviousBarButtonItemText {
+                prevConfiguration = IQBarButtonItemConfiguration(title: doneBarButtonItemText, action: #selector(self.previousAction(_:)))
+            } else {
+                prevConfiguration = IQBarButtonItemConfiguration(image: (UIImage.keyboardPreviousImage() ?? UIImage()), action: #selector(self.previousAction(_:)))
+            }
+            prevConfiguration.accessibilityLabel = toolbarPreviousBarButtonItemAccessibilityLabel ?? "Previous"
+
+            let nextConfiguration: IQBarButtonItemConfiguration
+
+            if let doneBarButtonItemImage = toolbarNextBarButtonItemImage {
+                nextConfiguration = IQBarButtonItemConfiguration(image: doneBarButtonItemImage, action: #selector(self.nextAction(_:)))
+            } else if let doneBarButtonItemText = toolbarNextBarButtonItemText {
+                nextConfiguration = IQBarButtonItemConfiguration(title: doneBarButtonItemText, action: #selector(self.nextAction(_:)))
+            } else {
+                nextConfiguration = IQBarButtonItemConfiguration(image: (UIImage.keyboardNextImage() ?? UIImage()), action: #selector(self.nextAction(_:)))
+            }
+            nextConfiguration.accessibilityLabel = toolbarNextBarButtonItemAccessibilityLabel ?? "Next"
+
+            textField.addKeyboardToolbarWithTarget(target: self, titleText: (shouldShowToolbarPlaceholder ? textField.drawingToolbarPlaceholder: nil), rightBarButtonConfiguration: rightConfiguration, previousBarButtonConfiguration: prevConfiguration, nextBarButtonConfiguration: nextConfiguration)
+
+            textField.inputAccessoryView?.tag = IQKeyboardManager.kIQPreviousNextButtonToolbarTag //  (Bug ID: #78)
+        }
+
+        let toolbar = textField.keyboardToolbar
+
+        //Setting toolbar tintColor //  (Enhancement ID: #30)
+        toolbar.tintColor = shouldToolbarUsesTextFieldTintColor ? textField.tintColor : toolbarTintColor
+
+        //  Setting toolbar to keyboard.
+        if let textFieldView = textField as? UITextInput {
+
+            //Bar style according to keyboard appearance
+            switch textFieldView.keyboardAppearance {
+
+            case .dark?:
+                toolbar.barStyle = .black
+                toolbar.barTintColor = nil
+            default:
+                toolbar.barStyle = .default
+                toolbar.barTintColor = toolbarBarTintColor
+            }
+        }
+
+        //Setting toolbar title font.   //  (Enhancement ID: #30)
+        if shouldShowToolbarPlaceholder, !textField.shouldHideToolbarPlaceholder {
+
+            //Updating placeholder font to toolbar.     //(Bug ID: #148, #272)
+            if toolbar.titleBarButton.title == nil ||
+                toolbar.titleBarButton.title != textField.drawingToolbarPlaceholder {
+                toolbar.titleBarButton.title = textField.drawingToolbarPlaceholder
+            }
+
+            //Setting toolbar title font.   //  (Enhancement ID: #30)
+            toolbar.titleBarButton.titleFont = placeholderFont
+
+            //Setting toolbar title color.   //  (Enhancement ID: #880)
+            toolbar.titleBarButton.titleColor = placeholderColor
+
+            //Setting toolbar button title color.   //  (Enhancement ID: #880)
+            toolbar.titleBarButton.selectableTitleColor = placeholderButtonColor
+
+        } else {
+            toolbar.titleBarButton.title = nil
+        }
+
+        //In case of UITableView (Special), the next/previous buttons has to be refreshed everytime.    (Bug ID: #56)
+
+        textField.keyboardToolbar.previousBarButton.isEnabled = (siblings.first != textField)   //    If firstTextField, then previous should not be enabled.
+        textField.keyboardToolbar.nextBarButton.isEnabled = (siblings.last != textField)        //    If lastTextField then next should not be enaled.
+
+        let elapsedTime = CACurrentMediaTime() - startTime
+        showLog("<<<<< \(#function) ended: \(elapsedTime) seconds <<<<<", indentation: -1)
+    }
+
+    /** Remove any toolbar if it is IQToolbar. */
+    internal func removeToolbarIfRequired() {    //  (Bug ID: #18)
+
+        guard let siblings = responderViews(), !siblings.isEmpty,
+              let textField = textFieldView, textField.responds(to: #selector(setter: UITextField.inputAccessoryView)),
+              (textField.inputAccessoryView == nil ||
+                textField.inputAccessoryView?.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag ||
+                textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag) else {
+            return
+        }
+
+        let startTime = CACurrentMediaTime()
+        showLog(">>>>> \(#function) started >>>>>", indentation: 1)
+
+        showLog("Found \(siblings.count) responder sibling(s)")
+
+        for view in siblings {
+            if let toolbar = view.inputAccessoryView as? IQToolbar {
+
+                //setInputAccessoryView: check   (Bug ID: #307)
+                if view.responds(to: #selector(setter: UITextField.inputAccessoryView)),
+                    (toolbar.tag == IQKeyboardManager.kIQDoneButtonToolbarTag || toolbar.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag) {
+
+                    if let textField = view as? UITextField {
+                        textField.inputAccessoryView = nil
+                    } else if let textView = view as? UITextView {
+                        textView.inputAccessoryView = nil
+                    }
+
+                    view.reloadInputViews()
+                }
+            }
+        }
+
+        let elapsedTime = CACurrentMediaTime() - startTime
+        showLog("<<<<< \(#function) ended: \(elapsedTime) seconds <<<<<", indentation: -1)
+    }
+
+    /**    reloadInputViews to reload toolbar buttons enable/disable state on the fly Enhancement ID #434. */
+    @objc func reloadInputViews() {
+
+        //If enabled then adding toolbar.
+        if privateIsEnableAutoToolbar() {
+            self.addToolbarIfRequired()
+        } else {
+            self.removeToolbarIfRequired()
+        }
+    }
+}
+
+// MARK: Previous next button actions
+@available(iOSApplicationExtension, unavailable)
+public extension IQKeyboardManager {
+
+    /**
+    Returns YES if can navigate to previous responder textField/textView, otherwise NO.
+    */
+    @objc var canGoPrevious: Bool {
+        //If it is not first textField. then it's previous object canBecomeFirstResponder.
+        guard let textFields = responderViews(), let textFieldRetain = textFieldView, let index = textFields.firstIndex(of: textFieldRetain), index > 0 else {
+            return false
+        }
+        return true
+    }
+
+    /**
+    Returns YES if can navigate to next responder textField/textView, otherwise NO.
+    */
+    @objc var canGoNext: Bool {
+        //If it is not first textField. then it's previous object canBecomeFirstResponder.
+        guard let textFields = responderViews(), let textFieldRetain = textFieldView, let index = textFields.firstIndex(of: textFieldRetain), index < textFields.count-1 else {
+            return false
+        }
+        return true
+    }
+
+    /**
+    Navigate to previous responder textField/textView.
+    */
+    @objc @discardableResult func goPrevious() -> Bool {
+
+        //If it is not first textField. then it's previous object becomeFirstResponder.
+        guard let textFields = responderViews(), let textFieldRetain = textFieldView, let index = textFields.firstIndex(of: textFieldRetain), index > 0 else {
+            return false
+        }
+
+        let nextTextField = textFields[index-1]
+
+        let isAcceptAsFirstResponder = nextTextField.becomeFirstResponder()
+
+        //  If it refuses then becoming previous textFieldView as first responder again.    (Bug ID: #96)
+        if isAcceptAsFirstResponder == false {
+            showLog("Refuses to become first responder: \(nextTextField)")
+        }
+
+        return isAcceptAsFirstResponder
+    }
+
+    /**
+    Navigate to next responder textField/textView.
+    */
+    @objc @discardableResult func goNext() -> Bool {
+
+        //If it is not first textField. then it's previous object becomeFirstResponder.
+        guard let textFields = responderViews(), let textFieldRetain = textFieldView, let index = textFields.firstIndex(of: textFieldRetain), index < textFields.count-1 else {
+            return false
+        }
+
+        let nextTextField = textFields[index+1]
+
+        let isAcceptAsFirstResponder = nextTextField.becomeFirstResponder()
+
+        //  If it refuses then becoming previous textFieldView as first responder again.    (Bug ID: #96)
+        if isAcceptAsFirstResponder == false {
+            showLog("Refuses to become first responder: \(nextTextField)")
+        }
+
+        return isAcceptAsFirstResponder
+    }
+
+    /**    previousAction. */
+    @objc internal func previousAction (_ barButton: IQBarButtonItem) {
+
+        //If user wants to play input Click sound.
+        if shouldPlayInputClicks {
+            //Play Input Click Sound.
+            UIDevice.current.playInputClick()
+        }
+
+        guard canGoPrevious, let textFieldRetain = textFieldView else {
+            return
+        }
+
+        let isAcceptAsFirstResponder = goPrevious()
+
+        var invocation = barButton.invocation
+        var sender = textFieldRetain
+
+        //Handling search bar special case
+        do {
+            if let searchBar = textFieldRetain.textFieldSearchBar() {
+                invocation = searchBar.keyboardToolbar.previousBarButton.invocation
+                sender = searchBar
+            }
+        }
+
+        if isAcceptAsFirstResponder {
+            invocation?.invoke(from: sender)
+        }
+    }
+
+    /**    nextAction. */
+    @objc internal func nextAction (_ barButton: IQBarButtonItem) {
+
+        //If user wants to play input Click sound.
+        if shouldPlayInputClicks {
+            //Play Input Click Sound.
+            UIDevice.current.playInputClick()
+        }
+
+        guard canGoNext, let textFieldRetain = textFieldView else {
+            return
+        }
+
+        let isAcceptAsFirstResponder = goNext()
+
+        var invocation = barButton.invocation
+        var sender = textFieldRetain
+
+        //Handling search bar special case
+        do {
+            if let searchBar = textFieldRetain.textFieldSearchBar() {
+                invocation = searchBar.keyboardToolbar.nextBarButton.invocation
+                sender = searchBar
+            }
+        }
+
+        if isAcceptAsFirstResponder {
+            invocation?.invoke(from: sender)
+        }
+    }
+
+    /**    doneAction. Resigning current textField. */
+    @objc internal func doneAction (_ barButton: IQBarButtonItem) {
+
+        //If user wants to play input Click sound.
+        if shouldPlayInputClicks {
+            //Play Input Click Sound.
+            UIDevice.current.playInputClick()
+        }
+
+        guard let textFieldRetain = textFieldView else {
+            return
+        }
+
+        //Resign textFieldView.
+        let isResignedFirstResponder = resignFirstResponder()
+
+        var invocation = barButton.invocation
+        var sender = textFieldRetain
+
+        //Handling search bar special case
+        do {
+            if let searchBar = textFieldRetain.textFieldSearchBar() {
+                invocation = searchBar.keyboardToolbar.doneBarButton.invocation
+                sender = searchBar
+            }
+        }
+
+        if isResignedFirstResponder {
+            invocation?.invoke(from: sender)
+        }
+    }
+}

+ 365 - 0
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQKeyboardManager+UIKeyboardNotification.swift

@@ -0,0 +1,365 @@
+//
+//  IQKeyboardManager+UIKeyboardNotification.swift
+// https://github.com/hackiftekhar/IQKeyboardManager
+// Copyright (c) 2013-20 Iftekhar Qurashi.
+//
+// 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 - UIKit contains Foundation
+import UIKit
+
+// MARK: UIKeyboard Notifications
+@available(iOSApplicationExtension, unavailable)
+public extension IQKeyboardManager {
+
+    typealias SizeBlock = (_ size: CGSize) -> Void
+
+    private final class KeyboardSizeObserver: NSObject {
+        weak var observer: NSObject?
+        var sizeHandler: (_ size: CGSize) -> Void
+
+        init(observer: NSObject?, sizeHandler: @escaping (_ size: CGSize) -> Void) {
+            self.observer = observer
+            self.sizeHandler = sizeHandler
+        }
+    }
+
+    private struct AssociatedKeys {
+        static var keyboardSizeObservers = "keyboardSizeObservers"
+        static var keyboardLastNotifySize = "keyboardLastNotifySize"
+        static var keyboardShowing = "keyboardShowing"
+        static var keyboardShowNotification = "keyboardShowNotification"
+        static var keyboardFrame = "keyboardFrame"
+        static var animationDuration = "animationDuration"
+        static var animationCurve = "animationCurve"
+    }
+
+    private var keyboardLastNotifySize: CGSize {
+        get {
+            return objc_getAssociatedObject(self, &AssociatedKeys.keyboardLastNotifySize) as? CGSize ?? .zero
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.keyboardLastNotifySize, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+        }
+    }
+
+    private var keyboardSizeObservers: [AnyHashable: SizeBlock] {
+        get {
+            return objc_getAssociatedObject(self, &AssociatedKeys.keyboardSizeObservers) as? [AnyHashable: SizeBlock] ?? [:]
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.keyboardSizeObservers, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+        }
+    }
+
+    @objc func registerKeyboardSizeChange(identifier: AnyHashable, sizeHandler: @escaping SizeBlock) {
+        keyboardSizeObservers[identifier] = sizeHandler
+    }
+
+    @objc func unregisterKeyboardSizeChange(identifier: AnyHashable) {
+        keyboardSizeObservers[identifier] = nil
+    }
+
+    internal func notifyKeyboardSize(size: CGSize) {
+
+        guard !size.equalTo(keyboardLastNotifySize) else {
+            return
+        }
+
+        keyboardLastNotifySize = size
+
+        for block in keyboardSizeObservers.values {
+            block(size)
+        }
+    }
+
+    /**
+     Boolean to know if keyboard is showing.
+     */
+    @objc private(set) var keyboardShowing: Bool {
+        get {
+            return objc_getAssociatedObject(self, &AssociatedKeys.keyboardShowing) as? Bool ?? false
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.keyboardShowing, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+        }
+    }
+
+    /** To save keyboardWillShowNotification. Needed for enable keyboard functionality. */
+    internal var keyboardShowNotification: Notification? {
+        get {
+            return objc_getAssociatedObject(self, &AssociatedKeys.keyboardShowNotification) as? Notification
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.keyboardShowNotification, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+        }
+    }
+
+    /** To save keyboard rame. */
+    @objc private(set) var keyboardFrame: CGRect {
+        get {
+            return objc_getAssociatedObject(self, &AssociatedKeys.keyboardFrame) as? CGRect ?? .zero
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.keyboardFrame, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+        }
+    }
+
+    /** To save keyboard animation duration. */
+    internal var animationDuration: TimeInterval {
+        get {
+            return objc_getAssociatedObject(self, &AssociatedKeys.animationDuration) as? TimeInterval ?? 0.25
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.animationDuration, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+        }
+    }
+
+    /** To mimic the keyboard animation */
+    internal var animationCurve: UIView.AnimationOptions {
+        get {
+            return objc_getAssociatedObject(self, &AssociatedKeys.animationCurve) as? UIView.AnimationOptions ?? .curveEaseOut
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.animationCurve, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+        }
+    }
+
+    /*  UIKeyboardWillShowNotification. */
+    @objc internal func keyboardWillShow(_ notification: Notification) {
+
+        keyboardShowNotification = notification
+
+        //  Boolean to know keyboard is showing/hiding
+        keyboardShowing = true
+
+        let oldKBFrame = keyboardFrame
+
+        if let info = notification.userInfo {
+
+            //  Getting keyboard animation.
+            if let curve = info[UIResponder.keyboardAnimationCurveUserInfoKey] as? UInt {
+                animationCurve = UIView.AnimationOptions(rawValue: curve).union(.beginFromCurrentState)
+            } else {
+                animationCurve = UIView.AnimationOptions.curveEaseOut.union(.beginFromCurrentState)
+            }
+
+            //  Getting keyboard animation duration
+            animationDuration = info[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval ?? 0.25
+
+            //  Getting UIKeyboardSize.
+            if let kbFrame = info[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect {
+
+                keyboardFrame = kbFrame
+                notifyKeyboardSize(size: keyboardFrame.size)
+                showLog("UIKeyboard Frame: \(keyboardFrame)")
+            }
+        }
+
+        guard privateIsEnabled() else {
+            restorePosition()
+            topViewBeginOrigin = IQKeyboardManager.kIQCGPointInvalid
+            return
+        }
+
+        let startTime = CACurrentMediaTime()
+        showLog("⌨️>>>>> \(#function) started >>>>>", indentation: 1)
+
+        showLog("Notification Object:\(notification.object ?? "NULL")")
+
+        //  (Bug ID: #5)
+        if let textFieldView = textFieldView, topViewBeginOrigin.equalTo(IQKeyboardManager.kIQCGPointInvalid) {
+
+            //  keyboard is not showing(At the beginning only). We should save rootViewRect.
+            rootViewController = textFieldView.parentContainerViewController()
+            if let controller = rootViewController {
+
+                if rootViewControllerWhilePopGestureRecognizerActive == controller {
+                    topViewBeginOrigin = topViewBeginOriginWhilePopGestureRecognizerActive
+                } else {
+                    topViewBeginOrigin = controller.view.frame.origin
+                }
+
+                rootViewControllerWhilePopGestureRecognizerActive = nil
+                topViewBeginOriginWhilePopGestureRecognizerActive = IQKeyboardManager.kIQCGPointInvalid
+
+                self.showLog("Saving \(controller) beginning origin: \(self.topViewBeginOrigin)")
+            }
+        }
+
+        //If last restored keyboard size is different(any orientation accure), then refresh. otherwise not.
+        if keyboardFrame.equalTo(oldKBFrame) == false {
+
+            //If textFieldView is inside UITableViewController then let UITableViewController to handle it (Bug ID: #37) (Bug ID: #76) See note:- https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html If it is UIAlertView textField then do not affect anything (Bug ID: #70).
+
+            if keyboardShowing,
+                let textFieldView = textFieldView,
+                textFieldView.isAlertViewTextField() == false {
+
+                //  keyboard is already showing. adjust position.
+                optimizedAdjustPosition()
+            }
+        }
+
+        let elapsedTime = CACurrentMediaTime() - startTime
+        showLog("⌨️<<<<< \(#function) ended: \(elapsedTime) seconds <<<<<", indentation: -1)
+    }
+
+    /*  UIKeyboardDidShowNotification. */
+    @objc internal func keyboardDidShow(_ notification: Notification) {
+
+        guard privateIsEnabled(),
+            let textFieldView = textFieldView,
+            let parentController = textFieldView.parentContainerViewController(), (parentController.modalPresentationStyle == UIModalPresentationStyle.formSheet || parentController.modalPresentationStyle == UIModalPresentationStyle.pageSheet),
+            textFieldView.isAlertViewTextField() == false else {
+                return
+        }
+
+        let startTime = CACurrentMediaTime()
+        showLog("⌨️>>>>> \(#function) started >>>>>", indentation: 1)
+        showLog("Notification Object:\(notification.object ?? "NULL")")
+
+        self.optimizedAdjustPosition()
+
+        let elapsedTime = CACurrentMediaTime() - startTime
+        showLog("⌨️<<<<< \(#function) ended: \(elapsedTime) seconds <<<<<", indentation: -1)
+    }
+
+    /*  UIKeyboardWillHideNotification. So setting rootViewController to it's default frame. */
+    @objc internal func keyboardWillHide(_ notification: Notification?) {
+
+        //If it's not a fake notification generated by [self setEnable:NO].
+        if notification != nil {
+            keyboardShowNotification = nil
+        }
+
+        //  Boolean to know keyboard is showing/hiding
+        keyboardShowing = false
+
+        if let info = notification?.userInfo {
+
+            //  Getting keyboard animation.
+            if let curve = info[UIResponder.keyboardAnimationCurveUserInfoKey] as? UInt {
+                animationCurve = UIView.AnimationOptions(rawValue: curve).union(.beginFromCurrentState)
+            } else {
+                animationCurve = UIView.AnimationOptions.curveEaseOut.union(.beginFromCurrentState)
+            }
+
+            //  Getting keyboard animation duration
+            animationDuration = info[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval ?? 0.25
+        }
+
+        //If not enabled then do nothing.
+        guard privateIsEnabled() else {
+            return
+        }
+
+        let startTime = CACurrentMediaTime()
+        showLog("⌨️>>>>> \(#function) started >>>>>", indentation: 1)
+        showLog("Notification Object:\(notification?.object ?? "NULL")")
+
+        //Commented due to #56. Added all the conditions below to handle WKWebView's textFields.    (Bug ID: #56)
+        //  We are unable to get textField object while keyboard showing on WKWebView's textField.  (Bug ID: #11)
+        //    if (_textFieldView == nil)   return
+
+        //Restoring the contentOffset of the lastScrollView
+        if let lastScrollView = lastScrollView {
+
+            UIView.animate(withDuration: animationDuration, delay: 0, options: animationCurve, animations: { () -> Void in
+
+                if lastScrollView.contentInset != self.startingContentInsets {
+                    self.showLog("Restoring contentInset to: \(self.startingContentInsets)")
+                    lastScrollView.contentInset = self.startingContentInsets
+                    lastScrollView.scrollIndicatorInsets = self.startingScrollIndicatorInsets
+                }
+
+                if lastScrollView.shouldRestoreScrollViewContentOffset, !lastScrollView.contentOffset.equalTo(self.startingContentOffset) {
+                    self.showLog("Restoring contentOffset to: \(self.startingContentOffset)")
+
+                    let animatedContentOffset = self.textFieldView?.superviewOfClassType(UIStackView.self, belowView: lastScrollView) != nil  //  (Bug ID: #1365, #1508, #1541)
+
+                    if animatedContentOffset {
+                        lastScrollView.setContentOffset(self.startingContentOffset, animated: UIView.areAnimationsEnabled)
+                    } else {
+                        lastScrollView.contentOffset = self.startingContentOffset
+                    }
+                }
+
+                // TODO: restore scrollView state
+                // This is temporary solution. Have to implement the save and restore scrollView state
+                var superScrollView: UIScrollView? = lastScrollView
+
+                while let scrollView = superScrollView {
+
+                    let contentSize = CGSize(width: max(scrollView.contentSize.width, scrollView.frame.width), height: max(scrollView.contentSize.height, scrollView.frame.height))
+
+                    let minimumY = contentSize.height - scrollView.frame.height
+
+                    if minimumY < scrollView.contentOffset.y {
+
+                        let newContentOffset = CGPoint(x: scrollView.contentOffset.x, y: minimumY)
+                        if scrollView.contentOffset.equalTo(newContentOffset) == false {
+
+                            let animatedContentOffset = self.textFieldView?.superviewOfClassType(UIStackView.self, belowView: scrollView) != nil  //  (Bug ID: #1365, #1508, #1541)
+
+                            if animatedContentOffset {
+                                scrollView.setContentOffset(newContentOffset, animated: UIView.areAnimationsEnabled)
+                            } else {
+                                scrollView.contentOffset = newContentOffset
+                            }
+
+                            self.showLog("Restoring contentOffset to: \(self.startingContentOffset)")
+                        }
+                    }
+
+                    superScrollView = scrollView.superviewOfClassType(UIScrollView.self) as? UIScrollView
+                }
+            })
+        }
+
+        restorePosition()
+
+        //Reset all values
+        lastScrollView = nil
+        keyboardFrame = CGRect.zero
+        notifyKeyboardSize(size: keyboardFrame.size)
+        startingContentInsets = UIEdgeInsets()
+        startingScrollIndicatorInsets = UIEdgeInsets()
+        startingContentOffset = CGPoint.zero
+        //    topViewBeginRect = CGRectZero    //Commented due to #82
+
+        let elapsedTime = CACurrentMediaTime() - startTime
+        showLog("⌨️<<<<< \(#function) ended: \(elapsedTime) seconds <<<<<", indentation: -1)
+    }
+
+    @objc internal func keyboardDidHide(_ notification: Notification) {
+
+        let startTime = CACurrentMediaTime()
+        showLog("⌨️>>>>> \(#function) started >>>>>", indentation: 1)
+        showLog("Notification Object:\(notification.object ?? "NULL")")
+
+        topViewBeginOrigin = IQKeyboardManager.kIQCGPointInvalid
+
+        keyboardFrame = CGRect.zero
+        notifyKeyboardSize(size: keyboardFrame.size)
+
+        let elapsedTime = CACurrentMediaTime() - startTime
+        showLog("⌨️<<<<< \(#function) ended: \(elapsedTime) seconds <<<<<", indentation: -1)
+    }
+}

+ 227 - 0
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQKeyboardManager+UITextFieldViewNotification.swift

@@ -0,0 +1,227 @@
+//
+//  IQKeyboardManager+UITextFieldViewNotification.swift
+// https://github.com/hackiftekhar/IQKeyboardManager
+// Copyright (c) 2013-20 Iftekhar Qurashi.
+//
+// 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 - UIKit contains Foundation
+import UIKit
+
+// MARK: UITextField/UITextView Notifications
+@available(iOSApplicationExtension, unavailable)
+internal extension IQKeyboardManager {
+
+    private struct AssociatedKeys {
+        static var textFieldView = "textFieldView"
+        static var topViewBeginOrigin = "topViewBeginOrigin"
+        static var rootViewController = "rootViewController"
+        static var rootViewControllerWhilePopGestureRecognizerActive = "rootViewControllerWhilePopGestureRecognizerActive"
+        static var topViewBeginOriginWhilePopGestureRecognizerActive = "topViewBeginOriginWhilePopGestureRecognizerActive"
+    }
+
+    /** To save UITextField/UITextView object voa textField/textView notifications. */
+    weak var textFieldView: UIView? {
+        get {
+            return (objc_getAssociatedObject(self, &AssociatedKeys.textFieldView) as? WeakObjectContainer)?.object as? UIView
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.textFieldView, WeakObjectContainer(object: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+        }
+    }
+
+    var topViewBeginOrigin: CGPoint {
+        get {
+            return objc_getAssociatedObject(self, &AssociatedKeys.topViewBeginOrigin) as? CGPoint ?? IQKeyboardManager.kIQCGPointInvalid
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.topViewBeginOrigin, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+        }
+    }
+
+    /** To save rootViewController */
+    weak var rootViewController: UIViewController? {
+        get {
+            return (objc_getAssociatedObject(self, &AssociatedKeys.rootViewController) as? WeakObjectContainer)?.object as? UIViewController
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.rootViewController, WeakObjectContainer(object: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+        }
+    }
+
+    /** To overcome with popGestureRecognizer issue Bug ID: #1361 */
+    weak var rootViewControllerWhilePopGestureRecognizerActive: UIViewController? {
+        get {
+            return (objc_getAssociatedObject(self, &AssociatedKeys.rootViewControllerWhilePopGestureRecognizerActive) as? WeakObjectContainer)?.object as? UIViewController
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.rootViewControllerWhilePopGestureRecognizerActive, WeakObjectContainer(object: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+        }
+    }
+
+    var topViewBeginOriginWhilePopGestureRecognizerActive: CGPoint {
+        get {
+            return objc_getAssociatedObject(self, &AssociatedKeys.topViewBeginOriginWhilePopGestureRecognizerActive) as? CGPoint ?? IQKeyboardManager.kIQCGPointInvalid
+        }
+        set(newValue) {
+            objc_setAssociatedObject(self, &AssociatedKeys.topViewBeginOriginWhilePopGestureRecognizerActive, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+        }
+    }
+
+    /**  UITextFieldTextDidBeginEditingNotification, UITextViewTextDidBeginEditingNotification. Fetching UITextFieldView object. */
+    @objc func textFieldViewDidBeginEditing(_ notification: Notification) {
+
+        guard let object = notification.object as? UIView, let isKeyWindow = object.window?.isKeyWindow, isKeyWindow else {
+            return
+        }
+
+        let startTime = CACurrentMediaTime()
+        showLog("📝>>>>> \(#function) started >>>>>", indentation: 1)
+        showLog("Notification Object:\(notification.object ?? "NULL")")
+
+        //  Getting object
+        textFieldView = notification.object as? UIView
+
+        if overrideKeyboardAppearance, let textInput = textFieldView as? UITextInput, textInput.keyboardAppearance != keyboardAppearance {
+            //Setting textField keyboard appearance and reloading inputViews.
+            if let textFieldView = textFieldView as? UITextField {
+                textFieldView.keyboardAppearance = keyboardAppearance
+            } else if  let textFieldView = textFieldView as? UITextView {
+                textFieldView.keyboardAppearance = keyboardAppearance
+            }
+            textFieldView?.reloadInputViews()
+        }
+
+        //If autoToolbar enable, then add toolbar on all the UITextField/UITextView's if required.
+        if privateIsEnableAutoToolbar() {
+
+            //UITextView special case. Keyboard Notification is firing before textView notification so we need to resign it first and then again set it as first responder to add toolbar on it.
+            if let textView = textFieldView as? UIScrollView, textView.responds(to: #selector(getter: UITextView.isEditable)),
+                textView.inputAccessoryView == nil {
+
+                UIView.animate(withDuration: 0.00001, delay: 0, options: animationCurve, animations: { () -> Void in
+
+                    self.addToolbarIfRequired()
+
+                }, completion: { (_) -> Void in
+
+                    //On textView toolbar didn't appear on first time, so forcing textView to reload it's inputViews.
+                    textView.reloadInputViews()
+                })
+            } else {
+                //Adding toolbar
+                addToolbarIfRequired()
+            }
+        } else {
+            removeToolbarIfRequired()
+        }
+
+        resignFirstResponderGesture.isEnabled = privateShouldResignOnTouchOutside()
+        textFieldView?.window?.addGestureRecognizer(resignFirstResponderGesture)    //   (Enhancement ID: #14)
+
+        if privateIsEnabled() == false {
+            restorePosition()
+            topViewBeginOrigin = IQKeyboardManager.kIQCGPointInvalid
+        } else {
+            if topViewBeginOrigin.equalTo(IQKeyboardManager.kIQCGPointInvalid) {    //  (Bug ID: #5)
+
+                rootViewController = textFieldView?.parentContainerViewController()
+
+                if let controller = rootViewController {
+
+                    if rootViewControllerWhilePopGestureRecognizerActive == controller {
+                        topViewBeginOrigin = topViewBeginOriginWhilePopGestureRecognizerActive
+                    } else {
+                        topViewBeginOrigin = controller.view.frame.origin
+                    }
+
+                    rootViewControllerWhilePopGestureRecognizerActive = nil
+                    topViewBeginOriginWhilePopGestureRecognizerActive = IQKeyboardManager.kIQCGPointInvalid
+
+                    self.showLog("Saving \(controller) beginning origin: \(self.topViewBeginOrigin)")
+                }
+            }
+
+            //If textFieldView is inside ignored responder then do nothing. (Bug ID: #37, #74, #76)
+            //See notes:- https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html If it is UIAlertView textField then do not affect anything (Bug ID: #70).
+            if keyboardShowing,
+                let textFieldView = textFieldView,
+                textFieldView.isAlertViewTextField() == false {
+
+                //  keyboard is already showing. adjust position.
+                optimizedAdjustPosition()
+            }
+        }
+
+        let elapsedTime = CACurrentMediaTime() - startTime
+        showLog("📝<<<<< \(#function) ended: \(elapsedTime) seconds <<<<<", indentation: -1)
+    }
+
+    /**  UITextFieldTextDidEndEditingNotification, UITextViewTextDidEndEditingNotification. Removing fetched object. */
+    @objc func textFieldViewDidEndEditing(_ notification: Notification) {
+
+        guard let object = notification.object as? UIView, let isKeyWindow = object.window?.isKeyWindow, isKeyWindow else {
+            return
+        }
+
+        let startTime = CACurrentMediaTime()
+        showLog("📝>>>>> \(#function) started >>>>>", indentation: 1)
+        showLog("Notification Object:\(notification.object ?? "NULL")")
+
+        //Removing gesture recognizer   (Enhancement ID: #14)
+        textFieldView?.window?.removeGestureRecognizer(resignFirstResponderGesture)
+
+        // We check if there's a change in original frame or not.
+
+        if let textView = textFieldView as? UIScrollView, textView.responds(to: #selector(getter: UITextView.isEditable)) {
+
+            if isTextViewContentInsetChanged {
+                self.isTextViewContentInsetChanged = false
+
+                if textView.contentInset != self.startingTextViewContentInsets {
+                    self.showLog("Restoring textView.contentInset to: \(self.startingTextViewContentInsets)")
+
+                    UIView.animate(withDuration: animationDuration, delay: 0, options: animationCurve, animations: { () -> Void in
+
+                        //Setting textField to it's initial contentInset
+                        textView.contentInset = self.startingTextViewContentInsets
+                        textView.scrollIndicatorInsets = self.startingTextViewScrollIndicatorInsets
+
+                    }, completion: { (_) -> Void in })
+                }
+            }
+        }
+
+        //Setting object to nil
+#if swift(>=5.7)
+        if #available(iOS 16.0, *), let textView = object as? UITextView, textView.isFindInteractionEnabled {
+                //Not setting it nil, because it may be doing find interaction.
+                //As of now, here textView.findInteraction?.isFindNavigatorVisible returns false
+                //So there is no way to detect if this is dismissed due to findInteraction
+        } else {
+            textFieldView = nil
+        }
+ #else
+        textFieldView = nil
+#endif
+
+        let elapsedTime = CACurrentMediaTime() - startTime
+        showLog("📝<<<<< \(#function) ended: \(elapsedTime) seconds <<<<<", indentation: -1)
+    }
+}

+ 424 - 0
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQKeyboardManager.swift

@@ -0,0 +1,424 @@
+//
+//  IQKeyboardManager.swift
+// https://github.com/hackiftekhar/IQKeyboardManager
+// Copyright (c) 2013-20 Iftekhar Qurashi.
+//
+// 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 - UIKit contains Foundation
+import UIKit
+import CoreGraphics
+import QuartzCore
+
+// MARK: IQToolbar tags
+
+/**
+Codeless drop-in universal library allows to prevent issues of keyboard sliding up and cover UITextField/UITextView. Neither need to write any code nor any setup required and much more. A generic version of KeyboardManagement. https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html
+*/
+
+@available(iOSApplicationExtension, unavailable)
+@objc public final class IQKeyboardManager: NSObject {
+
+    /**
+    Returns the default singleton instance.
+    */
+    @objc public static let shared = IQKeyboardManager()
+
+    /**
+     Invalid point value.
+     */
+    internal static let kIQCGPointInvalid = CGPoint.init(x: CGFloat.greatestFiniteMagnitude, y: CGFloat.greatestFiniteMagnitude)
+
+    // MARK: UIKeyboard handling
+
+    /**
+    Enable/disable managing distance between keyboard and textField. Default is YES(Enabled when class loads in `+(void)load` method).
+    */
+    @objc public var enable = false {
+
+        didSet {
+            //If not enable, enable it.
+            if enable, !oldValue {
+                //If keyboard is currently showing. Sending a fake notification for keyboardWillHide to retain view's original position.
+                if let notification = keyboardShowNotification {
+                    keyboardWillShow(notification)
+                }
+                showLog("Enabled")
+            } else if !enable, oldValue {   //If not disable, desable it.
+                keyboardWillHide(nil)
+                showLog("Disabled")
+            }
+        }
+    }
+
+    /**
+    To set keyboard distance from textField. can't be less than zero. Default is 10.0.
+    */
+    @objc public var keyboardDistanceFromTextField: CGFloat = 10.0
+
+    // MARK: IQToolbar handling
+
+    /**
+    Automatic add the IQToolbar functionality. Default is YES.
+    */
+    @objc public var enableAutoToolbar = true {
+        didSet {
+            privateIsEnableAutoToolbar() ? addToolbarIfRequired() : removeToolbarIfRequired()
+
+            let enableToolbar = enableAutoToolbar ? "Yes" : "NO"
+
+            showLog("enableAutoToolbar: \(enableToolbar)")
+        }
+    }
+
+    /**
+     /**
+     IQAutoToolbarBySubviews:   Creates Toolbar according to subview's hirarchy of Textfield's in view.
+     IQAutoToolbarByTag:        Creates Toolbar according to tag property of TextField's.
+     IQAutoToolbarByPosition:   Creates Toolbar according to the y,x position of textField in it's superview coordinate.
+
+     Default is IQAutoToolbarBySubviews.
+     */
+    AutoToolbar managing behaviour. Default is IQAutoToolbarBySubviews.
+    */
+    @objc public var toolbarManageBehaviour = IQAutoToolbarManageBehaviour.bySubviews
+
+    /**
+    If YES, then uses textField's tintColor property for IQToolbar, otherwise tint color is default. Default is NO.
+    */
+    @objc public var shouldToolbarUsesTextFieldTintColor = false
+
+    /**
+    This is used for toolbar.tintColor when textfield.keyboardAppearance is UIKeyboardAppearanceDefault. If shouldToolbarUsesTextFieldTintColor is YES then this property is ignored. Default is nil and uses black color.
+    */
+    @objc public var toolbarTintColor: UIColor?
+
+    /**
+     This is used for toolbar.barTintColor. Default is nil.
+     */
+    @objc public var toolbarBarTintColor: UIColor?
+
+    /**
+     IQPreviousNextDisplayModeDefault:      Show NextPrevious when there are more than 1 textField otherwise hide.
+     IQPreviousNextDisplayModeAlwaysHide:   Do not show NextPrevious buttons in any case.
+     IQPreviousNextDisplayModeAlwaysShow:   Always show nextPrevious buttons, if there are more than 1 textField then both buttons will be visible but will be shown as disabled.
+     */
+    @objc public var previousNextDisplayMode = IQPreviousNextDisplayMode.default
+
+    /**
+     Toolbar previous/next/done button icon, If nothing is provided then check toolbarDoneBarButtonItemText to draw done button.
+     */
+    @objc public var toolbarPreviousBarButtonItemImage: UIImage?
+    @objc public var toolbarNextBarButtonItemImage: UIImage?
+    @objc public var toolbarDoneBarButtonItemImage: UIImage?
+
+    /**
+     Toolbar previous/next/done button text, If nothing is provided then system default 'UIBarButtonSystemItemDone' will be used.
+     */
+    @objc public var toolbarPreviousBarButtonItemText: String?
+    @objc public var toolbarPreviousBarButtonItemAccessibilityLabel: String?
+    @objc public var toolbarNextBarButtonItemText: String?
+    @objc public var toolbarNextBarButtonItemAccessibilityLabel: String?
+    @objc public var toolbarDoneBarButtonItemText: String?
+    @objc public var toolbarDoneBarButtonItemAccessibilityLabel: String?
+
+    /**
+    If YES, then it add the textField's placeholder text on IQToolbar. Default is YES.
+    */
+    @objc public var shouldShowToolbarPlaceholder = true
+
+    /**
+    Placeholder Font. Default is nil.
+    */
+    @objc public var placeholderFont: UIFont?
+
+    /**
+     Placeholder Color. Default is nil. Which means lightGray
+     */
+    @objc public var placeholderColor: UIColor?
+
+    /**
+     Placeholder Button Color when it's treated as button. Default is nil.
+     */
+    @objc public var placeholderButtonColor: UIColor?
+
+    // MARK: UIKeyboard appearance overriding
+
+    /**
+    Override the keyboardAppearance for all textField/textView. Default is NO.
+    */
+    @objc public var overrideKeyboardAppearance = false
+
+    /**
+    If overrideKeyboardAppearance is YES, then all the textField keyboardAppearance is set using this property.
+    */
+    @objc public var keyboardAppearance = UIKeyboardAppearance.default
+
+    // MARK: UITextField/UITextView Next/Previous/Resign handling
+
+    /**
+    Resigns Keyboard on touching outside of UITextField/View. Default is NO.
+    */
+    @objc public var shouldResignOnTouchOutside = false {
+
+        didSet {
+            resignFirstResponderGesture.isEnabled = privateShouldResignOnTouchOutside()
+
+            let shouldResign = shouldResignOnTouchOutside ? "Yes" : "NO"
+
+            showLog("shouldResignOnTouchOutside: \(shouldResign)")
+        }
+    }
+
+    /** TapGesture to resign keyboard on view's touch. It's a readonly property and exposed only for adding/removing dependencies if your added gesture does have collision with this one */
+    @objc lazy public var resignFirstResponderGesture: UITapGestureRecognizer = {
+
+        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapRecognized(_:)))
+        tapGesture.cancelsTouchesInView = false
+        tapGesture.delegate = self
+
+        return tapGesture
+    }()
+
+    /*******************************************/
+
+    /**
+    Resigns currently first responder field.
+    */
+    @objc @discardableResult public func resignFirstResponder() -> Bool {
+
+        guard let textFieldRetain = textFieldView else {
+            return false
+        }
+
+        //Resigning first responder
+        guard textFieldRetain.resignFirstResponder() else {
+            showLog("Refuses to resign first responder: \(textFieldRetain)")
+            //  If it refuses then becoming it as first responder again.    (Bug ID: #96)
+            //If it refuses to resign then becoming it first responder again for getting notifications callback.
+            textFieldRetain.becomeFirstResponder()
+            return false
+        }
+        return true
+    }
+
+    // MARK: UISound handling
+
+    /**
+    If YES, then it plays inputClick sound on next/previous/done click.
+    */
+    @objc public var shouldPlayInputClicks = true
+
+    // MARK: UIAnimation handling
+
+    /**
+    If YES, then calls 'setNeedsLayout' and 'layoutIfNeeded' on any frame update of to viewController's view.
+    */
+    @objc public var layoutIfNeededOnUpdate = false
+
+    // MARK: Class Level disabling methods
+
+    /**
+     Disable distance handling within the scope of disabled distance handling viewControllers classes. Within this scope, 'enabled' property is ignored. Class should be kind of UIViewController.
+     */
+    @objc public var disabledDistanceHandlingClasses  = [UIViewController.Type]()
+
+    /**
+     Enable distance handling within the scope of enabled distance handling viewControllers classes. Within this scope, 'enabled' property is ignored. Class should be kind of UIViewController. If same Class is added in disabledDistanceHandlingClasses list, then enabledDistanceHandlingClasses will be ignored.
+     */
+    @objc public var enabledDistanceHandlingClasses  = [UIViewController.Type]()
+
+    /**
+     Disable automatic toolbar creation within the scope of disabled toolbar viewControllers classes. Within this scope, 'enableAutoToolbar' property is ignored. Class should be kind of UIViewController.
+     */
+    @objc public var disabledToolbarClasses  = [UIViewController.Type]()
+
+    /**
+     Enable automatic toolbar creation within the scope of enabled toolbar viewControllers classes. Within this scope, 'enableAutoToolbar' property is ignored. Class should be kind of UIViewController. If same Class is added in disabledToolbarClasses list, then enabledToolbarClasses will be ignore.
+     */
+    @objc public var enabledToolbarClasses  = [UIViewController.Type]()
+
+    /**
+     Allowed subclasses of UIView to add all inner textField, this will allow to navigate between textField contains in different superview. Class should be kind of UIView.
+     */
+    @objc public var toolbarPreviousNextAllowedClasses  = [UIView.Type]()
+
+    /**
+     Disabled classes to ignore 'shouldResignOnTouchOutside' property, Class should be kind of UIViewController.
+     */
+    @objc public var disabledTouchResignedClasses  = [UIViewController.Type]()
+
+    /**
+     Enabled classes to forcefully enable 'shouldResignOnTouchOutsite' property. Class should be kind of UIViewController. If same Class is added in disabledTouchResignedClasses list, then enabledTouchResignedClasses will be ignored.
+     */
+    @objc public var enabledTouchResignedClasses  = [UIViewController.Type]()
+
+    /**
+     if shouldResignOnTouchOutside is enabled then you can customise the behaviour to not recognise gesture touches on some specific view subclasses. Class should be kind of UIView. Default is [UIControl, UINavigationBar]
+     */
+    @objc public var touchResignedGestureIgnoreClasses  = [UIView.Type]()
+
+    // MARK: Third Party Library support
+    /// Add TextField/TextView Notifications customised Notifications. For example while using YYTextView https://github.com/ibireme/YYText
+
+    /**
+    Add/Remove customised Notification for third party customised TextField/TextView. Please be aware that the Notification object must be idential to UITextField/UITextView Notification objects and customised TextField/TextView support must be idential to UITextField/UITextView.
+    @param didBeginEditingNotificationName This should be identical to UITextViewTextDidBeginEditingNotification
+    @param didEndEditingNotificationName This should be identical to UITextViewTextDidEndEditingNotification
+    */
+
+    @objc public func registerTextFieldViewClass(_ aClass: UIView.Type, didBeginEditingNotificationName: String, didEndEditingNotificationName: String) {
+
+        NotificationCenter.default.addObserver(self, selector: #selector(self.textFieldViewDidBeginEditing(_:)), name: Notification.Name(rawValue: didBeginEditingNotificationName), object: nil)
+        NotificationCenter.default.addObserver(self, selector: #selector(self.textFieldViewDidEndEditing(_:)), name: Notification.Name(rawValue: didEndEditingNotificationName), object: nil)
+    }
+
+    @objc public func unregisterTextFieldViewClass(_ aClass: UIView.Type, didBeginEditingNotificationName: String, didEndEditingNotificationName: String) {
+
+        NotificationCenter.default.removeObserver(self, name: Notification.Name(rawValue: didBeginEditingNotificationName), object: nil)
+        NotificationCenter.default.removeObserver(self, name: Notification.Name(rawValue: didEndEditingNotificationName), object: nil)
+    }
+
+    /**************************************************************************************/
+    internal struct WeakObjectContainer {
+        weak var object: AnyObject?
+    }
+
+    /**************************************************************************************/
+
+    // MARK: Initialization/Deinitialization
+
+    /*  Singleton Object Initialization. */
+    override init() {
+
+        super.init()
+
+        self.registerAllNotifications()
+
+        //Creating gesture for @shouldResignOnTouchOutside. (Enhancement ID: #14)
+        resignFirstResponderGesture.isEnabled = shouldResignOnTouchOutside
+
+        //Loading IQToolbar, IQTitleBarButtonItem, IQBarButtonItem to fix first time keyboard appearance delay (Bug ID: #550)
+        //If you experience exception breakpoint issue at below line then try these solutions https://stackoverflow.com/questions/27375640/all-exception-break-point-is-stopping-for-no-reason-on-simulator
+        let textField = UITextField()
+        textField.addDoneOnKeyboardWithTarget(nil, action: #selector(self.doneAction(_:)))
+        textField.addPreviousNextDoneOnKeyboardWithTarget(nil, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), doneAction: #selector(self.doneAction(_:)))
+
+        disabledDistanceHandlingClasses.append(UITableViewController.self)
+        disabledDistanceHandlingClasses.append(UIAlertController.self)
+        disabledToolbarClasses.append(UIAlertController.self)
+        disabledTouchResignedClasses.append(UIAlertController.self)
+        toolbarPreviousNextAllowedClasses.append(UITableView.self)
+        toolbarPreviousNextAllowedClasses.append(UICollectionView.self)
+        toolbarPreviousNextAllowedClasses.append(IQPreviousNextView.self)
+        touchResignedGestureIgnoreClasses.append(UIControl.self)
+        touchResignedGestureIgnoreClasses.append(UINavigationBar.self)
+    }
+
+    deinit {
+        //  Disable the keyboard manager.
+        enable = false
+    }
+
+    /** Getting keyWindow. */
+    internal func keyWindow() -> UIWindow? {
+
+        if let keyWindow = textFieldView?.window {
+            return keyWindow
+        } else {
+
+            struct Static {
+                /** @abstract   Save keyWindow object for reuse.
+                @discussion Sometimes [[UIApplication sharedApplication] keyWindow] is returning nil between the app.   */
+                static weak var keyWindow: UIWindow?
+            }
+
+            var originalKeyWindow: UIWindow?
+
+            #if swift(>=5.1)
+            if #available(iOS 13, *) {
+                originalKeyWindow = UIApplication.shared.connectedScenes
+                    .compactMap { $0 as? UIWindowScene }
+                    .flatMap { $0.windows }
+                    .first(where: { $0.isKeyWindow })
+            } else {
+                originalKeyWindow = UIApplication.shared.keyWindow
+            }
+            #else
+            originalKeyWindow = UIApplication.shared.keyWindow
+            #endif
+
+            //If original key window is not nil and the cached keywindow is also not original keywindow then changing keywindow.
+            if let originalKeyWindow = originalKeyWindow {
+                Static.keyWindow = originalKeyWindow
+            }
+
+            //Return KeyWindow
+            return Static.keyWindow
+        }
+    }
+
+    // MARK: Public Methods
+
+    /*  Refreshes textField/textView position if any external changes is explicitly made by user.   */
+    @objc public func reloadLayoutIfNeeded() {
+
+        guard privateIsEnabled(),
+            keyboardShowing,
+            topViewBeginOrigin.equalTo(IQKeyboardManager.kIQCGPointInvalid) == false, let textFieldView = textFieldView,
+            textFieldView.isAlertViewTextField() == false else {
+                return
+        }
+        optimizedAdjustPosition()
+    }
+}
+
+@available(iOSApplicationExtension, unavailable)
+extension IQKeyboardManager: UIGestureRecognizerDelegate {
+
+    /** Resigning on tap gesture.   (Enhancement ID: #14)*/
+    @objc internal func tapRecognized(_ gesture: UITapGestureRecognizer) {
+
+        if gesture.state == .ended {
+
+            //Resigning currently responder textField.
+            resignFirstResponder()
+        }
+    }
+
+    /** Note: returning YES is guaranteed to allow simultaneous recognition. returning NO is not guaranteed to prevent simultaneous recognition, as the other gesture's delegate may return YES. */
+    @objc public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
+        return false
+    }
+
+    /** To not detect touch events in a subclass of UIControl, these may have added their own selector for specific work */
+    @objc public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
+        //  Should not recognize gesture if the clicked view is either UIControl or UINavigationBar(<Back button etc...)    (Bug ID: #145)
+
+        for ignoreClass in touchResignedGestureIgnoreClasses {
+
+            if touch.view?.isKind(of: ignoreClass) ?? false {
+                return false
+            }
+        }
+
+        return true
+    }
+
+}

+ 645 - 0
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQKeyboardReturnKeyHandler.swift

@@ -0,0 +1,645 @@
+//
+//  IQKeyboardReturnKeyHandler.swift
+// https://github.com/hackiftekhar/IQKeyboardManager
+// Copyright (c) 2013-20 Iftekhar Qurashi.
+//
+// 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 - UIKit contains Foundation
+import UIKit
+
+@available(iOSApplicationExtension, unavailable)
+private final class IQTextFieldViewInfoModal: NSObject {
+
+    fileprivate weak var textFieldDelegate: UITextFieldDelegate?
+    fileprivate weak var textViewDelegate: UITextViewDelegate?
+    fileprivate weak var textFieldView: UIView?
+    fileprivate var originalReturnKeyType = UIReturnKeyType.default
+
+    init(textFieldView: UIView?, textFieldDelegate: UITextFieldDelegate?, textViewDelegate: UITextViewDelegate?, originalReturnKeyType: UIReturnKeyType = .default) {
+        self.textFieldView = textFieldView
+        self.textFieldDelegate = textFieldDelegate
+        self.textViewDelegate = textViewDelegate
+        self.originalReturnKeyType = originalReturnKeyType
+    }
+}
+
+/**
+Manages the return key to work like next/done in a view hierarchy.
+*/
+@available(iOSApplicationExtension, unavailable)
+@objc public final class IQKeyboardReturnKeyHandler: NSObject {
+
+    // MARK: Settings
+
+    /**
+    Delegate of textField/textView.
+    */
+    @objc public weak var delegate: (UITextFieldDelegate & UITextViewDelegate)?
+
+    /**
+    Set the last textfield return key type. Default is UIReturnKeyDefault.
+    */
+    @objc public var lastTextFieldReturnKeyType: UIReturnKeyType = UIReturnKeyType.default {
+
+        didSet {
+
+            for modal in textFieldInfoCache {
+
+                if let view = modal.textFieldView {
+                    updateReturnKeyTypeOnTextField(view)
+                }
+            }
+        }
+    }
+
+    // MARK: Initialization/Deinitialization
+
+    @objc public override init() {
+        super.init()
+    }
+
+    /**
+    Add all the textFields available in UIViewController's view.
+    */
+    @objc public init(controller: UIViewController) {
+        super.init()
+
+        addResponderFromView(controller.view)
+    }
+
+    deinit {
+
+        for modal in textFieldInfoCache {
+
+            if let textField = modal.textFieldView as? UITextField {
+                textField.returnKeyType = modal.originalReturnKeyType
+
+                textField.delegate = modal.textFieldDelegate
+
+            } else if let textView = modal.textFieldView as? UITextView {
+
+                textView.returnKeyType = modal.originalReturnKeyType
+
+                textView.delegate = modal.textViewDelegate
+            }
+        }
+
+        textFieldInfoCache.removeAll()
+    }
+
+    // MARK: Private variables
+    private var textFieldInfoCache          =   [IQTextFieldViewInfoModal]()
+
+    // MARK: Private Functions
+    private func textFieldViewCachedInfo(_ textField: UIView) -> IQTextFieldViewInfoModal? {
+
+        for modal in textFieldInfoCache {
+
+            if let view = modal.textFieldView {
+
+                if view == textField {
+                    return modal
+                }
+            }
+        }
+
+        return nil
+    }
+
+    private func updateReturnKeyTypeOnTextField(_ view: UIView) {
+        var superConsideredView: UIView?
+
+        //If find any consider responderView in it's upper hierarchy then will get deepResponderView. (Bug ID: #347)
+        for disabledClass in IQKeyboardManager.shared.toolbarPreviousNextAllowedClasses {
+
+            superConsideredView = view.superviewOfClassType(disabledClass)
+
+            if superConsideredView != nil {
+                break
+            }
+        }
+
+        var textFields = [UIView]()
+
+        //If there is a tableView in view's hierarchy, then fetching all it's subview that responds.
+        if let unwrappedTableView = superConsideredView {     //   (Enhancement ID: #22)
+            textFields = unwrappedTableView.deepResponderViews()
+        } else {  //Otherwise fetching all the siblings
+
+            textFields = view.responderSiblings()
+
+            //Sorting textFields according to behaviour
+            switch IQKeyboardManager.shared.toolbarManageBehaviour {
+                //If needs to sort it by tag
+            case .byTag:        textFields = textFields.sortedArrayByTag()
+                //If needs to sort it by Position
+            case .byPosition:   textFields = textFields.sortedArrayByPosition()
+            default:    break
+            }
+        }
+
+        if let lastView = textFields.last {
+
+            if let textField = view as? UITextField {
+
+                //If it's the last textField in responder view, else next
+                textField.returnKeyType = (view == lastView)    ?   lastTextFieldReturnKeyType: UIReturnKeyType.next
+            } else if let textView = view as? UITextView {
+
+                //If it's the last textField in responder view, else next
+                textView.returnKeyType = (view == lastView)    ?   lastTextFieldReturnKeyType: UIReturnKeyType.next
+            }
+        }
+    }
+
+    // MARK: Registering/Unregistering textFieldView
+
+    /**
+    Should pass UITextField/UITextView intance. Assign textFieldView delegate to self, change it's returnKeyType.
+    
+    @param view UITextField/UITextView object to register.
+    */
+    @objc public func addTextFieldView(_ view: UIView) {
+
+        let modal = IQTextFieldViewInfoModal(textFieldView: view, textFieldDelegate: nil, textViewDelegate: nil)
+
+        if let textField = view as? UITextField {
+
+            modal.originalReturnKeyType = textField.returnKeyType
+            modal.textFieldDelegate = textField.delegate
+            textField.delegate = self
+
+        } else if let textView = view as? UITextView {
+
+            modal.originalReturnKeyType = textView.returnKeyType
+            modal.textViewDelegate = textView.delegate
+            textView.delegate = self
+        }
+
+        textFieldInfoCache.append(modal)
+    }
+
+    /**
+    Should pass UITextField/UITextView intance. Restore it's textFieldView delegate and it's returnKeyType.
+    
+    @param view UITextField/UITextView object to unregister.
+    */
+    @objc public func removeTextFieldView(_ view: UIView) {
+
+        if let modal = textFieldViewCachedInfo(view) {
+
+            if let textField = view as? UITextField {
+
+                textField.returnKeyType = modal.originalReturnKeyType
+                textField.delegate = modal.textFieldDelegate
+            } else if let textView = view as? UITextView {
+
+                textView.returnKeyType = modal.originalReturnKeyType
+                textView.delegate = modal.textViewDelegate
+            }
+
+            if let index = textFieldInfoCache.firstIndex(where: { $0.textFieldView == view}) {
+
+                textFieldInfoCache.remove(at: index)
+            }
+        }
+    }
+
+    /**
+    Add all the UITextField/UITextView responderView's.
+    
+    @param view UIView object to register all it's responder subviews.
+    */
+    @objc public func addResponderFromView(_ view: UIView) {
+
+        let textFields = view.deepResponderViews()
+
+        for textField in textFields {
+
+            addTextFieldView(textField)
+        }
+    }
+
+    /**
+    Remove all the UITextField/UITextView responderView's.
+    
+    @param view UIView object to unregister all it's responder subviews.
+    */
+    @objc public func removeResponderFromView(_ view: UIView) {
+
+        let textFields = view.deepResponderViews()
+
+        for textField in textFields {
+
+            removeTextFieldView(textField)
+        }
+    }
+
+    @discardableResult private func goToNextResponderOrResign(_ view: UIView) -> Bool {
+
+        var superConsideredView: UIView?
+
+        //If find any consider responderView in it's upper hierarchy then will get deepResponderView. (Bug ID: #347)
+        for disabledClass in IQKeyboardManager.shared.toolbarPreviousNextAllowedClasses {
+
+            superConsideredView = view.superviewOfClassType(disabledClass)
+
+            if superConsideredView != nil {
+                break
+            }
+        }
+
+        var textFields = [UIView]()
+
+        //If there is a tableView in view's hierarchy, then fetching all it's subview that responds.
+        if let unwrappedTableView = superConsideredView {     //   (Enhancement ID: #22)
+            textFields = unwrappedTableView.deepResponderViews()
+        } else {  //Otherwise fetching all the siblings
+
+            textFields = view.responderSiblings()
+
+            //Sorting textFields according to behaviour
+            switch IQKeyboardManager.shared.toolbarManageBehaviour {
+                //If needs to sort it by tag
+            case .byTag:        textFields = textFields.sortedArrayByTag()
+                //If needs to sort it by Position
+            case .byPosition:   textFields = textFields.sortedArrayByPosition()
+            default:
+                break
+            }
+        }
+
+        //Getting index of current textField.
+        if let index = textFields.firstIndex(of: view) {
+            //If it is not last textField. then it's next object becomeFirstResponder.
+            if index < (textFields.count - 1) {
+
+                let nextTextField = textFields[index+1]
+                nextTextField.becomeFirstResponder()
+                return false
+            } else {
+
+                view.resignFirstResponder()
+                return true
+            }
+        } else {
+            return true
+        }
+    }
+}
+
+// MARK: UITextFieldDelegate
+@available(iOSApplicationExtension, unavailable)
+extension IQKeyboardReturnKeyHandler: UITextFieldDelegate {
+
+    @objc public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
+
+        if delegate == nil {
+
+            if let unwrapDelegate = textFieldViewCachedInfo(textField)?.textFieldDelegate {
+                if unwrapDelegate.responds(to: #selector(UITextFieldDelegate.textFieldShouldBeginEditing(_:))) {
+                    return unwrapDelegate.textFieldShouldBeginEditing?(textField) ?? false
+                }
+            }
+        }
+
+        return true
+    }
+
+    @objc public func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
+
+        if delegate == nil {
+
+            if let unwrapDelegate = textFieldViewCachedInfo(textField)?.textFieldDelegate {
+                if unwrapDelegate.responds(to: #selector(UITextFieldDelegate.textFieldShouldEndEditing(_:))) {
+                    return unwrapDelegate.textFieldShouldEndEditing?(textField) ?? false
+                }
+            }
+        }
+
+        return true
+    }
+
+    @objc public func textFieldDidBeginEditing(_ textField: UITextField) {
+        updateReturnKeyTypeOnTextField(textField)
+
+        var aDelegate: UITextFieldDelegate? = delegate
+
+        if aDelegate == nil {
+
+            if let modal = textFieldViewCachedInfo(textField) {
+                aDelegate = modal.textFieldDelegate
+            }
+        }
+
+        aDelegate?.textFieldDidBeginEditing?(textField)
+    }
+
+    @objc public func textFieldDidEndEditing(_ textField: UITextField) {
+
+        var aDelegate: UITextFieldDelegate? = delegate
+
+        if aDelegate == nil {
+
+            if let modal = textFieldViewCachedInfo(textField) {
+                aDelegate = modal.textFieldDelegate
+            }
+        }
+
+        aDelegate?.textFieldDidEndEditing?(textField)
+    }
+
+    @available(iOS 10.0, *)
+    @objc public func textFieldDidEndEditing(_ textField: UITextField, reason: UITextField.DidEndEditingReason) {
+
+        var aDelegate: UITextFieldDelegate? = delegate
+
+        if aDelegate == nil {
+
+            if let modal = textFieldViewCachedInfo(textField) {
+                aDelegate = modal.textFieldDelegate
+            }
+        }
+
+        aDelegate?.textFieldDidEndEditing?(textField, reason: reason)
+    }
+
+    @objc public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
+
+        if delegate == nil {
+
+            if let unwrapDelegate = textFieldViewCachedInfo(textField)?.textFieldDelegate {
+                if unwrapDelegate.responds(to: #selector(UITextFieldDelegate.textField(_:shouldChangeCharactersIn:replacementString:))) {
+                    return unwrapDelegate.textField?(textField, shouldChangeCharactersIn: range, replacementString: string) ?? false
+                }
+            }
+        }
+        return true
+    }
+
+    @objc public func textFieldShouldClear(_ textField: UITextField) -> Bool {
+
+        if delegate == nil {
+
+            if let unwrapDelegate = textFieldViewCachedInfo(textField)?.textFieldDelegate {
+                if unwrapDelegate.responds(to: #selector(UITextFieldDelegate.textFieldShouldClear(_:))) {
+                    return unwrapDelegate.textFieldShouldClear?(textField) ?? false
+                }
+            }
+        }
+
+        return true
+    }
+
+    @objc public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
+
+        var shouldReturn = true
+
+        if delegate == nil {
+
+            if let unwrapDelegate = textFieldViewCachedInfo(textField)?.textFieldDelegate {
+                if unwrapDelegate.responds(to: #selector(UITextFieldDelegate.textFieldShouldReturn(_:))) {
+                    shouldReturn = unwrapDelegate.textFieldShouldReturn?(textField) ?? false
+                }
+            }
+        }
+
+        if shouldReturn {
+            goToNextResponderOrResign(textField)
+            return true
+        } else {
+            return goToNextResponderOrResign(textField)
+        }
+    }
+}
+
+// MARK: UITextViewDelegate
+@available(iOSApplicationExtension, unavailable)
+extension IQKeyboardReturnKeyHandler: UITextViewDelegate {
+
+    @objc public func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
+
+        if delegate == nil {
+
+            if let unwrapDelegate = textFieldViewCachedInfo(textView)?.textViewDelegate {
+                if unwrapDelegate.responds(to: #selector(UITextViewDelegate.textViewShouldBeginEditing(_:))) {
+                    return unwrapDelegate.textViewShouldBeginEditing?(textView) ?? false
+                }
+            }
+        }
+
+        return true
+    }
+
+    @objc public func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
+
+        if delegate == nil {
+
+            if let unwrapDelegate = textFieldViewCachedInfo(textView)?.textViewDelegate {
+                if unwrapDelegate.responds(to: #selector(UITextViewDelegate.textViewShouldEndEditing(_:))) {
+                    return unwrapDelegate.textViewShouldEndEditing?(textView) ?? false
+                }
+            }
+        }
+
+        return true
+    }
+
+    @objc public func textViewDidBeginEditing(_ textView: UITextView) {
+        updateReturnKeyTypeOnTextField(textView)
+
+        var aDelegate: UITextViewDelegate? = delegate
+
+        if aDelegate == nil {
+
+            if let modal = textFieldViewCachedInfo(textView) {
+                aDelegate = modal.textViewDelegate
+            }
+        }
+
+        aDelegate?.textViewDidBeginEditing?(textView)
+    }
+
+    @objc public func textViewDidEndEditing(_ textView: UITextView) {
+
+        var aDelegate: UITextViewDelegate? = delegate
+
+        if aDelegate == nil {
+
+            if let modal = textFieldViewCachedInfo(textView) {
+                aDelegate = modal.textViewDelegate
+            }
+        }
+
+        aDelegate?.textViewDidEndEditing?(textView)
+    }
+
+    @objc public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
+
+        var shouldReturn = true
+
+        if delegate == nil {
+
+            if let unwrapDelegate = textFieldViewCachedInfo(textView)?.textViewDelegate {
+                if unwrapDelegate.responds(to: #selector(UITextViewDelegate.textView(_:shouldChangeTextIn:replacementText:))) {
+                    shouldReturn = (unwrapDelegate.textView?(textView, shouldChangeTextIn: range, replacementText: text)) ?? false
+                }
+            }
+        }
+
+        if shouldReturn, text == "\n" {
+            shouldReturn = goToNextResponderOrResign(textView)
+        }
+
+        return shouldReturn
+    }
+
+    @objc public func textViewDidChange(_ textView: UITextView) {
+
+        var aDelegate: UITextViewDelegate? = delegate
+
+        if aDelegate == nil {
+
+            if let modal = textFieldViewCachedInfo(textView) {
+                aDelegate = modal.textViewDelegate
+            }
+        }
+
+        aDelegate?.textViewDidChange?(textView)
+    }
+
+    @objc public func textViewDidChangeSelection(_ textView: UITextView) {
+
+        var aDelegate: UITextViewDelegate? = delegate
+
+        if aDelegate == nil {
+
+            if let modal = textFieldViewCachedInfo(textView) {
+                aDelegate = modal.textViewDelegate
+            }
+        }
+
+        aDelegate?.textViewDidChangeSelection?(textView)
+    }
+
+    @available(iOS 10.0, *)
+    @objc public func textView(_ aTextView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
+
+        if delegate == nil {
+
+            if let unwrapDelegate = textFieldViewCachedInfo(aTextView)?.textViewDelegate {
+                if unwrapDelegate.responds(to: #selector(textView as (UITextView, URL, NSRange, UITextItemInteraction) -> Bool)) {
+                    return unwrapDelegate.textView?(aTextView, shouldInteractWith: URL, in: characterRange, interaction: interaction) ?? false
+                }
+            }
+        }
+
+        return true
+    }
+
+    @available(iOS 10.0, *)
+    @objc public func textView(_ aTextView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
+
+        if delegate == nil {
+
+            if let unwrapDelegate = textFieldViewCachedInfo(aTextView)?.textViewDelegate {
+                if unwrapDelegate.responds(to: #selector(textView as (UITextView, NSTextAttachment, NSRange, UITextItemInteraction) -> Bool)) {
+                    return unwrapDelegate.textView?(aTextView, shouldInteractWith: textAttachment, in: characterRange, interaction: interaction) ?? false
+                }
+            }
+        }
+
+        return true
+    }
+
+    @available(iOS, deprecated: 10.0)
+    @objc public func textView(_ aTextView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
+
+        if delegate == nil {
+
+            if let unwrapDelegate = textFieldViewCachedInfo(aTextView)?.textViewDelegate {
+                if unwrapDelegate.responds(to: #selector(textView as (UITextView, URL, NSRange) -> Bool)) {
+                    return unwrapDelegate.textView?(aTextView, shouldInteractWith: URL, in: characterRange) ?? false
+                }
+            }
+        }
+
+        return true
+    }
+
+    @available(iOS, deprecated: 10.0)
+    @objc public func textView(_ aTextView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange) -> Bool {
+
+        if delegate == nil {
+
+            if let unwrapDelegate = textFieldViewCachedInfo(aTextView)?.textViewDelegate {
+                if unwrapDelegate.responds(to: #selector(textView as (UITextView, NSTextAttachment, NSRange) -> Bool)) {
+                    return unwrapDelegate.textView?(aTextView, shouldInteractWith: textAttachment, in: characterRange) ?? false
+                }
+            }
+        }
+
+        return true
+    }
+
+#if swift(>=5.7)
+    @available(iOS 16.0, *)
+    public func textView(_ aTextView: UITextView, editMenuForTextIn range: NSRange, suggestedActions: [UIMenuElement]) -> UIMenu? {
+        if delegate == nil {
+
+            if let unwrapDelegate = textFieldViewCachedInfo(aTextView)?.textViewDelegate {
+                if unwrapDelegate.responds(to: #selector(textView as (UITextView, NSRange, [UIMenuElement]) -> UIMenu?)) {
+                    return unwrapDelegate.textView?(aTextView, editMenuForTextIn: range, suggestedActions: suggestedActions)
+                }
+            }
+        }
+
+        return nil
+    }
+
+    @available(iOS 16.0, *)
+    public func textView(_ aTextView: UITextView, willPresentEditMenuWith animator: UIEditMenuInteractionAnimating) {
+        var aDelegate: UITextViewDelegate? = delegate
+
+        if aDelegate == nil {
+
+            if let modal = textFieldViewCachedInfo(aTextView) {
+                aDelegate = modal.textViewDelegate
+            }
+        }
+
+        aDelegate?.textView?(aTextView, willPresentEditMenuWith: animator)
+    }
+
+    @available(iOS 16.0, *)
+    public func textView(_ aTextView: UITextView, willDismissEditMenuWith animator: UIEditMenuInteractionAnimating) {
+        var aDelegate: UITextViewDelegate? = delegate
+
+        if aDelegate == nil {
+
+            if let modal = textFieldViewCachedInfo(aTextView) {
+                aDelegate = modal.textViewDelegate
+            }
+        }
+
+        aDelegate?.textView?(aTextView, willDismissEditMenuWith: animator)
+    }
+#endif
+}

+ 189 - 0
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQTextView/IQTextView.swift

@@ -0,0 +1,189 @@
+//
+//  IQTextView.swift
+// https://github.com/hackiftekhar/IQKeyboardManager
+// Copyright (c) 2013-20 Iftekhar Qurashi.
+//
+// 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
+
+/** @abstract UITextView with placeholder support   */
+@available(iOSApplicationExtension, unavailable)
+@objc open class IQTextView: UITextView {
+
+    @objc required public init?(coder aDecoder: NSCoder) {
+        super.init(coder: aDecoder)
+        NotificationCenter.default.addObserver(self, selector: #selector(self.refreshPlaceholder), name: UITextView.textDidChangeNotification, object: self)
+    }
+
+    @objc override public init(frame: CGRect, textContainer: NSTextContainer?) {
+        super.init(frame: frame, textContainer: textContainer)
+        NotificationCenter.default.addObserver(self, selector: #selector(self.refreshPlaceholder), name: UITextView.textDidChangeNotification, object: self)
+    }
+
+    @objc override open func awakeFromNib() {
+        super.awakeFromNib()
+        NotificationCenter.default.addObserver(self, selector: #selector(self.refreshPlaceholder), name: UITextView.textDidChangeNotification, object: self)
+    }
+
+    deinit {
+        IQ_PlaceholderLabel.removeFromSuperview()
+    }
+
+    private var placeholderInsets: UIEdgeInsets {
+        return UIEdgeInsets(top: self.textContainerInset.top, left: self.textContainerInset.left + self.textContainer.lineFragmentPadding, bottom: self.textContainerInset.bottom, right: self.textContainerInset.right + self.textContainer.lineFragmentPadding)
+    }
+
+    private var placeholderExpectedFrame: CGRect {
+        let placeholderInsets = self.placeholderInsets
+        let maxWidth = self.frame.width-placeholderInsets.left-placeholderInsets.right
+        let expectedSize = IQ_PlaceholderLabel.sizeThatFits(CGSize(width: maxWidth, height: self.frame.height-placeholderInsets.top-placeholderInsets.bottom))
+
+        return CGRect(x: placeholderInsets.left, y: placeholderInsets.top, width: maxWidth, height: expectedSize.height)
+    }
+
+    lazy var IQ_PlaceholderLabel: UILabel = {
+        let label = UILabel()
+
+        label.autoresizingMask = [.flexibleWidth, .flexibleHeight]
+        label.lineBreakMode = .byWordWrapping
+        label.numberOfLines = 0
+        label.font = self.font
+        label.textAlignment = self.textAlignment
+        label.backgroundColor = UIColor.clear
+        label.isAccessibilityElement = false
+        #if swift(>=5.1)
+        label.textColor = UIColor.systemGray
+        #else
+        label.textColor = UIColor.lightText
+        #endif
+        label.alpha = 0
+        self.addSubview(label)
+
+        return label
+    }()
+
+    /** @abstract To set textView's placeholder text color. */
+    @IBInspectable open var placeholderTextColor: UIColor? {
+
+        get {
+            return IQ_PlaceholderLabel.textColor
+        }
+
+        set {
+            IQ_PlaceholderLabel.textColor = newValue
+        }
+    }
+
+    /** @abstract To set textView's placeholder text. Default is nil.    */
+    @IBInspectable open var placeholder: String? {
+
+        get {
+            return IQ_PlaceholderLabel.text
+        }
+
+        set {
+            IQ_PlaceholderLabel.text = newValue
+            refreshPlaceholder()
+        }
+    }
+
+    /** @abstract To set textView's placeholder attributed text. Default is nil.    */
+    open var attributedPlaceholder: NSAttributedString? {
+        get {
+            return IQ_PlaceholderLabel.attributedText
+        }
+
+        set {
+            IQ_PlaceholderLabel.attributedText = newValue
+            refreshPlaceholder()
+        }
+    }
+
+    @objc override open func layoutSubviews() {
+        super.layoutSubviews()
+
+        IQ_PlaceholderLabel.frame = placeholderExpectedFrame
+    }
+
+    @objc internal func refreshPlaceholder() {
+
+        if !text.isEmpty || !attributedText.string.isEmpty {
+            IQ_PlaceholderLabel.alpha = 0
+        } else {
+            IQ_PlaceholderLabel.alpha = 1
+        }
+    }
+
+    @objc override open var text: String! {
+
+        didSet {
+            refreshPlaceholder()
+        }
+    }
+
+    open override var attributedText: NSAttributedString! {
+
+        didSet {
+            refreshPlaceholder()
+        }
+    }
+
+    @objc override open var font: UIFont? {
+
+        didSet {
+
+            if let unwrappedFont = font {
+                IQ_PlaceholderLabel.font = unwrappedFont
+            } else {
+                IQ_PlaceholderLabel.font = UIFont.systemFont(ofSize: 12)
+            }
+        }
+    }
+
+    @objc override open var textAlignment: NSTextAlignment {
+        didSet {
+            IQ_PlaceholderLabel.textAlignment = textAlignment
+        }
+    }
+
+    @objc override weak open var delegate: UITextViewDelegate? {
+
+        get {
+            refreshPlaceholder()
+            return super.delegate
+        }
+
+        set {
+            super.delegate = newValue
+        }
+    }
+
+    @objc override open var intrinsicContentSize: CGSize {
+        guard !hasText else {
+            return super.intrinsicContentSize
+        }
+
+        var newSize = super.intrinsicContentSize
+        let placeholderInsets = self.placeholderInsets
+        newSize.height = placeholderExpectedFrame.height + placeholderInsets.top + placeholderInsets.bottom
+
+        return newSize
+    }
+}

+ 99 - 0
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQToolbar/IQBarButtonItem.swift

@@ -0,0 +1,99 @@
+//
+//  IQBarButtonItem.swift
+// https://github.com/hackiftekhar/IQKeyboardManager
+// Copyright (c) 2013-20 Iftekhar Qurashi.
+//
+// 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 - UIKit contains Foundation
+import UIKit
+
+@available(iOSApplicationExtension, unavailable)
+@objc open class IQBarButtonItem: UIBarButtonItem {
+
+    @objc public override init() {
+        super.init()
+        initialize()
+    }
+
+    @objc public required init?(coder aDecoder: NSCoder) {
+        super.init(coder: aDecoder)
+        initialize()
+    }
+
+    private func initialize() {
+
+        let states: [UIControl.State] = [.normal, .highlighted, .disabled, .focused]
+
+        for state in states {
+
+            setBackgroundImage(nil, for: state, barMetrics: .default)
+            setBackgroundImage(nil, for: state, style: .plain, barMetrics: .default)
+            setBackButtonBackgroundImage(nil, for: state, barMetrics: .default)
+        }
+
+        setTitlePositionAdjustment(UIOffset(), for: .default)
+        setBackgroundVerticalPositionAdjustment(0, for: .default)
+        setBackButtonBackgroundVerticalPositionAdjustment(0, for: .default)
+    }
+
+    @objc override open var tintColor: UIColor? {
+        didSet {
+
+            var textAttributes = [NSAttributedString.Key: Any]()
+            textAttributes[.foregroundColor] = tintColor
+
+            if let attributes = titleTextAttributes(for: .normal) {
+                for (key, value) in attributes {
+                    textAttributes[key] = value
+                }
+            }
+
+            setTitleTextAttributes(textAttributes, for: .normal)
+        }
+    }
+
+    /**
+     Boolean to know if it's a system item or custom item, we are having a limitation that we cannot override a designated initializer, so we are manually setting this property once in initialization
+     */
+    @objc internal var isSystemItem = false
+
+    /**
+     Additional target & action to do get callback action. Note that setting custom target & selector doesn't affect native functionality, this is just an additional target to get a callback.
+     
+     @param target Target object.
+     @param action Target Selector.
+     */
+    @objc open func setTarget(_ target: AnyObject?, action: Selector?) {
+        if let target = target, let action = action {
+            invocation = IQInvocation(target, action)
+        } else {
+            invocation = nil
+        }
+    }
+
+    /**
+     Customized Invocation to be called when button is pressed. invocation is internally created using setTarget:action: method.
+     */
+    @objc open var invocation: IQInvocation?
+
+    deinit {
+        target = nil
+    }
+}

+ 45 - 0
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQToolbar/IQInvocation.swift

@@ -0,0 +1,45 @@
+//
+//  IQInvocation.swift
+// https://github.com/hackiftekhar/IQKeyboardManager
+// Copyright (c) 2013-20 Iftekhar Qurashi.
+//
+// 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
+
+@available(iOSApplicationExtension, unavailable)
+@objc public final class IQInvocation: NSObject {
+    @objc public weak var target: AnyObject?
+    @objc public var action: Selector
+
+    @objc public init(_ target: AnyObject, _ action: Selector) {
+        self.target = target
+        self.action = action
+    }
+
+    @objc public func invoke(from: Any) {
+        if let target = target {
+            UIApplication.shared.sendAction(action, to: target, from: from, for: UIEvent())
+        }
+    }
+
+    deinit {
+        target = nil
+    }
+}

+ 29 - 0
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQToolbar/IQPreviousNextView.swift

@@ -0,0 +1,29 @@
+//
+// IQPreviousNextView.swift
+// https://github.com/hackiftekhar/IQKeyboardManager
+// Copyright (c) 2013-20 Iftekhar Qurashi.
+//
+// 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
+
+@available(iOSApplicationExtension, unavailable)
+@objc open class IQPreviousNextView: UIView {
+
+}

+ 167 - 0
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQToolbar/IQTitleBarButtonItem.swift

@@ -0,0 +1,167 @@
+//
+//  IQTitleBarButtonItem.swift
+// https://github.com/hackiftekhar/IQKeyboardManager
+// Copyright (c) 2013-20 Iftekhar Qurashi.
+//
+// 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
+
+@available(iOSApplicationExtension, unavailable)
+@objc open class IQTitleBarButtonItem: IQBarButtonItem {
+
+    @objc open var titleFont: UIFont? {
+
+        didSet {
+            if let unwrappedFont = titleFont {
+                titleButton?.titleLabel?.font = unwrappedFont
+            } else {
+                titleButton?.titleLabel?.font = UIFont.systemFont(ofSize: 13)
+            }
+        }
+    }
+
+    @objc override open var title: String? {
+        didSet {
+                titleButton?.setTitle(title, for: .normal)
+        }
+    }
+
+    /**
+     titleColor to be used for displaying button text when displaying title (disabled state).
+     */
+    @objc open var titleColor: UIColor? {
+
+        didSet {
+
+            if let color = titleColor {
+                titleButton?.setTitleColor(color, for: .disabled)
+            } else {
+                titleButton?.setTitleColor(UIColor.lightGray, for: .disabled)
+            }
+        }
+    }
+
+    /**
+     selectableTitleColor to be used for displaying button text when button is enabled.
+     */
+    @objc open var selectableTitleColor: UIColor? {
+
+        didSet {
+
+            if let color = selectableTitleColor {
+                titleButton?.setTitleColor(color, for: .normal)
+            } else {
+                #if swift(>=5.1)
+                titleButton?.setTitleColor(UIColor.systemBlue, for: .normal)
+                #else
+                titleButton?.setTitleColor(UIColor(red: 0.0, green: 0.5, blue: 1.0, alpha: 1), for: .normal)
+                #endif
+            }
+        }
+    }
+
+    /**
+     Customized Invocation to be called on title button action. titleInvocation is internally created using setTitleTarget:action: method.
+     */
+    @objc override open var invocation: IQInvocation? {
+
+        didSet {
+
+            if let target = invocation?.target, let action = invocation?.action {
+                self.isEnabled = true
+                titleButton?.isEnabled = true
+                titleButton?.addTarget(target, action: action, for: .touchUpInside)
+            } else {
+                self.isEnabled = false
+                titleButton?.isEnabled = false
+                titleButton?.removeTarget(nil, action: nil, for: .touchUpInside)
+            }
+        }
+    }
+
+    internal var titleButton: UIButton?
+    private var _titleView: UIView?
+
+    override init() {
+        super.init()
+    }
+
+    @objc public convenience init(title: String?) {
+
+        self.init(title: nil, style: .plain, target: nil, action: nil)
+
+        _titleView = UIView()
+        _titleView?.backgroundColor = UIColor.clear
+
+        titleButton = UIButton(type: .system)
+        titleButton?.isEnabled = false
+        titleButton?.titleLabel?.numberOfLines = 3
+        titleButton?.setTitleColor(UIColor.lightGray, for: .disabled)
+        #if swift(>=5.1)
+        titleButton?.setTitleColor(UIColor.systemBlue, for: .normal)
+        #else
+        titleButton?.setTitleColor(UIColor(red: 0.0, green: 0.5, blue: 1.0, alpha: 1), for: .normal)
+        #endif
+        titleButton?.backgroundColor = UIColor.clear
+        titleButton?.titleLabel?.textAlignment = .center
+        titleButton?.setTitle(title, for: .normal)
+        titleFont = UIFont.systemFont(ofSize: 13.0)
+        titleButton?.titleLabel?.font = self.titleFont
+        _titleView?.addSubview(titleButton!)
+
+        if #available(iOS 11, *) {
+
+            let layoutDefaultLowPriority = UILayoutPriority(rawValue: UILayoutPriority.defaultLow.rawValue-1)
+            let layoutDefaultHighPriority = UILayoutPriority(rawValue: UILayoutPriority.defaultHigh.rawValue-1)
+
+            _titleView?.translatesAutoresizingMaskIntoConstraints = false
+            _titleView?.setContentHuggingPriority(layoutDefaultLowPriority, for: .vertical)
+            _titleView?.setContentHuggingPriority(layoutDefaultLowPriority, for: .horizontal)
+            _titleView?.setContentCompressionResistancePriority(layoutDefaultHighPriority, for: .vertical)
+            _titleView?.setContentCompressionResistancePriority(layoutDefaultHighPriority, for: .horizontal)
+
+            titleButton?.translatesAutoresizingMaskIntoConstraints = false
+            titleButton?.setContentHuggingPriority(layoutDefaultLowPriority, for: .vertical)
+            titleButton?.setContentHuggingPriority(layoutDefaultLowPriority, for: .horizontal)
+            titleButton?.setContentCompressionResistancePriority(layoutDefaultHighPriority, for: .vertical)
+            titleButton?.setContentCompressionResistancePriority(layoutDefaultHighPriority, for: .horizontal)
+
+            let top = NSLayoutConstraint.init(item: titleButton!, attribute: .top, relatedBy: .equal, toItem: _titleView, attribute: .top, multiplier: 1, constant: 0)
+            let bottom = NSLayoutConstraint.init(item: titleButton!, attribute: .bottom, relatedBy: .equal, toItem: _titleView, attribute: .bottom, multiplier: 1, constant: 0)
+            let leading = NSLayoutConstraint.init(item: titleButton!, attribute: .leading, relatedBy: .equal, toItem: _titleView, attribute: .leading, multiplier: 1, constant: 0)
+            let trailing = NSLayoutConstraint.init(item: titleButton!, attribute: .trailing, relatedBy: .equal, toItem: _titleView, attribute: .trailing, multiplier: 1, constant: 0)
+
+            _titleView?.addConstraints([top, bottom, leading, trailing])
+        } else {
+            _titleView?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
+            titleButton?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
+        }
+
+        customView = _titleView
+    }
+
+    @objc required public init?(coder aDecoder: NSCoder) {
+        super.init(coder: aDecoder)
+    }
+
+    deinit {
+        customView = nil
+    }
+}

+ 252 - 0
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQToolbar/IQToolbar.swift

@@ -0,0 +1,252 @@
+//
+//  IQToolbar.swift
+// https://github.com/hackiftekhar/IQKeyboardManager
+// Copyright (c) 2013-20 Iftekhar Qurashi.
+//
+// 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
+
+/** @abstract   IQToolbar for IQKeyboardManager.    */
+@available(iOSApplicationExtension, unavailable)
+@objc open class IQToolbar: UIToolbar, UIInputViewAudioFeedback {
+
+    override init(frame: CGRect) {
+        super.init(frame: frame)
+
+        initialize()
+    }
+
+    @objc required public init?(coder aDecoder: NSCoder) {
+        super.init(coder: aDecoder)
+
+        initialize()
+    }
+
+    private func initialize() {
+
+        sizeToFit()
+
+        autoresizingMask = .flexibleWidth
+        self.isTranslucent = true
+        self.barTintColor = nil
+
+        let positions: [UIBarPosition] = [.any, .bottom, .top, .topAttached]
+
+        for position in positions {
+
+            self.setBackgroundImage(nil, forToolbarPosition: position, barMetrics: .default)
+            self.setShadowImage(nil, forToolbarPosition: .any)
+        }
+
+        //Background color
+        self.backgroundColor = nil
+    }
+
+    /**
+     Previous bar button of toolbar.
+     */
+    private var privatePreviousBarButton: IQBarButtonItem?
+    @objc open var previousBarButton: IQBarButtonItem {
+        get {
+            if privatePreviousBarButton == nil {
+                privatePreviousBarButton = IQBarButtonItem(image: nil, style: .plain, target: nil, action: nil)
+            }
+            return privatePreviousBarButton!
+        }
+
+        set (newValue) {
+            privatePreviousBarButton = newValue
+        }
+    }
+
+    /**
+     Next bar button of toolbar.
+     */
+    private var privateNextBarButton: IQBarButtonItem?
+    @objc open var nextBarButton: IQBarButtonItem {
+        get {
+            if privateNextBarButton == nil {
+                privateNextBarButton = IQBarButtonItem(image: nil, style: .plain, target: nil, action: nil)
+            }
+            return privateNextBarButton!
+        }
+
+        set (newValue) {
+            privateNextBarButton = newValue
+        }
+    }
+
+    /**
+     Title bar button of toolbar.
+     */
+    private var privateTitleBarButton: IQTitleBarButtonItem?
+    @objc open var titleBarButton: IQTitleBarButtonItem {
+        get {
+            if privateTitleBarButton == nil {
+                privateTitleBarButton = IQTitleBarButtonItem(title: nil)
+                privateTitleBarButton?.accessibilityLabel = "Title"
+                privateTitleBarButton?.accessibilityIdentifier = privateTitleBarButton?.accessibilityLabel
+            }
+            return privateTitleBarButton!
+        }
+
+        set (newValue) {
+            privateTitleBarButton = newValue
+        }
+    }
+
+    /**
+     Done bar button of toolbar.
+     */
+    private var privateDoneBarButton: IQBarButtonItem?
+    @objc open var doneBarButton: IQBarButtonItem {
+        get {
+            if privateDoneBarButton == nil {
+                privateDoneBarButton = IQBarButtonItem(title: nil, style: .done, target: nil, action: nil)
+            }
+            return privateDoneBarButton!
+        }
+
+        set (newValue) {
+            privateDoneBarButton = newValue
+        }
+    }
+
+    /**
+     Fixed space bar button of toolbar.
+     */
+    private var privateFixedSpaceBarButton: IQBarButtonItem?
+    @objc open var fixedSpaceBarButton: IQBarButtonItem {
+        get {
+            if privateFixedSpaceBarButton == nil {
+                privateFixedSpaceBarButton = IQBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
+            }
+            privateFixedSpaceBarButton!.isSystemItem = true
+
+            if #available(iOS 10, *) {
+                privateFixedSpaceBarButton!.width = 6
+            } else {
+                privateFixedSpaceBarButton!.width = 20
+            }
+
+            return privateFixedSpaceBarButton!
+        }
+
+        set (newValue) {
+            privateFixedSpaceBarButton = newValue
+        }
+    }
+
+    @objc override open func sizeThatFits(_ size: CGSize) -> CGSize {
+        var sizeThatFit = super.sizeThatFits(size)
+        sizeThatFit.height = 44
+        return sizeThatFit
+    }
+
+    @objc override open var tintColor: UIColor! {
+
+        didSet {
+            if let unwrappedItems = items {
+                for item in unwrappedItems {
+                    item.tintColor = tintColor
+                }
+            }
+        }
+    }
+
+    @objc override open func layoutSubviews() {
+
+        super.layoutSubviews()
+
+        if #available(iOS 11, *) {
+            return
+        } else if let customTitleView = titleBarButton.customView {
+            var leftRect = CGRect.null
+            var rightRect = CGRect.null
+            var isTitleBarButtonFound = false
+
+            let sortedSubviews = self.subviews.sorted(by: { (view1: UIView, view2: UIView) -> Bool in
+                if view1.frame.minX != view2.frame.minX {
+                    return view1.frame.minX < view2.frame.minX
+                } else {
+                    return view1.frame.minY < view2.frame.minY
+                }
+            })
+
+            for barButtonItemView in sortedSubviews {
+
+                if isTitleBarButtonFound {
+                    rightRect = barButtonItemView.frame
+                    break
+                } else if barButtonItemView === customTitleView {
+                    isTitleBarButtonFound = true
+                    //If it's UIToolbarButton or UIToolbarTextButton (which actually UIBarButtonItem)
+                } else if barButtonItemView.isKind(of: UIControl.self) {
+                    leftRect = barButtonItemView.frame
+                }
+            }
+
+            let titleMargin: CGFloat = 16
+
+            let maxWidth: CGFloat = self.frame.width - titleMargin*2 - (leftRect.isNull ? 0 : leftRect.maxX) - (rightRect.isNull ? 0 : self.frame.width - rightRect.minX)
+            let maxHeight = self.frame.height
+
+            let sizeThatFits = customTitleView.sizeThatFits(CGSize(width: maxWidth, height: maxHeight))
+
+            var titleRect: CGRect
+
+            if sizeThatFits.width > 0, sizeThatFits.height > 0 {
+                let width = min(sizeThatFits.width, maxWidth)
+                let height = min(sizeThatFits.height, maxHeight)
+
+                var xPosition: CGFloat
+
+                if !leftRect.isNull {
+                    xPosition = titleMargin + leftRect.maxX + ((maxWidth - width)/2)
+                } else {
+                    xPosition = titleMargin
+                }
+
+                let yPosition = (maxHeight - height)/2
+
+                titleRect = CGRect(x: xPosition, y: yPosition, width: width, height: height)
+            } else {
+
+                var xPosition: CGFloat
+
+                if !leftRect.isNull {
+                    xPosition = titleMargin + leftRect.maxX
+                } else {
+                    xPosition = titleMargin
+                }
+
+                let width: CGFloat = self.frame.width - titleMargin*2 - (leftRect.isNull ? 0 : leftRect.maxX) - (rightRect.isNull ? 0 : self.frame.width - rightRect.minX)
+
+                titleRect = CGRect(x: xPosition, y: 0, width: width, height: maxHeight)
+            }
+
+            customTitleView.frame = titleRect
+        }
+    }
+
+    @objc open var enableInputClicksWhenVisible: Bool {
+        return true
+    }
+}

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 80 - 0
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQToolbar/IQUIView+IQKeyboardToolbar.swift


+ 21 - 0
Pods/IQKeyboardManagerSwift/LICENSE.md

@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2013-2017 Iftekhar Qurashi
+
+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.

+ 223 - 0
Pods/IQKeyboardManagerSwift/README.md

@@ -0,0 +1,223 @@
+<p align="center">
+  <img src="https://raw.githubusercontent.com/hackiftekhar/IQKeyboardManager/master/Demo/Resources/icon.png" alt="Icon"/>
+</p>
+<H1 align="center">IQKeyboardManager</H1>
+<p align="center">
+  <img src="https://img.shields.io/github/license/hackiftekhar/IQKeyboardManager.svg"
+  alt="GitHub license"/>
+
+
+[![Build Status](https://travis-ci.org/hackiftekhar/IQKeyboardManager.svg)](https://travis-ci.org/hackiftekhar/IQKeyboardManager)
+
+
+While developing iOS apps, we often run into issues where the iPhone keyboard slides up and covers the `UITextField/UITextView`. `IQKeyboardManager` allows you to prevent this issue of keyboard sliding up and covering `UITextField/UITextView` without needing you to write any code or make any additional setup. To use `IQKeyboardManager` you simply need to add source files to your project.
+
+
+#### Key Features
+
+1) `**CODELESS**, Zero Lines of Code`
+
+2) `Works Automatically`
+
+3) `No More UIScrollView`
+
+4) `No More Subclasses`
+
+5) `No More Manual Work`
+
+6) `No More #imports`
+
+`IQKeyboardManager` works on all orientations, and with the toolbar. It also has nice optional features allowing you to customize the distance from the text field, behaviour of previous, next and done buttons in the keyboard toolbar, play sound when the user navigates through the form and more.
+
+
+## Screenshot
+[![IQKeyboardManager](https://raw.githubusercontent.com/hackiftekhar/IQKeyboardManager/v3.3.0/Screenshot/IQKeyboardManagerScreenshot.png)](http://youtu.be/6nhLw6hju2A)
+[![Settings](https://raw.githubusercontent.com/hackiftekhar/IQKeyboardManager/v3.3.0/Screenshot/IQKeyboardManagerSettings.png)](http://youtu.be/6nhLw6hju2A)
+
+## GIF animation
+[![IQKeyboardManager](https://raw.githubusercontent.com/hackiftekhar/IQKeyboardManager/v3.3.0/Screenshot/IQKeyboardManager.gif)](http://youtu.be/6nhLw6hju2A)
+
+## Video
+
+<a href="http://youtu.be/WAYc2Qj-OQg" target="_blank"><img src="http://img.youtube.com/vi/WAYc2Qj-OQg/0.jpg"
+alt="IQKeyboardManager Demo Video" width="480" height="360" border="10" /></a>
+
+## Tutorial video by @rebeloper ([#1135](https://github.com/hackiftekhar/IQKeyboardManager/issues/1135))
+
+@rebeloper demonstrated two videos on how to implement **IQKeyboardManager** at it's core:
+
+<a href="https://www.youtube.com/playlist?list=PL_csAAO9PQ8aTL87XnueOXi3RpWE2m_8v" target="_blank"><img src="https://raw.githubusercontent.com/hackiftekhar/IQKeyboardManager/master/Screenshot/ThirdPartyYoutubeTutorial.jpg"
+alt="Youtube Tutorial Playlist"/></a>
+
+https://www.youtube.com/playlist?list=PL_csAAO9PQ8aTL87XnueOXi3RpWE2m_8v
+
+## Warning
+
+- **If you're planning to build SDK/library/framework and want to handle UITextField/UITextView with IQKeyboardManager then you're totally going the wrong way.** I would never suggest to add **IQKeyboardManager** as **dependency/adding/shipping** with any third-party library. Instead of adding **IQKeyboardManager** you should implement your own solution to achieve same kind of results. **IQKeyboardManager** is totally designed for projects to help developers for their convenience, it's not designed for **adding/dependency/shipping** with any **third-party library**, because **doing this could block adoption by other developers for their projects as well (who are not using IQKeyboardManager and have implemented their custom solution to handle UITextField/UITextView in the project).**
+- If **IQKeyboardManager** conflicts with other **third-party library**, then it's **developer responsibility** to **enable/disable IQKeyboardManager** when **presenting/dismissing** third-party library UI. Third-party libraries are not responsible to handle IQKeyboardManager.
+
+## Requirements
+[![Platform iOS](https://img.shields.io/badge/Platform-iOS-blue.svg?style=fla)]()
+
+|                        | Language | Minimum iOS Target | Minimum Xcode Version |
+|------------------------|----------|--------------------|-----------------------|
+| IQKeyboardManager      | Obj-C    | iOS 8.0            | Xcode 9           |
+| IQKeyboardManagerSwift | Swift    | iOS 8.0            | Xcode 9           |
+| Demo Project           |          |                    | Xcode 11             |
+
+#### Swift versions support
+
+| Swift             | Xcode | IQKeyboardManagerSwift |
+|-------------------|-------|------------------------|
+| 5.1, 5.0, 4.2, 4.0, 3.2, 3.0| 11  | >= 6.5.0               |
+| 5.0,4.2, 4.0, 3.2, 3.0| 10.2  | >= 6.2.1               |
+| 4.2, 4.0, 3.2, 3.0| 10.0  | >= 6.0.4               |
+| 4.0, 3.2, 3.0     | 9.0   | 5.0.0                  |
+
+Installation
+==========================
+
+#### Installation with CocoaPods
+
+[![CocoaPods](https://img.shields.io/cocoapods/v/IQKeyboardManager.svg)](http://cocoadocs.org/docsets/IQKeyboardManager)
+
+***IQKeyboardManager (Objective-C):*** IQKeyboardManager is available through [CocoaPods](http://cocoapods.org). To install
+it, simply add the following line to your Podfile: ([#9](https://github.com/hackiftekhar/IQKeyboardManager/issues/9))
+
+```ruby
+pod 'IQKeyboardManager' #iOS8 and later
+```
+
+***IQKeyboardManager (Swift):*** IQKeyboardManagerSwift is available through [CocoaPods](http://cocoapods.org). To install
+it, simply add the following line to your Podfile: ([#236](https://github.com/hackiftekhar/IQKeyboardManager/issues/236))
+
+*Swift 5.1, 5.0, 4.2, 4.0, 3.2, 3.0 (Xcode 11)*
+
+```ruby
+pod 'IQKeyboardManagerSwift'
+```
+
+*Or you can choose the version you need based on Swift support table from [Requirements](README.md#requirements)*
+
+```ruby
+pod 'IQKeyboardManagerSwift', '6.3.0'
+```
+
+In AppDelegate.swift, just import IQKeyboardManagerSwift framework and enable IQKeyboardManager.
+
+```swift
+import IQKeyboardManagerSwift
+
+@UIApplicationMain
+class AppDelegate: UIResponder, UIApplicationDelegate {
+
+    var window: UIWindow?
+
+    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
+
+      IQKeyboardManager.shared.enable = true
+
+      return true
+    }
+}
+```
+
+#### Installation with Carthage
+
+[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.
+
+You can install Carthage with [Homebrew](http://brew.sh/) using the following command:
+
+```bash
+$ brew update
+$ brew install carthage
+```
+
+To integrate `IQKeyboardManger` or `IQKeyboardManagerSwift` into your Xcode project using Carthage, add the following line to your `Cartfile`:
+
+```ogdl
+github "hackiftekhar/IQKeyboardManager"
+```
+
+Run `carthage` to build the frameworks and drag the appropriate framework (`IQKeyboardManager.framework` or `IQKeyboardManagerSwift.framework`) into your Xcode project based on your need. Make sure to add only one framework and not both.
+
+
+#### Installation with Source Code
+
+[![Github tag](https://img.shields.io/github/tag/hackiftekhar/iqkeyboardmanager.svg)]()
+
+
+
+***IQKeyboardManager (Objective-C):*** Just ***drag and drop*** `IQKeyboardManager` directory from demo project to your project. That's it.
+
+***IQKeyboardManager (Swift):*** ***Drag and drop*** `IQKeyboardManagerSwift` directory from demo project to your project
+
+In AppDelegate.swift, just enable IQKeyboardManager.
+
+```swift
+@UIApplicationMain
+class AppDelegate: UIResponder, UIApplicationDelegate {
+
+    var window: UIWindow?
+
+    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
+
+      IQKeyboardManager.shared.enable = true
+
+      return true
+    }
+}
+```
+
+#### Installation with Swift Package Manager
+
+[Swift Package Manager(SPM)](https://swift.org/package-manager/) is Apple's dependency manager tool. It is now supported in Xcode 11. So it can be used in all appleOS types of projects. It can be used alongside other tools like CocoaPods and Carthage as well. 
+
+To install IQKeyboardManager package into your packages, add a reference to IQKeyboardManager and a targeting release version in the dependencies section in `Package.swift` file:
+
+```swift
+import PackageDescription
+
+let package = Package(
+    name: "YOUR_PROJECT_NAME",
+    products: [],
+    dependencies: [
+        .package(url: "https://github.com/hackiftekhar/IQKeyboardManager.git", from: "6.5.0")
+    ]
+)
+```
+
+To install IQKeyboardManager package via Xcode
+
+ * Go to File -> Swift Packages -> Add Package Dependency...
+ * Then search for https://github.com/hackiftekhar/IQKeyboardManager.git
+ * And choose the version you want
+
+Migration Guide
+==========================
+- [IQKeyboardManager 6.0.0 Migration Guide](https://github.com/hackiftekhar/IQKeyboardManager/wiki/IQKeyboardManager-6.0.0-Migration-Guide)
+
+Other Links
+==========================
+
+- [Known Issues](https://github.com/hackiftekhar/IQKeyboardManager/wiki/Known-Issues)
+- [Manual Management Tweaks](https://github.com/hackiftekhar/IQKeyboardManager/wiki/Manual-Management)
+- [Properties and functions usage](https://github.com/hackiftekhar/IQKeyboardManager/wiki/Properties-&-Functions)
+
+## Flow Diagram
+[![IQKeyboardManager CFD](https://raw.githubusercontent.com/hackiftekhar/IQKeyboardManager/master/Screenshot/IQKeyboardManagerFlowDiagram.jpg)](https://raw.githubusercontent.com/hackiftekhar/IQKeyboardManager/master/Screenshot/IQKeyboardManagerFlowDiagram.jpg)
+
+If you would like to see detailed Flow diagram then check [Detailed Flow Diagram](https://raw.githubusercontent.com/hackiftekhar/IQKeyboardManager/v3.3.0/Screenshot/IQKeyboardManagerCFD.jpg).
+
+
+LICENSE
+---
+Distributed under the MIT License.
+
+Contributions
+---
+Any contribution is more than welcome! You can contribute through pull requests and issues on GitHub.
+
+Author
+---
+If you wish to contact me, email at: hack.iftekhar@gmail.com

+ 22 - 0
Pods/Kingfisher/LICENSE

@@ -0,0 +1,22 @@
+The MIT License (MIT)
+
+Copyright (c) 2019 Wei Wang
+
+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.
+

+ 259 - 0
Pods/Kingfisher/README.md

@@ -0,0 +1,259 @@
+<p align="center">
+<img src="https://raw.githubusercontent.com/onevcat/Kingfisher/master/images/logo.png" alt="Kingfisher" title="Kingfisher" width="557"/>
+</p>
+
+<p align="center">
+<a href="https://github.com/onevcat/Kingfisher/actions?query=workflow%3Abuild"><img src="https://github.com/onevcat/kingfisher/workflows/build/badge.svg?branch=master"></a>
+<a href="https://swiftpackageindex.com/onevcat/Kingfisher/master/documentation/kingfisher"><img src="https://img.shields.io/badge/Swift-Doc-DE5C43.svg?style=flat"></a>
+<a href="https://cocoapods.org/pods/Kingfisher"><img src="https://img.shields.io/github/v/tag/onevcat/Kingfisher.svg?color=blue&include_prereleases=&sort=semver"></a>
+<a href="https://swift.org/package-manager/"><img src="https://img.shields.io/badge/SPM-supported-DE5C43.svg?style=flat"></a>
+<a href="https://raw.githubusercontent.com/onevcat/Kingfisher/master/LICENSE"><img src="https://img.shields.io/badge/license-MIT-black"></a>
+</p>
+
+Kingfisher is a powerful, pure-Swift library for downloading and caching images from the web. It provides you a chance to use a pure-Swift way to work with remote images in your next app.
+
+## Features
+
+- [x] Asynchronous image downloading and caching.
+- [x] Loading image from either `URLSession`-based networking or local provided data.
+- [x] Useful image processors and filters provided.
+- [x] Multiple-layer hybrid cache for both memory and disk.
+- [x] Fine control on cache behavior. Customizable expiration date and size limit.
+- [x] Cancelable downloading and auto-reusing previous downloaded content to improve performance.
+- [x] Independent components. Use the downloader, caching system, and image processors separately as you need.
+- [x] Prefetching images and showing them from the cache to boost your app.
+- [x] Extensions for `UIImageView`, `NSImageView`, `NSButton`, `UIButton`, `NSTextAttachment`, `WKInterfaceImage`, `TVMonogramView` and `CPListItem` to directly set an image from a URL.
+- [x] Built-in transition animation when setting images.
+- [x] Customizable placeholder and indicator while loading images.
+- [x] Extensible image processing and image format easily.
+- [x] Low Data Mode support.
+- [x] SwiftUI support.
+
+### Kingfisher 101
+
+The simplest use-case is setting an image to an image view with the `UIImageView` extension:
+
+```swift
+import Kingfisher
+
+let url = URL(string: "https://example.com/image.png")
+imageView.kf.setImage(with: url)
+```
+
+Kingfisher will download the image from `url`, send it to both memory cache and disk cache, and display it in `imageView`. 
+When you set it with the same URL later, the image will be retrieved from the cache and shown immediately.
+
+It also works if you use SwiftUI:
+
+```swift
+var body: some View {
+    KFImage(URL(string: "https://example.com/image.png")!)
+}
+```
+
+### A More Advanced Example
+
+With the powerful options, you can do hard tasks with Kingfisher in a simple way. For example, the code below: 
+
+1. Downloads a high-resolution image.
+2. Downsamples it to match the image view size.
+3. Makes it round cornered with a given radius.
+4. Shows a system indicator and a placeholder image while downloading.
+5. When prepared, it animates the small thumbnail image with a "fade in" effect. 
+6. The original large image is also cached to disk for later use, to get rid of downloading it again in a detail view.
+7. A console log is printed when the task finishes, either for success or failure.
+
+```swift
+let url = URL(string: "https://example.com/high_resolution_image.png")
+let processor = DownsamplingImageProcessor(size: imageView.bounds.size)
+             |> RoundCornerImageProcessor(cornerRadius: 20)
+imageView.kf.indicatorType = .activity
+imageView.kf.setImage(
+    with: url,
+    placeholder: UIImage(named: "placeholderImage"),
+    options: [
+        .processor(processor),
+        .scaleFactor(UIScreen.main.scale),
+        .transition(.fade(1)),
+        .cacheOriginalImage
+    ])
+{
+    result in
+    switch result {
+    case .success(let value):
+        print("Task done for: \(value.source.url?.absoluteString ?? "")")
+    case .failure(let error):
+        print("Job failed: \(error.localizedDescription)")
+    }
+}
+```
+
+It is a common situation I can meet in my daily work. Think about how many lines you need to write without
+Kingfisher!
+
+### Method Chaining
+
+If you are not a fan of the `kf` extension, you can also prefer to use the `KF` builder and chained the method 
+invocations. The code below is doing the same thing:
+
+```swift
+// Use `kf` extension
+imageView.kf.setImage(
+    with: url,
+    placeholder: placeholderImage,
+    options: [
+        .processor(processor),
+        .loadDiskFileSynchronously,
+        .cacheOriginalImage,
+        .transition(.fade(0.25)),
+        .lowDataMode(.network(lowResolutionURL))
+    ],
+    progressBlock: { receivedSize, totalSize in
+        // Progress updated
+    },
+    completionHandler: { result in
+        // Done
+    }
+)
+
+// Use `KF` builder
+KF.url(url)
+  .placeholder(placeholderImage)
+  .setProcessor(processor)
+  .loadDiskFileSynchronously()
+  .cacheMemoryOnly()
+  .fade(duration: 0.25)
+  .lowDataModeSource(.network(lowResolutionURL))
+  .onProgress { receivedSize, totalSize in  }
+  .onSuccess { result in  }
+  .onFailure { error in }
+  .set(to: imageView)
+```
+
+And even better, if later you want to switch to SwiftUI, just change the `KF` above to `KFImage`, and you've done:
+
+```swift
+struct ContentView: View {
+    var body: some View {
+        KFImage.url(url)
+          .placeholder(placeholderImage)
+          .setProcessor(processor)
+          .loadDiskFileSynchronously()
+          .cacheMemoryOnly()
+          .fade(duration: 0.25)
+          .lowDataModeSource(.network(lowResolutionURL))
+          .onProgress { receivedSize, totalSize in  }
+          .onSuccess { result in  }
+          .onFailure { error in }
+    }
+}
+```
+
+### Learn More
+
+To learn the use of Kingfisher by more examples, take a look at the well-prepared [Cheat Sheet](https://github.com/onevcat/Kingfisher/wiki/Cheat-Sheet).
+There we summarized the most common tasks in Kingfisher, you can get a better idea of what this framework can do. 
+There are also some performance tips, remember to check them too.
+
+## Requirements
+
+- iOS 12.0+ / macOS 10.14+ / tvOS 12.0+ / watchOS 5.0+ (if you use only UIKit/AppKit)
+- iOS 14.0+ / macOS 11.0+ / tvOS 14.0+ / watchOS 7.0+ (if you use it in SwiftUI)
+- Swift 5.0+
+
+> If you need support from iOS 10 (UIKit/AppKit) or iOS 13 (SwiftUI), use Kingfisher version 6.x. But it won't work 
+> with Xcode 13.0 and Xcode 13.1 [#1802](https://github.com/onevcat/Kingfisher/issues/1802).
+>
+> If you need to use Xcode 13.0 and 13.1 but cannot upgrade to v7, use the `version6-xcode13` branch. However, you have to drop 
+> iOS 10 support due to another Xcode 13 bug.
+>
+> | UIKit | SwiftUI | Xcode | Kingfisher |
+> |---|---|---|---|
+> | iOS 10+ | iOS 13+ | 12 | ~> 6.3.1 |
+> | iOS 11+ | iOS 13+ | 13 | `version6-xcode13` |
+> | iOS 12+ | iOS 14+ | 13 | ~> 7.0 |
+
+### Installation
+
+A detailed guide for installation can be found in [Installation Guide](https://github.com/onevcat/Kingfisher/wiki/Installation-Guide).
+
+#### Swift Package Manager
+
+- File > Swift Packages > Add Package Dependency
+- Add `https://github.com/onevcat/Kingfisher.git`
+- Select "Up to Next Major" with "7.0.0"
+
+#### CocoaPods
+
+```ruby
+source 'https://github.com/CocoaPods/Specs.git'
+platform :ios, '12.0'
+use_frameworks!
+
+target 'MyApp' do
+  pod 'Kingfisher', '~> 7.0'
+end
+```
+
+#### Carthage
+
+```
+github "onevcat/Kingfisher" ~> 7.0
+```
+
+
+### Migrating
+
+[Kingfisher 7.0 Migration](https://github.com/onevcat/Kingfisher/wiki/Kingfisher-7.0-Migration-Guide) - Kingfisher 7.x is NOT fully compatible with the previous version. However, changes should be trivial or not required at all. Please follow the [migration guide](https://github.com/onevcat/Kingfisher/wiki/Kingfisher-7.0-Migration-Guide) when you prepare to upgrade Kingfisher in your project.
+
+If you are using an even earlier version, see the guides below to know the steps for migrating.
+
+> - [Kingfisher 6.0 Migration](https://github.com/onevcat/Kingfisher/wiki/Kingfisher-6.0-Migration-Guide) - Kingfisher 6.x is NOT fully compatible with the previous version. However, migration is not difficult. Depending on your use cases, it may take no effect or several minutes to modify your existing code for the new version. Please follow the [migration guide](https://github.com/onevcat/Kingfisher/wiki/Kingfisher-6.0-Migration-Guide) when you prepare to upgrade Kingfisher in your project.
+> - [Kingfisher 5.0 Migration](https://github.com/onevcat/Kingfisher/wiki/Kingfisher-5.0-Migration-Guide) - If you are upgrading to Kingfisher 5.x from 4.x, please read this for more information.
+> - Kingfisher 4.0 Migration - Kingfisher 3.x should be source compatible to Kingfisher 4. The reason for a major update is that we need to specify the Swift version explicitly for Xcode. All deprecated methods in Kingfisher 3 were removed, so please ensure you have no warning left before you migrate from Kingfisher 3 with Kingfisher 4. If you have any trouble when migrating, please open an issue to discuss.
+> - [Kingfisher 3.0 Migration](https://github.com/onevcat/Kingfisher/wiki/Kingfisher-3.0-Migration-Guide) - If you are upgrading to Kingfisher 3.x from an earlier version, please read this for more information.
+
+## Next Steps
+
+We prepared a [wiki page](https://github.com/onevcat/Kingfisher/wiki). You can find tons of useful things there.
+
+* [Installation Guide](https://github.com/onevcat/Kingfisher/wiki/Installation-Guide) - Follow it to integrate Kingfisher into your project.
+* [Cheat Sheet](https://github.com/onevcat/Kingfisher/wiki/Cheat-Sheet)- Curious about what Kingfisher could do and how would it look like when used in your project? See this page for useful code snippets. If you are already familiar with Kingfisher, you could also learn new tricks to improve the way you use Kingfisher!
+* [API Reference](https://swiftpackageindex.com/onevcat/Kingfisher/master/documentation/kingfisher) - Lastly, please remember to read the full API reference whenever you need more detailed documentation.
+
+## Other
+
+### Future of Kingfisher
+
+I want to keep Kingfisher lightweight. This framework focuses on providing a simple solution for downloading and caching images. This doesn’t mean the framework can’t be improved. Kingfisher is far from perfect, so necessary and useful updates will be made to make it better.
+
+### Developments and Tests
+
+Any contributing and pull requests are warmly welcome. However, before you plan to implement some features or try to fix an uncertain issue, it is recommended to open a discussion first. It would be appreciated if your pull requests could build with all tests green. :)
+
+### About the logo
+
+The logo of Kingfisher is inspired by [Tangram (七巧板)](http://en.wikipedia.org/wiki/Tangram), a dissection puzzle consisting of seven flat shapes from China. I believe she's a kingfisher bird instead of a swift, but someone insists that she is a pigeon. I guess I should give her a name. Hi, guys, do you have any suggestions?
+
+### Contact
+
+Follow and contact me on [Twitter](http://twitter.com/onevcat) or [Sina Weibo](http://weibo.com/onevcat). If you find an issue, [open a ticket](https://github.com/onevcat/Kingfisher/issues/new). Pull requests are warmly welcome as well.
+
+## Backers & Sponsors
+
+Open-source projects cannot live long without your help. If you find Kingfisher to be useful, please consider supporting this 
+project by becoming a sponsor. Your user icon or company logo shows up [on my blog](https://onevcat.com/tabs/about/) with a link to your home page. 
+
+Become a sponsor through [GitHub Sponsors](https://github.com/sponsors/onevcat). :heart:
+
+Special thanks to:
+
+[![imgly](https://user-images.githubusercontent.com/1812216/106253726-271ed000-6218-11eb-98e0-c9c681925770.png)](https://img.ly/)
+
+[![emergetools](https://github-production-user-asset-6210df.s3.amazonaws.com/1019875/254794187-d44f6f50-993f-42e3-b79c-960f69c4adc1.png)](https://www.emergetools.com)
+
+
+
+### License
+
+Kingfisher is released under the MIT license. See LICENSE for details.

+ 137 - 0
Pods/Kingfisher/Sources/Cache/CacheSerializer.swift

@@ -0,0 +1,137 @@
+//
+//  CacheSerializer.swift
+//  Kingfisher
+//
+//  Created by Wei Wang on 2016/09/02.
+//
+//  Copyright (c) 2019 Wei Wang <onevcat@gmail.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
+import CoreGraphics
+#if os(macOS)
+import AppKit
+#else
+import UIKit
+#endif
+
+/// An `CacheSerializer` is used to convert some data to an image object after
+/// retrieving it from disk storage, and vice versa, to convert an image to data object
+/// for storing to the disk storage.
+public protocol CacheSerializer {
+    
+    /// Gets the serialized data from a provided image
+    /// and optional original data for caching to disk.
+    ///
+    /// - Parameters:
+    ///   - image: The image needed to be serialized.
+    ///   - original: The original data which is just downloaded.
+    ///               If the image is retrieved from cache instead of
+    ///               downloaded, it will be `nil`.
+    /// - Returns: The data object for storing to disk, or `nil` when no valid
+    ///            data could be serialized.
+    func data(with image: KFCrossPlatformImage, original: Data?) -> Data?
+
+    /// Gets an image from provided serialized data.
+    ///
+    /// - Parameters:
+    ///   - data: The data from which an image should be deserialized.
+    ///   - options: The parsed options for deserialization.
+    /// - Returns: An image deserialized or `nil` when no valid image
+    ///            could be deserialized.
+    func image(with data: Data, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage?
+    
+    /// Whether this serializer prefers to cache the original data in its implementation.
+    /// If `true`, after creating the image from the disk data, Kingfisher will continue to apply the processor to get
+    /// the final image.
+    ///
+    /// By default, it is `false` and the actual processed image is assumed to be serialized to the disk.
+    var originalDataUsed: Bool { get }
+}
+
+public extension CacheSerializer {
+    var originalDataUsed: Bool { false }
+}
+
+/// Represents a basic and default `CacheSerializer` used in Kingfisher disk cache system.
+/// It could serialize and deserialize images in PNG, JPEG and GIF format. For
+/// image other than these formats, a normalized `pngRepresentation` will be used.
+public struct DefaultCacheSerializer: CacheSerializer {
+    
+    /// The default general cache serializer used across Kingfisher's cache.
+    public static let `default` = DefaultCacheSerializer()
+
+    /// The compression quality when converting image to a lossy format data. Default is 1.0.
+    public var compressionQuality: CGFloat = 1.0
+
+    /// Whether the original data should be preferred when serializing the image.
+    /// If `true`, the input original data will be checked first and used unless the data is `nil`.
+    /// In that case, the serialization will fall back to creating data from image.
+    public var preferCacheOriginalData: Bool = false
+
+    /// Returnes the `preferCacheOriginalData` value. When the original data is used, Kingfisher needs to re-apply the
+    /// processors to get the desired final image.
+    public var originalDataUsed: Bool { preferCacheOriginalData }
+    
+    /// Creates a cache serializer that serialize and deserialize images in PNG, JPEG and GIF format.
+    ///
+    /// - Note:
+    /// Use `DefaultCacheSerializer.default` unless you need to specify your own properties.
+    ///
+    public init() { }
+
+    /// - Parameters:
+    ///   - image: The image needed to be serialized.
+    ///   - original: The original data which is just downloaded.
+    ///               If the image is retrieved from cache instead of
+    ///               downloaded, it will be `nil`.
+    /// - Returns: The data object for storing to disk, or `nil` when no valid
+    ///            data could be serialized.
+    ///
+    /// - Note:
+    /// Only when `original` contains valid PNG, JPEG and GIF format data, the `image` will be
+    /// converted to the corresponding data type. Otherwise, if the `original` is provided but it is not
+    /// If `original` is `nil`, the input `image` will be encoded as PNG data.
+    public func data(with image: KFCrossPlatformImage, original: Data?) -> Data? {
+        if preferCacheOriginalData {
+            return original ??
+                image.kf.data(
+                    format: original?.kf.imageFormat ?? .unknown,
+                    compressionQuality: compressionQuality
+                )
+        } else {
+            return image.kf.data(
+                format: original?.kf.imageFormat ?? .unknown,
+                compressionQuality: compressionQuality
+            )
+        }
+    }
+    
+    /// Gets an image deserialized from provided data.
+    ///
+    /// - Parameters:
+    ///   - data: The data from which an image should be deserialized.
+    ///   - options: Options for deserialization.
+    /// - Returns: An image deserialized or `nil` when no valid image
+    ///            could be deserialized.
+    public func image(with data: Data, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
+        return KingfisherWrapper.image(data: data, options: options.imageCreatingOptions)
+    }
+}

+ 616 - 0
Pods/Kingfisher/Sources/Cache/DiskStorage.swift

@@ -0,0 +1,616 @@
+//
+//  DiskStorage.swift
+//  Kingfisher
+//
+//  Created by Wei Wang on 2018/10/15.
+//
+//  Copyright (c) 2019 Wei Wang <onevcat@gmail.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
+
+
+/// Represents a set of conception related to storage which stores a certain type of value in disk.
+/// This is a namespace for the disk storage types. A `Backend` with a certain `Config` will be used to describe the
+/// storage. See these composed types for more information.
+public enum DiskStorage {
+
+    /// Represents a storage back-end for the `DiskStorage`. The value is serialized to data
+    /// and stored as file in the file system under a specified location.
+    ///
+    /// You can config a `DiskStorage.Backend` in its initializer by passing a `DiskStorage.Config` value.
+    /// or modifying the `config` property after it being created. `DiskStorage` will use file's attributes to keep
+    /// track of a file for its expiration or size limitation.
+    public class Backend<T: DataTransformable> {
+        /// The config used for this disk storage.
+        public var config: Config
+
+        // The final storage URL on disk, with `name` and `cachePathBlock` considered.
+        public let directoryURL: URL
+
+        let metaChangingQueue: DispatchQueue
+
+        var maybeCached : Set<String>?
+        let maybeCachedCheckingQueue = DispatchQueue(label: "com.onevcat.Kingfisher.maybeCachedCheckingQueue")
+
+        // `false` if the storage initialized with an error. This prevents unexpected forcibly crash when creating
+        // storage in the default cache.
+        private var storageReady: Bool = true
+
+        /// Creates a disk storage with the given `DiskStorage.Config`.
+        ///
+        /// - Parameter config: The config used for this disk storage.
+        /// - Throws: An error if the folder for storage cannot be got or created.
+        public convenience init(config: Config) throws {
+            self.init(noThrowConfig: config, creatingDirectory: false)
+            try prepareDirectory()
+        }
+
+        // If `creatingDirectory` is `false`, the directory preparation will be skipped.
+        // We need to call `prepareDirectory` manually after this returns.
+        init(noThrowConfig config: Config, creatingDirectory: Bool) {
+            var config = config
+
+            let creation = Creation(config)
+            self.directoryURL = creation.directoryURL
+
+            // Break any possible retain cycle set by outside.
+            config.cachePathBlock = nil
+            self.config = config
+
+            metaChangingQueue = DispatchQueue(label: creation.cacheName)
+            setupCacheChecking()
+
+            if creatingDirectory {
+                try? prepareDirectory()
+            }
+        }
+
+        private func setupCacheChecking() {
+            maybeCachedCheckingQueue.async {
+                do {
+                    self.maybeCached = Set()
+                    try self.config.fileManager.contentsOfDirectory(atPath: self.directoryURL.path).forEach { fileName in
+                        self.maybeCached?.insert(fileName)
+                    }
+                } catch {
+                    // Just disable the functionality if we fail to initialize it properly. This will just revert to
+                    // the behavior which is to check file existence on disk directly.
+                    self.maybeCached = nil
+                }
+            }
+        }
+
+        // Creates the storage folder.
+        private func prepareDirectory() throws {
+            let fileManager = config.fileManager
+            let path = directoryURL.path
+
+            guard !fileManager.fileExists(atPath: path) else { return }
+
+            do {
+                try fileManager.createDirectory(
+                    atPath: path,
+                    withIntermediateDirectories: true,
+                    attributes: nil)
+            } catch {
+                self.storageReady = false
+                throw KingfisherError.cacheError(reason: .cannotCreateDirectory(path: path, error: error))
+            }
+        }
+
+        /// Stores a value to the storage under the specified key and expiration policy.
+        /// - Parameters:
+        ///   - value: The value to be stored.
+        ///   - key: The key to which the `value` will be stored. If there is already a value under the key,
+        ///          the old value will be overwritten by `value`.
+        ///   - expiration: The expiration policy used by this store action.
+        ///   - writeOptions: Data writing options used the new files.
+        /// - Throws: An error during converting the value to a data format or during writing it to disk.
+        public func store(
+            value: T,
+            forKey key: String,
+            expiration: StorageExpiration? = nil,
+            writeOptions: Data.WritingOptions = []) throws
+        {
+            guard storageReady else {
+                throw KingfisherError.cacheError(reason: .diskStorageIsNotReady(cacheURL: directoryURL))
+            }
+
+            let expiration = expiration ?? config.expiration
+            // The expiration indicates that already expired, no need to store.
+            guard !expiration.isExpired else { return }
+            
+            let data: Data
+            do {
+                data = try value.toData()
+            } catch {
+                throw KingfisherError.cacheError(reason: .cannotConvertToData(object: value, error: error))
+            }
+
+            let fileURL = cacheFileURL(forKey: key)
+            do {
+                try data.write(to: fileURL, options: writeOptions)
+            } catch {
+                if error.isFolderMissing {
+                    // The whole cache folder is deleted. Try to recreate it and write file again.
+                    do {
+                        try prepareDirectory()
+                        try data.write(to: fileURL, options: writeOptions)
+                    } catch {
+                        throw KingfisherError.cacheError(
+                            reason: .cannotCreateCacheFile(fileURL: fileURL, key: key, data: data, error: error)
+                        )
+                    }
+                } else {
+                    throw KingfisherError.cacheError(
+                        reason: .cannotCreateCacheFile(fileURL: fileURL, key: key, data: data, error: error)
+                    )
+                }
+            }
+
+            let now = Date()
+            let attributes: [FileAttributeKey : Any] = [
+                // The last access date.
+                .creationDate: now.fileAttributeDate,
+                // The estimated expiration date.
+                .modificationDate: expiration.estimatedExpirationSinceNow.fileAttributeDate
+            ]
+            do {
+                try config.fileManager.setAttributes(attributes, ofItemAtPath: fileURL.path)
+            } catch {
+                try? config.fileManager.removeItem(at: fileURL)
+                throw KingfisherError.cacheError(
+                    reason: .cannotSetCacheFileAttribute(
+                        filePath: fileURL.path,
+                        attributes: attributes,
+                        error: error
+                    )
+                )
+            }
+
+            maybeCachedCheckingQueue.async {
+                self.maybeCached?.insert(fileURL.lastPathComponent)
+            }
+        }
+
+        /// Gets a value from the storage.
+        /// - Parameters:
+        ///   - key: The cache key of value.
+        ///   - extendingExpiration: The expiration policy used by this getting action.
+        /// - Throws: An error during converting the data to a value or during operation of disk files.
+        /// - Returns: The value under `key` if it is valid and found in the storage. Otherwise, `nil`.
+        public func value(forKey key: String, extendingExpiration: ExpirationExtending = .cacheTime) throws -> T? {
+            return try value(forKey: key, referenceDate: Date(), actuallyLoad: true, extendingExpiration: extendingExpiration)
+        }
+
+        func value(
+            forKey key: String,
+            referenceDate: Date,
+            actuallyLoad: Bool,
+            extendingExpiration: ExpirationExtending) throws -> T?
+        {
+            guard storageReady else {
+                throw KingfisherError.cacheError(reason: .diskStorageIsNotReady(cacheURL: directoryURL))
+            }
+
+            let fileManager = config.fileManager
+            let fileURL = cacheFileURL(forKey: key)
+            let filePath = fileURL.path
+
+            let fileMaybeCached = maybeCachedCheckingQueue.sync {
+                return maybeCached?.contains(fileURL.lastPathComponent) ?? true
+            }
+            guard fileMaybeCached else {
+                return nil
+            }
+            guard fileManager.fileExists(atPath: filePath) else {
+                return nil
+            }
+
+            let meta: FileMeta
+            do {
+                let resourceKeys: Set<URLResourceKey> = [.contentModificationDateKey, .creationDateKey]
+                meta = try FileMeta(fileURL: fileURL, resourceKeys: resourceKeys)
+            } catch {
+                throw KingfisherError.cacheError(
+                    reason: .invalidURLResource(error: error, key: key, url: fileURL))
+            }
+
+            if meta.expired(referenceDate: referenceDate) {
+                return nil
+            }
+            if !actuallyLoad { return T.empty }
+
+            do {
+                let data = try Data(contentsOf: fileURL)
+                let obj = try T.fromData(data)
+                metaChangingQueue.async {
+                    meta.extendExpiration(with: fileManager, extendingExpiration: extendingExpiration)
+                }
+                return obj
+            } catch {
+                throw KingfisherError.cacheError(reason: .cannotLoadDataFromDisk(url: fileURL, error: error))
+            }
+        }
+
+        /// Whether there is valid cached data under a given key.
+        /// - Parameter key: The cache key of value.
+        /// - Returns: If there is valid data under the key, `true`. Otherwise, `false`.
+        ///
+        /// - Note:
+        /// This method does not actually load the data from disk, so it is faster than directly loading the cached value
+        /// by checking the nullability of `value(forKey:extendingExpiration:)` method.
+        ///
+        public func isCached(forKey key: String) -> Bool {
+            return isCached(forKey: key, referenceDate: Date())
+        }
+
+        /// Whether there is valid cached data under a given key and a reference date.
+        /// - Parameters:
+        ///   - key: The cache key of value.
+        ///   - referenceDate: A reference date to check whether the cache is still valid.
+        /// - Returns: If there is valid data under the key, `true`. Otherwise, `false`.
+        ///
+        /// - Note:
+        /// If you pass `Date()` to `referenceDate`, this method is identical to `isCached(forKey:)`. Use the
+        /// `referenceDate` to determine whether the cache is still valid for a future date.
+        public func isCached(forKey key: String, referenceDate: Date) -> Bool {
+            do {
+                let result = try value(
+                    forKey: key,
+                    referenceDate: referenceDate,
+                    actuallyLoad: false,
+                    extendingExpiration: .none
+                )
+                return result != nil
+            } catch {
+                return false
+            }
+        }
+
+        /// Removes a value from a specified key.
+        /// - Parameter key: The cache key of value.
+        /// - Throws: An error during removing the value.
+        public func remove(forKey key: String) throws {
+            let fileURL = cacheFileURL(forKey: key)
+            try removeFile(at: fileURL)
+        }
+
+        func removeFile(at url: URL) throws {
+            try config.fileManager.removeItem(at: url)
+        }
+
+        /// Removes all values in this storage.
+        /// - Throws: An error during removing the values.
+        public func removeAll() throws {
+            try removeAll(skipCreatingDirectory: false)
+        }
+
+        func removeAll(skipCreatingDirectory: Bool) throws {
+            try config.fileManager.removeItem(at: directoryURL)
+            if !skipCreatingDirectory {
+                try prepareDirectory()
+            }
+        }
+
+        /// The URL of the cached file with a given computed `key`.
+        ///
+        /// - Parameter key: The final computed key used when caching the image. Please note that usually this is not
+        /// the `cacheKey` of an image `Source`. It is the computed key with processor identifier considered.
+        ///
+        /// - Note:
+        /// This method does not guarantee there is an image already cached in the returned URL. It just gives your
+        /// the URL that the image should be if it exists in disk storage, with the give key.
+        ///
+        public func cacheFileURL(forKey key: String) -> URL {
+            let fileName = cacheFileName(forKey: key)
+            return directoryURL.appendingPathComponent(fileName, isDirectory: false)
+        }
+
+        func cacheFileName(forKey key: String) -> String {
+            if config.usesHashedFileName {
+                let hashedKey = key.kf.md5
+                if let ext = config.pathExtension {
+                    return "\(hashedKey).\(ext)"
+                } else if config.autoExtAfterHashedFileName,
+                          let ext = key.kf.ext {
+                    return "\(hashedKey).\(ext)"
+                }
+                return hashedKey
+            } else {
+                if let ext = config.pathExtension {
+                    return "\(key).\(ext)"
+                }
+                return key
+            }
+        }
+
+        func allFileURLs(for propertyKeys: [URLResourceKey]) throws -> [URL] {
+            let fileManager = config.fileManager
+
+            guard let directoryEnumerator = fileManager.enumerator(
+                at: directoryURL, includingPropertiesForKeys: propertyKeys, options: .skipsHiddenFiles) else
+            {
+                throw KingfisherError.cacheError(reason: .fileEnumeratorCreationFailed(url: directoryURL))
+            }
+
+            guard let urls = directoryEnumerator.allObjects as? [URL] else {
+                throw KingfisherError.cacheError(reason: .invalidFileEnumeratorContent(url: directoryURL))
+            }
+            return urls
+        }
+
+        /// Removes all expired values from this storage.
+        /// - Throws: A file manager error during removing the file.
+        /// - Returns: The URLs for removed files.
+        public func removeExpiredValues() throws -> [URL] {
+            return try removeExpiredValues(referenceDate: Date())
+        }
+
+        func removeExpiredValues(referenceDate: Date) throws -> [URL] {
+            let propertyKeys: [URLResourceKey] = [
+                .isDirectoryKey,
+                .contentModificationDateKey
+            ]
+
+            let urls = try allFileURLs(for: propertyKeys)
+            let keys = Set(propertyKeys)
+            let expiredFiles = urls.filter { fileURL in
+                do {
+                    let meta = try FileMeta(fileURL: fileURL, resourceKeys: keys)
+                    if meta.isDirectory {
+                        return false
+                    }
+                    return meta.expired(referenceDate: referenceDate)
+                } catch {
+                    return true
+                }
+            }
+            try expiredFiles.forEach { url in
+                try removeFile(at: url)
+            }
+            return expiredFiles
+        }
+
+        /// Removes all size exceeded values from this storage.
+        /// - Throws: A file manager error during removing the file.
+        /// - Returns: The URLs for removed files.
+        ///
+        /// - Note: This method checks `config.sizeLimit` and remove cached files in an LRU (Least Recently Used) way.
+        func removeSizeExceededValues() throws -> [URL] {
+
+            if config.sizeLimit == 0 { return [] } // Back compatible. 0 means no limit.
+
+            var size = try totalSize()
+            if size < config.sizeLimit { return [] }
+
+            let propertyKeys: [URLResourceKey] = [
+                .isDirectoryKey,
+                .creationDateKey,
+                .fileSizeKey
+            ]
+            let keys = Set(propertyKeys)
+
+            let urls = try allFileURLs(for: propertyKeys)
+            var pendings: [FileMeta] = urls.compactMap { fileURL in
+                guard let meta = try? FileMeta(fileURL: fileURL, resourceKeys: keys) else {
+                    return nil
+                }
+                return meta
+            }
+            // Sort by last access date. Most recent file first.
+            pendings.sort(by: FileMeta.lastAccessDate)
+
+            var removed: [URL] = []
+            let target = config.sizeLimit / 2
+            while size > target, let meta = pendings.popLast() {
+                size -= UInt(meta.fileSize)
+                try removeFile(at: meta.url)
+                removed.append(meta.url)
+            }
+            return removed
+        }
+
+        /// Gets the total file size of the folder in bytes.
+        public func totalSize() throws -> UInt {
+            let propertyKeys: [URLResourceKey] = [.fileSizeKey]
+            let urls = try allFileURLs(for: propertyKeys)
+            let keys = Set(propertyKeys)
+            let totalSize: UInt = urls.reduce(0) { size, fileURL in
+                do {
+                    let meta = try FileMeta(fileURL: fileURL, resourceKeys: keys)
+                    return size + UInt(meta.fileSize)
+                } catch {
+                    return size
+                }
+            }
+            return totalSize
+        }
+    }
+}
+
+extension DiskStorage {
+    /// Represents the config used in a `DiskStorage`.
+    public struct Config {
+
+        /// The file size limit on disk of the storage in bytes. 0 means no limit.
+        public var sizeLimit: UInt
+
+        /// The `StorageExpiration` used in this disk storage. Default is `.days(7)`,
+        /// means that the disk cache would expire in one week.
+        public var expiration: StorageExpiration = .days(7)
+
+        /// The preferred extension of cache item. It will be appended to the file name as its extension.
+        /// Default is `nil`, means that the cache file does not contain a file extension.
+        public var pathExtension: String? = nil
+
+        /// Default is `true`, means that the cache file name will be hashed before storing.
+        public var usesHashedFileName = true
+
+        /// Default is `false`
+        /// If set to `true`, image extension will be extracted from original file name and append to
+        /// the hased file name and used as the cache key on disk.
+        public var autoExtAfterHashedFileName = false
+        
+        /// Closure that takes in initial directory path and generates
+        /// the final disk cache path. You can use it to fully customize your cache path.
+        public var cachePathBlock: ((_ directory: URL, _ cacheName: String) -> URL)! = {
+            (directory, cacheName) in
+            return directory.appendingPathComponent(cacheName, isDirectory: true)
+        }
+
+        let name: String
+        let fileManager: FileManager
+        let directory: URL?
+
+        /// Creates a config value based on given parameters.
+        ///
+        /// - Parameters:
+        ///   - name: The name of cache. It is used as a part of storage folder. It is used to identify the disk
+        ///           storage. Two storages with the same `name` would share the same folder in disk, and it should
+        ///           be prevented.
+        ///   - sizeLimit: The size limit in bytes for all existing files in the disk storage.
+        ///   - fileManager: The `FileManager` used to manipulate files on disk. Default is `FileManager.default`.
+        ///   - directory: The URL where the disk storage should live. The storage will use this as the root folder,
+        ///                and append a path which is constructed by input `name`. Default is `nil`, indicates that
+        ///                the cache directory under user domain mask will be used.
+        public init(
+            name: String,
+            sizeLimit: UInt,
+            fileManager: FileManager = .default,
+            directory: URL? = nil)
+        {
+            self.name = name
+            self.fileManager = fileManager
+            self.directory = directory
+            self.sizeLimit = sizeLimit
+        }
+    }
+}
+
+extension DiskStorage {
+    struct FileMeta {
+    
+        let url: URL
+        
+        let lastAccessDate: Date?
+        let estimatedExpirationDate: Date?
+        let isDirectory: Bool
+        let fileSize: Int
+        
+        static func lastAccessDate(lhs: FileMeta, rhs: FileMeta) -> Bool {
+            return lhs.lastAccessDate ?? .distantPast > rhs.lastAccessDate ?? .distantPast
+        }
+        
+        init(fileURL: URL, resourceKeys: Set<URLResourceKey>) throws {
+            let meta = try fileURL.resourceValues(forKeys: resourceKeys)
+            self.init(
+                fileURL: fileURL,
+                lastAccessDate: meta.creationDate,
+                estimatedExpirationDate: meta.contentModificationDate,
+                isDirectory: meta.isDirectory ?? false,
+                fileSize: meta.fileSize ?? 0)
+        }
+        
+        init(
+            fileURL: URL,
+            lastAccessDate: Date?,
+            estimatedExpirationDate: Date?,
+            isDirectory: Bool,
+            fileSize: Int)
+        {
+            self.url = fileURL
+            self.lastAccessDate = lastAccessDate
+            self.estimatedExpirationDate = estimatedExpirationDate
+            self.isDirectory = isDirectory
+            self.fileSize = fileSize
+        }
+
+        func expired(referenceDate: Date) -> Bool {
+            return estimatedExpirationDate?.isPast(referenceDate: referenceDate) ?? true
+        }
+        
+        func extendExpiration(with fileManager: FileManager, extendingExpiration: ExpirationExtending) {
+            guard let lastAccessDate = lastAccessDate,
+                  let lastEstimatedExpiration = estimatedExpirationDate else
+            {
+                return
+            }
+
+            let attributes: [FileAttributeKey : Any]
+
+            switch extendingExpiration {
+            case .none:
+                // not extending expiration time here
+                return
+            case .cacheTime:
+                let originalExpiration: StorageExpiration =
+                    .seconds(lastEstimatedExpiration.timeIntervalSince(lastAccessDate))
+                attributes = [
+                    .creationDate: Date().fileAttributeDate,
+                    .modificationDate: originalExpiration.estimatedExpirationSinceNow.fileAttributeDate
+                ]
+            case .expirationTime(let expirationTime):
+                attributes = [
+                    .creationDate: Date().fileAttributeDate,
+                    .modificationDate: expirationTime.estimatedExpirationSinceNow.fileAttributeDate
+                ]
+            }
+
+            try? fileManager.setAttributes(attributes, ofItemAtPath: url.path)
+        }
+    }
+}
+
+extension DiskStorage {
+    struct Creation {
+        let directoryURL: URL
+        let cacheName: String
+
+        init(_ config: Config) {
+            let url: URL
+            if let directory = config.directory {
+                url = directory
+            } else {
+                url = config.fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0]
+            }
+
+            cacheName = "com.onevcat.Kingfisher.ImageCache.\(config.name)"
+            directoryURL = config.cachePathBlock(url, cacheName)
+        }
+    }
+}
+
+fileprivate extension Error {
+    var isFolderMissing: Bool {
+        let nsError = self as NSError
+        guard nsError.domain == NSCocoaErrorDomain, nsError.code == 4 else {
+            return false
+        }
+        guard let underlyingError = nsError.userInfo[NSUnderlyingErrorKey] as? NSError else {
+            return false
+        }
+        guard underlyingError.domain == NSPOSIXErrorDomain, underlyingError.code == 2 else {
+            return false
+        }
+        return true
+    }
+}

+ 123 - 0
Pods/Kingfisher/Sources/Cache/FormatIndicatedCacheSerializer.swift

@@ -0,0 +1,123 @@
+//
+//  RequestModifier.swift
+//  Kingfisher
+//
+//  Created by Junyu Kuang on 5/28/17.
+//
+//  Copyright (c) 2019 Wei Wang <onevcat@gmail.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
+import CoreGraphics
+#if os(macOS)
+import AppKit
+#else
+import UIKit
+#endif
+
+/// `FormatIndicatedCacheSerializer` lets you indicate an image format for serialized caches.
+///
+/// It could serialize and deserialize PNG, JPEG and GIF images. For
+/// image other than these formats, a normalized `pngRepresentation` will be used.
+///
+/// Example:
+/// ````
+/// let profileImageSize = CGSize(width: 44, height: 44)
+///
+/// // A round corner image.
+/// let imageProcessor = RoundCornerImageProcessor(
+///     cornerRadius: profileImageSize.width / 2, targetSize: profileImageSize)
+///
+/// let optionsInfo: KingfisherOptionsInfo = [
+///     .cacheSerializer(FormatIndicatedCacheSerializer.png), 
+///     .processor(imageProcessor)]
+///
+/// A URL pointing to a JPEG image.
+/// let url = URL(string: "https://example.com/image.jpg")!
+///
+/// // Image will be always cached as PNG format to preserve alpha channel for round rectangle.
+/// // So when you load it from cache again later, it will be still round cornered.
+/// // Otherwise, the corner part would be filled by white color (since JPEG does not contain an alpha channel).
+/// imageView.kf.setImage(with: url, options: optionsInfo)
+/// ````
+public struct FormatIndicatedCacheSerializer: CacheSerializer {
+    
+    /// A `FormatIndicatedCacheSerializer` which converts image from and to PNG format. If the image cannot be
+    /// represented by PNG format, it will fallback to its real format which is determined by `original` data.
+    public static let png = FormatIndicatedCacheSerializer(imageFormat: .PNG, jpegCompressionQuality: nil)
+    
+    /// A `FormatIndicatedCacheSerializer` which converts image from and to JPEG format. If the image cannot be
+    /// represented by JPEG format, it will fallback to its real format which is determined by `original` data.
+    /// The compression quality is 1.0 when using this serializer. If you need to set a customized compression quality,
+    /// use `jpeg(compressionQuality:)`.
+    public static let jpeg = FormatIndicatedCacheSerializer(imageFormat: .JPEG, jpegCompressionQuality: 1.0)
+
+    /// A `FormatIndicatedCacheSerializer` which converts image from and to JPEG format with a settable compression
+    /// quality. If the image cannot be represented by JPEG format, it will fallback to its real format which is
+    /// determined by `original` data.
+    /// - Parameter compressionQuality: The compression quality when converting image to JPEG data.
+    public static func jpeg(compressionQuality: CGFloat) -> FormatIndicatedCacheSerializer {
+        return FormatIndicatedCacheSerializer(imageFormat: .JPEG, jpegCompressionQuality: compressionQuality)
+    }
+    
+    /// A `FormatIndicatedCacheSerializer` which converts image from and to GIF format. If the image cannot be
+    /// represented by GIF format, it will fallback to its real format which is determined by `original` data.
+    public static let gif = FormatIndicatedCacheSerializer(imageFormat: .GIF, jpegCompressionQuality: nil)
+    
+    /// The indicated image format.
+    private let imageFormat: ImageFormat
+
+    /// The compression quality used for loss image format (like JPEG).
+    private let jpegCompressionQuality: CGFloat?
+    
+    /// Creates data which represents the given `image` under a format.
+    public func data(with image: KFCrossPlatformImage, original: Data?) -> Data? {
+        
+        func imageData(withFormat imageFormat: ImageFormat) -> Data? {
+            return autoreleasepool { () -> Data? in
+                switch imageFormat {
+                case .PNG: return image.kf.pngRepresentation()
+                case .JPEG: return image.kf.jpegRepresentation(compressionQuality: jpegCompressionQuality ?? 1.0)
+                case .GIF: return image.kf.gifRepresentation()
+                case .unknown: return nil
+                }
+            }
+        }
+        
+        // generate data with indicated image format
+        if let data = imageData(withFormat: imageFormat) {
+            return data
+        }
+        
+        let originalFormat = original?.kf.imageFormat ?? .unknown
+        
+        // generate data with original image's format
+        if originalFormat != imageFormat, let data = imageData(withFormat: originalFormat) {
+            return data
+        }
+        
+        return original ?? image.kf.normalized.kf.pngRepresentation()
+    }
+    
+    /// Same implementation as `DefaultCacheSerializer`.
+    public func image(with data: Data, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
+        return KingfisherWrapper.image(data: data, options: options.imageCreatingOptions)
+    }
+}

+ 882 - 0
Pods/Kingfisher/Sources/Cache/ImageCache.swift

@@ -0,0 +1,882 @@
+//
+//  ImageCache.swift
+//  Kingfisher
+//
+//  Created by Wei Wang on 15/4/6.
+//
+//  Copyright (c) 2019 Wei Wang <onevcat@gmail.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.
+
+#if os(macOS)
+import AppKit
+#else
+import UIKit
+#endif
+
+extension Notification.Name {
+    /// This notification will be sent when the disk cache got cleaned either there are cached files expired or the
+    /// total size exceeding the max allowed size. The manually invoking of `clearDiskCache` method will not trigger
+    /// this notification.
+    ///
+    /// The `object` of this notification is the `ImageCache` object which sends the notification.
+    /// A list of removed hashes (files) could be retrieved by accessing the array under
+    /// `KingfisherDiskCacheCleanedHashKey` key in `userInfo` of the notification object you received.
+    /// By checking the array, you could know the hash codes of files are removed.
+    public static let KingfisherDidCleanDiskCache =
+        Notification.Name("com.onevcat.Kingfisher.KingfisherDidCleanDiskCache")
+}
+
+/// Key for array of cleaned hashes in `userInfo` of `KingfisherDidCleanDiskCacheNotification`.
+public let KingfisherDiskCacheCleanedHashKey = "com.onevcat.Kingfisher.cleanedHash"
+
+/// Cache type of a cached image.
+/// - none: The image is not cached yet when retrieving it.
+/// - memory: The image is cached in memory.
+/// - disk: The image is cached in disk.
+public enum CacheType {
+    /// The image is not cached yet when retrieving it.
+    case none
+    /// The image is cached in memory.
+    case memory
+    /// The image is cached in disk.
+    case disk
+    
+    /// Whether the cache type represents the image is already cached or not.
+    public var cached: Bool {
+        switch self {
+        case .memory, .disk: return true
+        case .none: return false
+        }
+    }
+}
+
+/// Represents the caching operation result.
+public struct CacheStoreResult {
+    
+    /// The cache result for memory cache. Caching an image to memory will never fail.
+    public let memoryCacheResult: Result<(), Never>
+    
+    /// The cache result for disk cache. If an error happens during caching operation,
+    /// you can get it from `.failure` case of this `diskCacheResult`.
+    public let diskCacheResult: Result<(), KingfisherError>
+}
+
+extension KFCrossPlatformImage: CacheCostCalculable {
+    /// Cost of an image
+    public var cacheCost: Int { return kf.cost }
+}
+
+extension Data: DataTransformable {
+    public func toData() throws -> Data {
+        return self
+    }
+
+    public static func fromData(_ data: Data) throws -> Data {
+        return data
+    }
+
+    public static let empty = Data()
+}
+
+
+/// Represents the getting image operation from the cache.
+///
+/// - disk: The image can be retrieved from disk cache.
+/// - memory: The image can be retrieved memory cache.
+/// - none: The image does not exist in the cache.
+public enum ImageCacheResult {
+    
+    /// The image can be retrieved from disk cache.
+    case disk(KFCrossPlatformImage)
+    
+    /// The image can be retrieved memory cache.
+    case memory(KFCrossPlatformImage)
+    
+    /// The image does not exist in the cache.
+    case none
+    
+    /// Extracts the image from cache result. It returns the associated `Image` value for
+    /// `.disk` and `.memory` case. For `.none` case, `nil` is returned.
+    public var image: KFCrossPlatformImage? {
+        switch self {
+        case .disk(let image): return image
+        case .memory(let image): return image
+        case .none: return nil
+        }
+    }
+    
+    /// Returns the corresponding `CacheType` value based on the result type of `self`.
+    public var cacheType: CacheType {
+        switch self {
+        case .disk: return .disk
+        case .memory: return .memory
+        case .none: return .none
+        }
+    }
+}
+
+/// Represents a hybrid caching system which is composed by a `MemoryStorage.Backend` and a `DiskStorage.Backend`.
+/// `ImageCache` is a high level abstract for storing an image as well as its data to memory and disk, and
+/// retrieving them back.
+///
+/// While a default image cache object will be used if you prefer the extension methods of Kingfisher, you can create
+/// your own cache object and configure its storages as your need. This class also provide an interface for you to set
+/// the memory and disk storage config.
+open class ImageCache {
+
+    // MARK: Singleton
+    /// The default `ImageCache` object. Kingfisher will use this cache for its related methods if there is no
+    /// other cache specified. The `name` of this default cache is "default", and you should not use this name
+    /// for any of your customize cache.
+    public static let `default` = ImageCache(name: "default")
+
+
+    // MARK: Public Properties
+    /// The `MemoryStorage.Backend` object used in this cache. This storage holds loaded images in memory with a
+    /// reasonable expire duration and a maximum memory usage. To modify the configuration of a storage, just set
+    /// the storage `config` and its properties.
+    public let memoryStorage: MemoryStorage.Backend<KFCrossPlatformImage>
+    
+    /// The `DiskStorage.Backend` object used in this cache. This storage stores loaded images in disk with a
+    /// reasonable expire duration and a maximum disk usage. To modify the configuration of a storage, just set
+    /// the storage `config` and its properties.
+    public let diskStorage: DiskStorage.Backend<Data>
+    
+    private let ioQueue: DispatchQueue
+    
+    /// Closure that defines the disk cache path from a given path and cacheName.
+    public typealias DiskCachePathClosure = (URL, String) -> URL
+
+    // MARK: Initializers
+
+    /// Creates an `ImageCache` from a customized `MemoryStorage` and `DiskStorage`.
+    ///
+    /// - Parameters:
+    ///   - memoryStorage: The `MemoryStorage.Backend` object to use in the image cache.
+    ///   - diskStorage: The `DiskStorage.Backend` object to use in the image cache.
+    public init(
+        memoryStorage: MemoryStorage.Backend<KFCrossPlatformImage>,
+        diskStorage: DiskStorage.Backend<Data>)
+    {
+        self.memoryStorage = memoryStorage
+        self.diskStorage = diskStorage
+        let ioQueueName = "com.onevcat.Kingfisher.ImageCache.ioQueue.\(UUID().uuidString)"
+        ioQueue = DispatchQueue(label: ioQueueName)
+
+        let notifications: [(Notification.Name, Selector)]
+        #if !os(macOS) && !os(watchOS)
+        notifications = [
+            (UIApplication.didReceiveMemoryWarningNotification, #selector(clearMemoryCache)),
+            (UIApplication.willTerminateNotification, #selector(cleanExpiredDiskCache)),
+            (UIApplication.didEnterBackgroundNotification, #selector(backgroundCleanExpiredDiskCache))
+        ]
+        #elseif os(macOS)
+        notifications = [
+            (NSApplication.willResignActiveNotification, #selector(cleanExpiredDiskCache)),
+        ]
+        #else
+        notifications = []
+        #endif
+        notifications.forEach {
+            NotificationCenter.default.addObserver(self, selector: $0.1, name: $0.0, object: nil)
+        }
+    }
+    
+    /// Creates an `ImageCache` with a given `name`. Both `MemoryStorage` and `DiskStorage` will be created
+    /// with a default config based on the `name`.
+    ///
+    /// - Parameter name: The name of cache object. It is used to setup disk cache directories and IO queue.
+    ///                   You should not use the same `name` for different caches, otherwise, the disk storage would
+    ///                   be conflicting to each other. The `name` should not be an empty string.
+    public convenience init(name: String) {
+        self.init(noThrowName: name, cacheDirectoryURL: nil, diskCachePathClosure: nil)
+    }
+
+    /// Creates an `ImageCache` with a given `name`, cache directory `path`
+    /// and a closure to modify the cache directory.
+    ///
+    /// - Parameters:
+    ///   - name: The name of cache object. It is used to setup disk cache directories and IO queue.
+    ///           You should not use the same `name` for different caches, otherwise, the disk storage would
+    ///           be conflicting to each other.
+    ///   - cacheDirectoryURL: Location of cache directory URL on disk. It will be internally pass to the
+    ///                        initializer of `DiskStorage` as the disk cache directory. If `nil`, the cache
+    ///                        directory under user domain mask will be used.
+    ///   - diskCachePathClosure: Closure that takes in an optional initial path string and generates
+    ///                           the final disk cache path. You could use it to fully customize your cache path.
+    /// - Throws: An error that happens during image cache creating, such as unable to create a directory at the given
+    ///           path.
+    public convenience init(
+        name: String,
+        cacheDirectoryURL: URL?,
+        diskCachePathClosure: DiskCachePathClosure? = nil
+    ) throws
+    {
+        if name.isEmpty {
+            fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.")
+        }
+
+        let memoryStorage = ImageCache.createMemoryStorage()
+
+        let config = ImageCache.createConfig(
+            name: name, cacheDirectoryURL: cacheDirectoryURL, diskCachePathClosure: diskCachePathClosure
+        )
+        let diskStorage = try DiskStorage.Backend<Data>(config: config)
+        self.init(memoryStorage: memoryStorage, diskStorage: diskStorage)
+    }
+
+    convenience init(
+        noThrowName name: String,
+        cacheDirectoryURL: URL?,
+        diskCachePathClosure: DiskCachePathClosure?
+    )
+    {
+        if name.isEmpty {
+            fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.")
+        }
+
+        let memoryStorage = ImageCache.createMemoryStorage()
+
+        let config = ImageCache.createConfig(
+            name: name, cacheDirectoryURL: cacheDirectoryURL, diskCachePathClosure: diskCachePathClosure
+        )
+        let diskStorage = DiskStorage.Backend<Data>(noThrowConfig: config, creatingDirectory: true)
+        self.init(memoryStorage: memoryStorage, diskStorage: diskStorage)
+    }
+
+    private static func createMemoryStorage() -> MemoryStorage.Backend<KFCrossPlatformImage> {
+        let totalMemory = ProcessInfo.processInfo.physicalMemory
+        let costLimit = totalMemory / 4
+        let memoryStorage = MemoryStorage.Backend<KFCrossPlatformImage>(config:
+            .init(totalCostLimit: (costLimit > Int.max) ? Int.max : Int(costLimit)))
+        return memoryStorage
+    }
+
+    private static func createConfig(
+        name: String,
+        cacheDirectoryURL: URL?,
+        diskCachePathClosure: DiskCachePathClosure? = nil
+    ) -> DiskStorage.Config
+    {
+        var diskConfig = DiskStorage.Config(
+            name: name,
+            sizeLimit: 0,
+            directory: cacheDirectoryURL
+        )
+        if let closure = diskCachePathClosure {
+            diskConfig.cachePathBlock = closure
+        }
+        return diskConfig
+    }
+    
+    deinit {
+        NotificationCenter.default.removeObserver(self)
+    }
+
+    // MARK: Storing Images
+
+    open func store(_ image: KFCrossPlatformImage,
+                    original: Data? = nil,
+                    forKey key: String,
+                    options: KingfisherParsedOptionsInfo,
+                    toDisk: Bool = true,
+                    completionHandler: ((CacheStoreResult) -> Void)? = nil)
+    {
+        let identifier = options.processor.identifier
+        let callbackQueue = options.callbackQueue
+        
+        let computedKey = key.computedKey(with: identifier)
+        // Memory storage should not throw.
+        memoryStorage.storeNoThrow(value: image, forKey: computedKey, expiration: options.memoryCacheExpiration)
+        
+        guard toDisk else {
+            if let completionHandler = completionHandler {
+                let result = CacheStoreResult(memoryCacheResult: .success(()), diskCacheResult: .success(()))
+                callbackQueue.execute { completionHandler(result) }
+            }
+            return
+        }
+        
+        ioQueue.async {
+            let serializer = options.cacheSerializer
+            if let data = serializer.data(with: image, original: original) {
+                self.syncStoreToDisk(
+                    data,
+                    forKey: key,
+                    processorIdentifier: identifier,
+                    callbackQueue: callbackQueue,
+                    expiration: options.diskCacheExpiration,
+                    writeOptions: options.diskStoreWriteOptions,
+                    completionHandler: completionHandler)
+            } else {
+                guard let completionHandler = completionHandler else { return }
+                
+                let diskError = KingfisherError.cacheError(
+                    reason: .cannotSerializeImage(image: image, original: original, serializer: serializer))
+                let result = CacheStoreResult(
+                    memoryCacheResult: .success(()),
+                    diskCacheResult: .failure(diskError))
+                callbackQueue.execute { completionHandler(result) }
+            }
+        }
+    }
+
+    /// Stores an image to the cache.
+    ///
+    /// - Parameters:
+    ///   - image: The image to be stored.
+    ///   - original: The original data of the image. This value will be forwarded to the provided `serializer` for
+    ///               further use. By default, Kingfisher uses a `DefaultCacheSerializer` to serialize the image to
+    ///               data for caching in disk, it checks the image format based on `original` data to determine in
+    ///               which image format should be used. For other types of `serializer`, it depends on their
+    ///               implementation detail on how to use this original data.
+    ///   - key: The key used for caching the image.
+    ///   - identifier: The identifier of processor being used for caching. If you are using a processor for the
+    ///                 image, pass the identifier of processor to this parameter.
+    ///   - serializer: The `CacheSerializer`
+    ///   - toDisk: Whether this image should be cached to disk or not. If `false`, the image is only cached in memory.
+    ///             Otherwise, it is cached in both memory storage and disk storage. Default is `true`.
+    ///   - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.untouch`. For case
+    ///                    that `toDisk` is `false`, a `.untouch` queue means `callbackQueue` will be invoked from the
+    ///                    caller queue of this method. If `toDisk` is `true`, the `completionHandler` will be called
+    ///                    from an internal file IO queue. To change this behavior, specify another `CallbackQueue`
+    ///                    value.
+    ///   - completionHandler: A closure which is invoked when the cache operation finishes.
+    open func store(_ image: KFCrossPlatformImage,
+                      original: Data? = nil,
+                      forKey key: String,
+                      processorIdentifier identifier: String = "",
+                      cacheSerializer serializer: CacheSerializer = DefaultCacheSerializer.default,
+                      toDisk: Bool = true,
+                      callbackQueue: CallbackQueue = .untouch,
+                      completionHandler: ((CacheStoreResult) -> Void)? = nil)
+    {
+        struct TempProcessor: ImageProcessor {
+            let identifier: String
+            func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
+                return nil
+            }
+        }
+        
+        let options = KingfisherParsedOptionsInfo([
+            .processor(TempProcessor(identifier: identifier)),
+            .cacheSerializer(serializer),
+            .callbackQueue(callbackQueue)
+        ])
+        store(image, original: original, forKey: key, options: options,
+              toDisk: toDisk, completionHandler: completionHandler)
+    }
+    
+    open func storeToDisk(
+        _ data: Data,
+        forKey key: String,
+        processorIdentifier identifier: String = "",
+        expiration: StorageExpiration? = nil,
+        callbackQueue: CallbackQueue = .untouch,
+        completionHandler: ((CacheStoreResult) -> Void)? = nil)
+    {
+        ioQueue.async {
+            self.syncStoreToDisk(
+                data,
+                forKey: key,
+                processorIdentifier: identifier,
+                callbackQueue: callbackQueue,
+                expiration: expiration,
+                completionHandler: completionHandler)
+        }
+    }
+    
+    private func syncStoreToDisk(
+        _ data: Data,
+        forKey key: String,
+        processorIdentifier identifier: String = "",
+        callbackQueue: CallbackQueue = .untouch,
+        expiration: StorageExpiration? = nil,
+        writeOptions: Data.WritingOptions = [],
+        completionHandler: ((CacheStoreResult) -> Void)? = nil)
+    {
+        let computedKey = key.computedKey(with: identifier)
+        let result: CacheStoreResult
+        do {
+            try self.diskStorage.store(value: data, forKey: computedKey, expiration: expiration, writeOptions: writeOptions)
+            result = CacheStoreResult(memoryCacheResult: .success(()), diskCacheResult: .success(()))
+        } catch {
+            let diskError: KingfisherError
+            if let error = error as? KingfisherError {
+                diskError = error
+            } else {
+                diskError = .cacheError(reason: .cannotConvertToData(object: data, error: error))
+            }
+            
+            result = CacheStoreResult(
+                memoryCacheResult: .success(()),
+                diskCacheResult: .failure(diskError)
+            )
+        }
+        if let completionHandler = completionHandler {
+            callbackQueue.execute { completionHandler(result) }
+        }
+    }
+
+    // MARK: Removing Images
+
+    /// Removes the image for the given key from the cache.
+    ///
+    /// - Parameters:
+    ///   - key: The key used for caching the image.
+    ///   - identifier: The identifier of processor being used for caching. If you are using a processor for the
+    ///                 image, pass the identifier of processor to this parameter.
+    ///   - fromMemory: Whether this image should be removed from memory storage or not.
+    ///                 If `false`, the image won't be removed from the memory storage. Default is `true`.
+    ///   - fromDisk: Whether this image should be removed from disk storage or not.
+    ///               If `false`, the image won't be removed from the disk storage. Default is `true`.
+    ///   - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.untouch`.
+    ///   - completionHandler: A closure which is invoked when the cache removing operation finishes.
+    open func removeImage(forKey key: String,
+                          processorIdentifier identifier: String = "",
+                          fromMemory: Bool = true,
+                          fromDisk: Bool = true,
+                          callbackQueue: CallbackQueue = .untouch,
+                          completionHandler: (() -> Void)? = nil)
+    {
+        let computedKey = key.computedKey(with: identifier)
+
+        if fromMemory {
+            memoryStorage.remove(forKey: computedKey)
+        }
+        
+        if fromDisk {
+            ioQueue.async{
+                try? self.diskStorage.remove(forKey: computedKey)
+                if let completionHandler = completionHandler {
+                    callbackQueue.execute { completionHandler() }
+                }
+            }
+        } else {
+            if let completionHandler = completionHandler {
+                callbackQueue.execute { completionHandler() }
+            }
+        }
+    }
+
+    // MARK: Getting Images
+
+    /// Gets an image for a given key from the cache, either from memory storage or disk storage.
+    ///
+    /// - Parameters:
+    ///   - key: The key used for caching the image.
+    ///   - options: The `KingfisherParsedOptionsInfo` options setting used for retrieving the image.
+    ///   - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.mainCurrentOrAsync`.
+    ///   - completionHandler: A closure which is invoked when the image getting operation finishes. If the
+    ///                        image retrieving operation finishes without problem, an `ImageCacheResult` value
+    ///                        will be sent to this closure as result. Otherwise, a `KingfisherError` result
+    ///                        with detail failing reason will be sent.
+    open func retrieveImage(
+        forKey key: String,
+        options: KingfisherParsedOptionsInfo,
+        callbackQueue: CallbackQueue = .mainCurrentOrAsync,
+        completionHandler: ((Result<ImageCacheResult, KingfisherError>) -> Void)?)
+    {
+        // No completion handler. No need to start working and early return.
+        guard let completionHandler = completionHandler else { return }
+
+        // Try to check the image from memory cache first.
+        if let image = retrieveImageInMemoryCache(forKey: key, options: options) {
+            callbackQueue.execute { completionHandler(.success(.memory(image))) }
+        } else if options.fromMemoryCacheOrRefresh {
+            callbackQueue.execute { completionHandler(.success(.none)) }
+        } else {
+
+            // Begin to disk search.
+            self.retrieveImageInDiskCache(forKey: key, options: options, callbackQueue: callbackQueue) {
+                result in
+                switch result {
+                case .success(let image):
+
+                    guard let image = image else {
+                        // No image found in disk storage.
+                        callbackQueue.execute { completionHandler(.success(.none)) }
+                        return
+                    }
+
+                    // Cache the disk image to memory.
+                    // We are passing `false` to `toDisk`, the memory cache does not change
+                    // callback queue, we can call `completionHandler` without another dispatch.
+                    var cacheOptions = options
+                    cacheOptions.callbackQueue = .untouch
+                    self.store(
+                        image,
+                        forKey: key,
+                        options: cacheOptions,
+                        toDisk: false)
+                    {
+                        _ in
+                        callbackQueue.execute { completionHandler(.success(.disk(image))) }
+                    }
+                case .failure(let error):
+                    callbackQueue.execute { completionHandler(.failure(error)) }
+                }
+            }
+        }
+    }
+
+    /// Gets an image for a given key from the cache, either from memory storage or disk storage.
+    ///
+    /// - Parameters:
+    ///   - key: The key used for caching the image.
+    ///   - options: The `KingfisherOptionsInfo` options setting used for retrieving the image.
+    ///   - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.mainCurrentOrAsync`.
+    ///   - completionHandler: A closure which is invoked when the image getting operation finishes. If the
+    ///                        image retrieving operation finishes without problem, an `ImageCacheResult` value
+    ///                        will be sent to this closure as result. Otherwise, a `KingfisherError` result
+    ///                        with detail failing reason will be sent.
+    ///
+    /// Note: This method is marked as `open` for only compatible purpose. Do not overide this method. Instead, override
+    ///       the version receives `KingfisherParsedOptionsInfo` instead.
+    open func retrieveImage(forKey key: String,
+                               options: KingfisherOptionsInfo? = nil,
+                        callbackQueue: CallbackQueue = .mainCurrentOrAsync,
+                     completionHandler: ((Result<ImageCacheResult, KingfisherError>) -> Void)?)
+    {
+        retrieveImage(
+            forKey: key,
+            options: KingfisherParsedOptionsInfo(options),
+            callbackQueue: callbackQueue,
+            completionHandler: completionHandler)
+    }
+
+    /// Gets an image for a given key from the memory storage.
+    ///
+    /// - Parameters:
+    ///   - key: The key used for caching the image.
+    ///   - options: The `KingfisherParsedOptionsInfo` options setting used for retrieving the image.
+    /// - Returns: The image stored in memory cache, if exists and valid. Otherwise, if the image does not exist or
+    ///            has already expired, `nil` is returned.
+    open func retrieveImageInMemoryCache(
+        forKey key: String,
+        options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage?
+    {
+        let computedKey = key.computedKey(with: options.processor.identifier)
+        return memoryStorage.value(forKey: computedKey, extendingExpiration: options.memoryCacheAccessExtendingExpiration)
+    }
+
+    /// Gets an image for a given key from the memory storage.
+    ///
+    /// - Parameters:
+    ///   - key: The key used for caching the image.
+    ///   - options: The `KingfisherOptionsInfo` options setting used for retrieving the image.
+    /// - Returns: The image stored in memory cache, if exists and valid. Otherwise, if the image does not exist or
+    ///            has already expired, `nil` is returned.
+    ///
+    /// Note: This method is marked as `open` for only compatible purpose. Do not overide this method. Instead, override
+    ///       the version receives `KingfisherParsedOptionsInfo` instead.
+    open func retrieveImageInMemoryCache(
+        forKey key: String,
+        options: KingfisherOptionsInfo? = nil) -> KFCrossPlatformImage?
+    {
+        return retrieveImageInMemoryCache(forKey: key, options: KingfisherParsedOptionsInfo(options))
+    }
+
+    func retrieveImageInDiskCache(
+        forKey key: String,
+        options: KingfisherParsedOptionsInfo,
+        callbackQueue: CallbackQueue = .untouch,
+        completionHandler: @escaping (Result<KFCrossPlatformImage?, KingfisherError>) -> Void)
+    {
+        let computedKey = key.computedKey(with: options.processor.identifier)
+        let loadingQueue: CallbackQueue = options.loadDiskFileSynchronously ? .untouch : .dispatch(ioQueue)
+        loadingQueue.execute {
+            do {
+                var image: KFCrossPlatformImage? = nil
+                if let data = try self.diskStorage.value(forKey: computedKey, extendingExpiration: options.diskCacheAccessExtendingExpiration) {
+                    image = options.cacheSerializer.image(with: data, options: options)
+                }
+                if options.backgroundDecode {
+                    image = image?.kf.decoded(scale: options.scaleFactor)
+                }
+                callbackQueue.execute { completionHandler(.success(image)) }
+            } catch let error as KingfisherError {
+                callbackQueue.execute { completionHandler(.failure(error)) }
+            } catch {
+                assertionFailure("The internal thrown error should be a `KingfisherError`.")
+            }
+        }
+    }
+    
+    /// Gets an image for a given key from the disk storage.
+    ///
+    /// - Parameters:
+    ///   - key: The key used for caching the image.
+    ///   - options: The `KingfisherOptionsInfo` options setting used for retrieving the image.
+    ///   - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.untouch`.
+    ///   - completionHandler: A closure which is invoked when the operation finishes.
+    open func retrieveImageInDiskCache(
+        forKey key: String,
+        options: KingfisherOptionsInfo? = nil,
+        callbackQueue: CallbackQueue = .untouch,
+        completionHandler: @escaping (Result<KFCrossPlatformImage?, KingfisherError>) -> Void)
+    {
+        retrieveImageInDiskCache(
+            forKey: key,
+            options: KingfisherParsedOptionsInfo(options),
+            callbackQueue: callbackQueue,
+            completionHandler: completionHandler)
+    }
+
+    // MARK: Cleaning
+    /// Clears the memory & disk storage of this cache. This is an async operation.
+    ///
+    /// - Parameter handler: A closure which is invoked when the cache clearing operation finishes.
+    ///                      This `handler` will be called from the main queue.
+    public func clearCache(completion handler: (() -> Void)? = nil) {
+        clearMemoryCache()
+        clearDiskCache(completion: handler)
+    }
+    
+    /// Clears the memory storage of this cache.
+    @objc public func clearMemoryCache() {
+        memoryStorage.removeAll()
+    }
+    
+    /// Clears the disk storage of this cache. This is an async operation.
+    ///
+    /// - Parameter handler: A closure which is invoked when the cache clearing operation finishes.
+    ///                      This `handler` will be called from the main queue.
+    open func clearDiskCache(completion handler: (() -> Void)? = nil) {
+        ioQueue.async {
+            do {
+                try self.diskStorage.removeAll()
+            } catch _ { }
+            if let handler = handler {
+                DispatchQueue.main.async { handler() }
+            }
+        }
+    }
+    
+    /// Clears the expired images from memory & disk storage. This is an async operation.
+    open func cleanExpiredCache(completion handler: (() -> Void)? = nil) {
+        cleanExpiredMemoryCache()
+        cleanExpiredDiskCache(completion: handler)
+    }
+
+    /// Clears the expired images from disk storage.
+    open func cleanExpiredMemoryCache() {
+        memoryStorage.removeExpired()
+    }
+    
+    /// Clears the expired images from disk storage. This is an async operation.
+    @objc func cleanExpiredDiskCache() {
+        cleanExpiredDiskCache(completion: nil)
+    }
+
+    /// Clears the expired images from disk storage. This is an async operation.
+    ///
+    /// - Parameter handler: A closure which is invoked when the cache clearing operation finishes.
+    ///                      This `handler` will be called from the main queue.
+    open func cleanExpiredDiskCache(completion handler: (() -> Void)? = nil) {
+        ioQueue.async {
+            do {
+                var removed: [URL] = []
+                let removedExpired = try self.diskStorage.removeExpiredValues()
+                removed.append(contentsOf: removedExpired)
+
+                let removedSizeExceeded = try self.diskStorage.removeSizeExceededValues()
+                removed.append(contentsOf: removedSizeExceeded)
+
+                if !removed.isEmpty {
+                    DispatchQueue.main.async {
+                        let cleanedHashes = removed.map { $0.lastPathComponent }
+                        NotificationCenter.default.post(
+                            name: .KingfisherDidCleanDiskCache,
+                            object: self,
+                            userInfo: [KingfisherDiskCacheCleanedHashKey: cleanedHashes])
+                    }
+                }
+
+                if let handler = handler {
+                    DispatchQueue.main.async { handler() }
+                }
+            } catch {}
+        }
+    }
+
+#if !os(macOS) && !os(watchOS)
+    /// Clears the expired images from disk storage when app is in background. This is an async operation.
+    /// In most cases, you should not call this method explicitly.
+    /// It will be called automatically when `UIApplicationDidEnterBackgroundNotification` received.
+    @objc public func backgroundCleanExpiredDiskCache() {
+        // if 'sharedApplication()' is unavailable, then return
+        guard let sharedApplication = KingfisherWrapper<UIApplication>.shared else { return }
+
+        func endBackgroundTask(_ task: inout UIBackgroundTaskIdentifier) {
+            sharedApplication.endBackgroundTask(task)
+            task = UIBackgroundTaskIdentifier.invalid
+        }
+        
+        var backgroundTask: UIBackgroundTaskIdentifier!
+        backgroundTask = sharedApplication.beginBackgroundTask {
+            endBackgroundTask(&backgroundTask!)
+        }
+        
+        cleanExpiredDiskCache {
+            endBackgroundTask(&backgroundTask!)
+        }
+    }
+#endif
+
+    // MARK: Image Cache State
+
+    /// Returns the cache type for a given `key` and `identifier` combination.
+    /// This method is used for checking whether an image is cached in current cache.
+    /// It also provides information on which kind of cache can it be found in the return value.
+    ///
+    /// - Parameters:
+    ///   - key: The key used for caching the image.
+    ///   - identifier: Processor identifier which used for this image. Default is the `identifier` of
+    ///                 `DefaultImageProcessor.default`.
+    /// - Returns: A `CacheType` instance which indicates the cache status.
+    ///            `.none` means the image is not in cache or it is already expired.
+    open func imageCachedType(
+        forKey key: String,
+        processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> CacheType
+    {
+        let computedKey = key.computedKey(with: identifier)
+        if memoryStorage.isCached(forKey: computedKey) { return .memory }
+        if diskStorage.isCached(forKey: computedKey) { return .disk }
+        return .none
+    }
+    
+    /// Returns whether the file exists in cache for a given `key` and `identifier` combination.
+    ///
+    /// - Parameters:
+    ///   - key: The key used for caching the image.
+    ///   - identifier: Processor identifier which used for this image. Default is the `identifier` of
+    ///                 `DefaultImageProcessor.default`.
+    /// - Returns: A `Bool` which indicates whether a cache could match the given `key` and `identifier` combination.
+    ///
+    /// - Note:
+    /// The return value does not contain information about from which kind of storage the cache matches.
+    /// To get the information about cache type according `CacheType`,
+    /// use `imageCachedType(forKey:processorIdentifier:)` instead.
+    public func isCached(
+        forKey key: String,
+        processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> Bool
+    {
+        return imageCachedType(forKey: key, processorIdentifier: identifier).cached
+    }
+    
+    /// Gets the hash used as cache file name for the key.
+    ///
+    /// - Parameters:
+    ///   - key: The key used for caching the image.
+    ///   - identifier: Processor identifier which used for this image. Default is the `identifier` of
+    ///                 `DefaultImageProcessor.default`.
+    /// - Returns: The hash which is used as the cache file name.
+    ///
+    /// - Note:
+    /// By default, for a given combination of `key` and `identifier`, `ImageCache` will use the value
+    /// returned by this method as the cache file name. You can use this value to check and match cache file
+    /// if you need.
+    open func hash(
+        forKey key: String,
+        processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> String
+    {
+        let computedKey = key.computedKey(with: identifier)
+        return diskStorage.cacheFileName(forKey: computedKey)
+    }
+    
+    /// Calculates the size taken by the disk storage.
+    /// It is the total file size of all cached files in the `diskStorage` on disk in bytes.
+    ///
+    /// - Parameter handler: Called with the size calculating finishes. This closure is invoked from the main queue.
+    open func calculateDiskStorageSize(completion handler: @escaping ((Result<UInt, KingfisherError>) -> Void)) {
+        ioQueue.async {
+            do {
+                let size = try self.diskStorage.totalSize()
+                DispatchQueue.main.async { handler(.success(size)) }
+            } catch let error as KingfisherError {
+                DispatchQueue.main.async { handler(.failure(error)) }
+            } catch {
+                assertionFailure("The internal thrown error should be a `KingfisherError`.")
+            }
+        }
+    }
+    
+    #if swift(>=5.5)
+    #if canImport(_Concurrency)
+    @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
+    open var diskStorageSize: UInt {
+        get async throws {
+            try await withCheckedThrowingContinuation { continuation in
+                calculateDiskStorageSize { result in
+                    continuation.resume(with: result)
+                }
+            }
+        }
+    }
+    #endif
+    #endif
+    
+    /// Gets the cache path for the key.
+    /// It is useful for projects with web view or anyone that needs access to the local file path.
+    ///
+    /// i.e. Replacing the `<img src='path_for_key'>` tag in your HTML.
+    ///
+    /// - Parameters:
+    ///   - key: The key used for caching the image.
+    ///   - identifier: Processor identifier which used for this image. Default is the `identifier` of
+    ///                 `DefaultImageProcessor.default`.
+    /// - Returns: The disk path of cached image under the given `key` and `identifier`.
+    ///
+    /// - Note:
+    /// This method does not guarantee there is an image already cached in the returned path. It just gives your
+    /// the path that the image should be, if it exists in disk storage.
+    ///
+    /// You could use `isCached(forKey:)` method to check whether the image is cached under that key in disk.
+    open func cachePath(
+        forKey key: String,
+        processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> String
+    {
+        let computedKey = key.computedKey(with: identifier)
+        return diskStorage.cacheFileURL(forKey: computedKey).path
+    }
+}
+
+#if !os(macOS) && !os(watchOS)
+// MARK: - For App Extensions
+extension UIApplication: KingfisherCompatible { }
+extension KingfisherWrapper where Base: UIApplication {
+    public static var shared: UIApplication? {
+        let selector = NSSelectorFromString("sharedApplication")
+        guard Base.responds(to: selector) else { return nil }
+        return Base.perform(selector).takeUnretainedValue() as? UIApplication
+    }
+}
+#endif
+
+extension String {
+    func computedKey(with identifier: String) -> String {
+        if identifier.isEmpty {
+            return self
+        } else {
+            return appending("@\(identifier)")
+        }
+    }
+}

+ 283 - 0
Pods/Kingfisher/Sources/Cache/MemoryStorage.swift

@@ -0,0 +1,283 @@
+//
+//  MemoryStorage.swift
+//  Kingfisher
+//
+//  Created by Wei Wang on 2018/10/15.
+//
+//  Copyright (c) 2019 Wei Wang <onevcat@gmail.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
+
+/// Represents a set of conception related to storage which stores a certain type of value in memory.
+/// This is a namespace for the memory storage types. A `Backend` with a certain `Config` will be used to describe the
+/// storage. See these composed types for more information.
+public enum MemoryStorage {
+
+    /// Represents a storage which stores a certain type of value in memory. It provides fast access,
+    /// but limited storing size. The stored value type needs to conform to `CacheCostCalculable`,
+    /// and its `cacheCost` will be used to determine the cost of size for the cache item.
+    ///
+    /// You can config a `MemoryStorage.Backend` in its initializer by passing a `MemoryStorage.Config` value.
+    /// or modifying the `config` property after it being created. The backend of `MemoryStorage` has
+    /// upper limitation on cost size in memory and item count. All items in the storage has an expiration
+    /// date. When retrieved, if the target item is already expired, it will be recognized as it does not
+    /// exist in the storage. The `MemoryStorage` also contains a scheduled self clean task, to evict expired
+    /// items from memory.
+    public class Backend<T: CacheCostCalculable> {
+        let storage = NSCache<NSString, StorageObject<T>>()
+
+        // Keys trackes the objects once inside the storage. For object removing triggered by user, the corresponding
+        // key would be also removed. However, for the object removing triggered by cache rule/policy of system, the
+        // key will be remained there until next `removeExpired` happens.
+        //
+        // Breaking the strict tracking could save additional locking behaviors.
+        // See https://github.com/onevcat/Kingfisher/issues/1233
+        var keys = Set<String>()
+
+        private var cleanTimer: Timer? = nil
+        private let lock = NSLock()
+
+        /// The config used in this storage. It is a value you can set and
+        /// use to config the storage in air.
+        public var config: Config {
+            didSet {
+                storage.totalCostLimit = config.totalCostLimit
+                storage.countLimit = config.countLimit
+            }
+        }
+
+        /// Creates a `MemoryStorage` with a given `config`.
+        ///
+        /// - Parameter config: The config used to create the storage. It determines the max size limitation,
+        ///                     default expiration setting and more.
+        public init(config: Config) {
+            self.config = config
+            storage.totalCostLimit = config.totalCostLimit
+            storage.countLimit = config.countLimit
+
+            cleanTimer = .scheduledTimer(withTimeInterval: config.cleanInterval, repeats: true) { [weak self] _ in
+                guard let self = self else { return }
+                self.removeExpired()
+            }
+        }
+
+        /// Removes the expired values from the storage.
+        public func removeExpired() {
+            lock.lock()
+            defer { lock.unlock() }
+            for key in keys {
+                let nsKey = key as NSString
+                guard let object = storage.object(forKey: nsKey) else {
+                    // This could happen if the object is moved by cache `totalCostLimit` or `countLimit` rule.
+                    // We didn't remove the key yet until now, since we do not want to introduce additional lock.
+                    // See https://github.com/onevcat/Kingfisher/issues/1233
+                    keys.remove(key)
+                    continue
+                }
+                if object.isExpired {
+                    storage.removeObject(forKey: nsKey)
+                    keys.remove(key)
+                }
+            }
+        }
+
+        /// Stores a value to the storage under the specified key and expiration policy.
+        /// - Parameters:
+        ///   - value: The value to be stored.
+        ///   - key: The key to which the `value` will be stored.
+        ///   - expiration: The expiration policy used by this store action.
+        /// - Throws: No error will
+        public func store(
+            value: T,
+            forKey key: String,
+            expiration: StorageExpiration? = nil)
+        {
+            storeNoThrow(value: value, forKey: key, expiration: expiration)
+        }
+
+        // The no throw version for storing value in cache. Kingfisher knows the detail so it
+        // could use this version to make syntax simpler internally.
+        func storeNoThrow(
+            value: T,
+            forKey key: String,
+            expiration: StorageExpiration? = nil)
+        {
+            lock.lock()
+            defer { lock.unlock() }
+            let expiration = expiration ?? config.expiration
+            // The expiration indicates that already expired, no need to store.
+            guard !expiration.isExpired else { return }
+            
+            let object: StorageObject<T>
+            if config.keepWhenEnteringBackground {
+                object = BackgroundKeepingStorageObject(value, expiration: expiration)
+            } else {
+                object = StorageObject(value, expiration: expiration)
+            }
+            storage.setObject(object, forKey: key as NSString, cost: value.cacheCost)
+            keys.insert(key)
+        }
+        
+        /// Gets a value from the storage.
+        ///
+        /// - Parameters:
+        ///   - key: The cache key of value.
+        ///   - extendingExpiration: The expiration policy used by this getting action.
+        /// - Returns: The value under `key` if it is valid and found in the storage. Otherwise, `nil`.
+        public func value(forKey key: String, extendingExpiration: ExpirationExtending = .cacheTime) -> T? {
+            guard let object = storage.object(forKey: key as NSString) else {
+                return nil
+            }
+            if object.isExpired {
+                return nil
+            }
+            object.extendExpiration(extendingExpiration)
+            return object.value
+        }
+
+        /// Whether there is valid cached data under a given key.
+        /// - Parameter key: The cache key of value.
+        /// - Returns: If there is valid data under the key, `true`. Otherwise, `false`.
+        public func isCached(forKey key: String) -> Bool {
+            guard let _ = value(forKey: key, extendingExpiration: .none) else {
+                return false
+            }
+            return true
+        }
+
+        /// Removes a value from a specified key.
+        /// - Parameter key: The cache key of value.
+        public func remove(forKey key: String) {
+            lock.lock()
+            defer { lock.unlock() }
+            storage.removeObject(forKey: key as NSString)
+            keys.remove(key)
+        }
+
+        /// Removes all values in this storage.
+        public func removeAll() {
+            lock.lock()
+            defer { lock.unlock() }
+            storage.removeAllObjects()
+            keys.removeAll()
+        }
+    }
+}
+
+extension MemoryStorage {
+    /// Represents the config used in a `MemoryStorage`.
+    public struct Config {
+
+        /// Total cost limit of the storage in bytes.
+        public var totalCostLimit: Int
+
+        /// The item count limit of the memory storage.
+        public var countLimit: Int = .max
+
+        /// The `StorageExpiration` used in this memory storage. Default is `.seconds(300)`,
+        /// means that the memory cache would expire in 5 minutes.
+        public var expiration: StorageExpiration = .seconds(300)
+
+        /// The time interval between the storage do clean work for swiping expired items.
+        public var cleanInterval: TimeInterval
+        
+        /// Whether the newly added items to memory cache should be purged when the app goes to background.
+        ///
+        /// By default, the cached items in memory will be purged as soon as the app goes to background to ensure
+        /// least memory footprint. Enabling this would prevent this behavior and keep the items alive in cache even
+        /// when your app is not in foreground anymore.
+        ///
+        /// Default is `false`. After setting `true`, only the newly added cache objects are affected. Existing
+        /// objects which are already in the cache while this value was `false` will be still be purged when entering
+        /// background.
+        public var keepWhenEnteringBackground: Bool = false
+
+        /// Creates a config from a given `totalCostLimit` value.
+        ///
+        /// - Parameters:
+        ///   - totalCostLimit: Total cost limit of the storage in bytes.
+        ///   - cleanInterval: The time interval between the storage do clean work for swiping expired items.
+        ///                    Default is 120, means the auto eviction happens once per two minutes.
+        ///
+        /// - Note:
+        /// Other members of `MemoryStorage.Config` will use their default values when created.
+        public init(totalCostLimit: Int, cleanInterval: TimeInterval = 120) {
+            self.totalCostLimit = totalCostLimit
+            self.cleanInterval = cleanInterval
+        }
+    }
+}
+
+extension MemoryStorage {
+    
+    class BackgroundKeepingStorageObject<T>: StorageObject<T>, NSDiscardableContent {
+        var accessing = true
+        func beginContentAccess() -> Bool {
+            if value != nil {
+                accessing = true
+            } else {
+                accessing = false
+            }
+            return accessing
+        }
+        
+        func endContentAccess() {
+            accessing = false
+        }
+        
+        func discardContentIfPossible() {
+            value = nil
+        }
+        
+        func isContentDiscarded() -> Bool {
+            return value == nil
+        }
+    }
+    
+    class StorageObject<T> {
+        var value: T?
+        let expiration: StorageExpiration
+        
+        private(set) var estimatedExpiration: Date
+        
+        init(_ value: T, expiration: StorageExpiration) {
+            self.value = value
+            self.expiration = expiration
+            
+            self.estimatedExpiration = expiration.estimatedExpirationSinceNow
+        }
+
+        func extendExpiration(_ extendingExpiration: ExpirationExtending = .cacheTime) {
+            switch extendingExpiration {
+            case .none:
+                return
+            case .cacheTime:
+                self.estimatedExpiration = expiration.estimatedExpirationSinceNow
+            case .expirationTime(let expirationTime):
+                self.estimatedExpiration = expirationTime.estimatedExpirationSinceNow
+            }
+        }
+        
+        var isExpired: Bool {
+            return estimatedExpiration.isPast
+        }
+    }
+}

+ 110 - 0
Pods/Kingfisher/Sources/Cache/Storage.swift

@@ -0,0 +1,110 @@
+//
+//  Storage.swift
+//  Kingfisher
+//
+//  Created by Wei Wang on 2018/10/15.
+//
+//  Copyright (c) 2019 Wei Wang <onevcat@gmail.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
+
+/// Constants for some time intervals
+struct TimeConstants {
+    static let secondsInOneDay = 86_400
+}
+
+/// Represents the expiration strategy used in storage.
+///
+/// - never: The item never expires.
+/// - seconds: The item expires after a time duration of given seconds from now.
+/// - days: The item expires after a time duration of given days from now.
+/// - date: The item expires after a given date.
+public enum StorageExpiration {
+    /// The item never expires.
+    case never
+    /// The item expires after a time duration of given seconds from now.
+    case seconds(TimeInterval)
+    /// The item expires after a time duration of given days from now.
+    case days(Int)
+    /// The item expires after a given date.
+    case date(Date)
+    /// Indicates the item is already expired. Use this to skip cache.
+    case expired
+
+    func estimatedExpirationSince(_ date: Date) -> Date {
+        switch self {
+        case .never: return .distantFuture
+        case .seconds(let seconds):
+            return date.addingTimeInterval(seconds)
+        case .days(let days):
+            let duration: TimeInterval = TimeInterval(TimeConstants.secondsInOneDay) * TimeInterval(days)
+            return date.addingTimeInterval(duration)
+        case .date(let ref):
+            return ref
+        case .expired:
+            return .distantPast
+        }
+    }
+    
+    var estimatedExpirationSinceNow: Date {
+        return estimatedExpirationSince(Date())
+    }
+    
+    var isExpired: Bool {
+        return timeInterval <= 0
+    }
+
+    var timeInterval: TimeInterval {
+        switch self {
+        case .never: return .infinity
+        case .seconds(let seconds): return seconds
+        case .days(let days): return TimeInterval(TimeConstants.secondsInOneDay) * TimeInterval(days)
+        case .date(let ref): return ref.timeIntervalSinceNow
+        case .expired: return -(.infinity)
+        }
+    }
+}
+
+/// Represents the expiration extending strategy used in storage to after access.
+///
+/// - none: The item expires after the original time, without extending after access.
+/// - cacheTime: The item expiration extends by the original cache time after each access.
+/// - expirationTime: The item expiration extends by the provided time after each access.
+public enum ExpirationExtending {
+    /// The item expires after the original time, without extending after access.
+    case none
+    /// The item expiration extends by the original cache time after each access.
+    case cacheTime
+    /// The item expiration extends by the provided time after each access.
+    case expirationTime(_ expiration: StorageExpiration)
+}
+
+/// Represents types which cost in memory can be calculated.
+public protocol CacheCostCalculable {
+    var cacheCost: Int { get }
+}
+
+/// Represents types which can be converted to and from data.
+public protocol DataTransformable {
+    func toData() throws -> Data
+    static func fromData(_ data: Data) throws -> Self
+    static var empty: Self { get }
+}

+ 245 - 0
Pods/Kingfisher/Sources/Extensions/CPListItem+Kingfisher.swift

@@ -0,0 +1,245 @@
+
+//
+//  CPListItem+Kingfisher.swift
+//  Kingfisher
+//
+//  Created by Wayne Hartman on 2021-08-29.
+//
+//  Copyright (c) 2019 Wei Wang <onevcat@gmail.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.
+
+#if canImport(CarPlay) && !targetEnvironment(macCatalyst)
+import CarPlay
+
+@available(iOS 14.0, *)
+extension KingfisherWrapper where Base: CPListItem {
+    
+    // MARK: Setting Image
+    
+    /// Sets an image to the image view with a source.
+    ///
+    /// - Parameters:
+    ///   - source: The `Source` object contains information about the image.
+    ///   - placeholder: A placeholder to show while retrieving the image from the given `resource`.
+    ///   - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
+    ///   - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
+    ///                    `expectedContentLength`, this block will not be called.
+    ///   - completionHandler: Called when the image retrieved and set finished.
+    /// - Returns: A task represents the image downloading.
+    ///
+    /// - Note:
+    ///
+    /// Internally, this method will use `KingfisherManager` to get the requested source
+    /// Since this method will perform UI changes, you must call it from the main thread.
+    /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
+    ///
+    @discardableResult
+    public func setImage(
+        with source: Source?,
+        placeholder: KFCrossPlatformImage? = nil,
+        options: KingfisherOptionsInfo? = nil,
+        progressBlock: DownloadProgressBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? []))
+        return setImage(
+            with: source,
+            placeholder: placeholder,
+            parsedOptions: options,
+            progressBlock: progressBlock,
+            completionHandler: completionHandler
+        )
+    }
+    
+    /// Sets an image to the image view with a requested resource.
+    ///
+    /// - Parameters:
+    ///   - resource: The `Resource` object contains information about the image.
+    ///   - placeholder: A placeholder to show while retrieving the image from the given `resource`.
+    ///   - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
+    ///   - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
+    ///                    `expectedContentLength`, this block will not be called.
+    ///   - completionHandler: Called when the image retrieved and set finished.
+    /// - Returns: A task represents the image downloading.
+    ///
+    /// - Note:
+    ///
+    /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
+    /// or network. Since this method will perform UI changes, you must call it from the main thread.
+    /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
+    ///
+    @discardableResult
+    public func setImage(
+        with resource: Resource?,
+        placeholder: KFCrossPlatformImage? = nil,
+        options: KingfisherOptionsInfo? = nil,
+        progressBlock: DownloadProgressBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        return setImage(
+            with: resource?.convertToSource(),
+            placeholder: placeholder,
+            options: options,
+            progressBlock: progressBlock,
+            completionHandler: completionHandler)
+    }
+
+    func setImage(
+        with source: Source?,
+        placeholder: KFCrossPlatformImage? = nil,
+        parsedOptions: KingfisherParsedOptionsInfo,
+        progressBlock: DownloadProgressBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        var mutatingSelf = self
+        guard let source = source else {
+            /**
+             * In iOS SDK 14.0-14.4 the image param was non-`nil`. The SDK changed in 14.5
+             * to allow `nil`. The compiler version 5.4 was introduced in this same SDK,
+             * which allows >=14.5 SDK to set a `nil` image. This compile check allows
+             * newer SDK users to set the image to `nil`, while still allowing older SDK
+             * users to compile the framework.
+             */
+            #if compiler(>=5.4)
+            self.base.setImage(placeholder)
+            #else
+            if let placeholder = placeholder {
+                self.base.setImage(placeholder)
+            }
+            #endif
+
+            mutatingSelf.taskIdentifier = nil
+            completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
+            return nil
+        }
+        
+        var options = parsedOptions
+        if !options.keepCurrentImageWhileLoading {
+            /**
+             * In iOS SDK 14.0-14.4 the image param was non-`nil`. The SDK changed in 14.5
+             * to allow `nil`. The compiler version 5.4 was introduced in this same SDK,
+             * which allows >=14.5 SDK to set a `nil` image. This compile check allows
+             * newer SDK users to set the image to `nil`, while still allowing older SDK
+             * users to compile the framework.
+             */
+            #if compiler(>=5.4)
+            self.base.setImage(placeholder)
+            #else // Let older SDK users deal with the older behavior.
+            if let placeholder = placeholder {
+                self.base.setImage(placeholder)
+            }
+            #endif
+        }
+        
+        let issuedIdentifier = Source.Identifier.next()
+        mutatingSelf.taskIdentifier = issuedIdentifier
+        
+        if let block = progressBlock {
+            options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
+        }
+        
+        let task = KingfisherManager.shared.retrieveImage(
+            with: source,
+            options: options,
+            downloadTaskUpdated: { mutatingSelf.imageTask = $0 },
+            progressiveImageSetter: { self.base.setImage($0) },
+            referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier },
+            completionHandler: { result in
+                CallbackQueue.mainCurrentOrAsync.execute {
+                    guard issuedIdentifier == self.taskIdentifier else {
+                        let reason: KingfisherError.ImageSettingErrorReason
+                        do {
+                            let value = try result.get()
+                            reason = .notCurrentSourceTask(result: value, error: nil, source: source)
+                        } catch {
+                            reason = .notCurrentSourceTask(result: nil, error: error, source: source)
+                        }
+                        let error = KingfisherError.imageSettingError(reason: reason)
+                        completionHandler?(.failure(error))
+                        return
+                    }
+                    
+                    mutatingSelf.imageTask = nil
+                    mutatingSelf.taskIdentifier = nil
+                    
+                    switch result {
+                        case .success(let value):
+                            self.base.setImage(value.image)
+                            completionHandler?(result)
+                            
+                        case .failure:
+                            if let image = options.onFailureImage {
+                                /**
+                                 * In iOS SDK 14.0-14.4 the image param was non-`nil`. The SDK changed in 14.5
+                                 * to allow `nil`. The compiler version 5.4 was introduced in this same SDK,
+                                 * which allows >=14.5 SDK to set a `nil` image. This compile check allows
+                                 * newer SDK users to set the image to `nil`, while still allowing older SDK
+                                 * users to compile the framework.
+                                 */
+                                #if compiler(>=5.4)
+                                self.base.setImage(image)
+                                #else // Let older SDK users deal with the older behavior.
+                                if let unwrapped = image {
+                                    self.base.setImage(unwrapped)
+                                }
+                                #endif   
+                            }
+                            completionHandler?(result)
+                    }
+                }
+            }
+        )
+        
+        mutatingSelf.imageTask = task
+        return task
+    }
+    
+    // MARK: Cancelling Image
+    
+    /// Cancel the image download task bounded to the image view if it is running.
+    /// Nothing will happen if the downloading has already finished.
+    public func cancelDownloadTask() {
+        imageTask?.cancel()
+    }
+}
+
+private var taskIdentifierKey: Void?
+private var imageTaskKey: Void?
+
+// MARK: Properties
+extension KingfisherWrapper where Base: CPListItem {
+
+    public private(set) var taskIdentifier: Source.Identifier.Value? {
+        get {
+            let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey)
+            return box?.value
+        }
+        set {
+            let box = newValue.map { Box($0) }
+            setRetainedAssociatedObject(base, &taskIdentifierKey, box)
+        }
+    }
+
+    private var imageTask: DownloadTask? {
+        get { return getAssociatedObject(base, &imageTaskKey) }
+        set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
+    }
+}
+#endif

+ 537 - 0
Pods/Kingfisher/Sources/Extensions/ImageView+Kingfisher.swift

@@ -0,0 +1,537 @@
+//
+//  ImageView+Kingfisher.swift
+//  Kingfisher
+//
+//  Created by Wei Wang on 15/4/6.
+//
+//  Copyright (c) 2019 Wei Wang <onevcat@gmail.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.
+
+#if !os(watchOS)
+
+#if os(macOS)
+import AppKit
+#else
+import UIKit
+#endif
+
+extension KingfisherWrapper where Base: KFCrossPlatformImageView {
+
+    // MARK: Setting Image
+
+    /// Sets an image to the image view with a `Source`.
+    ///
+    /// - Parameters:
+    ///   - source: The `Source` object defines data information from network or a data provider.
+    ///   - placeholder: A placeholder to show while retrieving the image from the given `resource`.
+    ///   - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
+    ///   - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
+    ///                    `expectedContentLength`, this block will not be called.
+    ///   - completionHandler: Called when the image retrieved and set finished.
+    /// - Returns: A task represents the image downloading.
+    ///
+    /// - Note:
+    /// This is the easiest way to use Kingfisher to boost the image setting process from a source. Since all parameters
+    /// have a default value except the `source`, you can set an image from a certain URL to an image view like this:
+    ///
+    /// ```
+    /// // Set image from a network source.
+    /// let url = URL(string: "https://example.com/image.png")!
+    /// imageView.kf.setImage(with: .network(url))
+    ///
+    /// // Or set image from a data provider.
+    /// let provider = LocalFileImageDataProvider(fileURL: fileURL)
+    /// imageView.kf.setImage(with: .provider(provider))
+    /// ```
+    ///
+    /// For both `.network` and `.provider` source, there are corresponding view extension methods. So the code
+    /// above is equivalent to:
+    ///
+    /// ```
+    /// imageView.kf.setImage(with: url)
+    /// imageView.kf.setImage(with: provider)
+    /// ```
+    ///
+    /// Internally, this method will use `KingfisherManager` to get the source.
+    /// Since this method will perform UI changes, you must call it from the main thread.
+    /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
+    ///
+    @discardableResult
+    public func setImage(
+        with source: Source?,
+        placeholder: Placeholder? = nil,
+        options: KingfisherOptionsInfo? = nil,
+        progressBlock: DownloadProgressBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
+        return setImage(with: source, placeholder: placeholder, parsedOptions: options, progressBlock: progressBlock, completionHandler: completionHandler)
+    }
+
+    /// Sets an image to the image view with a `Source`.
+    ///
+    /// - Parameters:
+    ///   - source: The `Source` object defines data information from network or a data provider.
+    ///   - placeholder: A placeholder to show while retrieving the image from the given `resource`.
+    ///   - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
+    ///   - completionHandler: Called when the image retrieved and set finished.
+    /// - Returns: A task represents the image downloading.
+    ///
+    /// - Note:
+    /// This is the easiest way to use Kingfisher to boost the image setting process from a source. Since all parameters
+    /// have a default value except the `source`, you can set an image from a certain URL to an image view like this:
+    ///
+    /// ```
+    /// // Set image from a network source.
+    /// let url = URL(string: "https://example.com/image.png")!
+    /// imageView.kf.setImage(with: .network(url))
+    ///
+    /// // Or set image from a data provider.
+    /// let provider = LocalFileImageDataProvider(fileURL: fileURL)
+    /// imageView.kf.setImage(with: .provider(provider))
+    /// ```
+    ///
+    /// For both `.network` and `.provider` source, there are corresponding view extension methods. So the code
+    /// above is equivalent to:
+    ///
+    /// ```
+    /// imageView.kf.setImage(with: url)
+    /// imageView.kf.setImage(with: provider)
+    /// ```
+    ///
+    /// Internally, this method will use `KingfisherManager` to get the source.
+    /// Since this method will perform UI changes, you must call it from the main thread.
+    /// The `completionHandler` will be also executed in the main thread.
+    ///
+    @discardableResult
+    public func setImage(
+        with source: Source?,
+        placeholder: Placeholder? = nil,
+        options: KingfisherOptionsInfo? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        return setImage(
+            with: source,
+            placeholder: placeholder,
+            options: options,
+            progressBlock: nil,
+            completionHandler: completionHandler
+        )
+    }
+
+    /// Sets an image to the image view with a requested resource.
+    ///
+    /// - Parameters:
+    ///   - resource: The `Resource` object contains information about the resource.
+    ///   - placeholder: A placeholder to show while retrieving the image from the given `resource`.
+    ///   - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
+    ///   - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
+    ///                    `expectedContentLength`, this block will not be called.
+    ///   - completionHandler: Called when the image retrieved and set finished.
+    /// - Returns: A task represents the image downloading.
+    ///
+    /// - Note:
+    /// This is the easiest way to use Kingfisher to boost the image setting process from network. Since all parameters
+    /// have a default value except the `resource`, you can set an image from a certain URL to an image view like this:
+    ///
+    /// ```
+    /// let url = URL(string: "https://example.com/image.png")!
+    /// imageView.kf.setImage(with: url)
+    /// ```
+    ///
+    /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
+    /// or network. Since this method will perform UI changes, you must call it from the main thread.
+    /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
+    ///
+    @discardableResult
+    public func setImage(
+        with resource: Resource?,
+        placeholder: Placeholder? = nil,
+        options: KingfisherOptionsInfo? = nil,
+        progressBlock: DownloadProgressBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        return setImage(
+            with: resource?.convertToSource(),
+            placeholder: placeholder,
+            options: options,
+            progressBlock: progressBlock,
+            completionHandler: completionHandler)
+    }
+
+    /// Sets an image to the image view with a requested resource.
+    ///
+    /// - Parameters:
+    ///   - resource: The `Resource` object contains information about the resource.
+    ///   - placeholder: A placeholder to show while retrieving the image from the given `resource`.
+    ///   - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
+    ///   - completionHandler: Called when the image retrieved and set finished.
+    /// - Returns: A task represents the image downloading.
+    ///
+    /// - Note:
+    /// This is the easiest way to use Kingfisher to boost the image setting process from network. Since all parameters
+    /// have a default value except the `resource`, you can set an image from a certain URL to an image view like this:
+    ///
+    /// ```
+    /// let url = URL(string: "https://example.com/image.png")!
+    /// imageView.kf.setImage(with: url)
+    /// ```
+    ///
+    /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
+    /// or network. Since this method will perform UI changes, you must call it from the main thread.
+    /// The `completionHandler` will be also executed in the main thread.
+    ///
+    @discardableResult
+    public func setImage(
+        with resource: Resource?,
+        placeholder: Placeholder? = nil,
+        options: KingfisherOptionsInfo? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        return setImage(
+            with: resource,
+            placeholder: placeholder,
+            options: options,
+            progressBlock: nil,
+            completionHandler: completionHandler
+        )
+    }
+
+    /// Sets an image to the image view with a data provider.
+    ///
+    /// - Parameters:
+    ///   - provider: The `ImageDataProvider` object contains information about the data.
+    ///   - placeholder: A placeholder to show while retrieving the image from the given `resource`.
+    ///   - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
+    ///   - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
+    ///                    `expectedContentLength`, this block will not be called.
+    ///   - completionHandler: Called when the image retrieved and set finished.
+    /// - Returns: A task represents the image downloading.
+    ///
+    /// Internally, this method will use `KingfisherManager` to get the image data, from either cache
+    /// or the data provider. Since this method will perform UI changes, you must call it from the main thread.
+    /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
+    ///
+    @discardableResult
+    public func setImage(
+        with provider: ImageDataProvider?,
+        placeholder: Placeholder? = nil,
+        options: KingfisherOptionsInfo? = nil,
+        progressBlock: DownloadProgressBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        return setImage(
+            with: provider.map { .provider($0) },
+            placeholder: placeholder,
+            options: options,
+            progressBlock: progressBlock,
+            completionHandler: completionHandler)
+    }
+
+    /// Sets an image to the image view with a data provider.
+    ///
+    /// - Parameters:
+    ///   - provider: The `ImageDataProvider` object contains information about the data.
+    ///   - placeholder: A placeholder to show while retrieving the image from the given `resource`.
+    ///   - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
+    ///   - completionHandler: Called when the image retrieved and set finished.
+    /// - Returns: A task represents the image downloading.
+    ///
+    /// Internally, this method will use `KingfisherManager` to get the image data, from either cache
+    /// or the data provider. Since this method will perform UI changes, you must call it from the main thread.
+    /// The `completionHandler` will be also executed in the main thread.
+    ///
+    @discardableResult
+    public func setImage(
+        with provider: ImageDataProvider?,
+        placeholder: Placeholder? = nil,
+        options: KingfisherOptionsInfo? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        return setImage(
+            with: provider,
+            placeholder: placeholder,
+            options: options,
+            progressBlock: nil,
+            completionHandler: completionHandler
+        )
+    }
+
+
+    func setImage(
+        with source: Source?,
+        placeholder: Placeholder? = nil,
+        parsedOptions: KingfisherParsedOptionsInfo,
+        progressBlock: DownloadProgressBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        var mutatingSelf = self
+        guard let source = source else {
+            mutatingSelf.placeholder = placeholder
+            mutatingSelf.taskIdentifier = nil
+            completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
+            return nil
+        }
+
+        var options = parsedOptions
+
+        let isEmptyImage = base.image == nil && self.placeholder == nil
+        if !options.keepCurrentImageWhileLoading || isEmptyImage {
+            // Always set placeholder while there is no image/placeholder yet.
+            mutatingSelf.placeholder = placeholder
+        }
+
+        let maybeIndicator = indicator
+        maybeIndicator?.startAnimatingView()
+
+        let issuedIdentifier = Source.Identifier.next()
+        mutatingSelf.taskIdentifier = issuedIdentifier
+
+        if base.shouldPreloadAllAnimation() {
+            options.preloadAllAnimationData = true
+        }
+
+        if let block = progressBlock {
+            options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
+        }
+
+        let task = KingfisherManager.shared.retrieveImage(
+            with: source,
+            options: options,
+            downloadTaskUpdated: { mutatingSelf.imageTask = $0 },
+            progressiveImageSetter: { self.base.image = $0 },
+            referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier },
+            completionHandler: { result in
+                CallbackQueue.mainCurrentOrAsync.execute {
+                    maybeIndicator?.stopAnimatingView()
+                    guard issuedIdentifier == self.taskIdentifier else {
+                        let reason: KingfisherError.ImageSettingErrorReason
+                        do {
+                            let value = try result.get()
+                            reason = .notCurrentSourceTask(result: value, error: nil, source: source)
+                        } catch {
+                            reason = .notCurrentSourceTask(result: nil, error: error, source: source)
+                        }
+                        let error = KingfisherError.imageSettingError(reason: reason)
+                        completionHandler?(.failure(error))
+                        return
+                    }
+
+                    mutatingSelf.imageTask = nil
+                    mutatingSelf.taskIdentifier = nil
+
+                    switch result {
+                    case .success(let value):
+                        guard self.needsTransition(options: options, cacheType: value.cacheType) else {
+                            mutatingSelf.placeholder = nil
+                            self.base.image = value.image
+                            completionHandler?(result)
+                            return
+                        }
+
+                        self.makeTransition(image: value.image, transition: options.transition) {
+                            completionHandler?(result)
+                        }
+
+                    case .failure:
+                        if let image = options.onFailureImage {
+                            mutatingSelf.placeholder = nil
+                            self.base.image = image
+                        }
+                        completionHandler?(result)
+                    }
+                }
+            }
+        )
+        mutatingSelf.imageTask = task
+        return task
+    }
+
+    // MARK: Cancelling Downloading Task
+
+    /// Cancels the image download task of the image view if it is running.
+    /// Nothing will happen if the downloading has already finished.
+    public func cancelDownloadTask() {
+        imageTask?.cancel()
+    }
+
+    private func needsTransition(options: KingfisherParsedOptionsInfo, cacheType: CacheType) -> Bool {
+        switch options.transition {
+        case .none:
+            return false
+        #if os(macOS)
+        case .fade: // Fade is only a placeholder for SwiftUI on macOS.
+            return false
+        #else
+        default:
+            if options.forceTransition { return true }
+            if cacheType == .none { return true }
+            return false
+        #endif
+        }
+    }
+
+    private func makeTransition(image: KFCrossPlatformImage, transition: ImageTransition, done: @escaping () -> Void) {
+        #if !os(macOS)
+        // Force hiding the indicator without transition first.
+        UIView.transition(
+            with: self.base,
+            duration: 0.0,
+            options: [],
+            animations: { self.indicator?.stopAnimatingView() },
+            completion: { _ in
+                var mutatingSelf = self
+                mutatingSelf.placeholder = nil
+                UIView.transition(
+                    with: self.base,
+                    duration: transition.duration,
+                    options: [transition.animationOptions, .allowUserInteraction],
+                    animations: { transition.animations?(self.base, image) },
+                    completion: { finished in
+                        transition.completion?(finished)
+                        done()
+                    }
+                )
+            }
+        )
+        #else
+        done()
+        #endif
+    }
+}
+
+// MARK: - Associated Object
+private var taskIdentifierKey: Void?
+private var indicatorKey: Void?
+private var indicatorTypeKey: Void?
+private var placeholderKey: Void?
+private var imageTaskKey: Void?
+
+extension KingfisherWrapper where Base: KFCrossPlatformImageView {
+
+    // MARK: Properties
+    public private(set) var taskIdentifier: Source.Identifier.Value? {
+        get {
+            let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey)
+            return box?.value
+        }
+        set {
+            let box = newValue.map { Box($0) }
+            setRetainedAssociatedObject(base, &taskIdentifierKey, box)
+        }
+    }
+
+    /// Holds which indicator type is going to be used.
+    /// Default is `.none`, means no indicator will be shown while downloading.
+    public var indicatorType: IndicatorType {
+        get {
+            return getAssociatedObject(base, &indicatorTypeKey) ?? .none
+        }
+        
+        set {
+            switch newValue {
+            case .none: indicator = nil
+            case .activity: indicator = ActivityIndicator()
+            case .image(let data): indicator = ImageIndicator(imageData: data)
+            case .custom(let anIndicator): indicator = anIndicator
+            }
+
+            setRetainedAssociatedObject(base, &indicatorTypeKey, newValue)
+        }
+    }
+    
+    /// Holds any type that conforms to the protocol `Indicator`.
+    /// The protocol `Indicator` has a `view` property that will be shown when loading an image.
+    /// It will be `nil` if `indicatorType` is `.none`.
+    public private(set) var indicator: Indicator? {
+        get {
+            let box: Box<Indicator>? = getAssociatedObject(base, &indicatorKey)
+            return box?.value
+        }
+        
+        set {
+            // Remove previous
+            if let previousIndicator = indicator {
+                previousIndicator.view.removeFromSuperview()
+            }
+            
+            // Add new
+            if let newIndicator = newValue {
+                // Set default indicator layout
+                let view = newIndicator.view
+                
+                base.addSubview(view)
+                view.translatesAutoresizingMaskIntoConstraints = false
+                view.centerXAnchor.constraint(
+                    equalTo: base.centerXAnchor, constant: newIndicator.centerOffset.x).isActive = true
+                view.centerYAnchor.constraint(
+                    equalTo: base.centerYAnchor, constant: newIndicator.centerOffset.y).isActive = true
+
+                switch newIndicator.sizeStrategy(in: base) {
+                case .intrinsicSize:
+                    break
+                case .full:
+                    view.heightAnchor.constraint(equalTo: base.heightAnchor, constant: 0).isActive = true
+                    view.widthAnchor.constraint(equalTo: base.widthAnchor, constant: 0).isActive = true
+                case .size(let size):
+                    view.heightAnchor.constraint(equalToConstant: size.height).isActive = true
+                    view.widthAnchor.constraint(equalToConstant: size.width).isActive = true
+                }
+                
+                newIndicator.view.isHidden = true
+            }
+
+            // Save in associated object
+            // Wrap newValue with Box to workaround an issue that Swift does not recognize
+            // and casting protocol for associate object correctly. https://github.com/onevcat/Kingfisher/issues/872
+            setRetainedAssociatedObject(base, &indicatorKey, newValue.map(Box.init))
+        }
+    }
+    
+    private var imageTask: DownloadTask? {
+        get { return getAssociatedObject(base, &imageTaskKey) }
+        set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
+    }
+
+    /// Represents the `Placeholder` used for this image view. A `Placeholder` will be shown in the view while
+    /// it is downloading an image.
+    public private(set) var placeholder: Placeholder? {
+        get { return getAssociatedObject(base, &placeholderKey) }
+        set {
+            if let previousPlaceholder = placeholder {
+                previousPlaceholder.remove(from: base)
+            }
+            
+            if let newPlaceholder = newValue {
+                newPlaceholder.add(to: base)
+            } else {
+                base.image = nil
+            }
+            setRetainedAssociatedObject(base, &placeholderKey, newValue)
+        }
+    }
+}
+
+
+extension KFCrossPlatformImageView {
+    @objc func shouldPreloadAllAnimation() -> Bool { return true }
+}
+
+#endif

+ 362 - 0
Pods/Kingfisher/Sources/Extensions/NSButton+Kingfisher.swift

@@ -0,0 +1,362 @@
+//
+//  NSButton+Kingfisher.swift
+//  Kingfisher
+//
+//  Created by Jie Zhang on 14/04/2016.
+//
+//  Copyright (c) 2019 Wei Wang <onevcat@gmail.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.
+
+#if canImport(AppKit) && !targetEnvironment(macCatalyst)
+
+import AppKit
+
+extension KingfisherWrapper where Base: NSButton {
+
+    // MARK: Setting Image
+
+    /// Sets an image to the button with a source.
+    ///
+    /// - Parameters:
+    ///   - source: The `Source` object contains information about how to get the image.
+    ///   - placeholder: A placeholder to show while retrieving the image from the given `resource`.
+    ///   - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
+    ///   - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
+    ///                    `expectedContentLength`, this block will not be called.
+    ///   - completionHandler: Called when the image retrieved and set finished.
+    /// - Returns: A task represents the image downloading.
+    ///
+    /// - Note:
+    /// Internally, this method will use `KingfisherManager` to get the requested source.
+    /// Since this method will perform UI changes, you must call it from the main thread.
+    /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
+    ///
+    @discardableResult
+    public func setImage(
+        with source: Source?,
+        placeholder: KFCrossPlatformImage? = nil,
+        options: KingfisherOptionsInfo? = nil,
+        progressBlock: DownloadProgressBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
+        return setImage(
+            with: source,
+            placeholder: placeholder,
+            parsedOptions: options,
+            progressBlock: progressBlock,
+            completionHandler: completionHandler
+        )
+    }
+
+    /// Sets an image to the button with a requested resource.
+    ///
+    /// - Parameters:
+    ///   - resource: The `Resource` object contains information about the resource.
+    ///   - placeholder: A placeholder to show while retrieving the image from the given `resource`.
+    ///   - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
+    ///   - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
+    ///                    `expectedContentLength`, this block will not be called.
+    ///   - completionHandler: Called when the image retrieved and set finished.
+    /// - Returns: A task represents the image downloading.
+    ///
+    /// - Note:
+    /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
+    /// or network. Since this method will perform UI changes, you must call it from the main thread.
+    /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
+    ///
+    @discardableResult
+    public func setImage(
+        with resource: Resource?,
+        placeholder: KFCrossPlatformImage? = nil,
+        options: KingfisherOptionsInfo? = nil,
+        progressBlock: DownloadProgressBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        return setImage(
+            with: resource?.convertToSource(),
+            placeholder: placeholder,
+            options: options,
+            progressBlock: progressBlock,
+            completionHandler: completionHandler)
+    }
+
+    func setImage(
+        with source: Source?,
+        placeholder: KFCrossPlatformImage? = nil,
+        parsedOptions: KingfisherParsedOptionsInfo,
+        progressBlock: DownloadProgressBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        var mutatingSelf = self
+        guard let source = source else {
+            base.image = placeholder
+            mutatingSelf.taskIdentifier = nil
+            completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
+            return nil
+        }
+
+        var options = parsedOptions
+        if !options.keepCurrentImageWhileLoading {
+            base.image = placeholder
+        }
+
+        let issuedIdentifier = Source.Identifier.next()
+        mutatingSelf.taskIdentifier = issuedIdentifier
+
+        if let block = progressBlock {
+            options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
+        }
+
+        let task = KingfisherManager.shared.retrieveImage(
+            with: source,
+            options: options,
+            downloadTaskUpdated: { mutatingSelf.imageTask = $0 },
+            progressiveImageSetter: { self.base.image = $0 },
+            referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier },
+            completionHandler: { result in
+                CallbackQueue.mainCurrentOrAsync.execute {
+                    guard issuedIdentifier == self.taskIdentifier else {
+                        let reason: KingfisherError.ImageSettingErrorReason
+                        do {
+                            let value = try result.get()
+                            reason = .notCurrentSourceTask(result: value, error: nil, source: source)
+                        } catch {
+                            reason = .notCurrentSourceTask(result: nil, error: error, source: source)
+                        }
+                        let error = KingfisherError.imageSettingError(reason: reason)
+                        completionHandler?(.failure(error))
+                        return
+                    }
+
+                    mutatingSelf.imageTask = nil
+                    mutatingSelf.taskIdentifier = nil
+
+                    switch result {
+                    case .success(let value):
+                        self.base.image = value.image
+                        completionHandler?(result)
+
+                    case .failure:
+                        if let image = options.onFailureImage {
+                            self.base.image = image
+                        }
+                        completionHandler?(result)
+                    }
+                }
+            }
+        )
+
+        mutatingSelf.imageTask = task
+        return task
+    }
+
+    // MARK: Cancelling Downloading Task
+
+    /// Cancels the image download task of the button if it is running.
+    /// Nothing will happen if the downloading has already finished.
+    public func cancelImageDownloadTask() {
+        imageTask?.cancel()
+    }
+
+    // MARK: Setting Alternate Image
+
+    @discardableResult
+    public func setAlternateImage(
+        with source: Source?,
+        placeholder: KFCrossPlatformImage? = nil,
+        options: KingfisherOptionsInfo? = nil,
+        progressBlock: DownloadProgressBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
+        return setAlternateImage(
+            with: source,
+            placeholder: placeholder,
+            parsedOptions: options,
+            progressBlock: progressBlock,
+            completionHandler: completionHandler
+        )
+    }
+
+    /// Sets an alternate image to the button with a requested resource.
+    ///
+    /// - Parameters:
+    ///   - resource: The `Resource` object contains information about the resource.
+    ///   - placeholder: A placeholder to show while retrieving the image from the given `resource`.
+    ///   - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
+    ///   - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
+    ///                    `expectedContentLength`, this block will not be called.
+    ///   - completionHandler: Called when the image retrieved and set finished.
+    /// - Returns: A task represents the image downloading.
+    ///
+    /// - Note:
+    /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
+    /// or network. Since this method will perform UI changes, you must call it from the main thread.
+    /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
+    ///
+    @discardableResult
+    public func setAlternateImage(
+        with resource: Resource?,
+        placeholder: KFCrossPlatformImage? = nil,
+        options: KingfisherOptionsInfo? = nil,
+        progressBlock: DownloadProgressBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        return setAlternateImage(
+            with: resource?.convertToSource(),
+            placeholder: placeholder,
+            options: options,
+            progressBlock: progressBlock,
+            completionHandler: completionHandler)
+    }
+
+    func setAlternateImage(
+        with source: Source?,
+        placeholder: KFCrossPlatformImage? = nil,
+        parsedOptions: KingfisherParsedOptionsInfo,
+        progressBlock: DownloadProgressBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        var mutatingSelf = self
+        guard let source = source else {
+            base.alternateImage = placeholder
+            mutatingSelf.alternateTaskIdentifier = nil
+            completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
+            return nil
+        }
+
+        var options = parsedOptions
+        if !options.keepCurrentImageWhileLoading {
+            base.alternateImage = placeholder
+        }
+
+        let issuedIdentifier = Source.Identifier.next()
+        mutatingSelf.alternateTaskIdentifier = issuedIdentifier
+
+        if let block = progressBlock {
+            options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
+        }
+
+        if let provider = ImageProgressiveProvider(options, refresh: { image in
+            self.base.alternateImage = image
+        }) {
+            options.onDataReceived = (options.onDataReceived ?? []) + [provider]
+        }
+
+        options.onDataReceived?.forEach {
+            $0.onShouldApply = { issuedIdentifier == self.alternateTaskIdentifier }
+        }
+
+        let task = KingfisherManager.shared.retrieveImage(
+            with: source,
+            options: options,
+            downloadTaskUpdated: { mutatingSelf.alternateImageTask = $0 },
+            completionHandler: { result in
+                CallbackQueue.mainCurrentOrAsync.execute {
+                    guard issuedIdentifier == self.alternateTaskIdentifier else {
+                        let reason: KingfisherError.ImageSettingErrorReason
+                        do {
+                            let value = try result.get()
+                            reason = .notCurrentSourceTask(result: value, error: nil, source: source)
+                        } catch {
+                            reason = .notCurrentSourceTask(result: nil, error: error, source: source)
+                        }
+                        let error = KingfisherError.imageSettingError(reason: reason)
+                        completionHandler?(.failure(error))
+                        return
+                    }
+
+                    mutatingSelf.alternateImageTask = nil
+                    mutatingSelf.alternateTaskIdentifier = nil
+
+                    switch result {
+                    case .success(let value):
+                        self.base.alternateImage = value.image
+                        completionHandler?(result)
+
+                    case .failure:
+                        if let image = options.onFailureImage {
+                            self.base.alternateImage = image
+                        }
+                        completionHandler?(result)
+                    }
+                }
+            }
+        )
+
+        mutatingSelf.alternateImageTask = task
+        return task
+    }
+
+    // MARK: Cancelling Alternate Image Downloading Task
+
+    /// Cancels the alternate image download task of the button if it is running.
+    /// Nothing will happen if the downloading has already finished.
+    public func cancelAlternateImageDownloadTask() {
+        alternateImageTask?.cancel()
+    }
+}
+
+
+// MARK: - Associated Object
+private var taskIdentifierKey: Void?
+private var imageTaskKey: Void?
+
+private var alternateTaskIdentifierKey: Void?
+private var alternateImageTaskKey: Void?
+
+extension KingfisherWrapper where Base: NSButton {
+
+    // MARK: Properties
+    
+    public private(set) var taskIdentifier: Source.Identifier.Value? {
+        get {
+            let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey)
+            return box?.value
+        }
+        set {
+            let box = newValue.map { Box($0) }
+            setRetainedAssociatedObject(base, &taskIdentifierKey, box)
+        }
+    }
+    
+    private var imageTask: DownloadTask? {
+        get { return getAssociatedObject(base, &imageTaskKey) }
+        set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
+    }
+
+    public private(set) var alternateTaskIdentifier: Source.Identifier.Value? {
+        get {
+            let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &alternateTaskIdentifierKey)
+            return box?.value
+        }
+        set {
+            let box = newValue.map { Box($0) }
+            setRetainedAssociatedObject(base, &alternateTaskIdentifierKey, box)
+        }
+    }
+
+    private var alternateImageTask: DownloadTask? {
+        get { return getAssociatedObject(base, &alternateImageTaskKey) }
+        set { setRetainedAssociatedObject(base, &alternateImageTaskKey, newValue)}
+    }
+}
+#endif

+ 271 - 0
Pods/Kingfisher/Sources/Extensions/NSTextAttachment+Kingfisher.swift

@@ -0,0 +1,271 @@
+//
+//  NSTextAttachment+Kingfisher.swift
+//  Kingfisher
+//
+//  Created by Benjamin Briggs on 22/07/2019.
+//
+//  Copyright (c) 2019 Wei Wang <onevcat@gmail.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.
+
+#if !os(watchOS)
+
+#if os(macOS)
+import AppKit
+#else
+import UIKit
+#endif
+
+extension KingfisherWrapper where Base: NSTextAttachment {
+
+    // MARK: Setting Image
+
+    /// Sets an image to the text attachment with a source.
+    ///
+    /// - Parameters:
+    ///   - source: The `Source` object defines data information from network or a data provider.
+    ///   - attributedView: The owner of the attributed string which this `NSTextAttachment` is added.
+    ///   - placeholder: A placeholder to show while retrieving the image from the given `resource`.
+    ///   - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
+    ///   - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
+    ///                    `expectedContentLength`, this block will not be called.
+    ///   - completionHandler: Called when the image retrieved and set finished.
+    /// - Returns: A task represents the image downloading.
+    ///
+    /// - Note:
+    ///
+    /// Internally, this method will use `KingfisherManager` to get the requested source
+    /// Since this method will perform UI changes, you must call it from the main thread.
+    ///
+    /// The retrieved image will be set to `NSTextAttachment.image` property. Because it is not an image view based
+    /// rendering, options related to view, such as `.transition`, are not supported.
+    ///
+    /// Kingfisher will call `setNeedsDisplay` on the `attributedView` when the image task done. It gives the view a
+    /// chance to render the attributed string again for displaying the downloaded image. For example, if you set an
+    /// attributed with this `NSTextAttachment` to a `UILabel` object, pass it as the `attributedView` parameter.
+    ///
+    /// Here is a typical use case:
+    ///
+    /// ```swift
+    /// let attributedText = NSMutableAttributedString(string: "Hello World")
+    /// let textAttachment = NSTextAttachment()
+    ///
+    /// textAttachment.kf.setImage(
+    ///     with: URL(string: "https://onevcat.com/assets/images/avatar.jpg")!,
+    ///     attributedView: label,
+    ///     options: [
+    ///        .processor(
+    ///            ResizingImageProcessor(referenceSize: .init(width: 30, height: 30))
+    ///            |> RoundCornerImageProcessor(cornerRadius: 15))
+    ///     ]
+    /// )
+    /// attributedText.replaceCharacters(in: NSRange(), with: NSAttributedString(attachment: textAttachment))
+    /// label.attributedText = attributedText
+    /// ```
+    ///
+    @discardableResult
+    public func setImage(
+        with source: Source?,
+        attributedView: @autoclosure @escaping () -> KFCrossPlatformView,
+        placeholder: KFCrossPlatformImage? = nil,
+        options: KingfisherOptionsInfo? = nil,
+        progressBlock: DownloadProgressBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
+        return setImage(
+            with: source,
+            attributedView: attributedView,
+            placeholder: placeholder,
+            parsedOptions: options,
+            progressBlock: progressBlock,
+            completionHandler: completionHandler
+        )
+    }
+
+    /// Sets an image to the text attachment with a source.
+    ///
+    /// - Parameters:
+    ///   - resource: The `Resource` object contains information about the resource.
+    ///   - attributedView: The owner of the attributed string which this `NSTextAttachment` is added.
+    ///   - placeholder: A placeholder to show while retrieving the image from the given `resource`.
+    ///   - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
+    ///   - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
+    ///                    `expectedContentLength`, this block will not be called.
+    ///   - completionHandler: Called when the image retrieved and set finished.
+    /// - Returns: A task represents the image downloading.
+    ///
+    /// - Note:
+    ///
+    /// Internally, this method will use `KingfisherManager` to get the requested source
+    /// Since this method will perform UI changes, you must call it from the main thread.
+    ///
+    /// The retrieved image will be set to `NSTextAttachment.image` property. Because it is not an image view based
+    /// rendering, options related to view, such as `.transition`, are not supported.
+    ///
+    /// Kingfisher will call `setNeedsDisplay` on the `attributedView` when the image task done. It gives the view a
+    /// chance to render the attributed string again for displaying the downloaded image. For example, if you set an
+    /// attributed with this `NSTextAttachment` to a `UILabel` object, pass it as the `attributedView` parameter.
+    ///
+    /// Here is a typical use case:
+    ///
+    /// ```swift
+    /// let attributedText = NSMutableAttributedString(string: "Hello World")
+    /// let textAttachment = NSTextAttachment()
+    ///
+    /// textAttachment.kf.setImage(
+    ///     with: URL(string: "https://onevcat.com/assets/images/avatar.jpg")!,
+    ///     attributedView: label,
+    ///     options: [
+    ///        .processor(
+    ///            ResizingImageProcessor(referenceSize: .init(width: 30, height: 30))
+    ///            |> RoundCornerImageProcessor(cornerRadius: 15))
+    ///     ]
+    /// )
+    /// attributedText.replaceCharacters(in: NSRange(), with: NSAttributedString(attachment: textAttachment))
+    /// label.attributedText = attributedText
+    /// ```
+    ///
+    @discardableResult
+    public func setImage(
+        with resource: Resource?,
+        attributedView: @autoclosure @escaping () -> KFCrossPlatformView,
+        placeholder: KFCrossPlatformImage? = nil,
+        options: KingfisherOptionsInfo? = nil,
+        progressBlock: DownloadProgressBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
+        return setImage(
+            with: resource.map { .network($0) },
+            attributedView: attributedView,
+            placeholder: placeholder,
+            parsedOptions: options,
+            progressBlock: progressBlock,
+            completionHandler: completionHandler
+        )
+    }
+
+    func setImage(
+        with source: Source?,
+        attributedView: @escaping () -> KFCrossPlatformView,
+        placeholder: KFCrossPlatformImage? = nil,
+        parsedOptions: KingfisherParsedOptionsInfo,
+        progressBlock: DownloadProgressBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        var mutatingSelf = self
+        guard let source = source else {
+            base.image = placeholder
+            mutatingSelf.taskIdentifier = nil
+            completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
+            return nil
+        }
+
+        var options = parsedOptions
+        if !options.keepCurrentImageWhileLoading {
+            base.image = placeholder
+        }
+
+        let issuedIdentifier = Source.Identifier.next()
+        mutatingSelf.taskIdentifier = issuedIdentifier
+
+        if let block = progressBlock {
+            options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
+        }
+
+        let task = KingfisherManager.shared.retrieveImage(
+            with: source,
+            options: options,
+            progressiveImageSetter: { self.base.image = $0 },
+            referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier },
+            completionHandler: { result in
+                CallbackQueue.mainCurrentOrAsync.execute {
+                    guard issuedIdentifier == self.taskIdentifier else {
+                        let reason: KingfisherError.ImageSettingErrorReason
+                        do {
+                            let value = try result.get()
+                            reason = .notCurrentSourceTask(result: value, error: nil, source: source)
+                        } catch {
+                            reason = .notCurrentSourceTask(result: nil, error: error, source: source)
+                        }
+                        let error = KingfisherError.imageSettingError(reason: reason)
+                        completionHandler?(.failure(error))
+                        return
+                    }
+
+                    mutatingSelf.imageTask = nil
+                    mutatingSelf.taskIdentifier = nil
+
+                    switch result {
+                    case .success(let value):
+                        self.base.image = value.image
+                        let view = attributedView()
+                        #if canImport(UIKit)
+                        view.setNeedsDisplay()
+                        #else
+                        view.setNeedsDisplay(view.bounds)
+                        #endif
+                    case .failure:
+                        if let image = options.onFailureImage {
+                            self.base.image = image
+                        }
+                    }
+                    completionHandler?(result)
+                }
+        }
+        )
+
+        mutatingSelf.imageTask = task
+        return task
+    }
+
+    // MARK: Cancelling Image
+
+    /// Cancel the image download task bounded to the text attachment if it is running.
+    /// Nothing will happen if the downloading has already finished.
+    public func cancelDownloadTask() {
+        imageTask?.cancel()
+    }
+}
+
+private var taskIdentifierKey: Void?
+private var imageTaskKey: Void?
+
+// MARK: Properties
+extension KingfisherWrapper where Base: NSTextAttachment {
+
+    public private(set) var taskIdentifier: Source.Identifier.Value? {
+        get {
+            let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey)
+            return box?.value
+        }
+        set {
+            let box = newValue.map { Box($0) }
+            setRetainedAssociatedObject(base, &taskIdentifierKey, box)
+        }
+    }
+
+    private var imageTask: DownloadTask? {
+        get { return getAssociatedObject(base, &imageTaskKey) }
+        set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
+    }
+}
+
+#endif

+ 209 - 0
Pods/Kingfisher/Sources/Extensions/TVMonogramView+Kingfisher.swift

@@ -0,0 +1,209 @@
+//
+//  TVMonogramView+Kingfisher.swift
+//  Kingfisher
+//
+//  Created by Marvin Nazari on 2020-12-07.
+//
+//  Copyright (c) 2020 Wei Wang <onevcat@gmail.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
+
+#if canImport(TVUIKit)
+
+import TVUIKit
+
+@available(tvOS 12.0, *)
+extension KingfisherWrapper where Base: TVMonogramView {
+
+    // MARK: Setting Image
+
+    /// Sets an image to the image view with a source.
+    ///
+    /// - Parameters:
+    ///   - source: The `Source` object contains information about the image.
+    ///   - placeholder: A placeholder to show while retrieving the image from the given `resource`.
+    ///   - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
+    ///   - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
+    ///                    `expectedContentLength`, this block will not be called.
+    ///   - completionHandler: Called when the image retrieved and set finished.
+    /// - Returns: A task represents the image downloading.
+    ///
+    /// - Note:
+    ///
+    /// Internally, this method will use `KingfisherManager` to get the requested source
+    /// Since this method will perform UI changes, you must call it from the main thread.
+    /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
+    ///
+    @discardableResult
+    public func setImage(
+        with source: Source?,
+        placeholder: KFCrossPlatformImage? = nil,
+        options: KingfisherOptionsInfo? = nil,
+        progressBlock: DownloadProgressBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
+        return setImage(
+            with: source,
+            placeholder: placeholder,
+            parsedOptions: options,
+            progressBlock: progressBlock,
+            completionHandler: completionHandler
+        )
+    }
+
+    func setImage(
+        with source: Source?,
+        placeholder: KFCrossPlatformImage? = nil,
+        parsedOptions: KingfisherParsedOptionsInfo,
+        progressBlock: DownloadProgressBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        var mutatingSelf = self
+        guard let source = source else {
+            base.image = placeholder
+            mutatingSelf.taskIdentifier = nil
+            completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
+            return nil
+        }
+
+        var options = parsedOptions
+        if !options.keepCurrentImageWhileLoading {
+            base.image = placeholder
+        }
+
+        let issuedIdentifier = Source.Identifier.next()
+        mutatingSelf.taskIdentifier = issuedIdentifier
+
+        if let block = progressBlock {
+            options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
+        }
+
+        let task = KingfisherManager.shared.retrieveImage(
+            with: source,
+            options: options,
+            downloadTaskUpdated: { mutatingSelf.imageTask = $0 },
+            progressiveImageSetter: { self.base.image = $0 },
+            referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier },
+            completionHandler: { result in
+                CallbackQueue.mainCurrentOrAsync.execute {
+                    guard issuedIdentifier == self.taskIdentifier else {
+                        let reason: KingfisherError.ImageSettingErrorReason
+                        do {
+                            let value = try result.get()
+                            reason = .notCurrentSourceTask(result: value, error: nil, source: source)
+                        } catch {
+                            reason = .notCurrentSourceTask(result: nil, error: error, source: source)
+                        }
+                        let error = KingfisherError.imageSettingError(reason: reason)
+                        completionHandler?(.failure(error))
+                        return
+                    }
+
+                    mutatingSelf.imageTask = nil
+                    mutatingSelf.taskIdentifier = nil
+
+                    switch result {
+                    case .success(let value):
+                        self.base.image = value.image
+                        completionHandler?(result)
+
+                    case .failure:
+                        if let image = options.onFailureImage {
+                            self.base.image = image
+                        }
+                        completionHandler?(result)
+                    }
+                }
+            }
+        )
+
+        mutatingSelf.imageTask = task
+        return task
+    }
+    
+    /// Sets an image to the image view with a requested resource.
+    ///
+    /// - Parameters:
+    ///   - resource: The `Resource` object contains information about the image.
+    ///   - placeholder: A placeholder to show while retrieving the image from the given `resource`.
+    ///   - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
+    ///   - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
+    ///                    `expectedContentLength`, this block will not be called.
+    ///   - completionHandler: Called when the image retrieved and set finished.
+    /// - Returns: A task represents the image downloading.
+    ///
+    /// - Note:
+    ///
+    /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
+    /// or network. Since this method will perform UI changes, you must call it from the main thread.
+    /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
+    ///
+    @discardableResult
+    public func setImage(
+        with resource: Resource?,
+        placeholder: KFCrossPlatformImage? = nil,
+        options: KingfisherOptionsInfo? = nil,
+        progressBlock: DownloadProgressBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        return setImage(
+            with: resource?.convertToSource(),
+            placeholder: placeholder,
+            options: options,
+            progressBlock: progressBlock,
+            completionHandler: completionHandler)
+    }
+
+    // MARK: Cancelling Image
+
+    /// Cancel the image download task bounded to the image view if it is running.
+    /// Nothing will happen if the downloading has already finished.
+    public func cancelDownloadTask() {
+        imageTask?.cancel()
+    }
+}
+
+private var taskIdentifierKey: Void?
+private var imageTaskKey: Void?
+
+// MARK: Properties
+@available(tvOS 12.0, *)
+extension KingfisherWrapper where Base: TVMonogramView {
+    
+    public private(set) var taskIdentifier: Source.Identifier.Value? {
+        get {
+            let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey)
+            return box?.value
+        }
+        set {
+            let box = newValue.map { Box($0) }
+            setRetainedAssociatedObject(base, &taskIdentifierKey, box)
+        }
+    }
+
+    private var imageTask: DownloadTask? {
+        get { return getAssociatedObject(base, &imageTaskKey) }
+        set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
+    }
+}
+
+#endif

+ 400 - 0
Pods/Kingfisher/Sources/Extensions/UIButton+Kingfisher.swift

@@ -0,0 +1,400 @@
+//
+//  UIButton+Kingfisher.swift
+//  Kingfisher
+//
+//  Created by Wei Wang on 15/4/13.
+//
+//  Copyright (c) 2019 Wei Wang <onevcat@gmail.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.
+
+#if !os(watchOS)
+
+#if canImport(UIKit)
+import UIKit
+
+extension KingfisherWrapper where Base: UIButton {
+
+    // MARK: Setting Image
+    /// Sets an image to the button for a specified state with a source.
+    ///
+    /// - Parameters:
+    ///   - source: The `Source` object contains information about the image.
+    ///   - state: The button state to which the image should be set.
+    ///   - placeholder: A placeholder to show while retrieving the image from the given `resource`.
+    ///   - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
+    ///   - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
+    ///                    `expectedContentLength`, this block will not be called.
+    ///   - completionHandler: Called when the image retrieved and set finished.
+    /// - Returns: A task represents the image downloading.
+    ///
+    /// - Note:
+    /// Internally, this method will use `KingfisherManager` to get the requested source, from either cache
+    /// or network. Since this method will perform UI changes, you must call it from the main thread.
+    /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
+    ///
+    @discardableResult
+    public func setImage(
+        with source: Source?,
+        for state: UIControl.State,
+        placeholder: UIImage? = nil,
+        options: KingfisherOptionsInfo? = nil,
+        progressBlock: DownloadProgressBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
+        return setImage(
+            with: source,
+            for: state,
+            placeholder: placeholder,
+            parsedOptions: options,
+            progressBlock: progressBlock,
+            completionHandler: completionHandler
+        )
+    }
+    
+    /// Sets an image to the button for a specified state with a requested resource.
+    ///
+    /// - Parameters:
+    ///   - resource: The `Resource` object contains information about the resource.
+    ///   - state: The button state to which the image should be set.
+    ///   - placeholder: A placeholder to show while retrieving the image from the given `resource`.
+    ///   - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
+    ///   - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
+    ///                    `expectedContentLength`, this block will not be called.
+    ///   - completionHandler: Called when the image retrieved and set finished.
+    /// - Returns: A task represents the image downloading.
+    ///
+    /// - Note:
+    /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
+    /// or network. Since this method will perform UI changes, you must call it from the main thread.
+    /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
+    ///
+    @discardableResult
+    public func setImage(
+        with resource: Resource?,
+        for state: UIControl.State,
+        placeholder: UIImage? = nil,
+        options: KingfisherOptionsInfo? = nil,
+        progressBlock: DownloadProgressBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        return setImage(
+            with: resource?.convertToSource(),
+            for: state,
+            placeholder: placeholder,
+            options: options,
+            progressBlock: progressBlock,
+            completionHandler: completionHandler)
+    }
+
+    @discardableResult
+    public func setImage(
+        with source: Source?,
+        for state: UIControl.State,
+        placeholder: UIImage? = nil,
+        parsedOptions: KingfisherParsedOptionsInfo,
+        progressBlock: DownloadProgressBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        guard let source = source else {
+            base.setImage(placeholder, for: state)
+            setTaskIdentifier(nil, for: state)
+            completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
+            return nil
+        }
+
+        var options = parsedOptions
+        if !options.keepCurrentImageWhileLoading {
+            base.setImage(placeholder, for: state)
+        }
+
+        var mutatingSelf = self
+        let issuedIdentifier = Source.Identifier.next()
+        setTaskIdentifier(issuedIdentifier, for: state)
+
+        if let block = progressBlock {
+            options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
+        }
+
+        let task = KingfisherManager.shared.retrieveImage(
+            with: source,
+            options: options,
+            downloadTaskUpdated: { mutatingSelf.imageTask = $0 },
+            progressiveImageSetter: { self.base.setImage($0, for: state) },
+            referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier(for: state) },
+            completionHandler: { result in
+                CallbackQueue.mainCurrentOrAsync.execute {
+                    guard issuedIdentifier == self.taskIdentifier(for: state) else {
+                        let reason: KingfisherError.ImageSettingErrorReason
+                        do {
+                            let value = try result.get()
+                            reason = .notCurrentSourceTask(result: value, error: nil, source: source)
+                        } catch {
+                            reason = .notCurrentSourceTask(result: nil, error: error, source: source)
+                        }
+                        let error = KingfisherError.imageSettingError(reason: reason)
+                        completionHandler?(.failure(error))
+                        return
+                    }
+
+                    mutatingSelf.imageTask = nil
+                    mutatingSelf.setTaskIdentifier(nil, for: state)
+
+                    switch result {
+                    case .success(let value):
+                        self.base.setImage(value.image, for: state)
+                        completionHandler?(result)
+
+                    case .failure:
+                        if let image = options.onFailureImage {
+                            self.base.setImage(image, for: state)
+                        }
+                        completionHandler?(result)
+                    }
+                }
+            }
+        )
+
+        mutatingSelf.imageTask = task
+        return task
+    }
+
+    // MARK: Cancelling Downloading Task
+    
+    /// Cancels the image download task of the button if it is running.
+    /// Nothing will happen if the downloading has already finished.
+    public func cancelImageDownloadTask() {
+        imageTask?.cancel()
+    }
+
+    // MARK: Setting Background Image
+
+    /// Sets a background image to the button for a specified state with a source.
+    ///
+    /// - Parameters:
+    ///   - source: The `Source` object contains information about the image.
+    ///   - state: The button state to which the image should be set.
+    ///   - placeholder: A placeholder to show while retrieving the image from the given `resource`.
+    ///   - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
+    ///   - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
+    ///                    `expectedContentLength`, this block will not be called.
+    ///   - completionHandler: Called when the image retrieved and set finished.
+    /// - Returns: A task represents the image downloading.
+    ///
+    /// - Note:
+    /// Internally, this method will use `KingfisherManager` to get the requested source
+    /// Since this method will perform UI changes, you must call it from the main thread.
+    /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
+    ///
+    @discardableResult
+    public func setBackgroundImage(
+        with source: Source?,
+        for state: UIControl.State,
+        placeholder: UIImage? = nil,
+        options: KingfisherOptionsInfo? = nil,
+        progressBlock: DownloadProgressBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
+        return setBackgroundImage(
+            with: source,
+            for: state,
+            placeholder: placeholder,
+            parsedOptions: options,
+            progressBlock: progressBlock,
+            completionHandler: completionHandler
+        )
+    }
+
+    /// Sets a background image to the button for a specified state with a requested resource.
+    ///
+    /// - Parameters:
+    ///   - resource: The `Resource` object contains information about the resource.
+    ///   - state: The button state to which the image should be set.
+    ///   - placeholder: A placeholder to show while retrieving the image from the given `resource`.
+    ///   - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
+    ///   - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
+    ///                    `expectedContentLength`, this block will not be called.
+    ///   - completionHandler: Called when the image retrieved and set finished.
+    /// - Returns: A task represents the image downloading.
+    ///
+    /// - Note:
+    /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
+    /// or network. Since this method will perform UI changes, you must call it from the main thread.
+    /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
+    ///
+    @discardableResult
+    public func setBackgroundImage(
+        with resource: Resource?,
+        for state: UIControl.State,
+        placeholder: UIImage? = nil,
+        options: KingfisherOptionsInfo? = nil,
+        progressBlock: DownloadProgressBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        return setBackgroundImage(
+            with: resource?.convertToSource(),
+            for: state,
+            placeholder: placeholder,
+            options: options,
+            progressBlock: progressBlock,
+            completionHandler: completionHandler)
+    }
+
+    func setBackgroundImage(
+        with source: Source?,
+        for state: UIControl.State,
+        placeholder: UIImage? = nil,
+        parsedOptions: KingfisherParsedOptionsInfo,
+        progressBlock: DownloadProgressBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        guard let source = source else {
+            base.setBackgroundImage(placeholder, for: state)
+            setBackgroundTaskIdentifier(nil, for: state)
+            completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
+            return nil
+        }
+
+        var options = parsedOptions
+        if !options.keepCurrentImageWhileLoading {
+            base.setBackgroundImage(placeholder, for: state)
+        }
+
+        var mutatingSelf = self
+        let issuedIdentifier = Source.Identifier.next()
+        setBackgroundTaskIdentifier(issuedIdentifier, for: state)
+
+        if let block = progressBlock {
+            options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
+        }
+
+        let task = KingfisherManager.shared.retrieveImage(
+            with: source,
+            options: options,
+            downloadTaskUpdated: { mutatingSelf.backgroundImageTask = $0 },
+            progressiveImageSetter: { self.base.setBackgroundImage($0, for: state) },
+            referenceTaskIdentifierChecker: { issuedIdentifier == self.backgroundTaskIdentifier(for: state) },
+            completionHandler: { result in
+                CallbackQueue.mainCurrentOrAsync.execute {
+                    guard issuedIdentifier == self.backgroundTaskIdentifier(for: state) else {
+                        let reason: KingfisherError.ImageSettingErrorReason
+                        do {
+                            let value = try result.get()
+                            reason = .notCurrentSourceTask(result: value, error: nil, source: source)
+                        } catch {
+                            reason = .notCurrentSourceTask(result: nil, error: error, source: source)
+                        }
+                        let error = KingfisherError.imageSettingError(reason: reason)
+                        completionHandler?(.failure(error))
+                        return
+                    }
+
+                    mutatingSelf.backgroundImageTask = nil
+                    mutatingSelf.setBackgroundTaskIdentifier(nil, for: state)
+
+                    switch result {
+                    case .success(let value):
+                        self.base.setBackgroundImage(value.image, for: state)
+                        completionHandler?(result)
+
+                    case .failure:
+                        if let image = options.onFailureImage {
+                            self.base.setBackgroundImage(image, for: state)
+                        }
+                        completionHandler?(result)
+                    }
+                }
+            }
+        )
+
+        mutatingSelf.backgroundImageTask = task
+        return task
+    }
+
+    // MARK: Cancelling Background Downloading Task
+    
+    /// Cancels the background image download task of the button if it is running.
+    /// Nothing will happen if the downloading has already finished.
+    public func cancelBackgroundImageDownloadTask() {
+        backgroundImageTask?.cancel()
+    }
+}
+
+// MARK: - Associated Object
+private var taskIdentifierKey: Void?
+private var imageTaskKey: Void?
+
+// MARK: Properties
+extension KingfisherWrapper where Base: UIButton {
+
+    private typealias TaskIdentifier = Box<[UInt: Source.Identifier.Value]>
+    
+    public func taskIdentifier(for state: UIControl.State) -> Source.Identifier.Value? {
+        return taskIdentifierInfo.value[state.rawValue]
+    }
+
+    private func setTaskIdentifier(_ identifier: Source.Identifier.Value?, for state: UIControl.State) {
+        taskIdentifierInfo.value[state.rawValue] = identifier
+    }
+    
+    private var taskIdentifierInfo: TaskIdentifier {
+        return  getAssociatedObject(base, &taskIdentifierKey) ?? {
+            setRetainedAssociatedObject(base, &taskIdentifierKey, $0)
+            return $0
+        } (TaskIdentifier([:]))
+    }
+    
+    private var imageTask: DownloadTask? {
+        get { return getAssociatedObject(base, &imageTaskKey) }
+        set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
+    }
+}
+
+
+private var backgroundTaskIdentifierKey: Void?
+private var backgroundImageTaskKey: Void?
+
+// MARK: Background Properties
+extension KingfisherWrapper where Base: UIButton {
+    
+    public func backgroundTaskIdentifier(for state: UIControl.State) -> Source.Identifier.Value? {
+        return backgroundTaskIdentifierInfo.value[state.rawValue]
+    }
+    
+    private func setBackgroundTaskIdentifier(_ identifier: Source.Identifier.Value?, for state: UIControl.State) {
+        backgroundTaskIdentifierInfo.value[state.rawValue] = identifier
+    }
+    
+    private var backgroundTaskIdentifierInfo: TaskIdentifier {
+        return  getAssociatedObject(base, &backgroundTaskIdentifierKey) ?? {
+            setRetainedAssociatedObject(base, &backgroundTaskIdentifierKey, $0)
+            return $0
+        } (TaskIdentifier([:]))
+    }
+    
+    private var backgroundImageTask: DownloadTask? {
+        get { return getAssociatedObject(base, &backgroundImageTaskKey) }
+        mutating set { setRetainedAssociatedObject(base, &backgroundImageTaskKey, newValue) }
+    }
+}
+#endif
+
+#endif

+ 204 - 0
Pods/Kingfisher/Sources/Extensions/WKInterfaceImage+Kingfisher.swift

@@ -0,0 +1,204 @@
+//
+//  WKInterfaceImage+Kingfisher.swift
+//  Kingfisher
+//
+//  Created by Rodrigo Borges Soares on 04/05/18.
+//
+//  Copyright (c) 2019 Wei Wang <onevcat@gmail.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.
+
+#if canImport(WatchKit)
+
+import WatchKit
+
+extension KingfisherWrapper where Base: WKInterfaceImage {
+
+    // MARK: Setting Image
+
+    /// Sets an image to the image view with a source.
+    ///
+    /// - Parameters:
+    ///   - source: The `Source` object contains information about the image.
+    ///   - placeholder: A placeholder to show while retrieving the image from the given `resource`.
+    ///   - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
+    ///   - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
+    ///                    `expectedContentLength`, this block will not be called.
+    ///   - completionHandler: Called when the image retrieved and set finished.
+    /// - Returns: A task represents the image downloading.
+    ///
+    /// - Note:
+    ///
+    /// Internally, this method will use `KingfisherManager` to get the requested source
+    /// Since this method will perform UI changes, you must call it from the main thread.
+    /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
+    ///
+    @discardableResult
+    public func setImage(
+        with source: Source?,
+        placeholder: KFCrossPlatformImage? = nil,
+        options: KingfisherOptionsInfo? = nil,
+        progressBlock: DownloadProgressBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
+        return setImage(
+            with: source,
+            placeholder: placeholder,
+            parsedOptions: options,
+            progressBlock: progressBlock,
+            completionHandler: completionHandler
+        )
+    }
+    
+    /// Sets an image to the image view with a requested resource.
+    ///
+    /// - Parameters:
+    ///   - resource: The `Resource` object contains information about the image.
+    ///   - placeholder: A placeholder to show while retrieving the image from the given `resource`.
+    ///   - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
+    ///   - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
+    ///                    `expectedContentLength`, this block will not be called.
+    ///   - completionHandler: Called when the image retrieved and set finished.
+    /// - Returns: A task represents the image downloading.
+    ///
+    /// - Note:
+    ///
+    /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
+    /// or network. Since this method will perform UI changes, you must call it from the main thread.
+    /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
+    ///
+    @discardableResult
+    public func setImage(
+        with resource: Resource?,
+        placeholder: KFCrossPlatformImage? = nil,
+        options: KingfisherOptionsInfo? = nil,
+        progressBlock: DownloadProgressBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        return setImage(
+            with: resource?.convertToSource(),
+            placeholder: placeholder,
+            options: options,
+            progressBlock: progressBlock,
+            completionHandler: completionHandler)
+    }
+
+    func setImage(
+        with source: Source?,
+        placeholder: KFCrossPlatformImage? = nil,
+        parsedOptions: KingfisherParsedOptionsInfo,
+        progressBlock: DownloadProgressBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
+    {
+        var mutatingSelf = self
+        guard let source = source else {
+            base.setImage(placeholder)
+            mutatingSelf.taskIdentifier = nil
+            completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
+            return nil
+        }
+
+        var options = parsedOptions
+        if !options.keepCurrentImageWhileLoading {
+            base.setImage(placeholder)
+        }
+
+        let issuedIdentifier = Source.Identifier.next()
+        mutatingSelf.taskIdentifier = issuedIdentifier
+
+        if let block = progressBlock {
+            options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
+        }
+
+        let task = KingfisherManager.shared.retrieveImage(
+            with: source,
+            options: options,
+            downloadTaskUpdated: { mutatingSelf.imageTask = $0 },
+            progressiveImageSetter: { self.base.setImage($0) },
+            referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier },
+            completionHandler: { result in
+                CallbackQueue.mainCurrentOrAsync.execute {
+                    guard issuedIdentifier == self.taskIdentifier else {
+                        let reason: KingfisherError.ImageSettingErrorReason
+                        do {
+                            let value = try result.get()
+                            reason = .notCurrentSourceTask(result: value, error: nil, source: source)
+                        } catch {
+                            reason = .notCurrentSourceTask(result: nil, error: error, source: source)
+                        }
+                        let error = KingfisherError.imageSettingError(reason: reason)
+                        completionHandler?(.failure(error))
+                        return
+                    }
+
+                    mutatingSelf.imageTask = nil
+                    mutatingSelf.taskIdentifier = nil
+
+                    switch result {
+                    case .success(let value):
+                        self.base.setImage(value.image)
+                        completionHandler?(result)
+
+                    case .failure:
+                        if let image = options.onFailureImage {
+                            self.base.setImage(image)
+                        }
+                        completionHandler?(result)
+                    }
+                }
+            }
+        )
+
+        mutatingSelf.imageTask = task
+        return task
+    }
+
+    // MARK: Cancelling Image
+
+    /// Cancel the image download task bounded to the image view if it is running.
+    /// Nothing will happen if the downloading has already finished.
+    public func cancelDownloadTask() {
+        imageTask?.cancel()
+    }
+}
+
+private var taskIdentifierKey: Void?
+private var imageTaskKey: Void?
+
+// MARK: Properties
+extension KingfisherWrapper where Base: WKInterfaceImage {
+    
+    public private(set) var taskIdentifier: Source.Identifier.Value? {
+        get {
+            let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey)
+            return box?.value
+        }
+        set {
+            let box = newValue.map { Box($0) }
+            setRetainedAssociatedObject(base, &taskIdentifierKey, box)
+        }
+    }
+
+    private var imageTask: DownloadTask? {
+        get { return getAssociatedObject(base, &imageTaskKey) }
+        set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
+    }
+}
+#endif

+ 151 - 0
Pods/Kingfisher/Sources/General/ImageSource/AVAssetImageDataProvider.swift

@@ -0,0 +1,151 @@
+//
+//  AVAssetImageDataProvider.swift
+//  Kingfisher
+//
+//  Created by onevcat on 2020/08/09.
+//
+//  Copyright (c) 2020 Wei Wang <onevcat@gmail.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.
+
+#if !os(watchOS)
+
+import Foundation
+import AVKit
+
+#if canImport(MobileCoreServices)
+import MobileCoreServices
+#else
+import CoreServices
+#endif
+
+/// A data provider to provide thumbnail data from a given AVKit asset.
+public struct AVAssetImageDataProvider: ImageDataProvider {
+
+    /// The possible error might be caused by the `AVAssetImageDataProvider`.
+    /// - userCancelled: The data provider process is cancelled.
+    /// - invalidImage: The retrieved image is invalid.
+    public enum AVAssetImageDataProviderError: Error {
+        case userCancelled
+        case invalidImage(_ image: CGImage?)
+    }
+
+    /// The asset image generator bound to `self`.
+    public let assetImageGenerator: AVAssetImageGenerator
+
+    /// The time at which the image should be generate in the asset.
+    public let time: CMTime
+
+    private var internalKey: String {
+        guard let url = (assetImageGenerator.asset as? AVURLAsset)?.url else {
+            return UUID().uuidString
+        }
+        return url.cacheKey
+    }
+
+    /// The cache key used by `self`.
+    public var cacheKey: String {
+        return "\(internalKey)_\(time.seconds)"
+    }
+
+    /// Creates an asset image data provider.
+    /// - Parameters:
+    ///   - assetImageGenerator: The asset image generator controls data providing behaviors.
+    ///   - time: At which time in the asset the image should be generated.
+    public init(assetImageGenerator: AVAssetImageGenerator, time: CMTime) {
+        self.assetImageGenerator = assetImageGenerator
+        self.time = time
+    }
+
+    /// Creates an asset image data provider.
+    /// - Parameters:
+    ///   - assetURL: The URL of asset for providing image data.
+    ///   - time: At which time in the asset the image should be generated.
+    ///
+    /// This method uses `assetURL` to create an `AVAssetImageGenerator` object and calls
+    /// the `init(assetImageGenerator:time:)` initializer.
+    ///
+    public init(assetURL: URL, time: CMTime) {
+        let asset = AVAsset(url: assetURL)
+        let generator = AVAssetImageGenerator(asset: asset)
+        generator.appliesPreferredTrackTransform = true
+        self.init(assetImageGenerator: generator, time: time)
+    }
+
+    /// Creates an asset image data provider.
+    ///
+    /// - Parameters:
+    ///   - assetURL: The URL of asset for providing image data.
+    ///   - seconds: At which time in seconds in the asset the image should be generated.
+    ///
+    /// This method uses `assetURL` to create an `AVAssetImageGenerator` object, uses `seconds` to create a `CMTime`,
+    /// and calls the `init(assetImageGenerator:time:)` initializer.
+    ///
+    public init(assetURL: URL, seconds: TimeInterval) {
+        let time = CMTime(seconds: seconds, preferredTimescale: 600)
+        self.init(assetURL: assetURL, time: time)
+    }
+
+    public func data(handler: @escaping (Result<Data, Error>) -> Void) {
+        assetImageGenerator.generateCGImagesAsynchronously(forTimes: [NSValue(time: time)]) {
+            (requestedTime, image, imageTime, result, error) in
+            if let error = error {
+                handler(.failure(error))
+                return
+            }
+
+            if result == .cancelled {
+                handler(.failure(AVAssetImageDataProviderError.userCancelled))
+                return
+            }
+
+            guard let cgImage = image, let data = cgImage.jpegData else {
+                handler(.failure(AVAssetImageDataProviderError.invalidImage(image)))
+                return
+            }
+
+            handler(.success(data))
+        }
+    }
+}
+
+extension CGImage {
+    var jpegData: Data? {
+        guard let mutableData = CFDataCreateMutable(nil, 0) else {
+            return nil
+        }
+#if os(visionOS)
+        guard let destination = CGImageDestinationCreateWithData(
+            mutableData, UTType.jpeg.identifier as CFString , 1, nil
+        ) else {
+            return nil
+        }
+#else
+        guard let destination = CGImageDestinationCreateWithData(mutableData, kUTTypeJPEG, 1, nil) else {
+            return nil
+        }
+#endif
+        
+        CGImageDestinationAddImage(destination, self, nil)
+        guard CGImageDestinationFinalize(destination) else { return nil }
+        return mutableData as Data
+    }
+}
+
+#endif

+ 190 - 0
Pods/Kingfisher/Sources/General/ImageSource/ImageDataProvider.swift

@@ -0,0 +1,190 @@
+//
+//  ImageDataProvider.swift
+//  Kingfisher
+//
+//  Created by onevcat on 2018/11/13.
+//
+//  Copyright (c) 2019 Wei Wang <onevcat@gmail.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
+
+/// Represents a data provider to provide image data to Kingfisher when setting with
+/// `Source.provider` source. Compared to `Source.network` member, it gives a chance
+/// to load some image data in your own way, as long as you can provide the data
+/// representation for the image.
+public protocol ImageDataProvider {
+    
+    /// The key used in cache.
+    var cacheKey: String { get }
+    
+    /// Provides the data which represents image. Kingfisher uses the data you pass in the
+    /// handler to process images and caches it for later use.
+    ///
+    /// - Parameter handler: The handler you should call when you prepared your data.
+    ///                      If the data is loaded successfully, call the handler with
+    ///                      a `.success` with the data associated. Otherwise, call it
+    ///                      with a `.failure` and pass the error.
+    ///
+    /// - Note:
+    /// If the `handler` is called with a `.failure` with error, a `dataProviderError` of
+    /// `ImageSettingErrorReason` will be finally thrown out to you as the `KingfisherError`
+    /// from the framework.
+    func data(handler: @escaping (Result<Data, Error>) -> Void)
+
+    /// The content URL represents this provider, if exists.
+    var contentURL: URL? { get }
+}
+
+public extension ImageDataProvider {
+    var contentURL: URL? { return nil }
+    func convertToSource() -> Source {
+        .provider(self)
+    }
+}
+
+/// Represents an image data provider for loading from a local file URL on disk.
+/// Uses this type for adding a disk image to Kingfisher. Compared to loading it
+/// directly, you can get benefit of using Kingfisher's extension methods, as well
+/// as applying `ImageProcessor`s and storing the image to `ImageCache` of Kingfisher.
+public struct LocalFileImageDataProvider: ImageDataProvider {
+
+    // MARK: Public Properties
+
+    /// The file URL from which the image be loaded.
+    public let fileURL: URL
+    private let loadingQueue: ExecutionQueue
+
+    // MARK: Initializers
+
+    /// Creates an image data provider by supplying the target local file URL.
+    ///
+    /// - Parameters:
+    ///   - fileURL: The file URL from which the image be loaded.
+    ///   - cacheKey: The key is used for caching the image data. By default,
+    ///               the `absoluteString` of `fileURL` is used.
+    ///   - loadingQueue: The queue where the file loading should happen. By default, the dispatch queue of
+    ///                   `.global(qos: .userInitiated)` will be used.
+    public init(
+        fileURL: URL,
+        cacheKey: String? = nil,
+        loadingQueue: ExecutionQueue = .dispatch(DispatchQueue.global(qos: .userInitiated))
+    ) {
+        self.fileURL = fileURL
+        self.cacheKey = cacheKey ?? fileURL.localFileCacheKey
+        self.loadingQueue = loadingQueue
+    }
+
+    // MARK: Protocol Conforming
+
+    /// The key used in cache.
+    public var cacheKey: String
+
+    public func data(handler:@escaping (Result<Data, Error>) -> Void) {
+        loadingQueue.execute {
+            handler(Result(catching: { try Data(contentsOf: fileURL) }))
+        }
+    }
+    
+    #if swift(>=5.5)
+    #if canImport(_Concurrency)
+    @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
+    public var data: Data {
+        get async throws {
+            try await withCheckedThrowingContinuation { continuation in
+                loadingQueue.execute {
+                    do {
+                        let data = try Data(contentsOf: fileURL)
+                        continuation.resume(returning: data)
+                    } catch {
+                        continuation.resume(throwing: error)
+                    }
+                }
+            }
+        }
+    }
+    #endif
+    #endif
+
+    /// The URL of the local file on the disk.
+    public var contentURL: URL? {
+        return fileURL
+    }
+}
+
+/// Represents an image data provider for loading image from a given Base64 encoded string.
+public struct Base64ImageDataProvider: ImageDataProvider {
+
+    // MARK: Public Properties
+    /// The encoded Base64 string for the image.
+    public let base64String: String
+
+    // MARK: Initializers
+
+    /// Creates an image data provider by supplying the Base64 encoded string.
+    ///
+    /// - Parameters:
+    ///   - base64String: The Base64 encoded string for an image.
+    ///   - cacheKey: The key is used for caching the image data. You need a different key for any different image.
+    public init(base64String: String, cacheKey: String) {
+        self.base64String = base64String
+        self.cacheKey = cacheKey
+    }
+
+    // MARK: Protocol Conforming
+
+    /// The key used in cache.
+    public var cacheKey: String
+
+    public func data(handler: (Result<Data, Error>) -> Void) {
+        let data = Data(base64Encoded: base64String)!
+        handler(.success(data))
+    }
+}
+
+/// Represents an image data provider for a raw data object.
+public struct RawImageDataProvider: ImageDataProvider {
+
+    // MARK: Public Properties
+
+    /// The raw data object to provide to Kingfisher image loader.
+    public let data: Data
+
+    // MARK: Initializers
+
+    /// Creates an image data provider by the given raw `data` value and a `cacheKey` be used in Kingfisher cache.
+    ///
+    /// - Parameters:
+    ///   - data: The raw data reprensents an image.
+    ///   - cacheKey: The key is used for caching the image data. You need a different key for any different image.
+    public init(data: Data, cacheKey: String) {
+        self.data = data
+        self.cacheKey = cacheKey
+    }
+
+    // MARK: Protocol Conforming
+    
+    /// The key used in cache.
+    public var cacheKey: String
+
+    public func data(handler: @escaping (Result<Data, Error>) -> Void) {
+        handler(.success(data))
+    }
+}

+ 121 - 0
Pods/Kingfisher/Sources/General/ImageSource/Resource.swift

@@ -0,0 +1,121 @@
+//
+//  Resource.swift
+//  Kingfisher
+//
+//  Created by Wei Wang on 15/4/6.
+//
+//  Copyright (c) 2019 Wei Wang <onevcat@gmail.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
+
+/// Represents an image resource at a certain url and a given cache key.
+/// Kingfisher will use a `Resource` to download a resource from network and cache it with the cache key when
+/// using `Source.network` as its image setting source.
+public protocol Resource {
+    
+    /// The key used in cache.
+    var cacheKey: String { get }
+    
+    /// The target image URL.
+    var downloadURL: URL { get }
+}
+
+extension Resource {
+
+    /// Converts `self` to a valid `Source` based on its `downloadURL` scheme. A `.provider` with
+    /// `LocalFileImageDataProvider` associated will be returned if the URL points to a local file. Otherwise,
+    /// `.network` is returned.
+    public func convertToSource(overrideCacheKey: String? = nil) -> Source {
+        let key = overrideCacheKey ?? cacheKey
+        return downloadURL.isFileURL ?
+            .provider(LocalFileImageDataProvider(fileURL: downloadURL, cacheKey: key)) :
+            .network(KF.ImageResource(downloadURL: downloadURL, cacheKey: key))
+    }
+}
+
+@available(*, deprecated, message: "This type conflicts with `GeneratedAssetSymbols.ImageResource` in Swift 5.9. Renamed to avoid issues in the future.", renamed: "KF.ImageResource")
+public typealias ImageResource = KF.ImageResource
+
+
+extension KF {
+    /// ImageResource is a simple combination of `downloadURL` and `cacheKey`.
+    /// When passed to image view set methods, Kingfisher will try to download the target
+    /// image from the `downloadURL`, and then store it with the `cacheKey` as the key in cache.
+    public struct ImageResource: Resource {
+
+        // MARK: - Initializers
+
+        /// Creates an image resource.
+        ///
+        /// - Parameters:
+        ///   - downloadURL: The target image URL from where the image can be downloaded.
+        ///   - cacheKey: The cache key. If `nil`, Kingfisher will use the `absoluteString` of `downloadURL` as the key.
+        ///               Default is `nil`.
+        public init(downloadURL: URL, cacheKey: String? = nil) {
+            self.downloadURL = downloadURL
+            self.cacheKey = cacheKey ?? downloadURL.cacheKey
+        }
+
+        // MARK: Protocol Conforming
+        
+        /// The key used in cache.
+        public let cacheKey: String
+
+        /// The target image URL.
+        public let downloadURL: URL
+    }
+}
+
+/// URL conforms to `Resource` in Kingfisher.
+/// The `absoluteString` of this URL is used as `cacheKey`. And the URL itself will be used as `downloadURL`.
+/// If you need customize the url and/or cache key, use `ImageResource` instead.
+extension URL: Resource {
+    public var cacheKey: String { return isFileURL ? localFileCacheKey : absoluteString }
+    public var downloadURL: URL { return self }
+}
+
+extension URL {
+    static let localFileCacheKeyPrefix = "kingfisher.local.cacheKey"
+    
+    // The special version of cache key for a local file on disk. Every time the app is reinstalled on the disk,
+    // the system assigns a new container folder to hold the .app (and the extensions, .appex) folder. So the URL for
+    // the same image in bundle might be different.
+    //
+    // This getter only uses the fixed part in the URL (until the bundle name folder) to provide a stable cache key
+    // for the image under the same path inside the bundle.
+    //
+    // See #1825 (https://github.com/onevcat/Kingfisher/issues/1825)
+    var localFileCacheKey: String {
+        var validComponents: [String] = []
+        for part in pathComponents.reversed() {
+            validComponents.append(part)
+            if part.hasSuffix(".app") || part.hasSuffix(".appex") {
+                break
+            }
+        }
+        let fixedPath = "\(Self.localFileCacheKeyPrefix)/\(validComponents.reversed().joined(separator: "/"))"
+        if let q = query {
+            return "\(fixedPath)?\(q)"
+        } else {
+            return fixedPath
+        }
+    }
+}

+ 116 - 0
Pods/Kingfisher/Sources/General/ImageSource/Source.swift

@@ -0,0 +1,116 @@
+//
+//  Source.swift
+//  Kingfisher
+//
+//  Created by onevcat on 2018/11/17.
+//
+//  Copyright (c) 2019 Wei Wang <onevcat@gmail.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
+
+/// Represents an image setting source for Kingfisher methods.
+///
+/// A `Source` value indicates the way how the target image can be retrieved and cached.
+///
+/// - network: The target image should be got from network remotely. The associated `Resource`
+///            value defines detail information like image URL and cache key.
+/// - provider: The target image should be provided in a data format. Normally, it can be an image
+///             from local storage or in any other encoding format (like Base64).
+public enum Source {
+
+    /// Represents the source task identifier when setting an image to a view with extension methods.
+    public enum Identifier {
+
+        /// The underlying value type of source identifier.
+        public typealias Value = UInt
+        static private(set) var current: Value = 0
+        static func next() -> Value {
+            current += 1
+            return current
+        }
+    }
+
+    // MARK: Member Cases
+
+    /// The target image should be got from network remotely. The associated `Resource`
+    /// value defines detail information like image URL and cache key.
+    case network(Resource)
+    
+    /// The target image should be provided in a data format. Normally, it can be an image
+    /// from local storage or in any other encoding format (like Base64).
+    case provider(ImageDataProvider)
+
+    // MARK: Getting Properties
+
+    /// The cache key defined for this source value.
+    public var cacheKey: String {
+        switch self {
+        case .network(let resource): return resource.cacheKey
+        case .provider(let provider): return provider.cacheKey
+        }
+    }
+
+    /// The URL defined for this source value.
+    ///
+    /// For a `.network` source, it is the `downloadURL` of associated `Resource` instance.
+    /// For a `.provider` value, it is always `nil`.
+    public var url: URL? {
+        switch self {
+        case .network(let resource): return resource.downloadURL
+        case .provider(let provider): return provider.contentURL
+        }
+    }
+}
+
+extension Source: Hashable {
+    public static func == (lhs: Source, rhs: Source) -> Bool {
+        switch (lhs, rhs) {
+        case (.network(let r1), .network(let r2)):
+            return r1.cacheKey == r2.cacheKey && r1.downloadURL == r2.downloadURL
+        case (.provider(let p1), .provider(let p2)):
+            return p1.cacheKey == p2.cacheKey && p1.contentURL == p2.contentURL
+        case (.provider(_), .network(_)):
+            return false
+        case (.network(_), .provider(_)):
+            return false
+        }
+    }
+
+    public func hash(into hasher: inout Hasher) {
+        switch self {
+        case .network(let r):
+            hasher.combine(r.cacheKey)
+            hasher.combine(r.downloadURL)
+        case .provider(let p):
+            hasher.combine(p.cacheKey)
+            hasher.combine(p.contentURL)
+        }
+    }
+}
+
+extension Source {
+    var asResource: Resource? {
+        guard case .network(let resource) = self else {
+            return nil
+        }
+        return resource
+    }
+}

+ 442 - 0
Pods/Kingfisher/Sources/General/KF.swift

@@ -0,0 +1,442 @@
+//
+//  KF.swift
+//  Kingfisher
+//
+//  Created by onevcat on 2020/09/21.
+//
+//  Copyright (c) 2020 Wei Wang <onevcat@gmail.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.
+
+#if canImport(UIKit)
+import UIKit
+#endif
+
+#if canImport(CarPlay) && !targetEnvironment(macCatalyst)
+import CarPlay
+#endif
+
+#if canImport(AppKit) && !targetEnvironment(macCatalyst)
+import AppKit
+#endif
+
+#if canImport(WatchKit)
+import WatchKit
+#endif
+
+#if canImport(TVUIKit)
+import TVUIKit
+#endif
+
+/// A helper type to create image setting tasks in a builder pattern.
+/// Use methods in this type to create a `KF.Builder` instance and configure image tasks there.
+public enum KF {
+
+    /// Creates a builder for a given `Source`.
+    /// - Parameter source: The `Source` object defines data information from network or a data provider.
+    /// - Returns: A `KF.Builder` for future configuration. After configuring the builder, call `set(to:)`
+    ///            to start the image loading.
+    public static func source(_ source: Source?) -> KF.Builder {
+        Builder(source: source)
+    }
+
+    /// Creates a builder for a given `Resource`.
+    /// - Parameter resource: The `Resource` object defines data information like key or URL.
+    /// - Returns: A `KF.Builder` for future configuration. After configuring the builder, call `set(to:)`
+    ///            to start the image loading.
+    public static func resource(_ resource: Resource?) -> KF.Builder {
+        source(resource?.convertToSource())
+    }
+
+    /// Creates a builder for a given `URL` and an optional cache key.
+    /// - Parameters:
+    ///   - url: The URL where the image should be downloaded.
+    ///   - cacheKey: The key used to store the downloaded image in cache.
+    ///               If `nil`, the `absoluteString` of `url` is used as the cache key.
+    /// - Returns: A `KF.Builder` for future configuration. After configuring the builder, call `set(to:)`
+    ///            to start the image loading.
+    public static func url(_ url: URL?, cacheKey: String? = nil) -> KF.Builder {
+        source(url?.convertToSource(overrideCacheKey: cacheKey))
+    }
+
+    /// Creates a builder for a given `ImageDataProvider`.
+    /// - Parameter provider: The `ImageDataProvider` object contains information about the data.
+    /// - Returns: A `KF.Builder` for future configuration. After configuring the builder, call `set(to:)`
+    ///            to start the image loading.
+    public static func dataProvider(_ provider: ImageDataProvider?) -> KF.Builder {
+        source(provider?.convertToSource())
+    }
+
+    /// Creates a builder for some given raw data and a cache key.
+    /// - Parameters:
+    ///   - data: The data object from which the image should be created.
+    ///   - cacheKey: The key used to store the downloaded image in cache.
+    /// - Returns: A `KF.Builder` for future configuration. After configuring the builder, call `set(to:)`
+    ///            to start the image loading.
+    public static func data(_ data: Data?, cacheKey: String) -> KF.Builder {
+        if let data = data {
+            return dataProvider(RawImageDataProvider(data: data, cacheKey: cacheKey))
+        } else {
+            return dataProvider(nil)
+        }
+    }
+}
+
+
+extension KF {
+
+    /// A builder class to configure an image retrieving task and set it to a holder view or component.
+    public class Builder {
+        private let source: Source?
+
+        #if os(watchOS)
+        private var placeholder: KFCrossPlatformImage?
+        #else
+        private var placeholder: Placeholder?
+        #endif
+
+        public var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions)
+
+        public let onFailureDelegate = Delegate<KingfisherError, Void>()
+        public let onSuccessDelegate = Delegate<RetrieveImageResult, Void>()
+        public let onProgressDelegate = Delegate<(Int64, Int64), Void>()
+
+        init(source: Source?) {
+            self.source = source
+        }
+
+        private var resultHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? {
+            {
+                switch $0 {
+                case .success(let result):
+                    self.onSuccessDelegate(result)
+                case .failure(let error):
+                    self.onFailureDelegate(error)
+                }
+            }
+        }
+
+        private var progressBlock: DownloadProgressBlock {
+            { self.onProgressDelegate(($0, $1)) }
+        }
+    }
+}
+
+extension KF.Builder {
+    #if !os(watchOS)
+
+    /// Builds the image task request and sets it to an image view.
+    /// - Parameter imageView: The image view which loads the task and should be set with the image.
+    /// - Returns: A task represents the image downloading, if initialized.
+    ///            This value is `nil` if the image is being loaded from cache.
+    @discardableResult
+    public func set(to imageView: KFCrossPlatformImageView) -> DownloadTask? {
+        imageView.kf.setImage(
+            with: source,
+            placeholder: placeholder,
+            parsedOptions: options,
+            progressBlock: progressBlock,
+            completionHandler: resultHandler
+        )
+    }
+
+    /// Builds the image task request and sets it to an `NSTextAttachment` object.
+    /// - Parameters:
+    ///   - attachment: The text attachment object which loads the task and should be set with the image.
+    ///   - attributedView: The owner of the attributed string which this `NSTextAttachment` is added.
+    /// - Returns: A task represents the image downloading, if initialized.
+    ///            This value is `nil` if the image is being loaded from cache.
+    @discardableResult
+    public func set(to attachment: NSTextAttachment, attributedView: @autoclosure @escaping () -> KFCrossPlatformView) -> DownloadTask? {
+        let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil
+        return attachment.kf.setImage(
+            with: source,
+            attributedView: attributedView,
+            placeholder: placeholderImage,
+            parsedOptions: options,
+            progressBlock: progressBlock,
+            completionHandler: resultHandler
+        )
+    }
+
+    #if canImport(UIKit)
+
+    /// Builds the image task request and sets it to a button.
+    /// - Parameters:
+    ///   - button: The button which loads the task and should be set with the image.
+    ///   - state: The button state to which the image should be set.
+    /// - Returns: A task represents the image downloading, if initialized.
+    ///            This value is `nil` if the image is being loaded from cache.
+    @discardableResult
+    public func set(to button: UIButton, for state: UIControl.State) -> DownloadTask? {
+        let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil
+        return button.kf.setImage(
+            with: source,
+            for: state,
+            placeholder: placeholderImage,
+            parsedOptions: options,
+            progressBlock: progressBlock,
+            completionHandler: resultHandler
+        )
+    }
+
+    /// Builds the image task request and sets it to the background image for a button.
+    /// - Parameters:
+    ///   - button: The button which loads the task and should be set with the image.
+    ///   - state: The button state to which the image should be set.
+    /// - Returns: A task represents the image downloading, if initialized.
+    ///            This value is `nil` if the image is being loaded from cache.
+    @discardableResult
+    public func setBackground(to button: UIButton, for state: UIControl.State) -> DownloadTask? {
+        let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil
+        return button.kf.setBackgroundImage(
+            with: source,
+            for: state,
+            placeholder: placeholderImage,
+            parsedOptions: options,
+            progressBlock: progressBlock,
+            completionHandler: resultHandler
+        )
+    }
+    #endif // end of canImport(UIKit)
+    
+    #if canImport(CarPlay) && !targetEnvironment(macCatalyst)
+    
+    /// Builds the image task request and sets it to the image for a list item.
+    /// - Parameters:
+    ///   - listItem: The list item which loads the task and should be set with the image.
+    /// - Returns: A task represents the image downloading, if initialized.
+    ///            This value is `nil` if the image is being loaded from cache.
+    @available(iOS 14.0, *)
+    @discardableResult
+    public func set(to listItem: CPListItem) -> DownloadTask? {
+        let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil
+        return listItem.kf.setImage(
+            with: source,
+            placeholder: placeholderImage,
+            parsedOptions: options,
+            progressBlock: progressBlock,
+            completionHandler: resultHandler
+        )
+        
+    }
+    
+    #endif
+
+    #if canImport(AppKit) && !targetEnvironment(macCatalyst)
+    /// Builds the image task request and sets it to a button.
+    /// - Parameter button: The button which loads the task and should be set with the image.
+    /// - Returns: A task represents the image downloading, if initialized.
+    ///            This value is `nil` if the image is being loaded from cache.
+    @discardableResult
+    public func set(to button: NSButton) -> DownloadTask? {
+        let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil
+        return button.kf.setImage(
+            with: source,
+            placeholder: placeholderImage,
+            parsedOptions: options,
+            progressBlock: progressBlock,
+            completionHandler: resultHandler
+        )
+    }
+
+    /// Builds the image task request and sets it to the alternative image for a button.
+    /// - Parameter button: The button which loads the task and should be set with the image.
+    /// - Returns: A task represents the image downloading, if initialized.
+    ///            This value is `nil` if the image is being loaded from cache.
+    @discardableResult
+    public func setAlternative(to button: NSButton) -> DownloadTask? {
+        let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil
+        return button.kf.setAlternateImage(
+            with: source,
+            placeholder: placeholderImage,
+            parsedOptions: options,
+            progressBlock: progressBlock,
+            completionHandler: resultHandler
+        )
+    }
+    #endif // end of canImport(AppKit)
+    #endif // end of !os(watchOS)
+
+    #if canImport(WatchKit)
+    /// Builds the image task request and sets it to a `WKInterfaceImage` object.
+    /// - Parameter interfaceImage: The watch interface image which loads the task and should be set with the image.
+    /// - Returns: A task represents the image downloading, if initialized.
+    ///            This value is `nil` if the image is being loaded from cache.
+    @discardableResult
+    public func set(to interfaceImage: WKInterfaceImage) -> DownloadTask? {
+        return interfaceImage.kf.setImage(
+            with: source,
+            placeholder: placeholder,
+            parsedOptions: options,
+            progressBlock: progressBlock,
+            completionHandler: resultHandler
+        )
+    }
+    #endif // end of canImport(WatchKit)
+
+    #if canImport(TVUIKit)
+    /// Builds the image task request and sets it to a TV monogram view.
+    /// - Parameter monogramView: The monogram view which loads the task and should be set with the image.
+    /// - Returns: A task represents the image downloading, if initialized.
+    ///            This value is `nil` if the image is being loaded from cache.
+    @available(tvOS 12.0, *)
+    @discardableResult
+    public func set(to monogramView: TVMonogramView) -> DownloadTask? {
+        let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil
+        return monogramView.kf.setImage(
+            with: source,
+            placeholder: placeholderImage,
+            parsedOptions: options,
+            progressBlock: progressBlock,
+            completionHandler: resultHandler
+        )
+    }
+    #endif // end of canImport(TVUIKit)
+}
+
+#if !os(watchOS)
+extension KF.Builder {
+    #if os(iOS) || os(tvOS) || os(visionOS)
+
+    /// Sets a placeholder which is used while retrieving the image.
+    /// - Parameter placeholder: A placeholder to show while retrieving the image from its source.
+    /// - Returns: A `KF.Builder` with changes applied.
+    public func placeholder(_ placeholder: Placeholder?) -> Self {
+        self.placeholder = placeholder
+        return self
+    }
+    #endif
+
+    /// Sets a placeholder image which is used while retrieving the image.
+    /// - Parameter placeholder: An image to show while retrieving the image from its source.
+    /// - Returns: A `KF.Builder` with changes applied.
+    public func placeholder(_ image: KFCrossPlatformImage?) -> Self {
+        self.placeholder = image
+        return self
+    }
+}
+#endif
+
+extension KF.Builder {
+
+    #if os(iOS) || os(tvOS) || os(visionOS)
+    /// Sets the transition for the image task.
+    /// - Parameter transition: The desired transition effect when setting the image to image view.
+    /// - Returns: A `KF.Builder` with changes applied.
+    ///
+    /// Kingfisher will use the `transition` to animate the image in if it is downloaded from web.
+    /// The transition will not happen when the
+    /// image is retrieved from either memory or disk cache by default. If you need to do the transition even when
+    /// the image being retrieved from cache, also call `forceRefresh()` on the returned `KF.Builder`.
+    public func transition(_ transition: ImageTransition) -> Self {
+        options.transition = transition
+        return self
+    }
+
+    /// Sets a fade transition for the image task.
+    /// - Parameter duration: The duration of the fade transition.
+    /// - Returns: A `KF.Builder` with changes applied.
+    ///
+    /// Kingfisher will use the fade transition to animate the image in if it is downloaded from web.
+    /// The transition will not happen when the
+    /// image is retrieved from either memory or disk cache by default. If you need to do the transition even when
+    /// the image being retrieved from cache, also call `forceRefresh()` on the returned `KF.Builder`.
+    public func fade(duration: TimeInterval) -> Self {
+        options.transition = .fade(duration)
+        return self
+    }
+    #endif
+
+    /// Sets whether keeping the existing image of image view while setting another image to it.
+    /// - Parameter enabled: Whether the existing image should be kept.
+    /// - Returns: A `KF.Builder` with changes applied.
+    ///
+    /// By setting this option, the placeholder image parameter of image view extension method
+    /// will be ignored and the current image will be kept while loading or downloading the new image.
+    ///
+    public func keepCurrentImageWhileLoading(_ enabled: Bool = true) -> Self {
+        options.keepCurrentImageWhileLoading = enabled
+        return self
+    }
+
+    /// Sets whether only the first frame from an animated image file should be loaded as a single image.
+    /// - Parameter enabled: Whether the only the first frame should be loaded.
+    /// - Returns: A `KF.Builder` with changes applied.
+    ///
+    /// Loading an animated images may take too much memory. It will be useful when you want to display a
+    /// static preview of the first frame from an animated image.
+    ///
+    /// This option will be ignored if the target image is not animated image data.
+    ///
+    public func onlyLoadFirstFrame(_ enabled: Bool = true) -> Self {
+        options.onlyLoadFirstFrame = enabled
+        return self
+    }
+
+    /// Enables progressive image loading with a specified `ImageProgressive` setting to process the
+    /// progressive JPEG data and display it in a progressive way.
+    /// - Parameter progressive: The progressive settings which is used while loading.
+    /// - Returns: A `KF.Builder` with changes applied.
+    public func progressiveJPEG(_ progressive: ImageProgressive? = .init()) -> Self {
+        options.progressiveJPEG = progressive
+        return self
+    }
+}
+
+// MARK: - Deprecated
+extension KF.Builder {
+    /// Starts the loading process of `self` immediately.
+    ///
+    /// By default, a `KFImage` will not load its source until the `onAppear` is called. This is a lazily loading
+    /// behavior and provides better performance. However, when you refresh the view, the lazy loading also causes a
+    /// flickering since the loading does not happen immediately. Call this method if you want to start the load at once
+    /// could help avoiding the flickering, with some performance trade-off.
+    ///
+    /// - Deprecated: This is not necessary anymore since `@StateObject` is used for holding the image data.
+    /// It does nothing now and please just remove it.
+    ///
+    /// - Returns: The `Self` value with changes applied.
+    @available(*, deprecated, message: "This is not necessary anymore since `@StateObject` is used. It does nothing now and please just remove it.")
+    public func loadImmediately(_ start: Bool = true) -> Self {
+        return self
+    }
+}
+
+// MARK: - Redirect Handler
+extension KF {
+
+    /// Represents the detail information when a task redirect happens. It is wrapping necessary information for a
+    /// `ImageDownloadRedirectHandler`. See that protocol for more information.
+    public struct RedirectPayload {
+
+        /// The related session data task when the redirect happens. It is
+        /// the current `SessionDataTask` which triggers this redirect.
+        public let task: SessionDataTask
+
+        /// The response received during redirection.
+        public let response: HTTPURLResponse
+
+        /// The request for redirection which can be modified.
+        public let newRequest: URLRequest
+
+        /// A closure for being called with modified request.
+        public let completionHandler: (URLRequest?) -> Void
+    }
+}

+ 711 - 0
Pods/Kingfisher/Sources/General/KFOptionsSetter.swift

@@ -0,0 +1,711 @@
+//
+//  KFOptionsSetter.swift
+//  Kingfisher
+//
+//  Created by onevcat on 2020/12/22.
+//
+//  Copyright (c) 2020 Wei Wang <onevcat@gmail.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
+import CoreGraphics
+#if os(macOS)
+import AppKit
+#else
+import UIKit
+#endif
+
+public protocol KFOptionSetter {
+    var options: KingfisherParsedOptionsInfo { get nonmutating set }
+
+    var onFailureDelegate: Delegate<KingfisherError, Void> { get }
+    var onSuccessDelegate: Delegate<RetrieveImageResult, Void> { get }
+    var onProgressDelegate: Delegate<(Int64, Int64), Void> { get }
+
+    var delegateObserver: AnyObject { get }
+}
+
+extension KF.Builder: KFOptionSetter {
+    public var delegateObserver: AnyObject { self }
+}
+
+// MARK: - Life cycles
+extension KFOptionSetter {
+    /// Sets the progress block to current builder.
+    /// - Parameter block: Called when the image downloading progress gets updated. If the response does not contain an
+    ///                    `expectedContentLength`, this block will not be called. If `block` is `nil`, the callback
+    ///                    will be reset.
+    /// - Returns: A `Self` value with changes applied.
+    public func onProgress(_ block: DownloadProgressBlock?) -> Self {
+        onProgressDelegate.delegate(on: delegateObserver) { (observer, result) in
+            block?(result.0, result.1)
+        }
+        return self
+    }
+
+    /// Sets the the done block to current builder.
+    /// - Parameter block: Called when the image task successfully completes and the the image set is done. If `block`
+    ///                    is `nil`, the callback will be reset.
+    /// - Returns: A `KF.Builder` with changes applied.
+    public func onSuccess(_ block: ((RetrieveImageResult) -> Void)?) -> Self {
+        onSuccessDelegate.delegate(on: delegateObserver) { (observer, result) in
+            block?(result)
+        }
+        return self
+    }
+
+    /// Sets the catch block to current builder.
+    /// - Parameter block: Called when an error happens during the image task. If `block`
+    ///                    is `nil`, the callback will be reset.
+    /// - Returns: A `KF.Builder` with changes applied.
+    public func onFailure(_ block: ((KingfisherError) -> Void)?) -> Self {
+        onFailureDelegate.delegate(on: delegateObserver) { (observer, error) in
+            block?(error)
+        }
+        return self
+    }
+}
+
+// MARK: - Basic options settings.
+extension KFOptionSetter {
+    /// Sets the target image cache for this task.
+    /// - Parameter cache: The target cache is about to be used for the task.
+    /// - Returns: A `Self` value with changes applied.
+    ///
+    /// Kingfisher will use the associated `ImageCache` object when handling related operations,
+    /// including trying to retrieve the cached images and store the downloaded image to it.
+    ///
+    public func targetCache(_ cache: ImageCache) -> Self {
+        options.targetCache = cache
+        return self
+    }
+
+    /// Sets the target image cache to store the original downloaded image for this task.
+    /// - Parameter cache: The target cache is about to be used for storing the original downloaded image from the task.
+    /// - Returns: A `Self` value with changes applied.
+    ///
+    /// The `ImageCache` for storing and retrieving original images. If `originalCache` is
+    /// contained in the options, it will be preferred for storing and retrieving original images.
+    /// If there is no `.originalCache` in the options, `.targetCache` will be used to store original images.
+    ///
+    /// When using KingfisherManager to download and store an image, if `cacheOriginalImage` is
+    /// applied in the option, the original image will be stored to this `originalCache`. At the
+    /// same time, if a requested final image (with processor applied) cannot be found in `targetCache`,
+    /// Kingfisher will try to search the original image to check whether it is already there. If found,
+    /// it will be used and applied with the given processor. It is an optimization for not downloading
+    /// the same image for multiple times.
+    ///
+    public func originalCache(_ cache: ImageCache) -> Self {
+        options.originalCache = cache
+        return self
+    }
+
+    /// Sets the downloader used to perform the image download task.
+    /// - Parameter downloader: The downloader which is about to be used for downloading.
+    /// - Returns: A `Self` value with changes applied.
+    ///
+    /// Kingfisher will use the set `ImageDownloader` object to download the requested images.
+    public func downloader(_ downloader: ImageDownloader) -> Self {
+        options.downloader = downloader
+        return self
+    }
+
+    /// Sets the download priority for the image task.
+    /// - Parameter priority: The download priority of image download task.
+    /// - Returns: A `Self` value with changes applied.
+    ///
+    /// The `priority` value will be set as the priority of the image download task. The value for it should be
+    /// between 0.0~1.0. You can choose a value between `URLSessionTask.defaultPriority`, `URLSessionTask.lowPriority`
+    /// or `URLSessionTask.highPriority`. If this option not set, the default value (`URLSessionTask.defaultPriority`)
+    /// will be used.
+    public func downloadPriority(_ priority: Float) -> Self {
+        options.downloadPriority = priority
+        return self
+    }
+
+    /// Sets whether Kingfisher should ignore the cache and try to start a download task for the image source.
+    /// - Parameter enabled: Enable the force refresh or not.
+    /// - Returns: A `Self` value with changes applied.
+    public func forceRefresh(_ enabled: Bool = true) -> Self {
+        options.forceRefresh = enabled
+        return self
+    }
+
+    /// Sets whether Kingfisher should try to retrieve the image from memory cache first. If not found, it ignores the
+    /// disk cache and starts a download task for the image source.
+    /// - Parameter enabled: Enable the memory-only cache searching or not.
+    /// - Returns: A `Self` value with changes applied.
+    ///
+    /// This is useful when you want to display a changeable image behind the same url at the same app session, while
+    /// avoiding download it for multiple times.
+    public func fromMemoryCacheOrRefresh(_ enabled: Bool = true) -> Self {
+        options.fromMemoryCacheOrRefresh = enabled
+        return self
+    }
+
+    /// Sets whether the image should only be cached in memory but not in disk.
+    /// - Parameter enabled: Whether the image should be only cache in memory or not.
+    /// - Returns: A `Self` value with changes applied.
+    public func cacheMemoryOnly(_ enabled: Bool = true) -> Self {
+        options.cacheMemoryOnly = enabled
+        return self
+    }
+
+    /// Sets whether Kingfisher should wait for caching operation to be completed before calling the
+    /// `onSuccess` or `onFailure` block.
+    /// - Parameter enabled: Whether Kingfisher should wait for caching operation.
+    /// - Returns: A `Self` value with changes applied.
+    public func waitForCache(_ enabled: Bool = true) -> Self {
+        options.waitForCache = enabled
+        return self
+    }
+
+    /// Sets whether Kingfisher should only try to retrieve the image from cache, but not from network.
+    /// - Parameter enabled: Whether Kingfisher should only try to retrieve the image from cache.
+    /// - Returns: A `Self` value with changes applied.
+    ///
+    /// If the image is not in cache, the image retrieving will fail with the
+    /// `KingfisherError.cacheError` with `.imageNotExisting` as its reason.
+    public func onlyFromCache(_ enabled: Bool = true) -> Self {
+        options.onlyFromCache = enabled
+        return self
+    }
+
+    /// Sets whether the image should be decoded in a background thread before using.
+    /// - Parameter enabled: Whether the image should be decoded in a background thread before using.
+    /// - Returns: A `Self` value with changes applied.
+    ///
+    /// Setting to `true` will decode the downloaded image data and do a off-screen rendering to extract pixel
+    /// information in background. This can speed up display, but will cost more time and memory to prepare the image
+    /// for using.
+    public func backgroundDecode(_ enabled: Bool = true) -> Self {
+        options.backgroundDecode = enabled
+        return self
+    }
+
+    /// Sets the callback queue which is used as the target queue of dispatch callbacks when retrieving images from
+    ///  cache. If not set, Kingfisher will use main queue for callbacks.
+    /// - Parameter queue: The target queue which the cache retrieving callback will be invoked on.
+    /// - Returns: A `Self` value with changes applied.
+    ///
+    /// - Note:
+    /// This option does not affect the callbacks for UI related extension methods or `KFImage` result handlers.
+    /// You will always get the callbacks called from main queue.
+    public func callbackQueue(_ queue: CallbackQueue) -> Self {
+        options.callbackQueue = queue
+        return self
+    }
+
+    /// Sets the scale factor value when converting retrieved data to an image.
+    /// - Parameter factor: The scale factor value.
+    /// - Returns: A `Self` value with changes applied.
+    ///
+    /// Specify the image scale, instead of your screen scale. You may need to set the correct scale when you dealing
+    /// with 2x or 3x retina images. Otherwise, Kingfisher will convert the data to image object at `scale` 1.0.
+    ///
+    public func scaleFactor(_ factor: CGFloat) -> Self {
+        options.scaleFactor = factor
+        return self
+    }
+
+    /// Sets whether the original image should be cached even when the original image has been processed by any other
+    /// `ImageProcessor`s.
+    /// - Parameter enabled: Whether the original image should be cached.
+    /// - Returns: A `Self` value with changes applied.
+    ///
+    /// If set and an `ImageProcessor` is used, Kingfisher will try to cache both the final result and original
+    /// image. Kingfisher will have a chance to use the original image when another processor is applied to the same
+    /// resource, instead of downloading it again. You can use `.originalCache` to specify a cache or the original
+    /// images if necessary.
+    ///
+    /// The original image will be only cached to disk storage.
+    ///
+    public func cacheOriginalImage(_ enabled: Bool = true) -> Self {
+        options.cacheOriginalImage = enabled
+        return self
+    }
+
+    /// Sets writing options for an original image on a first write
+    /// - Parameter writingOptions: Options to control the writing of data to a disk storage.
+    /// - Returns: A `Self` value with changes applied.
+    /// If set, options will be passed the store operation for a new files.
+    ///
+    /// This is useful if you want to implement file enctyption on first write - eg [.completeFileProtection]
+    ///
+    public func diskStoreWriteOptions(_ writingOptions: Data.WritingOptions) -> Self {
+        options.diskStoreWriteOptions = writingOptions
+        return self
+    }
+
+    /// Sets whether the disk storage loading should happen in the same calling queue.
+    /// - Parameter enabled: Whether the disk storage loading should happen in the same calling queue.
+    /// - Returns: A `Self` value with changes applied.
+    ///
+    /// By default, disk storage file loading
+    /// happens in its own queue with an asynchronous dispatch behavior. Although it provides better non-blocking disk
+    /// loading performance, it also causes a flickering when you reload an image from disk, if the image view already
+    /// has an image set.
+    ///
+    /// Set this options will stop that flickering by keeping all loading in the same queue (typically the UI queue
+    /// if you are using Kingfisher's extension methods to set an image), with a tradeoff of loading performance.
+    ///
+    public func loadDiskFileSynchronously(_ enabled: Bool = true) -> Self {
+        options.loadDiskFileSynchronously = enabled
+        return self
+    }
+
+    /// Sets a queue on which the image processing should happen.
+    /// - Parameter queue: The queue on which the image processing should happen.
+    /// - Returns: A `Self` value with changes applied.
+    ///
+    /// By default, Kingfisher uses a pre-defined serial
+    /// queue to process images. Use this option to change this behavior. For example, specify a `.mainCurrentOrAsync`
+    /// to let the image be processed in main queue to prevent a possible flickering (but with a possibility of
+    /// blocking the UI, especially if the processor needs a lot of time to run).
+    public func processingQueue(_ queue: CallbackQueue?) -> Self {
+        options.processingQueue = queue
+        return self
+    }
+
+    /// Sets the alternative sources that will be used when loading of the original input `Source` fails.
+    /// - Parameter sources: The alternative sources will be used.
+    /// - Returns: A `Self` value with changes applied.
+    ///
+    /// Values of the `sources` array will be used to start a new image loading task if the previous task
+    /// fails due to an error. The image source loading process will stop as soon as a source is loaded successfully.
+    /// If all `sources` are used but the loading is still failing, an `imageSettingError` with
+    /// `alternativeSourcesExhausted` as its reason will be given out in the `catch` block.
+    ///
+    /// This is useful if you want to implement a fallback solution for setting image.
+    ///
+    /// User cancellation will not trigger the alternative source loading.
+    public func alternativeSources(_ sources: [Source]?) -> Self {
+        options.alternativeSources = sources
+        return self
+    }
+
+    /// Sets a retry strategy that will be used when something gets wrong during the image retrieving.
+    /// - Parameter strategy: The provided strategy to define how the retrying should happen.
+    /// - Returns: A `Self` value with changes applied.
+    public func retry(_ strategy: RetryStrategy?) -> Self {
+        options.retryStrategy = strategy
+        return self
+    }
+
+    /// Sets a retry strategy with a max retry count and retrying interval.
+    /// - Parameters:
+    ///   - maxCount: The maximum count before the retry stops.
+    ///   - interval: The time interval between each retry attempt.
+    /// - Returns: A `Self` value with changes applied.
+    ///
+    /// This defines the simplest retry strategy, which retry a failing request for several times, with some certain
+    /// interval between each time. For example, `.retry(maxCount: 3, interval: .second(3))` means attempt for at most
+    /// three times, and wait for 3 seconds if a previous retry attempt fails, then start a new attempt.
+    public func retry(maxCount: Int, interval: DelayRetryStrategy.Interval = .seconds(3)) -> Self {
+        let strategy = DelayRetryStrategy(maxRetryCount: maxCount, retryInterval: interval)
+        options.retryStrategy = strategy
+        return self
+    }
+
+    /// Sets the `Source` should be loaded when user enables Low Data Mode and the original source fails with an
+    /// `NSURLErrorNetworkUnavailableReason.constrained` error.
+    /// - Parameter source: The `Source` will be loaded under low data mode.
+    /// - Returns: A `Self` value with changes applied.
+    ///
+    /// When this option is set, the
+    /// `allowsConstrainedNetworkAccess` property of the request for the original source will be set to `false` and the
+    /// `Source` in associated value will be used to retrieve the image for low data mode. Usually, you can provide a
+    /// low-resolution version of your image or a local image provider to display a placeholder.
+    ///
+    /// If not set or the `source` is `nil`, the device Low Data Mode will be ignored and the original source will
+    /// be loaded following the system default behavior, in a normal way.
+    public func lowDataModeSource(_ source: Source?) -> Self {
+        options.lowDataModeSource = source
+        return self
+    }
+
+    /// Sets whether the image setting for an image view should happen with transition even when retrieved from cache.
+    /// - Parameter enabled: Enable the force transition or not.
+    /// - Returns: A `Self` with changes applied.
+    public func forceTransition(_ enabled: Bool = true) -> Self {
+        options.forceTransition = enabled
+        return self
+    }
+
+    /// Sets the image that will be used if an image retrieving task fails.
+    /// - Parameter image: The image that will be used when something goes wrong.
+    /// - Returns: A `Self` with changes applied.
+    ///
+    /// If set and an image retrieving error occurred Kingfisher will set provided image (or empty)
+    /// in place of requested one. It's useful when you don't want to show placeholder
+    /// during loading time but wants to use some default image when requests will be failed.
+    ///
+    public func onFailureImage(_ image: KFCrossPlatformImage?) -> Self {
+        options.onFailureImage = .some(image)
+        return self
+    }
+}
+
+// MARK: - Request Modifier
+extension KFOptionSetter {
+    /// Sets an `ImageDownloadRequestModifier` to change the image download request before it being sent.
+    /// - Parameter modifier: The modifier will be used to change the request before it being sent.
+    /// - Returns: A `Self` value with changes applied.
+    ///
+    /// This is the last chance you can modify the image download request. You can modify the request for some
+    /// customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url mapping.
+    ///
+    public func requestModifier(_ modifier: AsyncImageDownloadRequestModifier) -> Self {
+        options.requestModifier = modifier
+        return self
+    }
+
+    /// Sets a block to change the image download request before it being sent.
+    /// - Parameter modifyBlock: The modifying block will be called to change the request before it being sent.
+    /// - Returns: A `Self` value with changes applied.
+    ///
+    /// This is the last chance you can modify the image download request. You can modify the request for some
+    /// customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url mapping.
+    ///
+    public func requestModifier(_ modifyBlock: @escaping (inout URLRequest) -> Void) -> Self {
+        options.requestModifier = AnyModifier { r -> URLRequest? in
+            var request = r
+            modifyBlock(&request)
+            return request
+        }
+        return self
+    }
+}
+
+// MARK: - Redirect Handler
+extension KFOptionSetter {
+    /// The `ImageDownloadRedirectHandler` argument will be used to change the request before redirection.
+    /// This is the possibility you can modify the image download request during redirect. You can modify the request for
+    /// some customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url
+    /// mapping.
+    /// The original redirection request will be sent without any modification by default.
+    /// - Parameter handler: The handler will be used for redirection.
+    /// - Returns: A `Self` value with changes applied.
+    public func redirectHandler(_ handler: ImageDownloadRedirectHandler) -> Self {
+        options.redirectHandler = handler
+        return self
+    }
+
+    /// The `block` will be used to change the request before redirection.
+    /// This is the possibility you can modify the image download request during redirect. You can modify the request for
+    /// some customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url
+    /// mapping.
+    /// The original redirection request will be sent without any modification by default.
+    /// - Parameter block: The block will be used for redirection.
+    /// - Returns: A `Self` value with changes applied.
+    public func redirectHandler(_ block: @escaping (KF.RedirectPayload) -> Void) -> Self {
+        let redirectHandler = AnyRedirectHandler { (task, response, request, handler) in
+            let payload = KF.RedirectPayload(
+                task: task, response: response, newRequest: request, completionHandler: handler
+            )
+            block(payload)
+        }
+        options.redirectHandler = redirectHandler
+        return self
+    }
+}
+
+// MARK: - Processor
+extension KFOptionSetter {
+
+    /// Sets an image processor for the image task. It replaces the current image processor settings.
+    ///
+    /// - Parameter processor: The processor you want to use to process the image after it is downloaded.
+    /// - Returns: A `Self` value with changes applied.
+    ///
+    /// - Note:
+    /// To append a processor to current ones instead of replacing them all, use `appendProcessor(_:)`.
+    public func setProcessor(_ processor: ImageProcessor) -> Self {
+        options.processor = processor
+        return self
+    }
+
+    /// Sets an array of image processors for the image task. It replaces the current image processor settings.
+    /// - Parameter processors: An array of processors. The processors inside this array will be concatenated one by one
+    ///                         to form a processor pipeline.
+    /// - Returns: A `Self` value with changes applied.
+    ///
+    /// - Note: To append processors to current ones instead of replacing them all, concatenate them by `|>`, then use
+    /// `appendProcessor(_:)`.
+    public func setProcessors(_ processors: [ImageProcessor]) -> Self {
+        switch processors.count {
+        case 0:
+            options.processor = DefaultImageProcessor.default
+        case 1...:
+            options.processor = processors.dropFirst().reduce(processors[0]) { $0 |> $1 }
+        default:
+            assertionFailure("Never happen")
+        }
+        return self
+    }
+
+    /// Appends a processor to the current set processors.
+    /// - Parameter processor: The processor which will be appended to current processor settings.
+    /// - Returns: A `Self` value with changes applied.
+    public func appendProcessor(_ processor: ImageProcessor) -> Self {
+        options.processor = options.processor |> processor
+        return self
+    }
+
+    /// Appends a `RoundCornerImageProcessor` to current processors.
+    /// - Parameters:
+    ///   - radius: The radius will be applied in processing. Specify a certain point value with `.point`, or a fraction
+    ///             of the target image with `.widthFraction`. or `.heightFraction`. For example, given a square image
+    ///             with width and height equals,  `.widthFraction(0.5)` means use half of the length of size and makes
+    ///             the final image a round one.
+    ///   - targetSize: Target size of output image should be. If `nil`, the image will keep its original size after processing.
+    ///   - corners: The target corners which will be applied rounding.
+    ///   - backgroundColor: Background color of the output image. If `nil`, it will use a transparent background.
+    /// - Returns: A `Self` value with changes applied.
+    public func roundCorner(
+        radius: Radius,
+        targetSize: CGSize? = nil,
+        roundingCorners corners: RectCorner = .all,
+        backgroundColor: KFCrossPlatformColor? = nil
+    ) -> Self
+    {
+        let processor = RoundCornerImageProcessor(
+            radius: radius,
+            targetSize: targetSize,
+            roundingCorners: corners,
+            backgroundColor: backgroundColor
+        )
+        return appendProcessor(processor)
+    }
+
+    /// Appends a `BlurImageProcessor` to current processors.
+    /// - Parameter radius: Blur radius for the simulated Gaussian blur.
+    /// - Returns: A `Self` value with changes applied.
+    public func blur(radius: CGFloat) -> Self {
+        appendProcessor(
+            BlurImageProcessor(blurRadius: radius)
+        )
+    }
+
+    /// Appends a `OverlayImageProcessor` to current processors.
+    /// - Parameters:
+    ///   - color: Overlay color will be used to overlay the input image.
+    ///   - fraction: Fraction will be used when overlay the color to image.
+    /// - Returns: A `Self` value with changes applied.
+    public func overlay(color: KFCrossPlatformColor, fraction: CGFloat = 0.5) -> Self {
+        appendProcessor(
+            OverlayImageProcessor(overlay: color, fraction: fraction)
+        )
+    }
+
+    /// Appends a `TintImageProcessor` to current processors.
+    /// - Parameter color: Tint color will be used to tint the input image.
+    /// - Returns: A `Self` value with changes applied.
+    public func tint(color: KFCrossPlatformColor) -> Self {
+        appendProcessor(
+            TintImageProcessor(tint: color)
+        )
+    }
+
+    /// Appends a `BlackWhiteProcessor` to current processors.
+    /// - Returns: A `Self` value with changes applied.
+    public func blackWhite() -> Self {
+        appendProcessor(
+            BlackWhiteProcessor()
+        )
+    }
+
+    /// Appends a `CroppingImageProcessor` to current processors.
+    /// - Parameters:
+    ///   - size: Target size of output image should be.
+    ///   - anchor: Anchor point from which the output size should be calculate. The anchor point is consisted by two
+    ///             values between 0.0 and 1.0. It indicates a related point in current image.
+    ///             See `CroppingImageProcessor.init(size:anchor:)` for more.
+    /// - Returns: A `Self` value with changes applied.
+    public func cropping(size: CGSize, anchor: CGPoint = .init(x: 0.5, y: 0.5)) -> Self {
+        appendProcessor(
+            CroppingImageProcessor(size: size, anchor: anchor)
+        )
+    }
+
+    /// Appends a `DownsamplingImageProcessor` to current processors.
+    ///
+    /// Compared to `ResizingImageProcessor`, the `DownsamplingImageProcessor` does not render the original images and
+    /// then resize it. Instead, it downsamples the input data directly to a thumbnail image. So it is a more efficient
+    /// than `ResizingImageProcessor`. Prefer to use `DownsamplingImageProcessor` as possible
+    /// as you can than the `ResizingImageProcessor`.
+    ///
+    /// Only CG-based images are supported. Animated images (like GIF) is not supported.
+    ///
+    /// - Parameter size: Target size of output image should be. It should be smaller than the size of input image.
+    ///                   If it is larger, the result image will be the same size of input data without downsampling.
+    /// - Returns: A `Self` value with changes applied.
+    public func downsampling(size: CGSize) -> Self {
+        let processor = DownsamplingImageProcessor(size: size)
+        if options.processor == DefaultImageProcessor.default {
+            return setProcessor(processor)
+        } else {
+            return appendProcessor(processor)
+        }
+    }
+
+
+    /// Appends a `ResizingImageProcessor` to current processors.
+    ///
+    /// If you need to resize a data represented image to a smaller size, use `DownsamplingImageProcessor`
+    /// instead, which is more efficient and uses less memory.
+    ///
+    /// - Parameters:
+    ///   - referenceSize: The reference size for resizing operation in point.
+    ///   - mode: Target content mode of output image should be. Default is `.none`.
+    /// - Returns: A `Self` value with changes applied.
+    public func resizing(referenceSize: CGSize, mode: ContentMode = .none) -> Self {
+        appendProcessor(
+            ResizingImageProcessor(referenceSize: referenceSize, mode: mode)
+        )
+    }
+}
+
+// MARK: - Cache Serializer
+extension KFOptionSetter {
+
+    /// Uses a given `CacheSerializer` to convert some data to an image object for retrieving from disk cache or vice
+    /// versa for storing to disk cache.
+    /// - Parameter cacheSerializer: The `CacheSerializer` which will be used.
+    /// - Returns: A `Self` value with changes applied.
+    public func serialize(by cacheSerializer: CacheSerializer) -> Self {
+        options.cacheSerializer = cacheSerializer
+        return self
+    }
+
+    /// Uses a given format to serializer the image data to disk. It converts the image object to the give data format.
+    /// - Parameters:
+    ///   - format: The desired data encoding format when store the image on disk.
+    ///   - jpegCompressionQuality: If the format is `.JPEG`, it specify the compression quality when converting the
+    ///                             image to a JPEG data. Otherwise, it is ignored.
+    /// - Returns: A `Self` value with changes applied.
+    public func serialize(as format: ImageFormat, jpegCompressionQuality: CGFloat? = nil) -> Self {
+        let cacheSerializer: FormatIndicatedCacheSerializer
+        switch format {
+        case .JPEG:
+            cacheSerializer = .jpeg(compressionQuality: jpegCompressionQuality ?? 1.0)
+        case .PNG:
+            cacheSerializer = .png
+        case .GIF:
+            cacheSerializer = .gif
+        case .unknown:
+            cacheSerializer = .png
+        }
+        options.cacheSerializer = cacheSerializer
+        return self
+    }
+}
+
+// MARK: - Image Modifier
+extension KFOptionSetter {
+
+    /// Sets an `ImageModifier` to the image task. Use this to modify the fetched image object properties if needed.
+    ///
+    /// If the image was fetched directly from the downloader, the modifier will run directly after the
+    /// `ImageProcessor`. If the image is being fetched from a cache, the modifier will run after the `CacheSerializer`.
+    /// - Parameter modifier: The `ImageModifier` which will be used to modify the image object.
+    /// - Returns: A `Self` value with changes applied.
+    public func imageModifier(_ modifier: ImageModifier?) -> Self {
+        options.imageModifier = modifier
+        return self
+    }
+
+    /// Sets a block to modify the image object. Use this to modify the fetched image object properties if needed.
+    ///
+    /// If the image was fetched directly from the downloader, the modifier block will run directly after the
+    /// `ImageProcessor`. If the image is being fetched from a cache, the modifier will run after the `CacheSerializer`.
+    ///
+    /// - Parameter block: The block which is used to modify the image object.
+    /// - Returns: A `Self` value with changes applied.
+    public func imageModifier(_ block: @escaping (inout KFCrossPlatformImage) throws -> Void) -> Self {
+        let modifier = AnyImageModifier { image -> KFCrossPlatformImage in
+            var image = image
+            try block(&image)
+            return image
+        }
+        options.imageModifier = modifier
+        return self
+    }
+}
+
+
+// MARK: - Cache Expiration
+extension KFOptionSetter {
+
+    /// Sets the expiration setting for memory cache of this image task.
+    ///
+    /// By default, the underlying `MemoryStorage.Backend` uses the
+    /// expiration in its config for all items. If set, the `MemoryStorage.Backend` will use this value to overwrite
+    /// the config setting for this caching item.
+    ///
+    /// - Parameter expiration: The expiration setting used in cache storage.
+    /// - Returns: A `Self` value with changes applied.
+    public func memoryCacheExpiration(_ expiration: StorageExpiration?) -> Self {
+        options.memoryCacheExpiration = expiration
+        return self
+    }
+
+    /// Sets the expiration extending setting for memory cache. The item expiration time will be incremented by this
+    /// value after access.
+    ///
+    /// By default, the underlying `MemoryStorage.Backend` uses the initial cache expiration as extending
+    /// value: .cacheTime.
+    ///
+    /// To disable extending option at all, sets `.none` to it.
+    ///
+    /// - Parameter extending: The expiration extending setting used in cache storage.
+    /// - Returns: A `Self` value with changes applied.
+    public func memoryCacheAccessExtending(_ extending: ExpirationExtending) -> Self {
+        options.memoryCacheAccessExtendingExpiration = extending
+        return self
+    }
+
+    /// Sets the expiration setting for disk cache of this image task.
+    ///
+    /// By default, the underlying `DiskStorage.Backend` uses the expiration in its config for all items. If set,
+    /// the `DiskStorage.Backend` will use this value to overwrite the config setting for this caching item.
+    ///
+    /// - Parameter expiration: The expiration setting used in cache storage.
+    /// - Returns: A `Self` value with changes applied.
+    public func diskCacheExpiration(_ expiration: StorageExpiration?) -> Self {
+        options.diskCacheExpiration = expiration
+        return self
+    }
+
+    /// Sets the expiration extending setting for disk cache. The item expiration time will be incremented by this
+    /// value after access.
+    ///
+    /// By default, the underlying `DiskStorage.Backend` uses the initial cache expiration as extending
+    /// value: .cacheTime.
+    ///
+    /// To disable extending option at all, sets `.none` to it.
+    ///
+    /// - Parameter extending: The expiration extending setting used in cache storage.
+    /// - Returns: A `Self` value with changes applied.
+    public func diskCacheAccessExtending(_ extending: ExpirationExtending) -> Self {
+        options.diskCacheAccessExtendingExpiration = extending
+        return self
+    }
+}

+ 106 - 0
Pods/Kingfisher/Sources/General/Kingfisher.swift

@@ -0,0 +1,106 @@
+//
+//  Kingfisher.swift
+//  Kingfisher
+//
+//  Created by Wei Wang on 16/9/14.
+//
+//  Copyright (c) 2019 Wei Wang <onevcat@gmail.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
+import ImageIO
+
+#if os(macOS)
+import AppKit
+public typealias KFCrossPlatformImage = NSImage
+public typealias KFCrossPlatformView = NSView
+public typealias KFCrossPlatformColor = NSColor
+public typealias KFCrossPlatformImageView = NSImageView
+public typealias KFCrossPlatformButton = NSButton
+#else
+import UIKit
+public typealias KFCrossPlatformImage = UIImage
+public typealias KFCrossPlatformColor = UIColor
+#if !os(watchOS)
+public typealias KFCrossPlatformImageView = UIImageView
+public typealias KFCrossPlatformView = UIView
+public typealias KFCrossPlatformButton = UIButton
+#if canImport(TVUIKit)
+import TVUIKit
+#endif
+#if canImport(CarPlay) && !targetEnvironment(macCatalyst)
+import CarPlay
+#endif
+#else
+import WatchKit
+#endif
+#endif
+
+/// Wrapper for Kingfisher compatible types. This type provides an extension point for
+/// convenience methods in Kingfisher.
+public struct KingfisherWrapper<Base> {
+    public let base: Base
+    public init(_ base: Base) {
+        self.base = base
+    }
+}
+
+/// Represents an object type that is compatible with Kingfisher. You can use `kf` property to get a
+/// value in the namespace of Kingfisher.
+public protocol KingfisherCompatible: AnyObject { }
+
+/// Represents a value type that is compatible with Kingfisher. You can use `kf` property to get a
+/// value in the namespace of Kingfisher.
+public protocol KingfisherCompatibleValue {}
+
+extension KingfisherCompatible {
+    /// Gets a namespace holder for Kingfisher compatible types.
+    public var kf: KingfisherWrapper<Self> {
+        get { return KingfisherWrapper(self) }
+        set { }
+    }
+}
+
+extension KingfisherCompatibleValue {
+    /// Gets a namespace holder for Kingfisher compatible types.
+    public var kf: KingfisherWrapper<Self> {
+        get { return KingfisherWrapper(self) }
+        set { }
+    }
+}
+
+extension KFCrossPlatformImage: KingfisherCompatible { }
+#if !os(watchOS)
+extension KFCrossPlatformImageView: KingfisherCompatible { }
+extension KFCrossPlatformButton: KingfisherCompatible { }
+extension NSTextAttachment: KingfisherCompatible { }
+#else
+extension WKInterfaceImage: KingfisherCompatible { }
+#endif
+
+#if os(tvOS) && canImport(TVUIKit)
+@available(tvOS 12.0, *)
+extension TVMonogramView: KingfisherCompatible { }
+#endif
+
+#if canImport(CarPlay) && !targetEnvironment(macCatalyst)
+@available(iOS 14.0, *)
+extension CPListItem: KingfisherCompatible { }
+#endif

+ 474 - 0
Pods/Kingfisher/Sources/General/KingfisherError.swift

@@ -0,0 +1,474 @@
+//
+//  KingfisherError.swift
+//  Kingfisher
+//
+//  Created by onevcat on 2018/09/26.
+//
+//  Copyright (c) 2019 Wei Wang <onevcat@gmail.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
+#if os(macOS)
+import AppKit
+#else
+import UIKit
+#endif
+
+extension Never {}
+
+/// Represents all the errors which can happen in Kingfisher framework.
+/// Kingfisher related methods always throw a `KingfisherError` or invoke the callback with `KingfisherError`
+/// as its error type. To handle errors from Kingfisher, you switch over the error to get a reason catalog,
+/// then switch over the reason to know error detail.
+public enum KingfisherError: Error {
+
+    // MARK: Error Reason Types
+
+    /// Represents the error reason during networking request phase.
+    ///
+    /// - emptyRequest: The request is empty. Code 1001.
+    /// - invalidURL: The URL of request is invalid. Code 1002.
+    /// - taskCancelled: The downloading task is cancelled by user. Code 1003.
+    public enum RequestErrorReason {
+        
+        /// The request is empty. Code 1001.
+        case emptyRequest
+        
+        /// The URL of request is invalid. Code 1002.
+        /// - request: The request is tend to be sent but its URL is invalid.
+        case invalidURL(request: URLRequest)
+        
+        /// The downloading task is cancelled by user. Code 1003.
+        /// - task: The session data task which is cancelled.
+        /// - token: The cancel token which is used for cancelling the task.
+        case taskCancelled(task: SessionDataTask, token: SessionDataTask.CancelToken)
+    }
+    
+    /// Represents the error reason during networking response phase.
+    ///
+    /// - invalidURLResponse: The response is not a valid URL response. Code 2001.
+    /// - invalidHTTPStatusCode: The response contains an invalid HTTP status code. Code 2002.
+    /// - URLSessionError: An error happens in the system URL session. Code 2003.
+    /// - dataModifyingFailed: Data modifying fails on returning a valid data. Code 2004.
+    /// - noURLResponse: The task is done but no URL response found. Code 2005.
+    public enum ResponseErrorReason {
+        
+        /// The response is not a valid URL response. Code 2001.
+        /// - response: The received invalid URL response.
+        ///             The response is expected to be an HTTP response, but it is not.
+        case invalidURLResponse(response: URLResponse)
+        
+        /// The response contains an invalid HTTP status code. Code 2002.
+        /// - Note:
+        ///   By default, status code 200..<400 is recognized as valid. You can override
+        ///   this behavior by conforming to the `ImageDownloaderDelegate`.
+        /// - response: The received response.
+        case invalidHTTPStatusCode(response: HTTPURLResponse)
+        
+        /// An error happens in the system URL session. Code 2003.
+        /// - error: The underlying URLSession error object.
+        case URLSessionError(error: Error)
+        
+        /// Data modifying fails on returning a valid data. Code 2004.
+        /// - task: The failed task.
+        case dataModifyingFailed(task: SessionDataTask)
+        
+        /// The task is done but no URL response found. Code 2005.
+        /// - task: The failed task.
+        case noURLResponse(task: SessionDataTask)
+
+        /// The task is cancelled by `ImageDownloaderDelegate` due to the `.cancel` response disposition is
+        /// specified by the delegate method. Code 2006.
+        case cancelledByDelegate(response: URLResponse)
+    }
+    
+    /// Represents the error reason during Kingfisher caching system.
+    ///
+    /// - fileEnumeratorCreationFailed: Cannot create a file enumerator for a certain disk URL. Code 3001.
+    /// - invalidFileEnumeratorContent: Cannot get correct file contents from a file enumerator. Code 3002.
+    /// - invalidURLResource: The file at target URL exists, but its URL resource is unavailable. Code 3003.
+    /// - cannotLoadDataFromDisk: The file at target URL exists, but the data cannot be loaded from it. Code 3004.
+    /// - cannotCreateDirectory: Cannot create a folder at a given path. Code 3005.
+    /// - imageNotExisting: The requested image does not exist in cache. Code 3006.
+    /// - cannotConvertToData: Cannot convert an object to data for storing. Code 3007.
+    /// - cannotSerializeImage: Cannot serialize an image to data for storing. Code 3008.
+    /// - cannotCreateCacheFile: Cannot create the cache file at a certain fileURL under a key. Code 3009.
+    /// - cannotSetCacheFileAttribute: Cannot set file attributes to a cached file. Code 3010.
+    public enum CacheErrorReason {
+        
+        /// Cannot create a file enumerator for a certain disk URL. Code 3001.
+        /// - url: The target disk URL from which the file enumerator should be created.
+        case fileEnumeratorCreationFailed(url: URL)
+        
+        /// Cannot get correct file contents from a file enumerator. Code 3002.
+        /// - url: The target disk URL from which the content of a file enumerator should be got.
+        case invalidFileEnumeratorContent(url: URL)
+        
+        /// The file at target URL exists, but its URL resource is unavailable. Code 3003.
+        /// - error: The underlying error thrown by file manager.
+        /// - key: The key used to getting the resource from cache.
+        /// - url: The disk URL where the target cached file exists.
+        case invalidURLResource(error: Error, key: String, url: URL)
+        
+        /// The file at target URL exists, but the data cannot be loaded from it. Code 3004.
+        /// - url: The disk URL where the target cached file exists.
+        /// - error: The underlying error which describes why this error happens.
+        case cannotLoadDataFromDisk(url: URL, error: Error)
+        
+        /// Cannot create a folder at a given path. Code 3005.
+        /// - path: The disk path where the directory creating operation fails.
+        /// - error: The underlying error which describes why this error happens.
+        case cannotCreateDirectory(path: String, error: Error)
+        
+        /// The requested image does not exist in cache. Code 3006.
+        /// - key: Key of the requested image in cache.
+        case imageNotExisting(key: String)
+        
+        /// Cannot convert an object to data for storing. Code 3007.
+        /// - object: The object which needs be convert to data.
+        case cannotConvertToData(object: Any, error: Error)
+        
+        /// Cannot serialize an image to data for storing. Code 3008.
+        /// - image: The input image needs to be serialized to cache.
+        /// - original: The original image data, if exists.
+        /// - serializer: The `CacheSerializer` used for the image serializing.
+        case cannotSerializeImage(image: KFCrossPlatformImage?, original: Data?, serializer: CacheSerializer)
+
+        /// Cannot create the cache file at a certain fileURL under a key. Code 3009.
+        /// - fileURL: The url where the cache file should be created.
+        /// - key: The cache key used for the cache. When caching a file through `KingfisherManager` and Kingfisher's
+        ///        extension method, it is the resolved cache key based on your input `Source` and the image processors.
+        /// - data: The data to be cached.
+        /// - error: The underlying error originally thrown by Foundation when writing the `data` to the disk file at
+        ///          `fileURL`.
+        case cannotCreateCacheFile(fileURL: URL, key: String, data: Data, error: Error)
+
+        /// Cannot set file attributes to a cached file. Code 3010.
+        /// - filePath: The path of target cache file.
+        /// - attributes: The file attribute to be set to the target file.
+        /// - error: The underlying error originally thrown by Foundation when setting the `attributes` to the disk
+        ///          file at `filePath`.
+        case cannotSetCacheFileAttribute(filePath: String, attributes: [FileAttributeKey : Any], error: Error)
+
+        /// The disk storage of cache is not ready. Code 3011.
+        ///
+        /// This is usually due to extremely lack of space on disk storage, and
+        /// Kingfisher failed even when creating the cache folder. The disk storage will be in unusable state. Normally,
+        /// ask user to free some spaces and restart the app to make the disk storage work again.
+        /// - cacheURL: The intended URL which should be the storage folder.
+        case diskStorageIsNotReady(cacheURL: URL)
+    }
+    
+    
+    /// Represents the error reason during image processing phase.
+    ///
+    /// - processingFailed: Image processing fails. There is no valid output image from the processor. Code 4001.
+    public enum ProcessorErrorReason {
+        /// Image processing fails. There is no valid output image from the processor. Code 4001.
+        /// - processor: The `ImageProcessor` used to process the image or its data in `item`.
+        /// - item: The image or its data content.
+        case processingFailed(processor: ImageProcessor, item: ImageProcessItem)
+    }
+
+    /// Represents the error reason during image setting in a view related class.
+    ///
+    /// - emptySource: The input resource is empty or `nil`. Code 5001.
+    /// - notCurrentSourceTask: The source task is finished, but it is not the one expected now. Code 5002.
+    /// - dataProviderError: An error happens during getting data from an `ImageDataProvider`. Code 5003.
+    public enum ImageSettingErrorReason {
+        
+        /// The input resource is empty or `nil`. Code 5001.
+        case emptySource
+        
+        /// The resource task is finished, but it is not the one expected now. This usually happens when you set another
+        /// resource on the view without cancelling the current on-going one. The previous setting task will fail with
+        /// this `.notCurrentSourceTask` error when a result got, regardless of it being successful or not for that task.
+        /// The result of this original task is contained in the associated value.
+        /// Code 5002.
+        /// - result: The `RetrieveImageResult` if the source task is finished without problem. `nil` if an error
+        ///           happens.
+        /// - error: The `Error` if an issue happens during image setting task. `nil` if the task finishes without
+        ///          problem.
+        /// - source: The original source value of the task.
+        case notCurrentSourceTask(result: RetrieveImageResult?, error: Error?, source: Source)
+
+        /// An error happens during getting data from an `ImageDataProvider`. Code 5003.
+        case dataProviderError(provider: ImageDataProvider, error: Error)
+
+        /// No more alternative `Source` can be used in current loading process. It means that the
+        /// `.alternativeSources` are used and Kingfisher tried to recovery from the original error, but still
+        /// fails for all the given alternative sources. The associated value holds all the errors encountered during
+        /// the load process, including the original source loading error and all the alternative sources errors.
+        /// Code 5004.
+        case alternativeSourcesExhausted([PropagationError])
+    }
+
+    // MARK: Member Cases
+    
+    /// Represents the error reason during networking request phase.
+    case requestError(reason: RequestErrorReason)
+    /// Represents the error reason during networking response phase.
+    case responseError(reason: ResponseErrorReason)
+    /// Represents the error reason during Kingfisher caching system.
+    case cacheError(reason: CacheErrorReason)
+    /// Represents the error reason during image processing phase.
+    case processorError(reason: ProcessorErrorReason)
+    /// Represents the error reason during image setting in a view related class.
+    case imageSettingError(reason: ImageSettingErrorReason)
+
+    // MARK: Helper Properties & Methods
+
+    /// Helper property to check whether this error is a `RequestErrorReason.taskCancelled` or not.
+    public var isTaskCancelled: Bool {
+        if case .requestError(reason: .taskCancelled) = self {
+            return true
+        }
+        return false
+    }
+
+    /// Helper method to check whether this error is a `ResponseErrorReason.invalidHTTPStatusCode` and the
+    /// associated value is a given status code.
+    ///
+    /// - Parameter code: The given status code.
+    /// - Returns: If `self` is a `ResponseErrorReason.invalidHTTPStatusCode` error
+    ///            and its status code equals to `code`, `true` is returned. Otherwise, `false`.
+    public func isInvalidResponseStatusCode(_ code: Int) -> Bool {
+        if case .responseError(reason: .invalidHTTPStatusCode(let response)) = self {
+            return response.statusCode == code
+        }
+        return false
+    }
+
+    public var isInvalidResponseStatusCode: Bool {
+        if case .responseError(reason: .invalidHTTPStatusCode) = self {
+            return true
+        }
+        return false
+    }
+
+    /// Helper property to check whether this error is a `ImageSettingErrorReason.notCurrentSourceTask` or not.
+    /// When a new image setting task starts while the old one is still running, the new task identifier will be
+    /// set and the old one is overwritten. A `.notCurrentSourceTask` error will be raised when the old task finishes
+    /// to let you know the setting process finishes with a certain result, but the image view or button is not set.
+    public var isNotCurrentTask: Bool {
+        if case .imageSettingError(reason: .notCurrentSourceTask(_, _, _)) = self {
+            return true
+        }
+        return false
+    }
+
+    var isLowDataModeConstrained: Bool {
+        if #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *),
+           case .responseError(reason: .URLSessionError(let sessionError)) = self,
+           let urlError = sessionError as? URLError,
+           urlError.networkUnavailableReason == .constrained
+        {
+            return true
+        }
+        return false
+    }
+
+}
+
+// MARK: - LocalizedError Conforming
+extension KingfisherError: LocalizedError {
+    
+    /// A localized message describing what error occurred.
+    public var errorDescription: String? {
+        switch self {
+        case .requestError(let reason): return reason.errorDescription
+        case .responseError(let reason): return reason.errorDescription
+        case .cacheError(let reason): return reason.errorDescription
+        case .processorError(let reason): return reason.errorDescription
+        case .imageSettingError(let reason): return reason.errorDescription
+        }
+    }
+}
+
+
+// MARK: - CustomNSError Conforming
+extension KingfisherError: CustomNSError {
+
+    /// The error domain of `KingfisherError`. All errors from Kingfisher is under this domain.
+    public static let domain = "com.onevcat.Kingfisher.Error"
+
+    /// The error code within the given domain.
+    public var errorCode: Int {
+        switch self {
+        case .requestError(let reason): return reason.errorCode
+        case .responseError(let reason): return reason.errorCode
+        case .cacheError(let reason): return reason.errorCode
+        case .processorError(let reason): return reason.errorCode
+        case .imageSettingError(let reason): return reason.errorCode
+        }
+    }
+}
+
+extension KingfisherError.RequestErrorReason {
+    var errorDescription: String? {
+        switch self {
+        case .emptyRequest:
+            return "The request is empty or `nil`."
+        case .invalidURL(let request):
+            return "The request contains an invalid or empty URL. Request: \(request)."
+        case .taskCancelled(let task, let token):
+            return "The session task was cancelled. Task: \(task), cancel token: \(token)."
+        }
+    }
+    
+    var errorCode: Int {
+        switch self {
+        case .emptyRequest: return 1001
+        case .invalidURL: return 1002
+        case .taskCancelled: return 1003
+        }
+    }
+}
+
+extension KingfisherError.ResponseErrorReason {
+    var errorDescription: String? {
+        switch self {
+        case .invalidURLResponse(let response):
+            return "The URL response is invalid: \(response)"
+        case .invalidHTTPStatusCode(let response):
+            return "The HTTP status code in response is invalid. Code: \(response.statusCode), response: \(response)."
+        case .URLSessionError(let error):
+            return "A URL session error happened. The underlying error: \(error)"
+        case .dataModifyingFailed(let task):
+            return "The data modifying delegate returned `nil` for the downloaded data. Task: \(task)."
+        case .noURLResponse(let task):
+            return "No URL response received. Task: \(task)."
+        case .cancelledByDelegate(let response):
+            return "The downloading task is cancelled by the downloader delegate. Response: \(response)."
+
+        }
+    }
+    
+    var errorCode: Int {
+        switch self {
+        case .invalidURLResponse: return 2001
+        case .invalidHTTPStatusCode: return 2002
+        case .URLSessionError: return 2003
+        case .dataModifyingFailed: return 2004
+        case .noURLResponse: return 2005
+        case .cancelledByDelegate: return 2006
+        }
+    }
+}
+
+extension KingfisherError.CacheErrorReason {
+    var errorDescription: String? {
+        switch self {
+        case .fileEnumeratorCreationFailed(let url):
+            return "Cannot create file enumerator for URL: \(url)."
+        case .invalidFileEnumeratorContent(let url):
+            return "Cannot get contents from the file enumerator at URL: \(url)."
+        case .invalidURLResource(let error, let key, let url):
+            return "Cannot get URL resource values or data for the given URL: \(url). " +
+                   "Cache key: \(key). Underlying error: \(error)"
+        case .cannotLoadDataFromDisk(let url, let error):
+            return "Cannot load data from disk at URL: \(url). Underlying error: \(error)"
+        case .cannotCreateDirectory(let path, let error):
+            return "Cannot create directory at given path: Path: \(path). Underlying error: \(error)"
+        case .imageNotExisting(let key):
+            return "The image is not in cache, but you requires it should only be " +
+                   "from cache by enabling the `.onlyFromCache` option. Key: \(key)."
+        case .cannotConvertToData(let object, let error):
+            return "Cannot convert the input object to a `Data` object when storing it to disk cache. " +
+                   "Object: \(object). Underlying error: \(error)"
+        case .cannotSerializeImage(let image, let originalData, let serializer):
+            return "Cannot serialize an image due to the cache serializer returning `nil`. " +
+                   "Image: \(String(describing:image)), original data: \(String(describing: originalData)), " +
+                   "serializer: \(serializer)."
+        case .cannotCreateCacheFile(let fileURL, let key, let data, let error):
+            return "Cannot create cache file at url: \(fileURL), key: \(key), data length: \(data.count). " +
+                   "Underlying foundation error: \(error)."
+        case .cannotSetCacheFileAttribute(let filePath, let attributes, let error):
+            return "Cannot set file attribute for the cache file at path: \(filePath), attributes: \(attributes)." +
+                   "Underlying foundation error: \(error)."
+        case .diskStorageIsNotReady(let cacheURL):
+            return "The disk storage is not ready to use yet at URL: '\(cacheURL)'. " +
+                "This is usually caused by extremely lack of disk space. Ask users to free up some space and restart the app."
+        }
+    }
+    
+    var errorCode: Int {
+        switch self {
+        case .fileEnumeratorCreationFailed: return 3001
+        case .invalidFileEnumeratorContent: return 3002
+        case .invalidURLResource: return 3003
+        case .cannotLoadDataFromDisk: return 3004
+        case .cannotCreateDirectory: return 3005
+        case .imageNotExisting: return 3006
+        case .cannotConvertToData: return 3007
+        case .cannotSerializeImage: return 3008
+        case .cannotCreateCacheFile: return 3009
+        case .cannotSetCacheFileAttribute: return 3010
+        case .diskStorageIsNotReady: return 3011
+        }
+    }
+}
+
+extension KingfisherError.ProcessorErrorReason {
+    var errorDescription: String? {
+        switch self {
+        case .processingFailed(let processor, let item):
+            return "Processing image failed. Processor: \(processor). Processing item: \(item)."
+        }
+    }
+    
+    var errorCode: Int {
+        switch self {
+        case .processingFailed: return 4001
+        }
+    }
+}
+
+extension KingfisherError.ImageSettingErrorReason {
+    var errorDescription: String? {
+        switch self {
+        case .emptySource:
+            return "The input resource is empty."
+        case .notCurrentSourceTask(let result, let error, let resource):
+            if let result = result {
+                return "Retrieving resource succeeded, but this source is " +
+                       "not the one currently expected. Result: \(result). Resource: \(resource)."
+            } else if let error = error {
+                return "Retrieving resource failed, and this resource is " +
+                       "not the one currently expected. Error: \(error). Resource: \(resource)."
+            } else {
+                return nil
+            }
+        case .dataProviderError(let provider, let error):
+            return "Image data provider fails to provide data. Provider: \(provider), error: \(error)"
+        case .alternativeSourcesExhausted(let errors):
+            return "Image setting from alternaive sources failed: \(errors)"
+        }
+    }
+    
+    var errorCode: Int {
+        switch self {
+        case .emptySource: return 5001
+        case .notCurrentSourceTask: return 5002
+        case .dataProviderError: return 5003
+        case .alternativeSourcesExhausted: return 5004
+        }
+    }
+}

+ 807 - 0
Pods/Kingfisher/Sources/General/KingfisherManager.swift

@@ -0,0 +1,807 @@
+//
+//  KingfisherManager.swift
+//  Kingfisher
+//
+//  Created by Wei Wang on 15/4/6.
+//
+//  Copyright (c) 2019 Wei Wang <onevcat@gmail.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
+#if os(macOS)
+import AppKit
+#else
+import UIKit
+#endif
+
+/// The downloading progress block type.
+/// The parameter value is the `receivedSize` of current response.
+/// The second parameter is the total expected data length from response's "Content-Length" header.
+/// If the expected length is not available, this block will not be called.
+public typealias DownloadProgressBlock = ((_ receivedSize: Int64, _ totalSize: Int64) -> Void)
+
+/// Represents the result of a Kingfisher retrieving image task.
+public struct RetrieveImageResult {
+    /// Gets the image object of this result.
+    public let image: KFCrossPlatformImage
+
+    /// Gets the cache source of the image. It indicates from which layer of cache this image is retrieved.
+    /// If the image is just downloaded from network, `.none` will be returned.
+    public let cacheType: CacheType
+
+    /// The `Source` which this result is related to. This indicated where the `image` of `self` is referring.
+    public let source: Source
+
+    /// The original `Source` from which the retrieve task begins. It can be different from the `source` property.
+    /// When an alternative source loading happened, the `source` will be the replacing loading target, while the
+    /// `originalSource` will be kept as the initial `source` which issued the image loading process.
+    public let originalSource: Source
+    
+    /// Gets the data behind the result.
+    ///
+    /// If this result is from a network downloading (when `cacheType == .none`), calling this returns the downloaded
+    /// data. If the reuslt is from cache, it serializes the image with the given cache serializer in the loading option
+    /// and returns the result.
+    ///
+    /// - Note:
+    /// This can be a time-consuming action, so if you need to use the data for multiple times, it is suggested to hold
+    /// it and prevent keeping calling this too frequently.
+    public let data: () -> Data?
+}
+
+/// A struct that stores some related information of an `KingfisherError`. It provides some context information for
+/// a pure error so you can identify the error easier.
+public struct PropagationError {
+
+    /// The `Source` to which current `error` is bound.
+    public let source: Source
+
+    /// The actual error happens in framework.
+    public let error: KingfisherError
+}
+
+
+/// The downloading task updated block type. The parameter `newTask` is the updated new task of image setting process.
+/// It is a `nil` if the image loading does not require an image downloading process. If an image downloading is issued,
+/// this value will contain the actual `DownloadTask` for you to keep and cancel it later if you need.
+public typealias DownloadTaskUpdatedBlock = ((_ newTask: DownloadTask?) -> Void)
+
+/// Main manager class of Kingfisher. It connects Kingfisher downloader and cache,
+/// to provide a set of convenience methods to use Kingfisher for tasks.
+/// You can use this class to retrieve an image via a specified URL from web or cache.
+public class KingfisherManager {
+
+    /// Represents a shared manager used across Kingfisher.
+    /// Use this instance for getting or storing images with Kingfisher.
+    public static let shared = KingfisherManager()
+
+    // Mark: Public Properties
+    /// The `ImageCache` used by this manager. It is `ImageCache.default` by default.
+    /// If a cache is specified in `KingfisherManager.defaultOptions`, the value in `defaultOptions` will be
+    /// used instead.
+    public var cache: ImageCache
+    
+    /// The `ImageDownloader` used by this manager. It is `ImageDownloader.default` by default.
+    /// If a downloader is specified in `KingfisherManager.defaultOptions`, the value in `defaultOptions` will be
+    /// used instead.
+    public var downloader: ImageDownloader
+    
+    /// Default options used by the manager. This option will be used in
+    /// Kingfisher manager related methods, as well as all view extension methods.
+    /// You can also passing other options for each image task by sending an `options` parameter
+    /// to Kingfisher's APIs. The per image options will overwrite the default ones,
+    /// if the option exists in both.
+    public var defaultOptions = KingfisherOptionsInfo.empty
+    
+    // Use `defaultOptions` to overwrite the `downloader` and `cache`.
+    private var currentDefaultOptions: KingfisherOptionsInfo {
+        return [.downloader(downloader), .targetCache(cache)] + defaultOptions
+    }
+
+    private let processingQueue: CallbackQueue
+    
+    private convenience init() {
+        self.init(downloader: .default, cache: .default)
+    }
+
+    /// Creates an image setting manager with specified downloader and cache.
+    ///
+    /// - Parameters:
+    ///   - downloader: The image downloader used to download images.
+    ///   - cache: The image cache which stores memory and disk images.
+    public init(downloader: ImageDownloader, cache: ImageCache) {
+        self.downloader = downloader
+        self.cache = cache
+
+        let processQueueName = "com.onevcat.Kingfisher.KingfisherManager.processQueue.\(UUID().uuidString)"
+        processingQueue = .dispatch(DispatchQueue(label: processQueueName))
+    }
+
+    // MARK: - Getting Images
+
+    /// Gets an image from a given resource.
+    /// - Parameters:
+    ///   - resource: The `Resource` object defines data information like key or URL.
+    ///   - options: Options to use when creating the image.
+    ///   - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
+    ///                    `expectedContentLength`, this block will not be called. `progressBlock` is always called in
+    ///                    main queue.
+    ///   - downloadTaskUpdated: Called when a new image downloading task is created for current image retrieving. This
+    ///                          usually happens when an alternative source is used to replace the original (failed)
+    ///                          task. You can update your reference of `DownloadTask` if you want to manually `cancel`
+    ///                          the new task.
+    ///   - completionHandler: Called when the image retrieved and set finished. This completion handler will be invoked
+    ///                        from the `options.callbackQueue`. If not specified, the main queue will be used.
+    /// - Returns: A task represents the image downloading. If there is a download task starts for `.network` resource,
+    ///            the started `DownloadTask` is returned. Otherwise, `nil` is returned.
+    ///
+    /// - Note:
+    ///    This method will first check whether the requested `resource` is already in cache or not. If cached,
+    ///    it returns `nil` and invoke the `completionHandler` after the cached image retrieved. Otherwise, it
+    ///    will download the `resource`, store it in cache, then call `completionHandler`.
+    @discardableResult
+    public func retrieveImage(
+        with resource: Resource,
+        options: KingfisherOptionsInfo? = nil,
+        progressBlock: DownloadProgressBlock? = nil,
+        downloadTaskUpdated: DownloadTaskUpdatedBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> DownloadTask?
+    {
+        return retrieveImage(
+            with: resource.convertToSource(),
+            options: options,
+            progressBlock: progressBlock,
+            downloadTaskUpdated: downloadTaskUpdated,
+            completionHandler: completionHandler
+        )
+    }
+
+    /// Gets an image from a given resource.
+    ///
+    /// - Parameters:
+    ///   - source: The `Source` object defines data information from network or a data provider.
+    ///   - options: Options to use when creating the image.
+    ///   - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
+    ///                    `expectedContentLength`, this block will not be called. `progressBlock` is always called in
+    ///                    main queue.
+    ///   - downloadTaskUpdated: Called when a new image downloading task is created for current image retrieving. This
+    ///                          usually happens when an alternative source is used to replace the original (failed)
+    ///                          task. You can update your reference of `DownloadTask` if you want to manually `cancel`
+    ///                          the new task.
+    ///   - completionHandler: Called when the image retrieved and set finished. This completion handler will be invoked
+    ///                        from the `options.callbackQueue`. If not specified, the main queue will be used.
+    /// - Returns: A task represents the image downloading. If there is a download task starts for `.network` resource,
+    ///            the started `DownloadTask` is returned. Otherwise, `nil` is returned.
+    ///
+    /// - Note:
+    ///    This method will first check whether the requested `source` is already in cache or not. If cached,
+    ///    it returns `nil` and invoke the `completionHandler` after the cached image retrieved. Otherwise, it
+    ///    will try to load the `source`, store it in cache, then call `completionHandler`.
+    ///
+    @discardableResult
+    public func retrieveImage(
+        with source: Source,
+        options: KingfisherOptionsInfo? = nil,
+        progressBlock: DownloadProgressBlock? = nil,
+        downloadTaskUpdated: DownloadTaskUpdatedBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> DownloadTask?
+    {
+        let options = currentDefaultOptions + (options ?? .empty)
+        let info = KingfisherParsedOptionsInfo(options)
+        return retrieveImage(
+            with: source,
+            options: info,
+            progressBlock: progressBlock,
+            downloadTaskUpdated: downloadTaskUpdated,
+            completionHandler: completionHandler)
+    }
+
+    func retrieveImage(
+        with source: Source,
+        options: KingfisherParsedOptionsInfo,
+        progressBlock: DownloadProgressBlock? = nil,
+        downloadTaskUpdated: DownloadTaskUpdatedBlock? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> DownloadTask?
+    {
+        var info = options
+        if let block = progressBlock {
+            info.onDataReceived = (info.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
+        }
+        return retrieveImage(
+            with: source,
+            options: info,
+            downloadTaskUpdated: downloadTaskUpdated,
+            progressiveImageSetter: nil,
+            completionHandler: completionHandler)
+    }
+
+    func retrieveImage(
+        with source: Source,
+        options: KingfisherParsedOptionsInfo,
+        downloadTaskUpdated: DownloadTaskUpdatedBlock? = nil,
+        progressiveImageSetter: ((KFCrossPlatformImage?) -> Void)? = nil,
+        referenceTaskIdentifierChecker: (() -> Bool)? = nil,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> DownloadTask?
+    {
+        var options = options
+        if let provider = ImageProgressiveProvider(options, refresh: { image in
+            guard let setter = progressiveImageSetter else {
+                return
+            }
+            guard let strategy = options.progressiveJPEG?.onImageUpdated(image) else {
+                setter(image)
+                return
+            }
+            switch strategy {
+            case .default: setter(image)
+            case .keepCurrent: break
+            case .replace(let newImage): setter(newImage)
+            }
+        }) {
+            options.onDataReceived = (options.onDataReceived ?? []) + [provider]
+        }
+        if let checker = referenceTaskIdentifierChecker {
+            options.onDataReceived?.forEach {
+                $0.onShouldApply = checker
+            }
+        }
+        
+        let retrievingContext = RetrievingContext(options: options, originalSource: source)
+        var retryContext: RetryContext?
+
+        func startNewRetrieveTask(
+            with source: Source,
+            downloadTaskUpdated: DownloadTaskUpdatedBlock?
+        ) {
+            let newTask = self.retrieveImage(with: source, context: retrievingContext) { result in
+                handler(currentSource: source, result: result)
+            }
+            downloadTaskUpdated?(newTask)
+        }
+
+        func failCurrentSource(_ source: Source, with error: KingfisherError) {
+            // Skip alternative sources if the user cancelled it.
+            guard !error.isTaskCancelled else {
+                completionHandler?(.failure(error))
+                return
+            }
+            // When low data mode constrained error, retry with the low data mode source instead of use alternative on fly.
+            guard !error.isLowDataModeConstrained else {
+                if let source = retrievingContext.options.lowDataModeSource {
+                    retrievingContext.options.lowDataModeSource = nil
+                    startNewRetrieveTask(with: source, downloadTaskUpdated: downloadTaskUpdated)
+                } else {
+                    // This should not happen.
+                    completionHandler?(.failure(error))
+                }
+                return
+            }
+            if let nextSource = retrievingContext.popAlternativeSource() {
+                retrievingContext.appendError(error, to: source)
+                startNewRetrieveTask(with: nextSource, downloadTaskUpdated: downloadTaskUpdated)
+            } else {
+                // No other alternative source. Finish with error.
+                if retrievingContext.propagationErrors.isEmpty {
+                    completionHandler?(.failure(error))
+                } else {
+                    retrievingContext.appendError(error, to: source)
+                    let finalError = KingfisherError.imageSettingError(
+                        reason: .alternativeSourcesExhausted(retrievingContext.propagationErrors)
+                    )
+                    completionHandler?(.failure(finalError))
+                }
+            }
+        }
+
+        func handler(currentSource: Source, result: (Result<RetrieveImageResult, KingfisherError>)) -> Void {
+            switch result {
+            case .success:
+                completionHandler?(result)
+            case .failure(let error):
+                if let retryStrategy = options.retryStrategy {
+                    let context = retryContext?.increaseRetryCount() ?? RetryContext(source: source, error: error)
+                    retryContext = context
+
+                    retryStrategy.retry(context: context) { decision in
+                        switch decision {
+                        case .retry(let userInfo):
+                            retryContext?.userInfo = userInfo
+                            startNewRetrieveTask(with: source, downloadTaskUpdated: downloadTaskUpdated)
+                        case .stop:
+                            failCurrentSource(currentSource, with: error)
+                        }
+                    }
+                } else {
+                    failCurrentSource(currentSource, with: error)
+                }
+            }
+        }
+
+        return retrieveImage(
+            with: source,
+            context: retrievingContext)
+        {
+            result in
+            handler(currentSource: source, result: result)
+        }
+
+    }
+    
+    private func retrieveImage(
+        with source: Source,
+        context: RetrievingContext,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> DownloadTask?
+    {
+        let options = context.options
+        if options.forceRefresh {
+            return loadAndCacheImage(
+                source: source,
+                context: context,
+                completionHandler: completionHandler)?.value
+            
+        } else {
+            let loadedFromCache = retrieveImageFromCache(
+                source: source,
+                context: context,
+                completionHandler: completionHandler)
+            
+            if loadedFromCache {
+                return nil
+            }
+            
+            if options.onlyFromCache {
+                let error = KingfisherError.cacheError(reason: .imageNotExisting(key: source.cacheKey))
+                completionHandler?(.failure(error))
+                return nil
+            }
+            
+            return loadAndCacheImage(
+                source: source,
+                context: context,
+                completionHandler: completionHandler)?.value
+        }
+    }
+
+    func provideImage(
+        provider: ImageDataProvider,
+        options: KingfisherParsedOptionsInfo,
+        completionHandler: ((Result<ImageLoadingResult, KingfisherError>) -> Void)?)
+    {
+        guard let  completionHandler = completionHandler else { return }
+        provider.data { result in
+            switch result {
+            case .success(let data):
+                (options.processingQueue ?? self.processingQueue).execute {
+                    let processor = options.processor
+                    let processingItem = ImageProcessItem.data(data)
+                    guard let image = processor.process(item: processingItem, options: options) else {
+                        options.callbackQueue.execute {
+                            let error = KingfisherError.processorError(
+                                reason: .processingFailed(processor: processor, item: processingItem))
+                            completionHandler(.failure(error))
+                        }
+                        return
+                    }
+
+                    options.callbackQueue.execute {
+                        let result = ImageLoadingResult(image: image, url: nil, originalData: data)
+                        completionHandler(.success(result))
+                    }
+                }
+            case .failure(let error):
+                options.callbackQueue.execute {
+                    let error = KingfisherError.imageSettingError(
+                        reason: .dataProviderError(provider: provider, error: error))
+                    completionHandler(.failure(error))
+                }
+
+            }
+        }
+    }
+
+    private func cacheImage(
+        source: Source,
+        options: KingfisherParsedOptionsInfo,
+        context: RetrievingContext,
+        result: Result<ImageLoadingResult, KingfisherError>,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?
+    )
+    {
+        switch result {
+        case .success(let value):
+            let needToCacheOriginalImage = options.cacheOriginalImage &&
+                                           options.processor != DefaultImageProcessor.default
+            let coordinator = CacheCallbackCoordinator(
+                shouldWaitForCache: options.waitForCache, shouldCacheOriginal: needToCacheOriginalImage)
+            let result = RetrieveImageResult(
+                image: options.imageModifier?.modify(value.image) ?? value.image,
+                cacheType: .none,
+                source: source,
+                originalSource: context.originalSource,
+                data: {  value.originalData }
+            )
+            // Add image to cache.
+            let targetCache = options.targetCache ?? self.cache
+            targetCache.store(
+                value.image,
+                original: value.originalData,
+                forKey: source.cacheKey,
+                options: options,
+                toDisk: !options.cacheMemoryOnly)
+            {
+                _ in
+                coordinator.apply(.cachingImage) {
+                    completionHandler?(.success(result))
+                }
+            }
+
+            // Add original image to cache if necessary.
+
+            if needToCacheOriginalImage {
+                let originalCache = options.originalCache ?? targetCache
+                originalCache.storeToDisk(
+                    value.originalData,
+                    forKey: source.cacheKey,
+                    processorIdentifier: DefaultImageProcessor.default.identifier,
+                    expiration: options.diskCacheExpiration)
+                {
+                    _ in
+                    coordinator.apply(.cachingOriginalImage) {
+                        completionHandler?(.success(result))
+                    }
+                }
+            }
+
+            coordinator.apply(.cacheInitiated) {
+                completionHandler?(.success(result))
+            }
+
+        case .failure(let error):
+            completionHandler?(.failure(error))
+        }
+    }
+
+    @discardableResult
+    func loadAndCacheImage(
+        source: Source,
+        context: RetrievingContext,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> DownloadTask.WrappedTask?
+    {
+        let options = context.options
+        func _cacheImage(_ result: Result<ImageLoadingResult, KingfisherError>) {
+            cacheImage(
+                source: source,
+                options: options,
+                context: context,
+                result: result,
+                completionHandler: completionHandler
+            )
+        }
+
+        switch source {
+        case .network(let resource):
+            let downloader = options.downloader ?? self.downloader
+            let task = downloader.downloadImage(
+                with: resource.downloadURL, options: options, completionHandler: _cacheImage
+            )
+
+
+            // The code below is neat, but it fails the Swift 5.2 compiler with a runtime crash when 
+            // `BUILD_LIBRARY_FOR_DISTRIBUTION` is turned on. I believe it is a bug in the compiler. 
+            // Let's fallback to a traditional style before it can be fixed in Swift.
+            //
+            // https://github.com/onevcat/Kingfisher/issues/1436
+            //
+            // return task.map(DownloadTask.WrappedTask.download)
+
+            if let task = task {
+                return .download(task)
+            } else {
+                return nil
+            }
+
+        case .provider(let provider):
+            provideImage(provider: provider, options: options, completionHandler: _cacheImage)
+            return .dataProviding
+        }
+    }
+    
+    /// Retrieves image from memory or disk cache.
+    ///
+    /// - Parameters:
+    ///   - source: The target source from which to get image.
+    ///   - key: The key to use when caching the image.
+    ///   - url: Image request URL. This is not used when retrieving image from cache. It is just used for
+    ///          `RetrieveImageResult` callback compatibility.
+    ///   - options: Options on how to get the image from image cache.
+    ///   - completionHandler: Called when the image retrieving finishes, either with succeeded
+    ///                        `RetrieveImageResult` or an error.
+    /// - Returns: `true` if the requested image or the original image before being processed is existing in cache.
+    ///            Otherwise, this method returns `false`.
+    ///
+    /// - Note:
+    ///    The image retrieving could happen in either memory cache or disk cache. The `.processor` option in
+    ///    `options` will be considered when searching in the cache. If no processed image is found, Kingfisher
+    ///    will try to check whether an original version of that image is existing or not. If there is already an
+    ///    original, Kingfisher retrieves it from cache and processes it. Then, the processed image will be store
+    ///    back to cache for later use.
+    func retrieveImageFromCache(
+        source: Source,
+        context: RetrievingContext,
+        completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> Bool
+    {
+        let options = context.options
+        // 1. Check whether the image was already in target cache. If so, just get it.
+        let targetCache = options.targetCache ?? cache
+        let key = source.cacheKey
+        let targetImageCached = targetCache.imageCachedType(
+            forKey: key, processorIdentifier: options.processor.identifier)
+        
+        let validCache = targetImageCached.cached &&
+            (options.fromMemoryCacheOrRefresh == false || targetImageCached == .memory)
+        if validCache {
+            targetCache.retrieveImage(forKey: key, options: options) { result in
+                guard let completionHandler = completionHandler else { return }
+                
+                // TODO: Optimize it when we can use async across all the project.
+                func checkResultImageAndCallback(_ inputImage: KFCrossPlatformImage) {
+                    var image = inputImage
+                    if image.kf.imageFrameCount != nil && image.kf.imageFrameCount != 1, let data = image.kf.animatedImageData {
+                        // Always recreate animated image representation since it is possible to be loaded in different options.
+                        // https://github.com/onevcat/Kingfisher/issues/1923
+                        image = options.processor.process(item: .data(data), options: options) ?? .init()
+                    }
+                    if let modifier = options.imageModifier {
+                        image = modifier.modify(image)
+                    }
+                    let value = result.map {
+                        RetrieveImageResult(
+                            image: image,
+                            cacheType: $0.cacheType,
+                            source: source,
+                            originalSource: context.originalSource,
+                            data: { options.cacheSerializer.data(with: image, original: nil) }
+                        )
+                    }
+                    completionHandler(value)
+                }
+                
+                result.match { cacheResult in
+                    options.callbackQueue.execute {
+                        guard let image = cacheResult.image else {
+                            completionHandler(.failure(KingfisherError.cacheError(reason: .imageNotExisting(key: key))))
+                            return
+                        }
+                        
+                        if options.cacheSerializer.originalDataUsed {
+                            let processor = options.processor
+                            (options.processingQueue ?? self.processingQueue).execute {
+                                let item = ImageProcessItem.image(image)
+                                guard let processedImage = processor.process(item: item, options: options) else {
+                                    let error = KingfisherError.processorError(
+                                        reason: .processingFailed(processor: processor, item: item))
+                                    options.callbackQueue.execute { completionHandler(.failure(error)) }
+                                    return
+                                }
+                                options.callbackQueue.execute {
+                                    checkResultImageAndCallback(processedImage)
+                                }
+                            }
+                        } else {
+                            checkResultImageAndCallback(image)
+                        }
+                    }
+                } onFailure: { error in
+                    options.callbackQueue.execute {
+                        completionHandler(.failure(KingfisherError.cacheError(reason: .imageNotExisting(key: key))))
+                    }
+                }
+            }
+            return true
+        }
+
+        // 2. Check whether the original image exists. If so, get it, process it, save to storage and return.
+        let originalCache = options.originalCache ?? targetCache
+        // No need to store the same file in the same cache again.
+        if originalCache === targetCache && options.processor == DefaultImageProcessor.default {
+            return false
+        }
+
+        // Check whether the unprocessed image existing or not.
+        let originalImageCacheType = originalCache.imageCachedType(
+            forKey: key, processorIdentifier: DefaultImageProcessor.default.identifier)
+        let canAcceptDiskCache = !options.fromMemoryCacheOrRefresh
+        
+        let canUseOriginalImageCache =
+            (canAcceptDiskCache && originalImageCacheType.cached) ||
+            (!canAcceptDiskCache && originalImageCacheType == .memory)
+        
+        if canUseOriginalImageCache {
+            // Now we are ready to get found the original image from cache. We need the unprocessed image, so remove
+            // any processor from options first.
+            var optionsWithoutProcessor = options
+            optionsWithoutProcessor.processor = DefaultImageProcessor.default
+            originalCache.retrieveImage(forKey: key, options: optionsWithoutProcessor) { result in
+
+                result.match(
+                    onSuccess: { cacheResult in
+                        guard let image = cacheResult.image else {
+                            assertionFailure("The image (under key: \(key) should be existing in the original cache.")
+                            return
+                        }
+
+                        let processor = options.processor
+                        (options.processingQueue ?? self.processingQueue).execute {
+                            let item = ImageProcessItem.image(image)
+                            guard let processedImage = processor.process(item: item, options: options) else {
+                                let error = KingfisherError.processorError(
+                                    reason: .processingFailed(processor: processor, item: item))
+                                options.callbackQueue.execute { completionHandler?(.failure(error)) }
+                                return
+                            }
+
+                            var cacheOptions = options
+                            cacheOptions.callbackQueue = .untouch
+
+                            let coordinator = CacheCallbackCoordinator(
+                                shouldWaitForCache: options.waitForCache, shouldCacheOriginal: false)
+
+                            let image = options.imageModifier?.modify(processedImage) ?? processedImage
+                            let result = RetrieveImageResult(
+                                image: image,
+                                cacheType: .none,
+                                source: source,
+                                originalSource: context.originalSource,
+                                data: { options.cacheSerializer.data(with: processedImage, original: nil) }
+                            )
+
+                            targetCache.store(
+                                processedImage,
+                                forKey: key,
+                                options: cacheOptions,
+                                toDisk: !options.cacheMemoryOnly)
+                            {
+                                _ in
+                                coordinator.apply(.cachingImage) {
+                                    options.callbackQueue.execute { completionHandler?(.success(result)) }
+                                }
+                            }
+
+                            coordinator.apply(.cacheInitiated) {
+                                options.callbackQueue.execute { completionHandler?(.success(result)) }
+                            }
+                        }
+                    },
+                    onFailure: { _ in
+                        // This should not happen actually, since we already confirmed `originalImageCached` is `true`.
+                        // Just in case...
+                        options.callbackQueue.execute {
+                            completionHandler?(
+                                .failure(KingfisherError.cacheError(reason: .imageNotExisting(key: key)))
+                            )
+                        }
+                    }
+                )
+            }
+            return true
+        }
+
+        return false
+    }
+}
+
+class RetrievingContext {
+
+    var options: KingfisherParsedOptionsInfo
+
+    let originalSource: Source
+    var propagationErrors: [PropagationError] = []
+
+    init(options: KingfisherParsedOptionsInfo, originalSource: Source) {
+        self.originalSource = originalSource
+        self.options = options
+    }
+
+    func popAlternativeSource() -> Source? {
+        guard var alternativeSources = options.alternativeSources, !alternativeSources.isEmpty else {
+            return nil
+        }
+        let nextSource = alternativeSources.removeFirst()
+        options.alternativeSources = alternativeSources
+        return nextSource
+    }
+
+    @discardableResult
+    func appendError(_ error: KingfisherError, to source: Source) -> [PropagationError] {
+        let item = PropagationError(source: source, error: error)
+        propagationErrors.append(item)
+        return propagationErrors
+    }
+}
+
+class CacheCallbackCoordinator {
+
+    enum State {
+        case idle
+        case imageCached
+        case originalImageCached
+        case done
+    }
+
+    enum Action {
+        case cacheInitiated
+        case cachingImage
+        case cachingOriginalImage
+    }
+
+    private let shouldWaitForCache: Bool
+    private let shouldCacheOriginal: Bool
+    private let stateQueue: DispatchQueue
+    private var threadSafeState: State = .idle
+
+    private (set) var state: State {
+        set { stateQueue.sync { threadSafeState = newValue } }
+        get { stateQueue.sync { threadSafeState } }
+    }
+
+    init(shouldWaitForCache: Bool, shouldCacheOriginal: Bool) {
+        self.shouldWaitForCache = shouldWaitForCache
+        self.shouldCacheOriginal = shouldCacheOriginal
+        let stateQueueName = "com.onevcat.Kingfisher.CacheCallbackCoordinator.stateQueue.\(UUID().uuidString)"
+        self.stateQueue = DispatchQueue(label: stateQueueName)
+    }
+
+    func apply(_ action: Action, trigger: () -> Void) {
+        switch (state, action) {
+        case (.done, _):
+            break
+
+        // From .idle
+        case (.idle, .cacheInitiated):
+            if !shouldWaitForCache {
+                state = .done
+                trigger()
+            }
+        case (.idle, .cachingImage):
+            if shouldCacheOriginal {
+                state = .imageCached
+            } else {
+                state = .done
+                trigger()
+            }
+        case (.idle, .cachingOriginalImage):
+            state = .originalImageCached
+
+        // From .imageCached
+        case (.imageCached, .cachingOriginalImage):
+            state = .done
+            trigger()
+
+        // From .originalImageCached
+        case (.originalImageCached, .cachingImage):
+            state = .done
+            trigger()
+
+        default:
+            assertionFailure("This case should not happen in CacheCallbackCoordinator: \(state) - \(action)")
+        }
+    }
+}

+ 400 - 0
Pods/Kingfisher/Sources/General/KingfisherOptionsInfo.swift

@@ -0,0 +1,400 @@
+//
+//  KingfisherOptionsInfo.swift
+//  Kingfisher
+//
+//  Created by Wei Wang on 15/4/23.
+//
+//  Copyright (c) 2019 Wei Wang <onevcat@gmail.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.
+
+#if os(macOS)
+import AppKit
+#else
+import UIKit
+#endif
+    
+
+/// KingfisherOptionsInfo is a typealias for [KingfisherOptionsInfoItem].
+/// You can use the enum of option item with value to control some behaviors of Kingfisher.
+public typealias KingfisherOptionsInfo = [KingfisherOptionsInfoItem]
+
+extension Array where Element == KingfisherOptionsInfoItem {
+    static let empty: KingfisherOptionsInfo = []
+}
+
+/// Represents the available option items could be used in `KingfisherOptionsInfo`.
+public enum KingfisherOptionsInfoItem {
+    
+    /// Kingfisher will use the associated `ImageCache` object when handling related operations,
+    /// including trying to retrieve the cached images and store the downloaded image to it.
+    case targetCache(ImageCache)
+    
+    /// The `ImageCache` for storing and retrieving original images. If `originalCache` is
+    /// contained in the options, it will be preferred for storing and retrieving original images.
+    /// If there is no `.originalCache` in the options, `.targetCache` will be used to store original images.
+    ///
+    /// When using KingfisherManager to download and store an image, if `cacheOriginalImage` is
+    /// applied in the option, the original image will be stored to this `originalCache`. At the
+    /// same time, if a requested final image (with processor applied) cannot be found in `targetCache`,
+    /// Kingfisher will try to search the original image to check whether it is already there. If found,
+    /// it will be used and applied with the given processor. It is an optimization for not downloading
+    /// the same image for multiple times.
+    case originalCache(ImageCache)
+    
+    /// Kingfisher will use the associated `ImageDownloader` object to download the requested images.
+    case downloader(ImageDownloader)
+
+    /// Member for animation transition when using `UIImageView`. Kingfisher will use the `ImageTransition` of
+    /// this enum to animate the image in if it is downloaded from web. The transition will not happen when the
+    /// image is retrieved from either memory or disk cache by default. If you need to do the transition even when
+    /// the image being retrieved from cache, set `.forceRefresh` as well.
+    case transition(ImageTransition)
+    
+    /// Associated `Float` value will be set as the priority of image download task. The value for it should be
+    /// between 0.0~1.0. If this option not set, the default value (`URLSessionTask.defaultPriority`) will be used.
+    case downloadPriority(Float)
+    
+    /// If set, Kingfisher will ignore the cache and try to start a download task for the image source.
+    case forceRefresh
+
+    /// If set, Kingfisher will try to retrieve the image from memory cache first. If the image is not in memory
+    /// cache, then it will ignore the disk cache but download the image again from network. This is useful when
+    /// you want to display a changeable image behind the same url at the same app session, while avoiding download
+    /// it for multiple times.
+    case fromMemoryCacheOrRefresh
+    
+    /// If set, setting the image to an image view will happen with transition even when retrieved from cache.
+    /// See `.transition` option for more.
+    case forceTransition
+    
+    /// If set, Kingfisher will only cache the value in memory but not in disk.
+    case cacheMemoryOnly
+    
+    /// If set, Kingfisher will wait for caching operation to be completed before calling the completion block.
+    case waitForCache
+    
+    /// If set, Kingfisher will only try to retrieve the image from cache, but not from network. If the image is not in
+    /// cache, the image retrieving will fail with the `KingfisherError.cacheError` with `.imageNotExisting` as its
+    /// reason.
+    case onlyFromCache
+    
+    /// Decode the image in background thread before using. It will decode the downloaded image data and do a off-screen
+    /// rendering to extract pixel information in background. This can speed up display, but will cost more time to
+    /// prepare the image for using.
+    case backgroundDecode
+
+    /// The associated value will be used as the target queue of dispatch callbacks when retrieving images from
+    /// cache. If not set, Kingfisher will use `.mainCurrentOrAsync` for callbacks.
+    ///
+    /// - Note:
+    /// This option does not affect the callbacks for UI related extension methods. You will always get the
+    /// callbacks called from main queue.
+    case callbackQueue(CallbackQueue)
+    
+    /// The associated value will be used as the scale factor when converting retrieved data to an image.
+    /// Specify the image scale, instead of your screen scale. You may need to set the correct scale when you dealing
+    /// with 2x or 3x retina images. Otherwise, Kingfisher will convert the data to image object at `scale` 1.0.
+    case scaleFactor(CGFloat)
+
+    /// Whether all the animated image data should be preloaded. Default is `false`, which means only following frames
+    /// will be loaded on need. If `true`, all the animated image data will be loaded and decoded into memory.
+    ///
+    /// This option is mainly used for back compatibility internally. You should not set it directly. Instead,
+    /// you should choose the image view class to control the GIF data loading. There are two classes in Kingfisher
+    /// support to display a GIF image. `AnimatedImageView` does not preload all data, it takes much less memory, but
+    /// uses more CPU when display. While a normal image view (`UIImageView` or `NSImageView`) loads all data at once,
+    /// which uses more memory but only decode image frames once.
+    case preloadAllAnimationData
+    
+    /// The `ImageDownloadRequestModifier` contained will be used to change the request before it being sent.
+    /// This is the last chance you can modify the image download request. You can modify the request for some
+    /// customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url mapping.
+    /// The original request will be sent without any modification by default.
+    case requestModifier(AsyncImageDownloadRequestModifier)
+    
+    /// The `ImageDownloadRedirectHandler` contained will be used to change the request before redirection.
+    /// This is the possibility you can modify the image download request during redirect. You can modify the request for
+    /// some customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url
+    /// mapping.
+    /// The original redirection request will be sent without any modification by default.
+    case redirectHandler(ImageDownloadRedirectHandler)
+    
+    /// Processor for processing when the downloading finishes, a processor will convert the downloaded data to an image
+    /// and/or apply some filter on it. If a cache is connected to the downloader (it happens when you are using
+    /// KingfisherManager or any of the view extension methods), the converted image will also be sent to cache as well.
+    /// If not set, the `DefaultImageProcessor.default` will be used.
+    case processor(ImageProcessor)
+    
+    /// Provides a `CacheSerializer` to convert some data to an image object for
+    /// retrieving from disk cache or vice versa for storing to disk cache.
+    /// If not set, the `DefaultCacheSerializer.default` will be used.
+    case cacheSerializer(CacheSerializer)
+
+    /// An `ImageModifier` is for modifying an image as needed right before it is used. If the image was fetched
+    /// directly from the downloader, the modifier will run directly after the `ImageProcessor`. If the image is being
+    /// fetched from a cache, the modifier will run after the `CacheSerializer`.
+    ///
+    /// Use `ImageModifier` when you need to set properties that do not persist when caching the image on a concrete
+    /// type of `Image`, such as the `renderingMode` or the `alignmentInsets` of `UIImage`.
+    case imageModifier(ImageModifier)
+    
+    /// Keep the existing image of image view while setting another image to it.
+    /// By setting this option, the placeholder image parameter of image view extension method
+    /// will be ignored and the current image will be kept while loading or downloading the new image.
+    case keepCurrentImageWhileLoading
+    
+    /// If set, Kingfisher will only load the first frame from an animated image file as a single image.
+    /// Loading an animated images may take too much memory. It will be useful when you want to display a
+    /// static preview of the first frame from an animated image.
+    ///
+    /// This option will be ignored if the target image is not animated image data.
+    case onlyLoadFirstFrame
+    
+    /// If set and an `ImageProcessor` is used, Kingfisher will try to cache both the final result and original
+    /// image. Kingfisher will have a chance to use the original image when another processor is applied to the same
+    /// resource, instead of downloading it again. You can use `.originalCache` to specify a cache or the original
+    /// images if necessary.
+    ///
+    /// The original image will be only cached to disk storage.
+    case cacheOriginalImage
+    
+    /// If set and an image retrieving error occurred Kingfisher will set provided image (or empty)
+    /// in place of requested one. It's useful when you don't want to show placeholder
+    /// during loading time but wants to use some default image when requests will be failed.
+    case onFailureImage(KFCrossPlatformImage?)
+    
+    /// If set and used in `ImagePrefetcher`, the prefetching operation will load the images into memory storage
+    /// aggressively. By default this is not contained in the options, that means if the requested image is already
+    /// in disk cache, Kingfisher will not try to load it to memory.
+    case alsoPrefetchToMemory
+    
+    /// If set, the disk storage loading will happen in the same calling queue. By default, disk storage file loading
+    /// happens in its own queue with an asynchronous dispatch behavior. Although it provides better non-blocking disk
+    /// loading performance, it also causes a flickering when you reload an image from disk, if the image view already
+    /// has an image set.
+    ///
+    /// Set this options will stop that flickering by keeping all loading in the same queue (typically the UI queue
+    /// if you are using Kingfisher's extension methods to set an image), with a tradeoff of loading performance.
+    case loadDiskFileSynchronously
+
+    /// Options to control the writing of data to disk storage
+    /// If set, options will be passed the store operation for a new files.
+    case diskStoreWriteOptions(Data.WritingOptions)
+
+    /// The expiration setting for memory cache. By default, the underlying `MemoryStorage.Backend` uses the
+    /// expiration in its config for all items. If set, the `MemoryStorage.Backend` will use this associated
+    /// value to overwrite the config setting for this caching item.
+    case memoryCacheExpiration(StorageExpiration)
+    
+    /// The expiration extending setting for memory cache. The item expiration time will be incremented by this
+    /// value after access.
+    /// By default, the underlying `MemoryStorage.Backend` uses the initial cache expiration as extending
+    /// value: .cacheTime.
+    ///
+    /// To disable extending option at all add memoryCacheAccessExtendingExpiration(.none) to options.
+    case memoryCacheAccessExtendingExpiration(ExpirationExtending)
+    
+    /// The expiration setting for disk cache. By default, the underlying `DiskStorage.Backend` uses the
+    /// expiration in its config for all items. If set, the `DiskStorage.Backend` will use this associated
+    /// value to overwrite the config setting for this caching item.
+    case diskCacheExpiration(StorageExpiration)
+
+    /// The expiration extending setting for disk cache. The item expiration time will be incremented by this value after access.
+    /// By default, the underlying `DiskStorage.Backend` uses the initial cache expiration as extending value: .cacheTime.
+    /// To disable extending option at all add diskCacheAccessExtendingExpiration(.none) to options.
+    case diskCacheAccessExtendingExpiration(ExpirationExtending)
+    
+    /// Decides on which queue the image processing should happen. By default, Kingfisher uses a pre-defined serial
+    /// queue to process images. Use this option to change this behavior. For example, specify a `.mainCurrentOrAsync`
+    /// to let the image be processed in main queue to prevent a possible flickering (but with a possibility of
+    /// blocking the UI, especially if the processor needs a lot of time to run).
+    case processingQueue(CallbackQueue)
+    
+    /// Enable progressive image loading, Kingfisher will use the associated `ImageProgressive` value to process the
+    /// progressive JPEG data and display it in a progressive way.
+    case progressiveJPEG(ImageProgressive)
+
+    /// The alternative sources will be used when the original input `Source` fails. The `Source`s in the associated
+    /// array will be used to start a new image loading task if the previous task fails due to an error. The image
+    /// source loading process will stop as soon as a source is loaded successfully. If all `[Source]`s are used but
+    /// the loading is still failing, an `imageSettingError` with `alternativeSourcesExhausted` as its reason will be
+    /// thrown out.
+    ///
+    /// This option is useful if you want to implement a fallback solution for setting image.
+    ///
+    /// User cancellation will not trigger the alternative source loading.
+    case alternativeSources([Source])
+
+    /// Provide a retry strategy which will be used when something gets wrong during the image retrieving process from
+    /// `KingfisherManager`. You can define a strategy by create a type conforming to the `RetryStrategy` protocol.
+    ///
+    /// - Note:
+    ///
+    /// All extension methods of Kingfisher (`kf` extensions on `UIImageView` or `UIButton`) retrieve images through
+    /// `KingfisherManager`, so the retry strategy also applies when using them. However, this option does not apply
+    /// when pass to an `ImageDownloader` or `ImageCache`.
+    ///
+    case retryStrategy(RetryStrategy)
+
+    /// The `Source` should be loaded when user enables Low Data Mode and the original source fails with an
+    /// `NSURLErrorNetworkUnavailableReason.constrained` error. When this option is set, the
+    /// `allowsConstrainedNetworkAccess` property of the request for the original source will be set to `false` and the
+    /// `Source` in associated value will be used to retrieve the image for low data mode. Usually, you can provide a
+    /// low-resolution version of your image or a local image provider to display a placeholder.
+    ///
+    /// If not set or the `source` is `nil`, the device Low Data Mode will be ignored and the original source will
+    /// be loaded following the system default behavior, in a normal way.
+    case lowDataMode(Source?)
+}
+
+// Improve performance by parsing the input `KingfisherOptionsInfo` (self) first.
+// So we can prevent the iterating over the options array again and again.
+/// The parsed options info used across Kingfisher methods. Each property in this type corresponds a case member
+/// in `KingfisherOptionsInfoItem`. When a `KingfisherOptionsInfo` sent to Kingfisher related methods, it will be
+/// parsed and converted to a `KingfisherParsedOptionsInfo` first, and pass through the internal methods.
+public struct KingfisherParsedOptionsInfo {
+
+    public var targetCache: ImageCache? = nil
+    public var originalCache: ImageCache? = nil
+    public var downloader: ImageDownloader? = nil
+    public var transition: ImageTransition = .none
+    public var downloadPriority: Float = URLSessionTask.defaultPriority
+    public var forceRefresh = false
+    public var fromMemoryCacheOrRefresh = false
+    public var forceTransition = false
+    public var cacheMemoryOnly = false
+    public var waitForCache = false
+    public var onlyFromCache = false
+    public var backgroundDecode = false
+    public var preloadAllAnimationData = false
+    public var callbackQueue: CallbackQueue = .mainCurrentOrAsync
+    public var scaleFactor: CGFloat = 1.0
+    public var requestModifier: AsyncImageDownloadRequestModifier? = nil
+    public var redirectHandler: ImageDownloadRedirectHandler? = nil
+    public var processor: ImageProcessor = DefaultImageProcessor.default
+    public var imageModifier: ImageModifier? = nil
+    public var cacheSerializer: CacheSerializer = DefaultCacheSerializer.default
+    public var keepCurrentImageWhileLoading = false
+    public var onlyLoadFirstFrame = false
+    public var cacheOriginalImage = false
+    public var onFailureImage: Optional<KFCrossPlatformImage?> = .none
+    public var alsoPrefetchToMemory = false
+    public var loadDiskFileSynchronously = false
+    public var diskStoreWriteOptions: Data.WritingOptions = []
+    public var memoryCacheExpiration: StorageExpiration? = nil
+    public var memoryCacheAccessExtendingExpiration: ExpirationExtending = .cacheTime
+    public var diskCacheExpiration: StorageExpiration? = nil
+    public var diskCacheAccessExtendingExpiration: ExpirationExtending = .cacheTime
+    public var processingQueue: CallbackQueue? = nil
+    public var progressiveJPEG: ImageProgressive? = nil
+    public var alternativeSources: [Source]? = nil
+    public var retryStrategy: RetryStrategy? = nil
+    public var lowDataModeSource: Source? = nil
+
+    var onDataReceived: [DataReceivingSideEffect]? = nil
+    
+    public init(_ info: KingfisherOptionsInfo?) {
+        guard let info = info else { return }
+        for option in info {
+            switch option {
+            case .targetCache(let value): targetCache = value
+            case .originalCache(let value): originalCache = value
+            case .downloader(let value): downloader = value
+            case .transition(let value): transition = value
+            case .downloadPriority(let value): downloadPriority = value
+            case .forceRefresh: forceRefresh = true
+            case .fromMemoryCacheOrRefresh: fromMemoryCacheOrRefresh = true
+            case .forceTransition: forceTransition = true
+            case .cacheMemoryOnly: cacheMemoryOnly = true
+            case .waitForCache: waitForCache = true
+            case .onlyFromCache: onlyFromCache = true
+            case .backgroundDecode: backgroundDecode = true
+            case .preloadAllAnimationData: preloadAllAnimationData = true
+            case .callbackQueue(let value): callbackQueue = value
+            case .scaleFactor(let value): scaleFactor = value
+            case .requestModifier(let value): requestModifier = value
+            case .redirectHandler(let value): redirectHandler = value
+            case .processor(let value): processor = value
+            case .imageModifier(let value): imageModifier = value
+            case .cacheSerializer(let value): cacheSerializer = value
+            case .keepCurrentImageWhileLoading: keepCurrentImageWhileLoading = true
+            case .onlyLoadFirstFrame: onlyLoadFirstFrame = true
+            case .cacheOriginalImage: cacheOriginalImage = true
+            case .onFailureImage(let value): onFailureImage = .some(value)
+            case .alsoPrefetchToMemory: alsoPrefetchToMemory = true
+            case .loadDiskFileSynchronously: loadDiskFileSynchronously = true
+            case .diskStoreWriteOptions(let options): diskStoreWriteOptions = options
+            case .memoryCacheExpiration(let expiration): memoryCacheExpiration = expiration
+            case .memoryCacheAccessExtendingExpiration(let expirationExtending): memoryCacheAccessExtendingExpiration = expirationExtending
+            case .diskCacheExpiration(let expiration): diskCacheExpiration = expiration
+            case .diskCacheAccessExtendingExpiration(let expirationExtending): diskCacheAccessExtendingExpiration = expirationExtending
+            case .processingQueue(let queue): processingQueue = queue
+            case .progressiveJPEG(let value): progressiveJPEG = value
+            case .alternativeSources(let sources): alternativeSources = sources
+            case .retryStrategy(let strategy): retryStrategy = strategy
+            case .lowDataMode(let source): lowDataModeSource = source
+            }
+        }
+
+        if originalCache == nil {
+            originalCache = targetCache
+        }
+    }
+}
+
+extension KingfisherParsedOptionsInfo {
+    var imageCreatingOptions: ImageCreatingOptions {
+        return ImageCreatingOptions(
+            scale: scaleFactor,
+            duration: 0.0,
+            preloadAll: preloadAllAnimationData,
+            onlyFirstFrame: onlyLoadFirstFrame)
+    }
+}
+
+protocol DataReceivingSideEffect: AnyObject {
+    var onShouldApply: () -> Bool { get set }
+    func onDataReceived(_ session: URLSession, task: SessionDataTask, data: Data)
+}
+
+class ImageLoadingProgressSideEffect: DataReceivingSideEffect {
+
+    var onShouldApply: () -> Bool = { return true }
+    
+    let block: DownloadProgressBlock
+
+    init(_ block: @escaping DownloadProgressBlock) {
+        self.block = block
+    }
+
+    func onDataReceived(_ session: URLSession, task: SessionDataTask, data: Data) {
+        guard self.onShouldApply() else { return }
+        guard let expectedContentLength = task.task.response?.expectedContentLength,
+                  expectedContentLength != -1 else
+        {
+            return
+        }
+
+        let dataLength = Int64(task.mutableData.count)
+        DispatchQueue.main.async {
+            self.block(dataLength, expectedContentLength)
+        }
+    }
+}

+ 152 - 0
Pods/Kingfisher/Sources/Image/Filter.swift

@@ -0,0 +1,152 @@
+//
+//  Filter.swift
+//  Kingfisher
+//
+//  Created by Wei Wang on 2016/08/31.
+//
+//  Copyright (c) 2019 Wei Wang <onevcat@gmail.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.
+
+#if !os(watchOS)
+
+#if os(macOS)
+import AppKit
+#else
+import UIKit
+#endif
+
+import CoreImage
+
+// Reuse the same CI Context for all CI drawing.
+private let ciContext = CIContext(options: nil)
+
+/// Represents the type of transformer method, which will be used in to provide a `Filter`.
+public typealias Transformer = (CIImage) -> CIImage?
+
+/// Represents a processor based on a `CIImage` `Filter`.
+/// It requires a filter to create an `ImageProcessor`.
+public protocol CIImageProcessor: ImageProcessor {
+    var filter: Filter { get }
+}
+
+extension CIImageProcessor {
+    
+    /// Processes the input `ImageProcessItem` with this processor.
+    ///
+    /// - Parameters:
+    ///   - item: Input item which will be processed by `self`.
+    ///   - options: Options when processing the item.
+    /// - Returns: The processed image.
+    ///
+    /// - Note: See documentation of `ImageProcessor` protocol for more.
+    public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
+        switch item {
+        case .image(let image):
+            return image.kf.apply(filter)
+        case .data:
+            return (DefaultImageProcessor.default |> self).process(item: item, options: options)
+        }
+    }
+}
+
+/// A wrapper struct for a `Transformer` of CIImage filters. A `Filter`
+/// value could be used to create a `CIImage` processor.
+public struct Filter {
+    
+    let transform: Transformer
+
+    public init(transform: @escaping Transformer) {
+        self.transform = transform
+    }
+    
+    /// Tint filter which will apply a tint color to images.
+    public static var tint: (KFCrossPlatformColor) -> Filter = {
+        color in
+        Filter {
+            input in
+            
+            let colorFilter = CIFilter(name: "CIConstantColorGenerator")!
+            colorFilter.setValue(CIColor(color: color), forKey: kCIInputColorKey)
+            
+            let filter = CIFilter(name: "CISourceOverCompositing")!
+            
+            let colorImage = colorFilter.outputImage
+            filter.setValue(colorImage, forKey: kCIInputImageKey)
+            filter.setValue(input, forKey: kCIInputBackgroundImageKey)
+            
+            return filter.outputImage?.cropped(to: input.extent)
+        }
+    }
+    
+    /// Represents color control elements. It is a tuple of
+    /// `(brightness, contrast, saturation, inputEV)`
+    public typealias ColorElement = (CGFloat, CGFloat, CGFloat, CGFloat)
+    
+    /// Color control filter which will apply color control change to images.
+    public static var colorControl: (ColorElement) -> Filter = { arg -> Filter in
+        let (brightness, contrast, saturation, inputEV) = arg
+        return Filter { input in
+            let paramsColor = [kCIInputBrightnessKey: brightness,
+                               kCIInputContrastKey: contrast,
+                               kCIInputSaturationKey: saturation]
+            let blackAndWhite = input.applyingFilter("CIColorControls", parameters: paramsColor)
+            let paramsExposure = [kCIInputEVKey: inputEV]
+            return blackAndWhite.applyingFilter("CIExposureAdjust", parameters: paramsExposure)
+        }
+    }
+}
+
+extension KingfisherWrapper where Base: KFCrossPlatformImage {
+
+    /// Applies a `Filter` containing `CIImage` transformer to `self`.
+    ///
+    /// - Parameter filter: The filter used to transform `self`.
+    /// - Returns: A transformed image by input `Filter`.
+    ///
+    /// - Note:
+    ///    Only CG-based images are supported. If any error happens
+    ///    during transforming, `self` will be returned.
+    public func apply(_ filter: Filter) -> KFCrossPlatformImage {
+        
+        guard let cgImage = cgImage else {
+            assertionFailure("[Kingfisher] Tint image only works for CG-based image.")
+            return base
+        }
+        
+        let inputImage = CIImage(cgImage: cgImage)
+        guard let outputImage = filter.transform(inputImage) else {
+            return base
+        }
+
+        guard let result = ciContext.createCGImage(outputImage, from: outputImage.extent) else {
+            assertionFailure("[Kingfisher] Can not make an tint image within context.")
+            return base
+        }
+        
+        #if os(macOS)
+            return fixedForRetinaPixel(cgImage: result, to: size)
+        #else
+            return KFCrossPlatformImage(cgImage: result, scale: base.scale, orientation: base.imageOrientation)
+        #endif
+    }
+
+}
+
+#endif

+ 177 - 0
Pods/Kingfisher/Sources/Image/GIFAnimatedImage.swift

@@ -0,0 +1,177 @@
+//
+//  AnimatedImage.swift
+//  Kingfisher
+//
+//  Created by onevcat on 2018/09/26.
+//
+//  Copyright (c) 2019 Wei Wang <onevcat@gmail.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
+import ImageIO
+
+/// Represents a set of image creating options used in Kingfisher.
+public struct ImageCreatingOptions {
+
+    /// The target scale of image needs to be created.
+    public let scale: CGFloat
+
+    /// The expected animation duration if an animated image being created.
+    public let duration: TimeInterval
+
+    /// For an animated image, whether or not all frames should be loaded before displaying.
+    public let preloadAll: Bool
+
+    /// For an animated image, whether or not only the first image should be
+    /// loaded as a static image. It is useful for preview purpose of an animated image.
+    public let onlyFirstFrame: Bool
+    
+    /// Creates an `ImageCreatingOptions` object.
+    ///
+    /// - Parameters:
+    ///   - scale: The target scale of image needs to be created. Default is `1.0`.
+    ///   - duration: The expected animation duration if an animated image being created.
+    ///               A value less or equal to `0.0` means the animated image duration will
+    ///               be determined by the frame data. Default is `0.0`.
+    ///   - preloadAll: For an animated image, whether or not all frames should be loaded before displaying.
+    ///                 Default is `false`.
+    ///   - onlyFirstFrame: For an animated image, whether or not only the first image should be
+    ///                     loaded as a static image. It is useful for preview purpose of an animated image.
+    ///                     Default is `false`.
+    public init(
+        scale: CGFloat = 1.0,
+        duration: TimeInterval = 0.0,
+        preloadAll: Bool = false,
+        onlyFirstFrame: Bool = false)
+    {
+        self.scale = scale
+        self.duration = duration
+        self.preloadAll = preloadAll
+        self.onlyFirstFrame = onlyFirstFrame
+    }
+}
+
+/// Represents the decoding for a GIF image. This class extracts frames from an `imageSource`, then
+/// hold the images for later use.
+public class GIFAnimatedImage {
+    let images: [KFCrossPlatformImage]
+    let duration: TimeInterval
+    
+    init?(from frameSource: ImageFrameSource, options: ImageCreatingOptions) {
+        let frameCount = frameSource.frameCount
+        var images = [KFCrossPlatformImage]()
+        var gifDuration = 0.0
+        
+        for i in 0 ..< frameCount {
+            guard let imageRef = frameSource.frame(at: i) else {
+                return nil
+            }
+            
+            if frameCount == 1 {
+                gifDuration = .infinity
+            } else {
+                // Get current animated GIF frame duration
+                gifDuration += frameSource.duration(at: i)
+            }
+            images.append(KingfisherWrapper.image(cgImage: imageRef, scale: options.scale, refImage: nil))
+            if options.onlyFirstFrame { break }
+        }
+        self.images = images
+        self.duration = gifDuration
+    }
+    
+    convenience init?(from imageSource: CGImageSource, for info: [String: Any], options: ImageCreatingOptions) {
+        let frameSource = CGImageFrameSource(data: nil, imageSource: imageSource, options: info)
+        self.init(from: frameSource, options: options)
+    }
+    
+    /// Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary.
+    public static func getFrameDuration(from gifInfo: [String: Any]?) -> TimeInterval {
+        let defaultFrameDuration = 0.1
+        guard let gifInfo = gifInfo else { return defaultFrameDuration }
+        
+        let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber
+        let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber
+        let duration = unclampedDelayTime ?? delayTime
+        
+        guard let frameDuration = duration else { return defaultFrameDuration }
+        return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : defaultFrameDuration
+    }
+
+    /// Calculates frame duration at a specific index for a gif from an `imageSource`.
+    public static func getFrameDuration(from imageSource: CGImageSource, at index: Int) -> TimeInterval {
+        guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, index, nil)
+            as? [String: Any] else { return 0.0 }
+
+        let gifInfo = properties[kCGImagePropertyGIFDictionary as String] as? [String: Any]
+        return getFrameDuration(from: gifInfo)
+    }
+}
+
+/// Represents a frame source for animated image
+public protocol ImageFrameSource {
+    /// Source data associated with this frame source.
+    var data: Data? { get }
+    
+    /// Count of total frames in this frame source.
+    var frameCount: Int { get }
+    
+    /// Retrieves the frame at a specific index. The result image is expected to be
+    /// no larger than `maxSize`. If the index is invalid, implementors should return `nil`.
+    func frame(at index: Int, maxSize: CGSize?) -> CGImage?
+    
+    /// Retrieves the duration at a specific index. If the index is invalid, implementors should return `0.0`.
+    func duration(at index: Int) -> TimeInterval
+}
+
+public extension ImageFrameSource {
+    /// Retrieves the frame at a specific index. If the index is invalid, implementors should return `nil`.
+    func frame(at index: Int) -> CGImage? {
+        return frame(at: index, maxSize: nil)
+    }
+}
+
+struct CGImageFrameSource: ImageFrameSource {
+    let data: Data?
+    let imageSource: CGImageSource
+    let options: [String: Any]?
+    
+    var frameCount: Int {
+        return CGImageSourceGetCount(imageSource)
+    }
+
+    func frame(at index: Int, maxSize: CGSize?) -> CGImage? {
+        var options = self.options as? [CFString: Any]
+        if let maxSize = maxSize, maxSize != .zero {
+            options = (options ?? [:]).merging([
+                kCGImageSourceCreateThumbnailFromImageIfAbsent: true,
+                kCGImageSourceCreateThumbnailWithTransform: true,
+                kCGImageSourceShouldCacheImmediately: true,
+                kCGImageSourceThumbnailMaxPixelSize: max(maxSize.width, maxSize.height)
+            ], uniquingKeysWith: { $1 })
+        }
+        return CGImageSourceCreateImageAtIndex(imageSource, index, options as CFDictionary?)
+    }
+
+    func duration(at index: Int) -> TimeInterval {
+        return GIFAnimatedImage.getFrameDuration(from: imageSource, at: index)
+    }
+}
+

+ 88 - 0
Pods/Kingfisher/Sources/Image/GraphicsContext.swift

@@ -0,0 +1,88 @@
+//
+//  GraphicsContext.swift
+//  Kingfisher
+//
+//  Created by taras on 19/04/2021.
+//
+//  Copyright (c) 2021 Wei Wang <onevcat@gmail.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.
+
+#if canImport(AppKit) && !targetEnvironment(macCatalyst)
+import AppKit
+#endif
+#if canImport(UIKit)
+import UIKit
+#endif
+
+enum GraphicsContext {
+    static func begin(size: CGSize, scale: CGFloat) {
+        #if os(macOS)
+        NSGraphicsContext.saveGraphicsState()
+        #else
+        UIGraphicsBeginImageContextWithOptions(size, false, scale)
+        #endif
+    }
+    
+    static func current(size: CGSize, scale: CGFloat, inverting: Bool, cgImage: CGImage?) -> CGContext? {
+        #if os(macOS)
+        guard let rep = NSBitmapImageRep(
+            bitmapDataPlanes: nil,
+            pixelsWide: Int(size.width),
+            pixelsHigh: Int(size.height),
+            bitsPerSample: cgImage?.bitsPerComponent ?? 8,
+            samplesPerPixel: 4,
+            hasAlpha: true,
+            isPlanar: false,
+            colorSpaceName: .calibratedRGB,
+            bytesPerRow: 0,
+            bitsPerPixel: 0) else
+        {
+            assertionFailure("[Kingfisher] Image representation cannot be created.")
+            return nil
+        }
+        rep.size = size
+        guard let context = NSGraphicsContext(bitmapImageRep: rep) else {
+            assertionFailure("[Kingfisher] Image context cannot be created.")
+            return nil
+        }
+        
+        NSGraphicsContext.current = context
+        return context.cgContext
+        #else
+        guard let context = UIGraphicsGetCurrentContext() else {
+            return nil
+        }
+        if inverting { // If drawing a CGImage, we need to make context flipped.
+            context.scaleBy(x: 1.0, y: -1.0)
+            context.translateBy(x: 0, y: -size.height)
+        }
+        return context
+        #endif
+    }
+    
+    static func end() {
+        #if os(macOS)
+        NSGraphicsContext.restoreGraphicsState()
+        #else
+        UIGraphicsEndImageContext()
+        #endif
+    }
+}
+

+ 426 - 0
Pods/Kingfisher/Sources/Image/Image.swift

@@ -0,0 +1,426 @@
+//
+//  Image.swift
+//  Kingfisher
+//
+//  Created by Wei Wang on 16/1/6.
+//
+//  Copyright (c) 2019 Wei Wang <onevcat@gmail.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.
+
+
+#if os(macOS)
+import AppKit
+private var imagesKey: Void?
+private var durationKey: Void?
+#else
+import UIKit
+import MobileCoreServices
+private var imageSourceKey: Void?
+#endif
+
+#if !os(watchOS)
+import CoreImage
+#endif
+
+import CoreGraphics
+import ImageIO
+
+#if canImport(UniformTypeIdentifiers)
+import UniformTypeIdentifiers
+#endif
+
+private var animatedImageDataKey: Void?
+private var imageFrameCountKey: Void?
+
+// MARK: - Image Properties
+extension KingfisherWrapper where Base: KFCrossPlatformImage {
+    private(set) var animatedImageData: Data? {
+        get { return getAssociatedObject(base, &animatedImageDataKey) }
+        set { setRetainedAssociatedObject(base, &animatedImageDataKey, newValue) }
+    }
+    
+    public var imageFrameCount: Int? {
+        get { return getAssociatedObject(base, &imageFrameCountKey) }
+        set { setRetainedAssociatedObject(base, &imageFrameCountKey, newValue) }
+    }
+    
+    #if os(macOS)
+    var cgImage: CGImage? {
+        return base.cgImage(forProposedRect: nil, context: nil, hints: nil)
+    }
+    
+    var scale: CGFloat {
+        return 1.0
+    }
+    
+    private(set) var images: [KFCrossPlatformImage]? {
+        get { return getAssociatedObject(base, &imagesKey) }
+        set { setRetainedAssociatedObject(base, &imagesKey, newValue) }
+    }
+    
+    private(set) var duration: TimeInterval {
+        get { return getAssociatedObject(base, &durationKey) ?? 0.0 }
+        set { setRetainedAssociatedObject(base, &durationKey, newValue) }
+    }
+    
+    var size: CGSize {
+        return base.representations.reduce(.zero) { size, rep in
+            let width = max(size.width, CGFloat(rep.pixelsWide))
+            let height = max(size.height, CGFloat(rep.pixelsHigh))
+            return CGSize(width: width, height: height)
+        }
+    }
+    #else
+    var cgImage: CGImage? { return base.cgImage }
+    var scale: CGFloat { return base.scale }
+    var images: [KFCrossPlatformImage]? { return base.images }
+    var duration: TimeInterval { return base.duration }
+    var size: CGSize { return base.size }
+    
+    /// The image source reference of current image.
+    public var imageSource: CGImageSource? {
+        get {
+            guard let frameSource = frameSource as? CGImageFrameSource else { return nil }
+            return frameSource.imageSource
+        }
+    }
+    
+    /// The custom frame source of current image.
+    public private(set) var frameSource: ImageFrameSource? {
+        get { return getAssociatedObject(base, &imageSourceKey) }
+        set { setRetainedAssociatedObject(base, &imageSourceKey, newValue) }
+    }
+    #endif
+
+    // Bitmap memory cost with bytes.
+    var cost: Int {
+        let pixel = Int(size.width * size.height * scale * scale)
+        guard let cgImage = cgImage else {
+            return pixel * 4
+        }
+        let bytesPerPixel = cgImage.bitsPerPixel / 8
+        guard let imageCount = images?.count else {
+            return pixel * bytesPerPixel
+        }
+        return pixel * bytesPerPixel * imageCount
+    }
+}
+
+// MARK: - Image Conversion
+extension KingfisherWrapper where Base: KFCrossPlatformImage {
+    #if os(macOS)
+    static func image(cgImage: CGImage, scale: CGFloat, refImage: KFCrossPlatformImage?) -> KFCrossPlatformImage {
+        return KFCrossPlatformImage(cgImage: cgImage, size: .zero)
+    }
+    
+    /// Normalize the image. This getter does nothing on macOS but return the image itself.
+    public var normalized: KFCrossPlatformImage { return base }
+
+    #else
+    /// Creating an image from a give `CGImage` at scale and orientation for refImage. The method signature is for
+    /// compatibility of macOS version.
+    static func image(cgImage: CGImage, scale: CGFloat, refImage: KFCrossPlatformImage?) -> KFCrossPlatformImage {
+        return KFCrossPlatformImage(cgImage: cgImage, scale: scale, orientation: refImage?.imageOrientation ?? .up)
+    }
+    
+    /// Returns normalized image for current `base` image.
+    /// This method will try to redraw an image with orientation and scale considered.
+    public var normalized: KFCrossPlatformImage {
+        // prevent animated image (GIF) lose it's images
+        guard images == nil else { return base.copy() as! KFCrossPlatformImage }
+        // No need to do anything if already up
+        guard base.imageOrientation != .up else { return base.copy() as! KFCrossPlatformImage }
+
+        return draw(to: size, inverting: true, refImage: KFCrossPlatformImage()) {
+            fixOrientation(in: $0)
+            return true
+        }
+    }
+
+    func fixOrientation(in context: CGContext) {
+
+        var transform = CGAffineTransform.identity
+
+        let orientation = base.imageOrientation
+
+        switch orientation {
+        case .down, .downMirrored:
+            transform = transform.translatedBy(x: size.width, y: size.height)
+            transform = transform.rotated(by: .pi)
+        case .left, .leftMirrored:
+            transform = transform.translatedBy(x: size.width, y: 0)
+            transform = transform.rotated(by: .pi / 2.0)
+        case .right, .rightMirrored:
+            transform = transform.translatedBy(x: 0, y: size.height)
+            transform = transform.rotated(by: .pi / -2.0)
+        case .up, .upMirrored:
+            break
+        #if compiler(>=5)
+        @unknown default:
+            break
+        #endif
+        }
+
+        //Flip image one more time if needed to, this is to prevent flipped image
+        switch orientation {
+        case .upMirrored, .downMirrored:
+            transform = transform.translatedBy(x: size.width, y: 0)
+            transform = transform.scaledBy(x: -1, y: 1)
+        case .leftMirrored, .rightMirrored:
+            transform = transform.translatedBy(x: size.height, y: 0)
+            transform = transform.scaledBy(x: -1, y: 1)
+        case .up, .down, .left, .right:
+            break
+        #if compiler(>=5)
+        @unknown default:
+            break
+        #endif
+        }
+
+        context.concatenate(transform)
+        switch orientation {
+        case .left, .leftMirrored, .right, .rightMirrored:
+            context.draw(cgImage!, in: CGRect(x: 0, y: 0, width: size.height, height: size.width))
+        default:
+            context.draw(cgImage!, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
+        }
+    }
+    #endif
+}
+
+// MARK: - Image Representation
+extension KingfisherWrapper where Base: KFCrossPlatformImage {
+    /// Returns PNG representation of `base` image.
+    ///
+    /// - Returns: PNG data of image.
+    public func pngRepresentation() -> Data? {
+        #if os(macOS)
+            guard let cgImage = cgImage else {
+                return nil
+            }
+            let rep = NSBitmapImageRep(cgImage: cgImage)
+            return rep.representation(using: .png, properties: [:])
+        #else
+            return base.pngData()
+        #endif
+    }
+
+    /// Returns JPEG representation of `base` image.
+    ///
+    /// - Parameter compressionQuality: The compression quality when converting image to JPEG data.
+    /// - Returns: JPEG data of image.
+    public func jpegRepresentation(compressionQuality: CGFloat) -> Data? {
+        #if os(macOS)
+            guard let cgImage = cgImage else {
+                return nil
+            }
+            let rep = NSBitmapImageRep(cgImage: cgImage)
+            return rep.representation(using:.jpeg, properties: [.compressionFactor: compressionQuality])
+        #else
+            return base.jpegData(compressionQuality: compressionQuality)
+        #endif
+    }
+
+    /// Returns GIF representation of `base` image.
+    ///
+    /// - Returns: Original GIF data of image.
+    public func gifRepresentation() -> Data? {
+        return animatedImageData
+    }
+
+    /// Returns a data representation for `base` image, with the `format` as the format indicator.
+    /// - Parameters:
+    ///   - format: The format in which the output data should be. If `unknown`, the `base` image will be
+    ///             converted in the PNG representation.
+    ///   - compressionQuality: The compression quality when converting image to a lossy format data.
+    ///
+    /// - Returns: The output data representing.
+    public func data(format: ImageFormat, compressionQuality: CGFloat = 1.0) -> Data? {
+        return autoreleasepool { () -> Data? in
+            let data: Data?
+            switch format {
+            case .PNG: data = pngRepresentation()
+            case .JPEG: data = jpegRepresentation(compressionQuality: compressionQuality)
+            case .GIF: data = gifRepresentation()
+            case .unknown: data = normalized.kf.pngRepresentation()
+            }
+            
+            return data
+        }
+    }
+}
+
+// MARK: - Creating Images
+extension KingfisherWrapper where Base: KFCrossPlatformImage {
+
+    /// Creates an animated image from a given data and options. Currently only GIF data is supported.
+    ///
+    /// - Parameters:
+    ///   - data: The animated image data.
+    ///   - options: Options to use when creating the animated image.
+    /// - Returns: An `Image` object represents the animated image. It is in form of an array of image frames with a
+    ///            certain duration. `nil` if anything wrong when creating animated image.
+    public static func animatedImage(data: Data, options: ImageCreatingOptions) -> KFCrossPlatformImage? {
+        #if os(visionOS)
+        let info: [String: Any] = [
+            kCGImageSourceShouldCache as String: true,
+            kCGImageSourceTypeIdentifierHint as String: UTType.gif.identifier
+        ]
+        #else
+        let info: [String: Any] = [
+            kCGImageSourceShouldCache as String: true,
+            kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF
+        ]
+        #endif
+        
+        guard let imageSource = CGImageSourceCreateWithData(data as CFData, info as CFDictionary) else {
+            return nil
+        }
+        let frameSource = CGImageFrameSource(data: data, imageSource: imageSource, options: info)
+        #if os(macOS)
+        let baseImage = KFCrossPlatformImage(data: data)
+        #else
+        let baseImage = KFCrossPlatformImage(data: data, scale: options.scale)
+        #endif
+        return animatedImage(source: frameSource, options: options, baseImage: baseImage)
+    }
+    
+    /// Creates an animated image from a given frame source.
+    ///
+    /// - Parameters:
+    ///   - source: The frame source to create animated image from.
+    ///   - options: Options to use when creating the animated image.
+    ///   - baseImage: An optional image object to be used as the key frame of the animated image. If `nil`, the first
+    ///                frame of the `source` will be used.
+    /// - Returns: An `Image` object represents the animated image. It is in form of an array of image frames with a
+    ///           certain duration. `nil` if anything wrong when creating animated image.
+    public static func animatedImage(source: ImageFrameSource, options: ImageCreatingOptions, baseImage: KFCrossPlatformImage? = nil) -> KFCrossPlatformImage? {
+        #if os(macOS)
+        guard let animatedImage = GIFAnimatedImage(from: source, options: options) else {
+            return nil
+        }
+        var image: KFCrossPlatformImage?
+        if options.onlyFirstFrame {
+            image = animatedImage.images.first
+        } else {
+            if let baseImage = baseImage {
+                image = baseImage
+            } else {
+                image = animatedImage.images.first
+            }
+            var kf = image?.kf
+            kf?.images = animatedImage.images
+            kf?.duration = animatedImage.duration
+        }
+        image?.kf.animatedImageData = source.data
+        image?.kf.imageFrameCount = source.frameCount
+        return image
+        #else
+        
+        var image: KFCrossPlatformImage?
+        if options.preloadAll || options.onlyFirstFrame {
+            // Use `images` image if you want to preload all animated data
+            guard let animatedImage = GIFAnimatedImage(from: source, options: options) else {
+                return nil
+            }
+            if options.onlyFirstFrame {
+                image = animatedImage.images.first
+            } else {
+                let duration = options.duration <= 0.0 ? animatedImage.duration : options.duration
+                image = .animatedImage(with: animatedImage.images, duration: duration)
+            }
+            image?.kf.animatedImageData = source.data
+        } else {
+            if let baseImage = baseImage {
+                image = baseImage
+            } else {
+                guard let firstFrame = source.frame(at: 0) else {
+                    return nil
+                }
+                image = KFCrossPlatformImage(cgImage: firstFrame, scale: options.scale, orientation: .up)
+            }
+            var kf = image?.kf
+            kf?.frameSource = source
+            kf?.animatedImageData = source.data
+        }
+        
+        image?.kf.imageFrameCount = source.frameCount
+        return image
+        #endif
+    }
+
+    /// Creates an image from a given data and options. `.JPEG`, `.PNG` or `.GIF` is supported. For other
+    /// image format, image initializer from system will be used. If no image object could be created from
+    /// the given `data`, `nil` will be returned.
+    ///
+    /// - Parameters:
+    ///   - data: The image data representation.
+    ///   - options: Options to use when creating the image.
+    /// - Returns: An `Image` object represents the image if created. If the `data` is invalid or not supported, `nil`
+    ///            will be returned.
+    public static func image(data: Data, options: ImageCreatingOptions) -> KFCrossPlatformImage? {
+        var image: KFCrossPlatformImage?
+        switch data.kf.imageFormat {
+        case .JPEG:
+            image = KFCrossPlatformImage(data: data, scale: options.scale)
+        case .PNG:
+            image = KFCrossPlatformImage(data: data, scale: options.scale)
+        case .GIF:
+            image = KingfisherWrapper.animatedImage(data: data, options: options)
+        case .unknown:
+            image = KFCrossPlatformImage(data: data, scale: options.scale)
+        }
+        return image
+    }
+    
+    /// Creates a downsampled image from given data to a certain size and scale.
+    ///
+    /// - Parameters:
+    ///   - data: The image data contains a JPEG or PNG image.
+    ///   - pointSize: The target size in point to which the image should be downsampled.
+    ///   - scale: The scale of result image.
+    /// - Returns: A downsampled `Image` object following the input conditions.
+    ///
+    /// - Note:
+    /// Different from image `resize` methods, downsampling will not render the original
+    /// input image in pixel format. It does downsampling from the image data, so it is much
+    /// more memory efficient and friendly. Choose to use downsampling as possible as you can.
+    ///
+    /// The pointsize should be smaller than the size of input image. If it is larger than the
+    /// original image size, the result image will be the same size of input without downsampling.
+    public static func downsampledImage(data: Data, to pointSize: CGSize, scale: CGFloat) -> KFCrossPlatformImage? {
+        let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
+        guard let imageSource = CGImageSourceCreateWithData(data as CFData, imageSourceOptions) else {
+            return nil
+        }
+        
+        let maxDimensionInPixels = max(pointSize.width, pointSize.height) * scale
+        let downsampleOptions: [CFString : Any] = [
+            kCGImageSourceCreateThumbnailFromImageAlways: true,
+            kCGImageSourceShouldCacheImmediately: true,
+            kCGImageSourceCreateThumbnailWithTransform: true,
+            kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels
+        ]
+        guard let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions as CFDictionary) else {
+            return nil
+        }
+        return KingfisherWrapper.image(cgImage: downsampledImage, scale: scale, refImage: nil)
+    }
+}

+ 636 - 0
Pods/Kingfisher/Sources/Image/ImageDrawing.swift

@@ -0,0 +1,636 @@
+//
+//  ImageDrawing.swift
+//  Kingfisher
+//
+//  Created by onevcat on 2018/09/28.
+//
+//  Copyright (c) 2019 Wei Wang <onevcat@gmail.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 Accelerate
+
+#if canImport(AppKit) && !targetEnvironment(macCatalyst)
+import AppKit
+#endif
+#if canImport(UIKit)
+import UIKit
+#endif
+
+// MARK: - Image Transforming
+extension KingfisherWrapper where Base: KFCrossPlatformImage {
+    // MARK: Blend Mode
+    /// Create image from `base` image and apply blend mode.
+    ///
+    /// - parameter blendMode:       The blend mode of creating image.
+    /// - parameter alpha:           The alpha should be used for image.
+    /// - parameter backgroundColor: The background color for the output image.
+    ///
+    /// - returns: An image with blend mode applied.
+    ///
+    /// - Note: This method only works for CG-based image.
+    #if !os(macOS)
+    public func image(withBlendMode blendMode: CGBlendMode,
+                      alpha: CGFloat = 1.0,
+                      backgroundColor: KFCrossPlatformColor? = nil) -> KFCrossPlatformImage
+    {
+        guard let _ = cgImage else {
+            assertionFailure("[Kingfisher] Blend mode image only works for CG-based image.")
+            return base
+        }
+        
+        let rect = CGRect(origin: .zero, size: size)
+        return draw(to: rect.size, inverting: false) { _ in
+            if let backgroundColor = backgroundColor {
+                backgroundColor.setFill()
+                UIRectFill(rect)
+            }
+            
+            base.draw(in: rect, blendMode: blendMode, alpha: alpha)
+            return false
+        }
+    }
+    #endif
+    
+    #if os(macOS)
+    // MARK: Compositing
+    /// Creates image from `base` image and apply compositing operation.
+    ///
+    /// - Parameters:
+    ///   - compositingOperation: The compositing operation of creating image.
+    ///   - alpha: The alpha should be used for image.
+    ///   - backgroundColor: The background color for the output image.
+    /// - Returns: An image with compositing operation applied.
+    ///
+    /// - Note: This method only works for CG-based image. For any non-CG-based image, `base` itself is returned.
+    public func image(withCompositingOperation compositingOperation: NSCompositingOperation,
+                      alpha: CGFloat = 1.0,
+                      backgroundColor: KFCrossPlatformColor? = nil) -> KFCrossPlatformImage
+    {
+        guard let _ = cgImage else {
+            assertionFailure("[Kingfisher] Compositing Operation image only works for CG-based image.")
+            return base
+        }
+        
+        let rect = CGRect(origin: .zero, size: size)
+        return draw(to: rect.size, inverting: false) { _ in
+            if let backgroundColor = backgroundColor {
+                backgroundColor.setFill()
+                rect.fill()
+            }
+            base.draw(in: rect, from: .zero, operation: compositingOperation, fraction: alpha)
+            return false
+        }
+    }
+    #endif
+    
+    // MARK: Round Corner
+    
+    /// Creates a round corner image from on `base` image.
+    ///
+    /// - Parameters:
+    ///   - radius: The round corner radius of creating image.
+    ///   - size: The target size of creating image.
+    ///   - corners: The target corners which will be applied rounding.
+    ///   - backgroundColor: The background color for the output image
+    /// - Returns: An image with round corner of `self`.
+    ///
+    /// - Note: This method only works for CG-based image. The current image scale is kept.
+    ///         For any non-CG-based image, `base` itself is returned.
+    public func image(
+        withRadius radius: Radius,
+        fit size: CGSize,
+        roundingCorners corners: RectCorner = .all,
+        backgroundColor: KFCrossPlatformColor? = nil
+    ) -> KFCrossPlatformImage
+    {
+
+        guard let _ = cgImage else {
+            assertionFailure("[Kingfisher] Round corner image only works for CG-based image.")
+            return base
+        }
+        
+        let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
+        return draw(to: size, inverting: false) { _ in
+            #if os(macOS)
+            if let backgroundColor = backgroundColor {
+                let rectPath = NSBezierPath(rect: rect)
+                backgroundColor.setFill()
+                rectPath.fill()
+            }
+            
+            let path = pathForRoundCorner(rect: rect, radius: radius, corners: corners)
+            path.addClip()
+            base.draw(in: rect)
+            #else
+            guard let context = UIGraphicsGetCurrentContext() else {
+                assertionFailure("[Kingfisher] Failed to create CG context for image.")
+                return false
+            }
+            
+            if let backgroundColor = backgroundColor {
+                let rectPath = UIBezierPath(rect: rect)
+                backgroundColor.setFill()
+                rectPath.fill()
+            }
+            
+            let path = pathForRoundCorner(rect: rect, radius: radius, corners: corners)
+            context.addPath(path.cgPath)
+            context.clip()
+            base.draw(in: rect)
+            #endif
+            return false
+        }
+    }
+    
+    /// Creates a round corner image from on `base` image.
+    ///
+    /// - Parameters:
+    ///   - radius: The round corner radius of creating image.
+    ///   - size: The target size of creating image.
+    ///   - corners: The target corners which will be applied rounding.
+    ///   - backgroundColor: The background color for the output image
+    /// - Returns: An image with round corner of `self`.
+    ///
+    /// - Note: This method only works for CG-based image. The current image scale is kept.
+    ///         For any non-CG-based image, `base` itself is returned.
+    public func image(
+        withRoundRadius radius: CGFloat,
+        fit size: CGSize,
+        roundingCorners corners: RectCorner = .all,
+        backgroundColor: KFCrossPlatformColor? = nil
+    ) -> KFCrossPlatformImage
+    {
+        image(withRadius: .point(radius), fit: size, roundingCorners: corners, backgroundColor: backgroundColor)
+    }
+    
+    #if os(macOS)
+    func pathForRoundCorner(rect: CGRect, radius: Radius, corners: RectCorner, offsetBase: CGFloat = 0) -> NSBezierPath {
+        let cornerRadius = radius.compute(with: rect.size)
+        let path = NSBezierPath(roundedRect: rect, byRoundingCorners: corners, radius: cornerRadius - offsetBase / 2)
+        path.windingRule = .evenOdd
+        return path
+    }
+    #else
+    func pathForRoundCorner(rect: CGRect, radius: Radius, corners: RectCorner, offsetBase: CGFloat = 0) -> UIBezierPath {
+        let cornerRadius = radius.compute(with: rect.size)
+        return UIBezierPath(
+            roundedRect: rect,
+            byRoundingCorners: corners.uiRectCorner,
+            cornerRadii: CGSize(
+                width: cornerRadius - offsetBase / 2,
+                height: cornerRadius - offsetBase / 2
+            )
+        )
+    }
+    #endif
+    
+    #if os(iOS) || os(tvOS) || os(visionOS)
+    func resize(to size: CGSize, for contentMode: UIView.ContentMode) -> KFCrossPlatformImage {
+        switch contentMode {
+        case .scaleAspectFit:
+            return resize(to: size, for: .aspectFit)
+        case .scaleAspectFill:
+            return resize(to: size, for: .aspectFill)
+        default:
+            return resize(to: size)
+        }
+    }
+    #endif
+    
+    // MARK: Resizing
+    /// Resizes `base` image to an image with new size.
+    ///
+    /// - Parameter size: The target size in point.
+    /// - Returns: An image with new size.
+    /// - Note: This method only works for CG-based image. The current image scale is kept.
+    ///         For any non-CG-based image, `base` itself is returned.
+    public func resize(to size: CGSize) -> KFCrossPlatformImage {
+        guard let _ = cgImage else {
+            assertionFailure("[Kingfisher] Resize only works for CG-based image.")
+            return base
+        }
+        
+        let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
+        return draw(to: size, inverting: false) { _ in
+            #if os(macOS)
+            base.draw(in: rect, from: .zero, operation: .copy, fraction: 1.0)
+            #else
+            base.draw(in: rect)
+            #endif
+            return false
+        }
+    }
+    
+    /// Resizes `base` image to an image of new size, respecting the given content mode.
+    ///
+    /// - Parameters:
+    ///   - targetSize: The target size in point.
+    ///   - contentMode: Content mode of output image should be.
+    /// - Returns: An image with new size.
+    ///
+    /// - Note: This method only works for CG-based image. The current image scale is kept.
+    ///         For any non-CG-based image, `base` itself is returned.
+    public func resize(to targetSize: CGSize, for contentMode: ContentMode) -> KFCrossPlatformImage {
+        let newSize = size.kf.resize(to: targetSize, for: contentMode)
+        return resize(to: newSize)
+    }
+
+    // MARK: Cropping
+    /// Crops `base` image to a new size with a given anchor.
+    ///
+    /// - Parameters:
+    ///   - size: The target size.
+    ///   - anchor: The anchor point from which the size should be calculated.
+    /// - Returns: An image with new size.
+    ///
+    /// - Note: This method only works for CG-based image. The current image scale is kept.
+    ///         For any non-CG-based image, `base` itself is returned.
+    public func crop(to size: CGSize, anchorOn anchor: CGPoint) -> KFCrossPlatformImage {
+        guard let cgImage = cgImage else {
+            assertionFailure("[Kingfisher] Crop only works for CG-based image.")
+            return base
+        }
+        
+        let rect = self.size.kf.constrainedRect(for: size, anchor: anchor)
+        guard let image = cgImage.cropping(to: rect.scaled(scale)) else {
+            assertionFailure("[Kingfisher] Cropping image failed.")
+            return base
+        }
+        
+        return KingfisherWrapper.image(cgImage: image, scale: scale, refImage: base)
+    }
+    
+    // MARK: Blur
+    /// Creates an image with blur effect based on `base` image.
+    ///
+    /// - Parameter radius: The blur radius should be used when creating blur effect.
+    /// - Returns: An image with blur effect applied.
+    ///
+    /// - Note: This method only works for CG-based image. The current image scale is kept.
+    ///         For any non-CG-based image, `base` itself is returned.
+    public func blurred(withRadius radius: CGFloat) -> KFCrossPlatformImage {
+        
+        guard let cgImage = cgImage else {
+            assertionFailure("[Kingfisher] Blur only works for CG-based image.")
+            return base
+        }
+        
+        // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
+        // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
+        // if d is odd, use three box-blurs of size 'd', centered on the output pixel.
+        let s = max(radius, 2.0)
+        // We will do blur on a resized image (*0.5), so the blur radius could be half as well.
+        
+        // Fix the slow compiling time for Swift 3.
+        // See https://github.com/onevcat/Kingfisher/issues/611
+        let pi2 = 2 * CGFloat.pi
+        let sqrtPi2 = sqrt(pi2)
+        var targetRadius = floor(s * 3.0 * sqrtPi2 / 4.0 + 0.5)
+        
+        if targetRadius.isEven { targetRadius += 1 }
+
+        // Determine necessary iteration count by blur radius.
+        let iterations: Int
+        if radius < 0.5 {
+            iterations = 1
+        } else if radius < 1.5 {
+            iterations = 2
+        } else {
+            iterations = 3
+        }
+        
+        let w = Int(size.width)
+        let h = Int(size.height)
+        
+        func createEffectBuffer(_ context: CGContext) -> vImage_Buffer {
+            let data = context.data
+            let width = vImagePixelCount(context.width)
+            let height = vImagePixelCount(context.height)
+            let rowBytes = context.bytesPerRow
+            
+            return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes)
+        }
+        GraphicsContext.begin(size: size, scale: scale)
+        guard let context = GraphicsContext.current(size: size, scale: scale, inverting: true, cgImage: cgImage) else {
+            assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
+            return base
+        }
+        context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h))
+        GraphicsContext.end()
+        
+        var inBuffer = createEffectBuffer(context)
+        
+        GraphicsContext.begin(size: size, scale: scale)
+        guard let outContext = GraphicsContext.current(size: size, scale: scale, inverting: true, cgImage: cgImage) else {
+            assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
+            return base
+        }
+        defer { GraphicsContext.end() }
+        var outBuffer = createEffectBuffer(outContext)
+        
+        for _ in 0 ..< iterations {
+            let flag = vImage_Flags(kvImageEdgeExtend)
+            vImageBoxConvolve_ARGB8888(
+                &inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, flag)
+            // Next inBuffer should be the outButter of current iteration
+            (inBuffer, outBuffer) = (outBuffer, inBuffer)
+        }
+        
+        #if os(macOS)
+        let result = outContext.makeImage().flatMap {
+            fixedForRetinaPixel(cgImage: $0, to: size)
+        }
+        #else
+        let result = outContext.makeImage().flatMap {
+            KFCrossPlatformImage(cgImage: $0, scale: base.scale, orientation: base.imageOrientation)
+        }
+        #endif
+        guard let blurredImage = result else {
+            assertionFailure("[Kingfisher] Can not make an blurred image within this context.")
+            return base
+        }
+        
+        return blurredImage
+    }
+    
+    public func addingBorder(_ border: Border) -> KFCrossPlatformImage
+    {
+        guard let _ = cgImage else {
+            assertionFailure("[Kingfisher] Blend mode image only works for CG-based image.")
+            return base
+        }
+        
+        let rect = CGRect(origin: .zero, size: size)
+        return draw(to: rect.size, inverting: false) { context in
+            
+            #if os(macOS)
+            base.draw(in: rect)
+            #else
+            base.draw(in: rect, blendMode: .normal, alpha: 1.0)
+            #endif
+            
+            
+            let strokeRect =  rect.insetBy(dx: border.lineWidth / 2, dy: border.lineWidth / 2)
+            context.setStrokeColor(border.color.cgColor)
+            context.setAlpha(border.color.rgba.a)
+            
+            let line = pathForRoundCorner(
+                rect: strokeRect,
+                radius: border.radius,
+                corners: border.roundingCorners,
+                offsetBase: border.lineWidth
+            )
+            line.lineCapStyle = .square
+            line.lineWidth = border.lineWidth
+            line.stroke()
+            
+            return false
+        }
+    }
+    
+    // MARK: Overlay
+    /// Creates an image from `base` image with a color overlay layer.
+    ///
+    /// - Parameters:
+    ///   - color: The color should be use to overlay.
+    ///   - fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color,
+    ///               1.0 means transparent overlay.
+    /// - Returns: An image with a color overlay applied.
+    ///
+    /// - Note: This method only works for CG-based image. The current image scale is kept.
+    ///         For any non-CG-based image, `base` itself is returned.
+    public func overlaying(with color: KFCrossPlatformColor, fraction: CGFloat) -> KFCrossPlatformImage {
+        
+        guard let _ = cgImage else {
+            assertionFailure("[Kingfisher] Overlaying only works for CG-based image.")
+            return base
+        }
+        
+        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
+        return draw(to: rect.size, inverting: false) { context in
+            #if os(macOS)
+            base.draw(in: rect)
+            if fraction > 0 {
+                color.withAlphaComponent(1 - fraction).set()
+                rect.fill(using: .sourceAtop)
+            }
+            #else
+            color.set()
+            UIRectFill(rect)
+            base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0)
+            
+            if fraction > 0 {
+                base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction)
+            }
+            #endif
+            return false
+        }
+    }
+    
+    // MARK: Tint
+    /// Creates an image from `base` image with a color tint.
+    ///
+    /// - Parameter color: The color should be used to tint `base`
+    /// - Returns: An image with a color tint applied.
+    public func tinted(with color: KFCrossPlatformColor) -> KFCrossPlatformImage {
+        #if os(watchOS)
+        return base
+        #else
+        return apply(.tint(color))
+        #endif
+    }
+    
+    // MARK: Color Control
+    
+    /// Create an image from `self` with color control.
+    ///
+    /// - Parameters:
+    ///   - brightness: Brightness changing to image.
+    ///   - contrast: Contrast changing to image.
+    ///   - saturation: Saturation changing to image.
+    ///   - inputEV: InputEV changing to image.
+    /// - Returns:  An image with color control applied.
+    public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> KFCrossPlatformImage {
+        #if os(watchOS)
+        return base
+        #else
+        return apply(.colorControl((brightness, contrast, saturation, inputEV)))
+        #endif
+    }
+    
+    /// Return an image with given scale.
+    ///
+    /// - Parameter scale: Target scale factor the new image should have.
+    /// - Returns: The image with target scale. If the base image is already in the scale, `base` will be returned.
+    public func scaled(to scale: CGFloat) -> KFCrossPlatformImage {
+        guard scale != self.scale else {
+            return base
+        }
+        guard let cgImage = cgImage else {
+            assertionFailure("[Kingfisher] Scaling only works for CG-based image.")
+            return base
+        }
+        return KingfisherWrapper.image(cgImage: cgImage, scale: scale, refImage: base)
+    }
+}
+
+// MARK: - Decoding Image
+extension KingfisherWrapper where Base: KFCrossPlatformImage {
+    
+    /// Returns the decoded image of the `base` image. It will draw the image in a plain context and return the data
+    /// from it. This could improve the drawing performance when an image is just created from data but not yet
+    /// displayed for the first time.
+    ///
+    /// - Note: This method only works for CG-based image. The current image scale is kept.
+    ///         For any non-CG-based image or animated image, `base` itself is returned.
+    public var decoded: KFCrossPlatformImage { return decoded(scale: scale) }
+    
+    /// Returns decoded image of the `base` image at a given scale. It will draw the image in a plain context and
+    /// return the data from it. This could improve the drawing performance when an image is just created from
+    /// data but not yet displayed for the first time.
+    ///
+    /// - Parameter scale: The given scale of target image should be.
+    /// - Returns: The decoded image ready to be displayed.
+    ///
+    /// - Note: This method only works for CG-based image. The current image scale is kept.
+    ///         For any non-CG-based image or animated image, `base` itself is returned.
+    public func decoded(scale: CGFloat) -> KFCrossPlatformImage {
+        // Prevent animated image (GIF) losing it's images
+        #if os(iOS) || os(visionOS)
+        if frameSource != nil { return base }
+        #else
+        if images != nil { return base }
+        #endif
+
+        guard let imageRef = cgImage else {
+            assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
+            return base
+        }
+
+        let size = CGSize(width: CGFloat(imageRef.width) / scale, height: CGFloat(imageRef.height) / scale)
+        return draw(to: size, inverting: true, scale: scale) { context in
+            context.draw(imageRef, in: CGRect(origin: .zero, size: size))
+            return true
+        }
+    }
+
+    /// Returns decoded image of the `base` image at a given scale. It will draw the image in a plain context and
+    /// return the data from it. This could improve the drawing performance when an image is just created from
+    /// data but not yet displayed for the first time.
+    ///
+    /// - Parameter context: The context for drawing.
+    /// - Returns: The decoded image ready to be displayed.
+    ///
+    /// - Note: This method only works for CG-based image. The current image scale is kept.
+    ///         For any non-CG-based image or animated image, `base` itself is returned.
+    public func decoded(on context: CGContext) -> KFCrossPlatformImage {
+        // Prevent animated image (GIF) losing it's images
+        #if os(iOS) || os(visionOS)
+        if frameSource != nil { return base }
+        #else
+        if images != nil { return base }
+        #endif
+
+        guard let refImage = cgImage,
+              let decodedRefImage = refImage.decoded(on: context, scale: scale) else
+        {
+            assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
+            return base
+        }
+        return KingfisherWrapper.image(cgImage: decodedRefImage, scale: scale, refImage: base)
+    }
+}
+
+extension CGImage {
+    func decoded(on context: CGContext, scale: CGFloat) -> CGImage? {
+        let size = CGSize(width: CGFloat(self.width) / scale, height: CGFloat(self.height) / scale)
+        context.draw(self, in: CGRect(origin: .zero, size: size))
+        guard let decodedImageRef = context.makeImage() else {
+            return nil
+        }
+        return decodedImageRef
+    }
+}
+
+extension KingfisherWrapper where Base: KFCrossPlatformImage {
+    func draw(
+        to size: CGSize,
+        inverting: Bool,
+        scale: CGFloat? = nil,
+        refImage: KFCrossPlatformImage? = nil,
+        draw: (CGContext) -> Bool // Whether use the refImage (`true`) or ignore image orientation (`false`)
+    ) -> KFCrossPlatformImage
+    {
+        #if os(macOS) || os(watchOS)
+        let targetScale = scale ?? self.scale
+        GraphicsContext.begin(size: size, scale: targetScale)
+        guard let context = GraphicsContext.current(size: size, scale: targetScale, inverting: inverting, cgImage: cgImage) else {
+            assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
+            return base
+        }
+        defer { GraphicsContext.end() }
+        let useRefImage = draw(context)
+        guard let cgImage = context.makeImage() else {
+            return base
+        }
+        let ref = useRefImage ? (refImage ?? base) : nil
+        return KingfisherWrapper.image(cgImage: cgImage, scale: targetScale, refImage: ref)
+        #else
+        
+        let format = UIGraphicsImageRendererFormat.preferred()
+        format.scale = scale ?? self.scale
+        let renderer = UIGraphicsImageRenderer(size: size, format: format)
+        
+        var useRefImage: Bool = false
+        let image = renderer.image { rendererContext in
+            
+            let context = rendererContext.cgContext
+            if inverting { // If drawing a CGImage, we need to make context flipped.
+                context.scaleBy(x: 1.0, y: -1.0)
+                context.translateBy(x: 0, y: -size.height)
+            }
+            
+            useRefImage = draw(context)
+        }
+        if useRefImage {
+            guard let cgImage = image.cgImage else {
+                return base
+            }
+            let ref = refImage ?? base
+            return KingfisherWrapper.image(cgImage: cgImage, scale: format.scale, refImage: ref)
+        } else {
+            return image
+        }
+        #endif
+    }
+    
+    #if os(macOS)
+    func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> KFCrossPlatformImage {
+        
+        let image = KFCrossPlatformImage(cgImage: cgImage, size: base.size)
+        let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
+        
+        return draw(to: self.size, inverting: false) { context in
+            image.draw(in: rect, from: .zero, operation: .copy, fraction: 1.0)
+            return false
+        }
+    }
+    #endif
+}

+ 130 - 0
Pods/Kingfisher/Sources/Image/ImageFormat.swift

@@ -0,0 +1,130 @@
+//
+//  ImageFormat.swift
+//  Kingfisher
+//
+//  Created by onevcat on 2018/09/28.
+//
+//  Copyright (c) 2019 Wei Wang <onevcat@gmail.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
+
+/// Represents image format.
+///
+/// - unknown: The format cannot be recognized or not supported yet.
+/// - PNG: PNG image format.
+/// - JPEG: JPEG image format.
+/// - GIF: GIF image format.
+public enum ImageFormat {
+    /// The format cannot be recognized or not supported yet.
+    case unknown
+    /// PNG image format.
+    case PNG
+    /// JPEG image format.
+    case JPEG
+    /// GIF image format.
+    case GIF
+    
+    struct HeaderData {
+        static var PNG: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
+        static var JPEG_SOI: [UInt8] = [0xFF, 0xD8]
+        static var JPEG_IF: [UInt8] = [0xFF]
+        static var GIF: [UInt8] = [0x47, 0x49, 0x46]
+    }
+    
+    /// https://en.wikipedia.org/wiki/JPEG
+    public enum JPEGMarker {
+        case SOF0           //baseline
+        case SOF2           //progressive
+        case DHT            //Huffman Table
+        case DQT            //Quantization Table
+        case DRI            //Restart Interval
+        case SOS            //Start Of Scan
+        case RSTn(UInt8)    //Restart
+        case APPn           //Application-specific
+        case COM            //Comment
+        case EOI            //End Of Image
+        
+        var bytes: [UInt8] {
+            switch self {
+            case .SOF0:         return [0xFF, 0xC0]
+            case .SOF2:         return [0xFF, 0xC2]
+            case .DHT:          return [0xFF, 0xC4]
+            case .DQT:          return [0xFF, 0xDB]
+            case .DRI:          return [0xFF, 0xDD]
+            case .SOS:          return [0xFF, 0xDA]
+            case .RSTn(let n):  return [0xFF, 0xD0 + n]
+            case .APPn:         return [0xFF, 0xE0]
+            case .COM:          return [0xFF, 0xFE]
+            case .EOI:          return [0xFF, 0xD9]
+            }
+        }
+    }
+}
+
+
+extension Data: KingfisherCompatibleValue {}
+
+// MARK: - Misc Helpers
+extension KingfisherWrapper where Base == Data {
+    /// Gets the image format corresponding to the data.
+    public var imageFormat: ImageFormat {
+        guard base.count > 8 else { return .unknown }
+        
+        var buffer = [UInt8](repeating: 0, count: 8)
+        base.copyBytes(to: &buffer, count: 8)
+        
+        if buffer == ImageFormat.HeaderData.PNG {
+            return .PNG
+            
+        } else if buffer[0] == ImageFormat.HeaderData.JPEG_SOI[0],
+            buffer[1] == ImageFormat.HeaderData.JPEG_SOI[1],
+            buffer[2] == ImageFormat.HeaderData.JPEG_IF[0]
+        {
+            return .JPEG
+            
+        } else if buffer[0] == ImageFormat.HeaderData.GIF[0],
+            buffer[1] == ImageFormat.HeaderData.GIF[1],
+            buffer[2] == ImageFormat.HeaderData.GIF[2]
+        {
+            return .GIF
+        }
+        
+        return .unknown
+    }
+    
+    public func contains(jpeg marker: ImageFormat.JPEGMarker) -> Bool {
+        guard imageFormat == .JPEG else {
+            return false
+        }
+        
+        let bytes = [UInt8](base)
+        let markerBytes = marker.bytes
+        for (index, item) in bytes.enumerated() where bytes.count > index + 1 {
+            guard
+                item == markerBytes.first,
+                bytes[index + 1] == markerBytes[1] else {
+                continue
+            }
+            return true
+        }
+        return false
+    }
+}

+ 922 - 0
Pods/Kingfisher/Sources/Image/ImageProcessor.swift

@@ -0,0 +1,922 @@
+//
+//  ImageProcessor.swift
+//  Kingfisher
+//
+//  Created by Wei Wang on 2016/08/26.
+//
+//  Copyright (c) 2019 Wei Wang <onevcat@gmail.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
+import CoreGraphics
+
+#if canImport(AppKit) && !targetEnvironment(macCatalyst)
+import AppKit
+#else
+import UIKit
+#endif
+
+/// Represents an item which could be processed by an `ImageProcessor`.
+///
+/// - image: Input image. The processor should provide a way to apply
+///          processing on this `image` and return the result image.
+/// - data:  Input data. The processor should provide a way to apply
+///          processing on this `data` and return the result image.
+public enum ImageProcessItem {
+    
+    /// Input image. The processor should provide a way to apply
+    /// processing on this `image` and return the result image.
+    case image(KFCrossPlatformImage)
+    
+    /// Input data. The processor should provide a way to apply
+    /// processing on this `data` and return the result image.
+    case data(Data)
+}
+
+/// An `ImageProcessor` would be used to convert some downloaded data to an image.
+public protocol ImageProcessor {
+    /// Identifier of the processor. It will be used to identify the processor when 
+    /// caching and retrieving an image. You might want to make sure that processors with
+    /// same properties/functionality have the same identifiers, so correct processed images
+    /// could be retrieved with proper key.
+    /// 
+    /// - Note: Do not supply an empty string for a customized processor, which is already reserved by
+    /// the `DefaultImageProcessor`. It is recommended to use a reverse domain name notation string of
+    /// your own for the identifier.
+    var identifier: String { get }
+
+    /// Processes the input `ImageProcessItem` with this processor.
+    ///
+    /// - Parameters:
+    ///   - item: Input item which will be processed by `self`.
+    ///   - options: The parsed options when processing the item.
+    /// - Returns: The processed image.
+    ///
+    /// - Note: The return value should be `nil` if processing failed while converting an input item to image.
+    ///         If `nil` received by the processing caller, an error will be reported and the process flow stops.
+    ///         If the processing flow is not critical for your flow, then when the input item is already an image
+    ///         (`.image` case) and there is any errors in the processing, you could return the input image itself
+    ///         to keep the processing pipeline continuing.
+    /// - Note: Most processor only supports CG-based images. watchOS is not supported for processors containing
+    ///         a filter, the input image will be returned directly on watchOS.
+    func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage?
+}
+
+extension ImageProcessor {
+    
+    /// Appends an `ImageProcessor` to another. The identifier of the new `ImageProcessor`
+    /// will be "\(self.identifier)|>\(another.identifier)".
+    ///
+    /// - Parameter another: An `ImageProcessor` you want to append to `self`.
+    /// - Returns: The new `ImageProcessor` will process the image in the order
+    ///            of the two processors concatenated.
+    public func append(another: ImageProcessor) -> ImageProcessor {
+        let newIdentifier = identifier.appending("|>\(another.identifier)")
+        return GeneralProcessor(identifier: newIdentifier) {
+            item, options in
+            if let image = self.process(item: item, options: options) {
+                return another.process(item: .image(image), options: options)
+            } else {
+                return nil
+            }
+        }
+    }
+}
+
+func ==(left: ImageProcessor, right: ImageProcessor) -> Bool {
+    return left.identifier == right.identifier
+}
+
+func !=(left: ImageProcessor, right: ImageProcessor) -> Bool {
+    return !(left == right)
+}
+
+typealias ProcessorImp = ((ImageProcessItem, KingfisherParsedOptionsInfo) -> KFCrossPlatformImage?)
+struct GeneralProcessor: ImageProcessor {
+    let identifier: String
+    let p: ProcessorImp
+    func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
+        return p(item, options)
+    }
+}
+
+/// The default processor. It converts the input data to a valid image.
+/// Images of .PNG, .JPEG and .GIF format are supported.
+/// If an image item is given as `.image` case, `DefaultImageProcessor` will
+/// do nothing on it and return the associated image.
+public struct DefaultImageProcessor: ImageProcessor {
+    
+    /// A default `DefaultImageProcessor` could be used across.
+    public static let `default` = DefaultImageProcessor()
+    
+    /// Identifier of the processor.
+    /// - Note: See documentation of `ImageProcessor` protocol for more.
+    public let identifier = ""
+    
+    /// Creates a `DefaultImageProcessor`. Use `DefaultImageProcessor.default` to get an instance,
+    /// if you do not have a good reason to create your own `DefaultImageProcessor`.
+    public init() {}
+    
+    /// Processes the input `ImageProcessItem` with this processor.
+    ///
+    /// - Parameters:
+    ///   - item: Input item which will be processed by `self`.
+    ///   - options: Options when processing the item.
+    /// - Returns: The processed image.
+    ///
+    /// - Note: See documentation of `ImageProcessor` protocol for more.
+    public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
+        switch item {
+        case .image(let image):
+            return image.kf.scaled(to: options.scaleFactor)
+        case .data(let data):
+            return KingfisherWrapper.image(data: data, options: options.imageCreatingOptions)
+        }
+    }
+}
+
+/// Represents the rect corner setting when processing a round corner image.
+public struct RectCorner: OptionSet {
+    
+    /// Raw value of the rect corner.
+    public let rawValue: Int
+    
+    /// Represents the top left corner.
+    public static let topLeft = RectCorner(rawValue: 1 << 0)
+    
+    /// Represents the top right corner.
+    public static let topRight = RectCorner(rawValue: 1 << 1)
+    
+    /// Represents the bottom left corner.
+    public static let bottomLeft = RectCorner(rawValue: 1 << 2)
+    
+    /// Represents the bottom right corner.
+    public static let bottomRight = RectCorner(rawValue: 1 << 3)
+    
+    /// Represents all corners.
+    public static let all: RectCorner = [.topLeft, .topRight, .bottomLeft, .bottomRight]
+    
+    /// Creates a `RectCorner` option set with a given value.
+    ///
+    /// - Parameter rawValue: The value represents a certain corner option.
+    public init(rawValue: Int) {
+        self.rawValue = rawValue
+    }
+    
+    var cornerIdentifier: String {
+        if self == .all {
+            return ""
+        }
+        return "_corner(\(rawValue))"
+    }
+}
+
+#if !os(macOS)
+/// Processor for adding an blend mode to images. Only CG-based images are supported.
+public struct BlendImageProcessor: ImageProcessor {
+
+    /// Identifier of the processor.
+    /// - Note: See documentation of `ImageProcessor` protocol for more.
+    public let identifier: String
+
+    /// Blend Mode will be used to blend the input image.
+    public let blendMode: CGBlendMode
+
+    /// Alpha will be used when blend image.
+    public let alpha: CGFloat
+
+    /// Background color of the output image. If `nil`, it will stay transparent.
+    public let backgroundColor: KFCrossPlatformColor?
+
+    /// Creates a `BlendImageProcessor`.
+    ///
+    /// - Parameters:
+    ///   - blendMode: Blend Mode will be used to blend the input image.
+    ///   - alpha: Alpha will be used when blend image. From 0.0 to 1.0. 1.0 means solid image,
+    ///            0.0 means transparent image (not visible at all). Default is 1.0.
+    ///   - backgroundColor: Background color to apply for the output image. Default is `nil`.
+    public init(blendMode: CGBlendMode, alpha: CGFloat = 1.0, backgroundColor: KFCrossPlatformColor? = nil) {
+        self.blendMode = blendMode
+        self.alpha = alpha
+        self.backgroundColor = backgroundColor
+        var identifier = "com.onevcat.Kingfisher.BlendImageProcessor(\(blendMode.rawValue),\(alpha))"
+        if let color = backgroundColor {
+            identifier.append("_\(color.rgbaDescription)")
+        }
+        self.identifier = identifier
+    }
+
+    /// Processes the input `ImageProcessItem` with this processor.
+    ///
+    /// - Parameters:
+    ///   - item: Input item which will be processed by `self`.
+    ///   - options: Options when processing the item.
+    /// - Returns: The processed image.
+    ///
+    /// - Note: See documentation of `ImageProcessor` protocol for more.
+    public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
+        switch item {
+        case .image(let image):
+            return image.kf.scaled(to: options.scaleFactor)
+                        .kf.image(withBlendMode: blendMode, alpha: alpha, backgroundColor: backgroundColor)
+        case .data:
+            return (DefaultImageProcessor.default |> self).process(item: item, options: options)
+        }
+    }
+}
+#endif
+
+#if os(macOS)
+/// Processor for adding an compositing operation to images. Only CG-based images are supported in macOS.
+public struct CompositingImageProcessor: ImageProcessor {
+
+    /// Identifier of the processor.
+    /// - Note: See documentation of `ImageProcessor` protocol for more.
+    public let identifier: String
+
+    /// Compositing operation will be used to the input image.
+    public let compositingOperation: NSCompositingOperation
+
+    /// Alpha will be used when compositing image.
+    public let alpha: CGFloat
+
+    /// Background color of the output image. If `nil`, it will stay transparent.
+    public let backgroundColor: KFCrossPlatformColor?
+
+    /// Creates a `CompositingImageProcessor`
+    ///
+    /// - Parameters:
+    ///   - compositingOperation: Compositing operation will be used to the input image.
+    ///   - alpha: Alpha will be used when compositing image.
+    ///            From 0.0 to 1.0. 1.0 means solid image, 0.0 means transparent image.
+    ///            Default is 1.0.
+    ///   - backgroundColor: Background color to apply for the output image. Default is `nil`.
+    public init(compositingOperation: NSCompositingOperation,
+                alpha: CGFloat = 1.0,
+                backgroundColor: KFCrossPlatformColor? = nil)
+    {
+        self.compositingOperation = compositingOperation
+        self.alpha = alpha
+        self.backgroundColor = backgroundColor
+        var identifier = "com.onevcat.Kingfisher.CompositingImageProcessor(\(compositingOperation.rawValue),\(alpha))"
+        if let color = backgroundColor {
+            identifier.append("_\(color.rgbaDescription)")
+        }
+        self.identifier = identifier
+    }
+
+    /// Processes the input `ImageProcessItem` with this processor.
+    ///
+    /// - Parameters:
+    ///   - item: Input item which will be processed by `self`.
+    ///   - options: Options when processing the item.
+    /// - Returns: The processed image.
+    ///
+    /// - Note: See documentation of `ImageProcessor` protocol for more.
+    public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
+        switch item {
+        case .image(let image):
+            return image.kf.scaled(to: options.scaleFactor)
+                        .kf.image(
+                            withCompositingOperation: compositingOperation,
+                            alpha: alpha,
+                            backgroundColor: backgroundColor)
+        case .data:
+            return (DefaultImageProcessor.default |> self).process(item: item, options: options)
+        }
+    }
+}
+#endif
+
+/// Represents a radius specified in a `RoundCornerImageProcessor`.
+public enum Radius {
+    /// The radius should be calculated as a fraction of the image width. Typically the associated value should be
+    /// between 0 and 0.5, where 0 represents no radius and 0.5 represents using half of the image width.
+    case widthFraction(CGFloat)
+    /// The radius should be calculated as a fraction of the image height. Typically the associated value should be
+    /// between 0 and 0.5, where 0 represents no radius and 0.5 represents using half of the image height.
+    case heightFraction(CGFloat)
+    /// Use a fixed point value as the round corner radius.
+    case point(CGFloat)
+
+    var radiusIdentifier: String {
+        switch self {
+        case .widthFraction(let f):
+            return "w_frac_\(f)"
+        case .heightFraction(let f):
+            return "h_frac_\(f)"
+        case .point(let p):
+            return p.description
+        }
+    }
+    
+    public func compute(with size: CGSize) -> CGFloat {
+        let cornerRadius: CGFloat
+        switch self {
+        case .point(let point):
+            cornerRadius = point
+        case .widthFraction(let widthFraction):
+            cornerRadius = size.width * widthFraction
+        case .heightFraction(let heightFraction):
+            cornerRadius = size.height * heightFraction
+        }
+        return cornerRadius
+    }
+}
+
+/// Processor for making round corner images. Only CG-based images are supported in macOS, 
+/// if a non-CG image passed in, the processor will do nothing.
+///
+/// - Note: The input image will be rendered with round corner pixels removed. If the image itself does not contain
+/// alpha channel (for example, a JPEG image), the processed image will contain an alpha channel in memory in order
+/// to show correctly. However, when cached to disk, Kingfisher respects the original image format by default. That
+/// means the alpha channel will be removed for these images. When you load the processed image from cache again, you
+/// will lose transparent corner.
+///
+/// You could use `FormatIndicatedCacheSerializer.png` to force Kingfisher to serialize the image to PNG format in this
+/// case.
+///
+public struct RoundCornerImageProcessor: ImageProcessor {
+
+    /// Identifier of the processor.
+    /// - Note: See documentation of `ImageProcessor` protocol for more.
+    public let identifier: String
+
+    /// The radius will be applied in processing. Specify a certain point value with `.point`, or a fraction of the
+    /// target image with `.widthFraction`. or `.heightFraction`. For example, given a square image with width and
+    /// height equals,  `.widthFraction(0.5)` means use half of the length of size and makes the final image a round one.
+    public let radius: Radius
+    
+    /// The target corners which will be applied rounding.
+    public let roundingCorners: RectCorner
+    
+    /// Target size of output image should be. If `nil`, the image will keep its original size after processing.
+    public let targetSize: CGSize?
+
+    /// Background color of the output image. If `nil`, it will use a transparent background.
+    public let backgroundColor: KFCrossPlatformColor?
+
+    /// Creates a `RoundCornerImageProcessor`.
+    ///
+    /// - Parameters:
+    ///   - cornerRadius: Corner radius in point will be applied in processing.
+    ///   - targetSize: Target size of output image should be. If `nil`,
+    ///                 the image will keep its original size after processing.
+    ///                 Default is `nil`.
+    ///   - corners: The target corners which will be applied rounding. Default is `.all`.
+    ///   - backgroundColor: Background color to apply for the output image. Default is `nil`.
+    ///
+    /// - Note:
+    ///
+    /// This initializer accepts a concrete point value for `cornerRadius`. If you do not know the image size, but still
+    /// want to apply a full round-corner (making the final image a round one), or specify the corner radius as a
+    /// fraction of one dimension of the target image, use the `Radius` version instead.
+    ///
+    public init(
+        cornerRadius: CGFloat,
+        targetSize: CGSize? = nil,
+        roundingCorners corners: RectCorner = .all,
+        backgroundColor: KFCrossPlatformColor? = nil
+    )
+    {
+        let radius = Radius.point(cornerRadius)
+        self.init(radius: radius, targetSize: targetSize, roundingCorners: corners, backgroundColor: backgroundColor)
+    }
+
+    /// Creates a `RoundCornerImageProcessor`.
+    ///
+    /// - Parameters:
+    ///   - radius: The radius will be applied in processing.
+    ///   - targetSize: Target size of output image should be. If `nil`,
+    ///                 the image will keep its original size after processing.
+    ///                 Default is `nil`.
+    ///   - corners: The target corners which will be applied rounding. Default is `.all`.
+    ///   - backgroundColor: Background color to apply for the output image. Default is `nil`.
+    public init(
+        radius: Radius,
+        targetSize: CGSize? = nil,
+        roundingCorners corners: RectCorner = .all,
+        backgroundColor: KFCrossPlatformColor? = nil
+    )
+    {
+        self.radius = radius
+        self.targetSize = targetSize
+        self.roundingCorners = corners
+        self.backgroundColor = backgroundColor
+
+        self.identifier = {
+            var identifier = ""
+
+            if let size = targetSize {
+                identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor" +
+                             "(\(radius.radiusIdentifier)_\(size)\(corners.cornerIdentifier))"
+            } else {
+                identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor" +
+                             "(\(radius.radiusIdentifier)\(corners.cornerIdentifier))"
+            }
+            if let backgroundColor = backgroundColor {
+                identifier += "_\(backgroundColor)"
+            }
+
+            return identifier
+        }()
+    }
+    
+    /// Processes the input `ImageProcessItem` with this processor.
+    ///
+    /// - Parameters:
+    ///   - item: Input item which will be processed by `self`.
+    ///   - options: Options when processing the item.
+    /// - Returns: The processed image.
+    ///
+    /// - Note: See documentation of `ImageProcessor` protocol for more.
+    public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
+        switch item {
+        case .image(let image):
+            let size = targetSize ?? image.kf.size
+            return image.kf.scaled(to: options.scaleFactor)
+                        .kf.image(
+                            withRadius: radius,
+                            fit: size,
+                            roundingCorners: roundingCorners,
+                            backgroundColor: backgroundColor)
+        case .data:
+            return (DefaultImageProcessor.default |> self).process(item: item, options: options)
+        }
+    }
+}
+
+public struct Border {
+    public var color: KFCrossPlatformColor
+    public var lineWidth: CGFloat
+    
+    /// The radius will be applied in processing. Specify a certain point value with `.point`, or a fraction of the
+    /// target image with `.widthFraction`. or `.heightFraction`. For example, given a square image with width and
+    /// height equals,  `.widthFraction(0.5)` means use half of the length of size and makes the final image a round one.
+    public var radius: Radius
+    
+    /// The target corners which will be applied rounding.
+    public var roundingCorners: RectCorner
+    
+    public init(
+        color: KFCrossPlatformColor = .black,
+        lineWidth: CGFloat = 4,
+        radius: Radius = .point(0),
+        roundingCorners: RectCorner = .all
+    ) {
+        self.color = color
+        self.lineWidth = lineWidth
+        self.radius = radius
+        self.roundingCorners = roundingCorners
+    }
+    
+    var identifier: String {
+        "\(color.rgbaDescription)_\(lineWidth)_\(radius.radiusIdentifier)_\(roundingCorners.cornerIdentifier)"
+    }
+}
+
+public struct BorderImageProcessor: ImageProcessor {
+    public var identifier: String { "com.onevcat.Kingfisher.RoundCornerImageProcessor(\(border)" }
+    public let border: Border
+    
+    public init(border: Border) {
+        self.border = border
+    }
+    
+    public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
+        switch item {
+        case .image(let image):
+            return image.kf.addingBorder(border)
+        case .data:
+            return (DefaultImageProcessor.default |> self).process(item: item, options: options)
+        }
+    }
+}
+
+/// Represents how a size adjusts itself to fit a target size.
+///
+/// - none: Not scale the content.
+/// - aspectFit: Scales the content to fit the size of the view by maintaining the aspect ratio.
+/// - aspectFill: Scales the content to fill the size of the view.
+public enum ContentMode {
+    /// Not scale the content.
+    case none
+    /// Scales the content to fit the size of the view by maintaining the aspect ratio.
+    case aspectFit
+    /// Scales the content to fill the size of the view.
+    case aspectFill
+}
+
+/// Processor for resizing images.
+/// If you need to resize a data represented image to a smaller size, use `DownsamplingImageProcessor`
+/// instead, which is more efficient and uses less memory.
+public struct ResizingImageProcessor: ImageProcessor {
+    
+    /// Identifier of the processor.
+    /// - Note: See documentation of `ImageProcessor` protocol for more.
+    public let identifier: String
+    
+    /// The reference size for resizing operation in point.
+    public let referenceSize: CGSize
+    
+    /// Target content mode of output image should be.
+    /// Default is `.none`.
+    public let targetContentMode: ContentMode
+    
+    /// Creates a `ResizingImageProcessor`.
+    ///
+    /// - Parameters:
+    ///   - referenceSize: The reference size for resizing operation in point.
+    ///   - mode: Target content mode of output image should be.
+    ///
+    /// - Note:
+    ///   The instance of `ResizingImageProcessor` will follow its `mode` property
+    ///   and try to resizing the input images to fit or fill the `referenceSize`.
+    ///   That means if you are using a `mode` besides of `.none`, you may get an
+    ///   image with its size not be the same as the `referenceSize`.
+    ///
+    ///   **Example**: With input image size: {100, 200}, 
+    ///   `referenceSize`: {100, 100}, `mode`: `.aspectFit`,
+    ///   you will get an output image with size of {50, 100}, which "fit"s
+    ///   the `referenceSize`.
+    ///
+    ///   If you need an output image exactly to be a specified size, append or use
+    ///   a `CroppingImageProcessor`.
+    public init(referenceSize: CGSize, mode: ContentMode = .none) {
+        self.referenceSize = referenceSize
+        self.targetContentMode = mode
+        
+        if mode == .none {
+            self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(referenceSize))"
+        } else {
+            self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(referenceSize), \(mode))"
+        }
+    }
+    
+    /// Processes the input `ImageProcessItem` with this processor.
+    ///
+    /// - Parameters:
+    ///   - item: Input item which will be processed by `self`.
+    ///   - options: Options when processing the item.
+    /// - Returns: The processed image.
+    ///
+    /// - Note: See documentation of `ImageProcessor` protocol for more.
+    public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
+        switch item {
+        case .image(let image):
+            return image.kf.scaled(to: options.scaleFactor)
+                        .kf.resize(to: referenceSize, for: targetContentMode)
+        case .data:
+            return (DefaultImageProcessor.default |> self).process(item: item, options: options)
+        }
+    }
+}
+
+/// Processor for adding blur effect to images. `Accelerate.framework` is used underhood for 
+/// a better performance. A simulated Gaussian blur with specified blur radius will be applied.
+public struct BlurImageProcessor: ImageProcessor {
+    
+    /// Identifier of the processor.
+    /// - Note: See documentation of `ImageProcessor` protocol for more.
+    public let identifier: String
+    
+    /// Blur radius for the simulated Gaussian blur.
+    public let blurRadius: CGFloat
+
+    /// Creates a `BlurImageProcessor`
+    ///
+    /// - parameter blurRadius: Blur radius for the simulated Gaussian blur.
+    public init(blurRadius: CGFloat) {
+        self.blurRadius = blurRadius
+        self.identifier = "com.onevcat.Kingfisher.BlurImageProcessor(\(blurRadius))"
+    }
+    
+    /// Processes the input `ImageProcessItem` with this processor.
+    ///
+    /// - Parameters:
+    ///   - item: Input item which will be processed by `self`.
+    ///   - options: Options when processing the item.
+    /// - Returns: The processed image.
+    ///
+    /// - Note: See documentation of `ImageProcessor` protocol for more.
+    public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
+        switch item {
+        case .image(let image):
+            let radius = blurRadius * options.scaleFactor
+            return image.kf.scaled(to: options.scaleFactor)
+                        .kf.blurred(withRadius: radius)
+        case .data:
+            return (DefaultImageProcessor.default |> self).process(item: item, options: options)
+        }
+    }
+}
+
+/// Processor for adding an overlay to images. Only CG-based images are supported in macOS.
+public struct OverlayImageProcessor: ImageProcessor {
+    
+    /// Identifier of the processor.
+    /// - Note: See documentation of `ImageProcessor` protocol for more.
+    public let identifier: String
+    
+    /// Overlay color will be used to overlay the input image.
+    public let overlay: KFCrossPlatformColor
+    
+    /// Fraction will be used when overlay the color to image.
+    public let fraction: CGFloat
+    
+    /// Creates an `OverlayImageProcessor`
+    ///
+    /// - parameter overlay:  Overlay color will be used to overlay the input image.
+    /// - parameter fraction: Fraction will be used when overlay the color to image. 
+    ///                       From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
+    public init(overlay: KFCrossPlatformColor, fraction: CGFloat = 0.5) {
+        self.overlay = overlay
+        self.fraction = fraction
+        self.identifier = "com.onevcat.Kingfisher.OverlayImageProcessor(\(overlay.rgbaDescription)_\(fraction))"
+    }
+    
+    /// Processes the input `ImageProcessItem` with this processor.
+    ///
+    /// - Parameters:
+    ///   - item: Input item which will be processed by `self`.
+    ///   - options: Options when processing the item.
+    /// - Returns: The processed image.
+    ///
+    /// - Note: See documentation of `ImageProcessor` protocol for more.
+    public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
+        switch item {
+        case .image(let image):
+            return image.kf.scaled(to: options.scaleFactor)
+                        .kf.overlaying(with: overlay, fraction: fraction)
+        case .data:
+            return (DefaultImageProcessor.default |> self).process(item: item, options: options)
+        }
+    }
+}
+
+/// Processor for tint images with color. Only CG-based images are supported.
+public struct TintImageProcessor: ImageProcessor {
+    
+    /// Identifier of the processor.
+    /// - Note: See documentation of `ImageProcessor` protocol for more.
+    public let identifier: String
+    
+    /// Tint color will be used to tint the input image.
+    public let tint: KFCrossPlatformColor
+    
+    /// Creates a `TintImageProcessor`
+    ///
+    /// - parameter tint: Tint color will be used to tint the input image.
+    public init(tint: KFCrossPlatformColor) {
+        self.tint = tint
+        self.identifier = "com.onevcat.Kingfisher.TintImageProcessor(\(tint.rgbaDescription))"
+    }
+    
+    /// Processes the input `ImageProcessItem` with this processor.
+    ///
+    /// - Parameters:
+    ///   - item: Input item which will be processed by `self`.
+    ///   - options: Options when processing the item.
+    /// - Returns: The processed image.
+    ///
+    /// - Note: See documentation of `ImageProcessor` protocol for more.
+    public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
+        switch item {
+        case .image(let image):
+            return image.kf.scaled(to: options.scaleFactor)
+                        .kf.tinted(with: tint)
+        case .data:
+            return (DefaultImageProcessor.default |> self).process(item: item, options: options)
+        }
+    }
+}
+
+/// Processor for applying some color control to images. Only CG-based images are supported.
+/// watchOS is not supported.
+public struct ColorControlsProcessor: ImageProcessor {
+    
+    /// Identifier of the processor.
+    /// - Note: See documentation of `ImageProcessor` protocol for more.
+    public let identifier: String
+    
+    /// Brightness changing to image.
+    public let brightness: CGFloat
+    
+    /// Contrast changing to image.
+    public let contrast: CGFloat
+    
+    /// Saturation changing to image.
+    public let saturation: CGFloat
+    
+    /// InputEV changing to image.
+    public let inputEV: CGFloat
+    
+    /// Creates a `ColorControlsProcessor`
+    ///
+    /// - Parameters:
+    ///   - brightness: Brightness changing to image.
+    ///   - contrast: Contrast changing to image.
+    ///   - saturation: Saturation changing to image.
+    ///   - inputEV: InputEV changing to image.
+    public init(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) {
+        self.brightness = brightness
+        self.contrast = contrast
+        self.saturation = saturation
+        self.inputEV = inputEV
+        self.identifier = "com.onevcat.Kingfisher.ColorControlsProcessor(\(brightness)_\(contrast)_\(saturation)_\(inputEV))"
+    }
+    
+    /// Processes the input `ImageProcessItem` with this processor.
+    ///
+    /// - Parameters:
+    ///   - item: Input item which will be processed by `self`.
+    ///   - options: Options when processing the item.
+    /// - Returns: The processed image.
+    ///
+    /// - Note: See documentation of `ImageProcessor` protocol for more.
+    public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
+        switch item {
+        case .image(let image):
+            return image.kf.scaled(to: options.scaleFactor)
+                        .kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV)
+        case .data:
+            return (DefaultImageProcessor.default |> self).process(item: item, options: options)
+        }
+    }
+}
+
+/// Processor for applying black and white effect to images. Only CG-based images are supported.
+/// watchOS is not supported.
+public struct BlackWhiteProcessor: ImageProcessor {
+    
+    /// Identifier of the processor.
+    /// - Note: See documentation of `ImageProcessor` protocol for more.
+    public let identifier = "com.onevcat.Kingfisher.BlackWhiteProcessor"
+    
+    /// Creates a `BlackWhiteProcessor`
+    public init() {}
+    
+    /// Processes the input `ImageProcessItem` with this processor.
+    ///
+    /// - Parameters:
+    ///   - item: Input item which will be processed by `self`.
+    ///   - options: Options when processing the item.
+    /// - Returns: The processed image.
+    ///
+    /// - Note: See documentation of `ImageProcessor` protocol for more.
+    public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
+        return ColorControlsProcessor(brightness: 0.0, contrast: 1.0, saturation: 0.0, inputEV: 0.7)
+            .process(item: item, options: options)
+    }
+}
+
+/// Processor for cropping an image. Only CG-based images are supported.
+/// watchOS is not supported.
+public struct CroppingImageProcessor: ImageProcessor {
+    
+    /// Identifier of the processor.
+    /// - Note: See documentation of `ImageProcessor` protocol for more.
+    public let identifier: String
+    
+    /// Target size of output image should be.
+    public let size: CGSize
+    
+    /// Anchor point from which the output size should be calculate.
+    /// The anchor point is consisted by two values between 0.0 and 1.0.
+    /// It indicates a related point in current image. 
+    /// See `CroppingImageProcessor.init(size:anchor:)` for more.
+    public let anchor: CGPoint
+    
+    /// Creates a `CroppingImageProcessor`.
+    ///
+    /// - Parameters:
+    ///   - size: Target size of output image should be.
+    ///   - anchor: The anchor point from which the size should be calculated.
+    ///             Default is `CGPoint(x: 0.5, y: 0.5)`, which means the center of input image.
+    /// - Note:
+    ///   The anchor point is consisted by two values between 0.0 and 1.0.
+    ///   It indicates a related point in current image, eg: (0.0, 0.0) for top-left
+    ///   corner, (0.5, 0.5) for center and (1.0, 1.0) for bottom-right corner.
+    ///   The `size` property of `CroppingImageProcessor` will be used along with
+    ///   `anchor` to calculate a target rectangle in the size of image.
+    ///    
+    ///   The target size will be automatically calculated with a reasonable behavior.
+    ///   For example, when you have an image size of `CGSize(width: 100, height: 100)`,
+    ///   and a target size of `CGSize(width: 20, height: 20)`: 
+    ///   - with a (0.0, 0.0) anchor (top-left), the crop rect will be `{0, 0, 20, 20}`; 
+    ///   - with a (0.5, 0.5) anchor (center), it will be `{40, 40, 20, 20}`
+    ///   - while with a (1.0, 1.0) anchor (bottom-right), it will be `{80, 80, 20, 20}`
+    public init(size: CGSize, anchor: CGPoint = CGPoint(x: 0.5, y: 0.5)) {
+        self.size = size
+        self.anchor = anchor
+        self.identifier = "com.onevcat.Kingfisher.CroppingImageProcessor(\(size)_\(anchor))"
+    }
+    
+    /// Processes the input `ImageProcessItem` with this processor.
+    ///
+    /// - Parameters:
+    ///   - item: Input item which will be processed by `self`.
+    ///   - options: Options when processing the item.
+    /// - Returns: The processed image.
+    ///
+    /// - Note: See documentation of `ImageProcessor` protocol for more.
+    public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
+        switch item {
+        case .image(let image):
+            return image.kf.scaled(to: options.scaleFactor)
+                        .kf.crop(to: size, anchorOn: anchor)
+        case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options)
+        }
+    }
+}
+
+/// Processor for downsampling an image. Compared to `ResizingImageProcessor`, this processor
+/// does not render the images to resize. Instead, it downsamples the input data directly to an
+/// image. It is a more efficient than `ResizingImageProcessor`. Prefer to use `DownsamplingImageProcessor` as possible
+/// as you can than the `ResizingImageProcessor`.
+///
+/// Only CG-based images are supported. Animated images (like GIF) is not supported.
+public struct DownsamplingImageProcessor: ImageProcessor {
+    
+    /// Target size of output image should be. It should be smaller than the size of
+    /// input image. If it is larger, the result image will be the same size of input
+    /// data without downsampling.
+    public let size: CGSize
+    
+    /// Identifier of the processor.
+    /// - Note: See documentation of `ImageProcessor` protocol for more.
+    public let identifier: String
+    
+    /// Creates a `DownsamplingImageProcessor`.
+    ///
+    /// - Parameter size: The target size of the downsample operation.
+    public init(size: CGSize) {
+        self.size = size
+        self.identifier = "com.onevcat.Kingfisher.DownsamplingImageProcessor(\(size))"
+    }
+    
+    /// Processes the input `ImageProcessItem` with this processor.
+    ///
+    /// - Parameters:
+    ///   - item: Input item which will be processed by `self`.
+    ///   - options: Options when processing the item.
+    /// - Returns: The processed image.
+    ///
+    /// - Note: See documentation of `ImageProcessor` protocol for more.
+    public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
+        switch item {
+        case .image(let image):
+            guard let data = image.kf.data(format: .unknown) else {
+                return nil
+            }
+            return KingfisherWrapper.downsampledImage(data: data, to: size, scale: options.scaleFactor)
+        case .data(let data):
+            return KingfisherWrapper.downsampledImage(data: data, to: size, scale: options.scaleFactor)
+        }
+    }
+}
+
+infix operator |>: AdditionPrecedence
+public func |>(left: ImageProcessor, right: ImageProcessor) -> ImageProcessor {
+    return left.append(another: right)
+}
+
+extension KFCrossPlatformColor {
+    
+    var rgba: (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) {
+        var r: CGFloat = 0
+        var g: CGFloat = 0
+        var b: CGFloat = 0
+        var a: CGFloat = 0
+
+        #if os(macOS)
+        (usingColorSpace(.extendedSRGB) ?? self).getRed(&r, green: &g, blue: &b, alpha: &a)
+        #else
+        getRed(&r, green: &g, blue: &b, alpha: &a)
+        #endif
+        
+        return (r, g, b, a)
+    }
+    
+    var rgbaDescription: String {
+        let components = self.rgba
+        return String(format: "(%.2f,%.2f,%.2f,%.2f)", components.r, components.g, components.b, components.a)
+    }
+}

+ 353 - 0
Pods/Kingfisher/Sources/Image/ImageProgressive.swift

@@ -0,0 +1,353 @@
+//
+//  ImageProgressive.swift
+//  Kingfisher
+//
+//  Created by lixiang on 2019/5/10.
+//
+//  Copyright (c) 2019 Wei Wang <onevcat@gmail.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
+import CoreGraphics
+#if os(macOS)
+import AppKit
+#else
+import UIKit
+#endif
+
+private let sharedProcessingQueue: CallbackQueue =
+    .dispatch(DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Process"))
+
+public struct ImageProgressive {
+    
+    /// The updating strategy when an intermediate progressive image is generated and about to be set to the hosting view.
+    ///
+    /// - default: Use the progressive image as it is. It is the standard behavior when handling the progressive image.
+    /// - keepCurrent: Discard this progressive image and keep the current displayed one.
+    /// - replace: Replace the image to a new one. If the progressive loading is initialized by a view extension in
+    ///            Kingfisher, the replacing image will be used to update the view.
+    public enum UpdatingStrategy {
+        case `default`
+        case keepCurrent
+        case replace(KFCrossPlatformImage?)
+    }
+    
+    /// A default `ImageProgressive` could be used across. It blurs the progressive loading with the fastest
+    /// scan enabled and scan interval as 0.
+    @available(*, deprecated, message: "Getting a default `ImageProgressive` is deprecated due to its syntax symatic is not clear. Use `ImageProgressive.init` instead.", renamed: "init()")
+    public static let `default` = ImageProgressive(
+        isBlur: true,
+        isFastestScan: true,
+        scanInterval: 0
+    )
+    
+    /// Whether to enable blur effect processing
+    let isBlur: Bool
+    /// Whether to enable the fastest scan
+    let isFastestScan: Bool
+    /// Minimum time interval for each scan
+    let scanInterval: TimeInterval
+    
+    /// Called when an intermediate image is prepared and about to be set to the image view. The return value of this
+    /// delegate will be used to update the hosting view, if any. Otherwise, if there is no hosting view (a.k.a the
+    /// image retrieving is not happening from a view extension method), the returned `UpdatingStrategy` is ignored.
+    public let onImageUpdated = Delegate<KFCrossPlatformImage, UpdatingStrategy>()
+    
+    /// Creates an `ImageProgressive` value with default sets. It blurs the progressive loading with the fastest
+    /// scan enabled and scan interval as 0.
+    public init() {
+        self.init(isBlur: true, isFastestScan: true, scanInterval: 0)
+    }
+    
+    /// Creates an `ImageProgressive` value the given values.
+    /// - Parameters:
+    ///   - isBlur: Whether to enable blur effect processing.
+    ///   - isFastestScan: Whether to enable the fastest scan.
+    ///   - scanInterval: Minimum time interval for each scan.
+    public init(isBlur: Bool,
+                isFastestScan: Bool,
+                scanInterval: TimeInterval
+    )
+    {
+        self.isBlur = isBlur
+        self.isFastestScan = isFastestScan
+        self.scanInterval = scanInterval
+    }
+}
+
+final class ImageProgressiveProvider: DataReceivingSideEffect {
+    
+    var onShouldApply: () -> Bool = { return true }
+    
+    func onDataReceived(_ session: URLSession, task: SessionDataTask, data: Data) {
+
+        DispatchQueue.main.async {
+            guard self.onShouldApply() else { return }
+            self.update(data: task.mutableData, with: task.callbacks)
+        }
+    }
+
+    private let option: ImageProgressive
+    private let refresh: (KFCrossPlatformImage) -> Void
+    
+    private let decoder: ImageProgressiveDecoder
+    private let queue = ImageProgressiveSerialQueue()
+    
+    init?(_ options: KingfisherParsedOptionsInfo,
+          refresh: @escaping (KFCrossPlatformImage) -> Void) {
+        guard let option = options.progressiveJPEG else { return nil }
+        
+        self.option = option
+        self.refresh = refresh
+        self.decoder = ImageProgressiveDecoder(
+            option,
+            processingQueue: options.processingQueue ?? sharedProcessingQueue,
+            creatingOptions: options.imageCreatingOptions
+        )
+    }
+    
+    func update(data: Data, with callbacks: [SessionDataTask.TaskCallback]) {
+        guard !data.isEmpty else { return }
+
+        queue.add(minimum: option.scanInterval) { completion in
+
+            func decode(_ data: Data) {
+                self.decoder.decode(data, with: callbacks) { image in
+                    defer { completion() }
+                    guard self.onShouldApply() else { return }
+                    guard let image = image else { return }
+                    self.refresh(image)
+                }
+            }
+            
+            let semaphore = DispatchSemaphore(value: 0)
+            var onShouldApply: Bool = false
+            
+            CallbackQueue.mainAsync.execute {
+                onShouldApply = self.onShouldApply()
+                semaphore.signal()
+            }
+            semaphore.wait()
+            guard onShouldApply else {
+                self.queue.clean()
+                completion()
+                return
+            }
+
+            if self.option.isFastestScan {
+                decode(self.decoder.scanning(data) ?? Data())
+            } else {
+                self.decoder.scanning(data).forEach { decode($0) }
+            }
+        }
+    }
+}
+
+private final class ImageProgressiveDecoder {
+    
+    private let option: ImageProgressive
+    private let processingQueue: CallbackQueue
+    private let creatingOptions: ImageCreatingOptions
+    private(set) var scannedCount = 0
+    private(set) var scannedIndex = -1
+    
+    init(_ option: ImageProgressive,
+         processingQueue: CallbackQueue,
+         creatingOptions: ImageCreatingOptions) {
+        self.option = option
+        self.processingQueue = processingQueue
+        self.creatingOptions = creatingOptions
+    }
+    
+    func scanning(_ data: Data) -> [Data] {
+        guard data.kf.contains(jpeg: .SOF2) else {
+            return []
+        }
+        guard scannedIndex + 1 < data.count else {
+            return []
+        }
+        
+        var datas: [Data] = []
+        var index = scannedIndex + 1
+        var count = scannedCount
+        
+        while index < data.count - 1 {
+            scannedIndex = index
+            // 0xFF, 0xDA - Start Of Scan
+            let SOS = ImageFormat.JPEGMarker.SOS.bytes
+            if data[index] == SOS[0], data[index + 1] == SOS[1] {
+                if count > 0 {
+                    datas.append(data[0 ..< index])
+                }
+                count += 1
+            }
+            index += 1
+        }
+        
+        // Found more scans this the previous time
+        guard count > scannedCount else { return [] }
+        scannedCount = count
+        
+        // `> 1` checks that we've received a first scan (SOS) and then received
+        // and also received a second scan (SOS). This way we know that we have
+        // at least one full scan available.
+        guard count > 1 else { return [] }
+        return datas
+    }
+    
+    func scanning(_ data: Data) -> Data? {
+        guard data.kf.contains(jpeg: .SOF2) else {
+            return nil
+        }
+        guard scannedIndex + 1 < data.count else {
+            return nil
+        }
+        
+        var index = scannedIndex + 1
+        var count = scannedCount
+        var lastSOSIndex = 0
+        
+        while index < data.count - 1 {
+            scannedIndex = index
+            // 0xFF, 0xDA - Start Of Scan
+            let SOS = ImageFormat.JPEGMarker.SOS.bytes
+            if data[index] == SOS[0], data[index + 1] == SOS[1] {
+                lastSOSIndex = index
+                count += 1
+            }
+            index += 1
+        }
+        
+        // Found more scans this the previous time
+        guard count > scannedCount else { return nil }
+        scannedCount = count
+        
+        // `> 1` checks that we've received a first scan (SOS) and then received
+        // and also received a second scan (SOS). This way we know that we have
+        // at least one full scan available.
+        guard count > 1 && lastSOSIndex > 0 else { return nil }
+        return data[0 ..< lastSOSIndex]
+    }
+    
+    func decode(_ data: Data,
+                with callbacks: [SessionDataTask.TaskCallback],
+                completion: @escaping (KFCrossPlatformImage?) -> Void) {
+        guard data.kf.contains(jpeg: .SOF2) else {
+            CallbackQueue.mainCurrentOrAsync.execute { completion(nil) }
+            return
+        }
+        
+        func processing(_ data: Data) {
+            let processor = ImageDataProcessor(
+                data: data,
+                callbacks: callbacks,
+                processingQueue: processingQueue
+            )
+            processor.onImageProcessed.delegate(on: self) { (self, result) in
+                guard let image = try? result.0.get() else {
+                    CallbackQueue.mainCurrentOrAsync.execute { completion(nil) }
+                    return
+                }
+                
+                CallbackQueue.mainCurrentOrAsync.execute { completion(image) }
+            }
+            processor.process()
+        }
+        
+        // Blur partial images.
+        let count = scannedCount
+        
+        if option.isBlur, count < 6 {
+            processingQueue.execute {
+                // Progressively reduce blur as we load more scans.
+                let image = KingfisherWrapper<KFCrossPlatformImage>.image(
+                    data: data,
+                    options: self.creatingOptions
+                )
+                let radius = max(2, 14 - count * 4)
+                let temp = image?.kf.blurred(withRadius: CGFloat(radius))
+                processing(temp?.kf.data(format: .JPEG) ?? data)
+            }
+            
+        } else {
+            processing(data)
+        }
+    }
+}
+
+private final class ImageProgressiveSerialQueue {
+    typealias ClosureCallback = ((@escaping () -> Void)) -> Void
+    
+    private let queue: DispatchQueue
+    private var items: [DispatchWorkItem] = []
+    private var notify: (() -> Void)?
+    private var lastTime: TimeInterval?
+
+    init() {
+        self.queue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageProgressive.SerialQueue")
+    }
+    
+    func add(minimum interval: TimeInterval, closure: @escaping ClosureCallback) {
+        let completion = { [weak self] in
+            guard let self = self else { return }
+            
+            self.queue.async { [weak self] in
+                guard let self = self else { return }
+                guard !self.items.isEmpty else { return }
+                
+                self.items.removeFirst()
+                
+                if let next = self.items.first {
+                    self.queue.asyncAfter(
+                        deadline: .now() + interval,
+                        execute: next
+                    )
+                    
+                } else {
+                    self.lastTime = Date().timeIntervalSince1970
+                    self.notify?()
+                    self.notify = nil
+                }
+            }
+        }
+        
+        queue.async { [weak self] in
+            guard let self = self else { return }
+            
+            let item = DispatchWorkItem {
+                closure(completion)
+            }
+            if self.items.isEmpty {
+                let difference = Date().timeIntervalSince1970 - (self.lastTime ?? 0)
+                let delay = difference < interval ? interval - difference : 0
+                self.queue.asyncAfter(deadline: .now() + delay, execute: item)
+            }
+            self.items.append(item)
+        }
+    }
+    
+    func clean() {
+        queue.async { [weak self] in
+            guard let self = self else { return }
+            self.items.forEach { $0.cancel() }
+            self.items.removeAll()
+        }
+    }
+}

+ 118 - 0
Pods/Kingfisher/Sources/Image/ImageTransition.swift

@@ -0,0 +1,118 @@
+//
+//  ImageTransition.swift
+//  Kingfisher
+//
+//  Created by Wei Wang on 15/9/18.
+//
+//  Copyright (c) 2019 Wei Wang <onevcat@gmail.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
+#if os(iOS) || os(tvOS) || os(visionOS)
+import UIKit
+
+/// Transition effect which will be used when an image downloaded and set by `UIImageView`
+/// extension API in Kingfisher. You can assign an enum value with transition duration as
+/// an item in `KingfisherOptionsInfo` to enable the animation transition.
+///
+/// Apple's UIViewAnimationOptions is used under the hood.
+/// For custom transition, you should specified your own transition options, animations and
+/// completion handler as well.
+///
+/// - none: No animation transition.
+/// - fade: Fade in the loaded image in a given duration.
+/// - flipFromLeft: Flip from left transition.
+/// - flipFromRight: Flip from right transition.
+/// - flipFromTop: Flip from top transition.
+/// - flipFromBottom: Flip from bottom transition.
+/// - custom: Custom transition.
+public enum ImageTransition {
+    /// No animation transition.
+    case none
+    /// Fade in the loaded image in a given duration.
+    case fade(TimeInterval)
+    /// Flip from left transition.
+    case flipFromLeft(TimeInterval)
+    /// Flip from right transition.
+    case flipFromRight(TimeInterval)
+    /// Flip from top transition.
+    case flipFromTop(TimeInterval)
+    /// Flip from bottom transition.
+    case flipFromBottom(TimeInterval)
+    /// Custom transition defined by a general animation block.
+    ///    - duration: The time duration of this custom transition.
+    ///    - options: `UIView.AnimationOptions` should be used in the transition.
+    ///    - animations: The animation block will be applied when setting image.
+    ///    - completion: A block called when the transition animation finishes.
+    case custom(duration: TimeInterval,
+                 options: UIView.AnimationOptions,
+              animations: ((UIImageView, UIImage) -> Void)?,
+              completion: ((Bool) -> Void)?)
+    
+    var duration: TimeInterval {
+        switch self {
+        case .none:                          return 0
+        case .fade(let duration):            return duration
+            
+        case .flipFromLeft(let duration):    return duration
+        case .flipFromRight(let duration):   return duration
+        case .flipFromTop(let duration):     return duration
+        case .flipFromBottom(let duration):  return duration
+            
+        case .custom(let duration, _, _, _): return duration
+        }
+    }
+    
+    var animationOptions: UIView.AnimationOptions {
+        switch self {
+        case .none:                         return []
+        case .fade:                         return .transitionCrossDissolve
+            
+        case .flipFromLeft:                 return .transitionFlipFromLeft
+        case .flipFromRight:                return .transitionFlipFromRight
+        case .flipFromTop:                  return .transitionFlipFromTop
+        case .flipFromBottom:               return .transitionFlipFromBottom
+            
+        case .custom(_, let options, _, _): return options
+        }
+    }
+    
+    var animations: ((UIImageView, UIImage) -> Void)? {
+        switch self {
+        case .custom(_, _, let animations, _): return animations
+        default: return { $0.image = $1 }
+        }
+    }
+    
+    var completion: ((Bool) -> Void)? {
+        switch self {
+        case .custom(_, _, _, let completion): return completion
+        default: return nil
+        }
+    }
+}
+#else
+// Just a placeholder for compiling on macOS.
+public enum ImageTransition {
+    case none
+    /// This is a placeholder on macOS now. It is for SwiftUI (KFImage) to identify the fade option only.
+    case fade(TimeInterval)
+}
+#endif

+ 82 - 0
Pods/Kingfisher/Sources/Image/Placeholder.swift

@@ -0,0 +1,82 @@
+//
+//  Placeholder.swift
+//  Kingfisher
+//
+//  Created by Tieme van Veen on 28/08/2017.
+//
+//  Copyright (c) 2019 Wei Wang <onevcat@gmail.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.
+
+#if !os(watchOS)
+
+#if canImport(AppKit) && !targetEnvironment(macCatalyst)
+import AppKit
+#endif
+
+#if canImport(UIKit)
+import UIKit
+#endif
+
+/// Represents a placeholder type which could be set while loading as well as
+/// loading finished without getting an image.
+public protocol Placeholder {
+    
+    /// How the placeholder should be added to a given image view.
+    func add(to imageView: KFCrossPlatformImageView)
+    
+    /// How the placeholder should be removed from a given image view.
+    func remove(from imageView: KFCrossPlatformImageView)
+}
+
+/// Default implementation of an image placeholder. The image will be set or
+/// reset directly for `image` property of the image view.
+extension KFCrossPlatformImage: Placeholder {
+    /// How the placeholder should be added to a given image view.
+    public func add(to imageView: KFCrossPlatformImageView) { imageView.image = self }
+
+    /// How the placeholder should be removed from a given image view.
+    public func remove(from imageView: KFCrossPlatformImageView) { imageView.image = nil }
+}
+
+/// Default implementation of an arbitrary view as placeholder. The view will be 
+/// added as a subview when adding and be removed from its super view when removing.
+///
+/// To use your customize View type as placeholder, simply let it conforming to 
+/// `Placeholder` by `extension MyView: Placeholder {}`.
+extension Placeholder where Self: KFCrossPlatformView {
+    
+    /// How the placeholder should be added to a given image view.
+    public func add(to imageView: KFCrossPlatformImageView) {
+        imageView.addSubview(self)
+        translatesAutoresizingMaskIntoConstraints = false
+
+        centerXAnchor.constraint(equalTo: imageView.centerXAnchor).isActive = true
+        centerYAnchor.constraint(equalTo: imageView.centerYAnchor).isActive = true
+        heightAnchor.constraint(equalTo: imageView.heightAnchor).isActive = true
+        widthAnchor.constraint(equalTo: imageView.widthAnchor).isActive = true
+    }
+
+    /// How the placeholder should be removed from a given image view.
+    public func remove(from imageView: KFCrossPlatformImageView) {
+        removeFromSuperview()
+    }
+}
+
+#endif

Algunos archivos no se mostraron porque demasiados archivos cambiaron en este cambio