diff --git a/ErrorHandler.podspec b/ErrorHandler.podspec index 9183a0d..70ecfeb 100644 --- a/ErrorHandler.podspec +++ b/ErrorHandler.podspec @@ -12,10 +12,10 @@ ErrorHandler enables expressing complex error handling logic with a few lines of s.license = { :type => "MIT", :file => "LICENSE" } s.authors = { "Kostas Kremizas" => "kremizask@gmail.com", "Eleni Papanikolopoulou" => "eleni.papanikolopoulou@gmail.com" } - s.ios.deployment_target = '8.0' - s.osx.deployment_target = '10.10' - s.watchos.deployment_target = '2.0' - s.tvos.deployment_target = '9.0' + s.ios.deployment_target = '10.0' + s.osx.deployment_target = '10.12' + s.tvos.deployment_target = '10.0' + s.watchos.deployment_target = '3.0' s.source = { :git => "https://github.com/Workable/swift-error-handler.git", :tag => s.version.to_s } s.default_subspec = "Core" @@ -27,7 +27,7 @@ ErrorHandler enables expressing complex error handling logic with a few lines of s.subspec "Alamofire" do |ss| ss.source_files = "ErrorHandler/Classes/Alamofire/**/*" - ss.dependency "Alamofire", "~> 4.1" + ss.dependency "Alamofire", "~> 5" ss.dependency "ErrorHandler/Core" end end diff --git a/Example/ErrorHandler.xcodeproj/project.pbxproj b/Example/ErrorHandler.xcodeproj/project.pbxproj index 61253d1..7dc7208 100644 --- a/Example/ErrorHandler.xcodeproj/project.pbxproj +++ b/Example/ErrorHandler.xcodeproj/project.pbxproj @@ -62,7 +62,7 @@ DD3C867C8D103A87C2587415 /* LICENSE */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; name = LICENSE; path = ../LICENSE; sourceTree = ""; }; E2BE7603C2640FC298DB64A2 /* Pods-ErrorHandler_Example.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ErrorHandler_Example.release.xcconfig"; path = "Pods/Target Support Files/Pods-ErrorHandler_Example/Pods-ErrorHandler_Example.release.xcconfig"; sourceTree = ""; }; FD3B0D15CF686C0E62782E92 /* Pods_ErrorHandler_Tests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_ErrorHandler_Tests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - FF35F71962890E9A372E0306 /* ErrorHandler.podspec */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; name = ErrorHandler.podspec; path = ../ErrorHandler.podspec; sourceTree = ""; }; + FF35F71962890E9A372E0306 /* ErrorHandler.podspec */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; name = ErrorHandler.podspec; path = ../ErrorHandler.podspec; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -455,7 +455,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 8.3; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -496,7 +496,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 8.3; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; diff --git a/Example/Podfile b/Example/Podfile index b12bba3..15c4181 100644 --- a/Example/Podfile +++ b/Example/Podfile @@ -1,3 +1,4 @@ +platform :ios, '10.0' source 'https://github.com/Workable/PodSpecs.git' source 'https://github.com/CocoaPods/Specs.git' use_frameworks! diff --git a/Example/Podfile.lock b/Example/Podfile.lock index d7625f7..f14bab8 100644 --- a/Example/Podfile.lock +++ b/Example/Podfile.lock @@ -1,9 +1,9 @@ PODS: - - Alamofire (4.9.1) + - Alamofire (5.0.2) - ErrorHandler (0.8.2): - ErrorHandler/Core (= 0.8.2) - ErrorHandler/Alamofire (0.8.2): - - Alamofire (~> 4.1) + - Alamofire (~> 5) - ErrorHandler/Core - ErrorHandler/Core (0.8.2) @@ -20,9 +20,9 @@ EXTERNAL SOURCES: :path: "../" SPEC CHECKSUMS: - Alamofire: 85e8a02c69d6020a0d734f6054870d7ecb75cf18 - ErrorHandler: 5184ce9905c80d20810cc1abcf2ebc3ea3d56021 + Alamofire: 3ba7a4db18b4f62c4a1c0e1cb39d7f3d52e10ada + ErrorHandler: 5b44764fe86ed8771f7b5e79599bd4d5fd753a4f -PODFILE CHECKSUM: 8e328fdbad084717f3c5a8e2ce8f3f3671d29c67 +PODFILE CHECKSUM: 1ecd38147b811789385bbac850686caa2f83077b -COCOAPODS: 1.8.3 +COCOAPODS: 1.8.4 diff --git a/Example/Pods/Alamofire/LICENSE b/Example/Pods/Alamofire/LICENSE index 38a301a..ccafad5 100644 --- a/Example/Pods/Alamofire/LICENSE +++ b/Example/Pods/Alamofire/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) +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 diff --git a/Example/Pods/Alamofire/README.md b/Example/Pods/Alamofire/README.md index bafa09a..72fd65b 100644 --- a/Example/Pods/Alamofire/README.md +++ b/Example/Pods/Alamofire/README.md @@ -1,11 +1,12 @@ ![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/master/alamofire.png) -[![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg?branch=master)](https://travis-ci.org/Alamofire/Alamofire) +[![Build Status](https://github.com/Alamofire/Alamofire/workflows/Alamofire%20CI/badge.svg?branch=master)](https://github.com/Alamofire/Alamofire/actions) [![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg) [![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![Platform](https://img.shields.io/cocoapods/p/Alamofire.svg?style=flat)](https://alamofire.github.io/Alamofire) [![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat)](https://twitter.com/AlamofireSF) [![Gitter](https://badges.gitter.im/Alamofire/Alamofire.svg)](https://gitter.im/Alamofire/Alamofire?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) +[![Open Source Helpers](https://www.codetriage.com/alamofire/alamofire/badges/users.svg)](https://www.codetriage.com/alamofire/alamofire) Alamofire is an HTTP networking library written in Swift. @@ -15,13 +16,13 @@ Alamofire is an HTTP networking library written in Swift. - [Migration Guides](#migration-guides) - [Communication](#communication) - [Installation](#installation) -- [Usage](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md) - - **Intro -** [Making a Request](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#making-a-request), [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), [Parameter Encoding](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#parameter-encoding), [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) +- [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-manager), [Session Delegate](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#session-delegate), [Request](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#request) + - **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) - **Model Objects -** [Custom Response Serialization](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#custom-response-serialization) - **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) @@ -34,7 +35,7 @@ Alamofire is an HTTP networking library written in Swift. ## Features - [x] Chainable Request / Response Methods -- [x] URL / JSON / plist Parameter Encoding +- [x] URL / JSON Parameter Encoding - [x] Upload File / Data / Stream / MultipartFormData - [x] Download File using Request or Resume Data - [x] Authentication with URLCredential @@ -56,84 +57,53 @@ In order to keep Alamofire focused specifically on core networking implementatio ## Requirements -- iOS 8.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ -- Xcode 9.3+ -- Swift 4.0+ +- iOS 10.0+ / macOS 10.12+ / tvOS 10.0+ / watchOS 3.0+ +- Xcode 10.2+ +- Swift 5+ ## 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**, use [Stack Overflow](https://stackoverflow.com/questions/tagged/alamofire) and tag `alamofire`. +- 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 and follow the guide. The more detail the better! -- If you **want to contribute**, submit a pull request. +- If you **found a bug**, open an issue here on GitHub and follow the guide. The more detail the better! +- If you **want to contribute**, submit a pull request! ## Installation ### CocoaPods -[CocoaPods](https://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command: - -```bash -$ gem install cocoapods -``` - -> CocoaPods 1.7+ is required to build Alamofire 4.9+. - -To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`: +[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 -source 'https://github.com/CocoaPods/Specs.git' -platform :ios, '10.0' -use_frameworks! - -target '' do - pod 'Alamofire', '~> 4.9' -end -``` - -Then, run the following command: - -```bash -$ pod install +pod 'Alamofire', '~> 5.0' ``` ### 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](https://brew.sh/) using the following command: - -```bash -$ brew install carthage -``` - -To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: +[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" ~> 4.9 +github "Alamofire/Alamofire" "5.0" ``` -Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project. - ### 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. It is in early development, but Alamofire does support its use on supported platforms. +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. It is in early development, but Alamofire does support its use on supported platforms. 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 4 - ```swift dependencies: [ - .package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.9") + .package(url: "https://github.com/Alamofire/Alamofire.git", from: "5.0") ] ``` @@ -167,7 +137,7 @@ If you prefer not to use any of the aforementioned dependency managers, you can > 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 OS X. +- 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 either `Alamofire iOS`, `Alamofire macOS`, `Alamofire tvOS` or `Alamofire watchOS`. @@ -182,26 +152,22 @@ 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 test case - `rdar://26870455` - Background URL Session Configurations do not work in the simulator - `rdar://26849668` - Some URLProtocol APIs do not properly handle `URLRequest` -- [`rdar://36082113`](http://openradar.appspot.com/radar?id=4942308441063424) - `URLSessionTaskMetrics` failing to link on watchOS 3.0+ ## 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 on 9/1/17 in Xcode 9 beta 6). - +- [`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. + ## 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. -### What logic belongs in a Router vs. a Request Adapter? - -Simple, static data such as paths, parameters and common headers belong in the `Router`. Dynamic data such as an `Authorization` header whose value can changed based on an authentication system belongs in a `RequestAdapter`. - -The reason the dynamic data MUST be placed into the `RequestAdapter` is to support retry operations. When a `Request` is retried, the original request is not rebuilt meaning the `Router` will not be called again. The `RequestAdapter` is called again allowing the dynamic data to be updated on the original request before retrying the `Request`. - ## 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. @@ -213,7 +179,7 @@ If you believe you have identified a security vulnerability with Alamofire, you ## Donations 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 us members to gain some legal protections and also allow us to put donations to use, tax free. +Registering will allow us members to gain some legal protections and also allow us to put donations to use, tax-free. Donating to the ASF will enable us to: - Pay our yearly legal fees to keep the non-profit in good status @@ -222,7 +188,7 @@ Donating to the ASF will enable us to: - 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. +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 today to help us reach our goal would be greatly appreciated. diff --git a/Example/Pods/Alamofire/Source/AFError.swift b/Example/Pods/Alamofire/Source/AFError.swift index b163f60..8ab282c 100644 --- a/Example/Pods/Alamofire/Source/AFError.swift +++ b/Example/Pods/Alamofire/Source/AFError.swift @@ -1,7 +1,7 @@ // // AFError.swift // -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) +// 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 @@ -26,158 +26,322 @@ import Foundation /// `AFError` is the error type returned by Alamofire. It encompasses a few different types of errors, each with /// their own associated reasons. -/// -/// - invalidURL: Returned when a `URLConvertible` type fails to create a valid `URL`. -/// - parameterEncodingFailed: Returned when a parameter encoding object throws an error during the encoding process. -/// - multipartEncodingFailed: Returned when some step in the multipart encoding process fails. -/// - responseValidationFailed: Returned when a `validate()` call fails. -/// - responseSerializationFailed: Returned when a response serializer encounters an error in the serialization process. public enum AFError: Error { - /// The underlying reason the parameter encoding error occurred. - /// - /// - missingURL: The URL request did not have a URL to encode. - /// - jsonEncodingFailed: JSON serialization failed with an underlying system error during the - /// encoding process. - /// - propertyListEncodingFailed: Property list serialization failed with an underlying system error during - /// encoding process. - public enum ParameterEncodingFailureReason { - case missingURL - case jsonEncodingFailed(error: Error) - case propertyListEncodingFailed(error: Error) - } - - /// The underlying reason the multipart encoding error occurred. - /// - /// - bodyPartURLInvalid: The `fileURL` provided for reading an encodable body part isn't a - /// file URL. - /// - bodyPartFilenameInvalid: The filename of the `fileURL` provided has either an empty - /// `lastPathComponent` or `pathExtension. - /// - bodyPartFileNotReachable: The file at the `fileURL` provided was not reachable. - /// - bodyPartFileNotReachableWithError: Attempting to check the reachability of the `fileURL` provided threw - /// an error. - /// - bodyPartFileIsDirectory: The file at the `fileURL` provided is actually a directory. - /// - bodyPartFileSizeNotAvailable: The size of the file at the `fileURL` provided was not returned by - /// the system. - /// - bodyPartFileSizeQueryFailedWithError: The attempt to find the size of the file at the `fileURL` provided - /// threw an error. - /// - bodyPartInputStreamCreationFailed: An `InputStream` could not be created for the provided `fileURL`. - /// - outputStreamCreationFailed: An `OutputStream` could not be created when attempting to write the - /// encoded data to disk. - /// - outputStreamFileAlreadyExists: The encoded body data could not be writtent disk because a file - /// already exists at the provided `fileURL`. - /// - outputStreamURLInvalid: The `fileURL` provided for writing the encoded body data to disk is - /// not a file URL. - /// - outputStreamWriteFailed: The attempt to write the encoded body data to disk failed with an - /// underlying error. - /// - inputStreamReadFailed: The attempt to read an encoded body part `InputStream` failed with - /// underlying system 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) } - /// The underlying reason the response validation error occurred. - /// - /// - dataFileNil: The data file containing the server response did not exist. - /// - dataFileReadFailed: The data file containing the server response could not be read. - /// - missingContentType: The response did not contain a `Content-Type` and the `acceptableContentTypes` - /// provided did not contain wildcard type. - /// - unacceptableContentType: The response `Content-Type` did not match any type in the provided - /// `acceptableContentTypes`. - /// - unacceptableStatusCode: The response status code was not acceptable. + /// 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. - /// - /// - inputDataNil: The server response contained no data. - /// - inputDataNilOrZeroLength: The server response contained no data or the data was zero length. - /// - inputFileNil: The file containing the server response did not exist. - /// - inputFileReadFailed: The file containing the server response could not be read. - /// - stringSerializationFailed: String serialization failed using the provided `String.Encoding`. - /// - jsonSerializationFailed: JSON serialization failed with an underlying system error. - /// - propertyListSerializationFailed: Property list serialization failed with an underlying system error. public enum ResponseSerializationFailureReason { - case inputDataNil + /// 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) - case propertyListSerializationFailed(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) } + /// 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) + } + + /// 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) - case parameterEncodingFailed(reason: ParameterEncodingFailureReason) + /// 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) + /// `ServerTrustEvaluating` instance threw an error during trust evaluation. + case serverTrustEvaluationFailed(reason: ServerTrustFailureReason) + /// `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) } -// MARK: - Adapt Error +extension Error { + /// Returns the instance cast as an `AFError`. + public var asAFError: AFError? { + return self as? AFError + } -struct AdaptError: Error { - let error: Error -} + /// 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 + } -extension Error { - var underlyingAdaptError: Error? { return (self as? AdaptError)?.error } + /// Casts the instance as `AFError` or returns `defaultAFError` + func asAFError(or defaultAFError: @autoclosure () -> AFError) -> AFError { + return self as? AFError ?? defaultAFError() + } } // MARK: - Error Booleans extension AFError { - /// Returns whether the AFError is an invalid URL error. + /// 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 AFError is a parameter encoding error. When `true`, the `underlyingError` property will + /// 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 AFError is a multipart encoding error. When `true`, the `url` and `underlyingError` properties - /// will contain the associated values. + /// 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 `AFError` is a response validation error. When `true`, the `acceptableContentTypes`, - /// `responseContentType`, and `responseCode` properties will contain the associated values. + /// 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 `AFError` is a response serialization error. When `true`, the `failedStringEncoding` and + /// 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 } + + /// 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 + } + + /// 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 @@ -185,86 +349,110 @@ extension AFError { extension AFError { /// The `URLConvertible` associated with the error. public var urlConvertible: URLConvertible? { - switch self { - case .invalidURL(let url): - return url - default: - return nil - } + guard case let .invalidURL(url) = self else { return nil } + return url } /// The `URL` associated with the error. public var url: URL? { - switch self { - case .multipartEncodingFailed(let reason): - return reason.url - default: - return nil - } + guard case let .multipartEncodingFailed(reason) = self else { return nil } + return reason.url } - /// The `Error` returned by a system framework associated with a `.parameterEncodingFailed`, - /// `.multipartEncodingFailed` or `.responseSerializationFailed` error. + /// 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 .parameterEncodingFailed(let reason): + case let .multipartEncodingFailed(reason): + return reason.underlyingError + case let .parameterEncodingFailed(reason): + return reason.underlyingError + case let .parameterEncoderFailed(reason): return reason.underlyingError - case .multipartEncodingFailed(let reason): + 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 - case .responseSerializationFailed(let reason): + case let .serverTrustEvaluationFailed(reason): return reason.underlyingError - default: + 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]? { - switch self { - case .responseValidationFailed(let reason): - return reason.acceptableContentTypes - default: - return nil - } + guard case let .responseValidationFailed(reason) = self else { return nil } + return reason.acceptableContentTypes } /// The response `Content-Type` of a `.responseValidationFailed` error. public var responseContentType: String? { - switch self { - case .responseValidationFailed(let reason): - return reason.responseContentType - default: - return nil - } + guard case let .responseValidationFailed(reason) = self else { return nil } + return reason.responseContentType } /// The response code of a `.responseValidationFailed` error. public var responseCode: Int? { - switch self { - case .responseValidationFailed(let reason): - return reason.responseCode - default: - return nil - } + 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 + } +} + +extension AFError.ParameterEncodingFailureReason { + var underlyingError: Error? { switch self { - case .responseSerializationFailed(let reason): - return reason.failedStringEncoding - default: + case let .jsonEncodingFailed(error), + let .customEncodingFailed(error): + return error + case .missingURL: return nil } } } -extension AFError.ParameterEncodingFailureReason { +extension AFError.ParameterEncoderFailureReason { var underlyingError: Error? { switch self { - case .jsonEncodingFailed(let error), .propertyListEncodingFailed(let error): + case let .encoderFailed(error): return error - default: + case .missingRequiredComponent: return nil } } @@ -273,23 +461,40 @@ extension AFError.ParameterEncodingFailureReason { extension AFError.MultipartEncodingFailureReason { var url: URL? { switch self { - case .bodyPartURLInvalid(let url), .bodyPartFilenameInvalid(let url), .bodyPartFileNotReachable(let url), - .bodyPartFileIsDirectory(let url), .bodyPartFileSizeNotAvailable(let url), - .bodyPartInputStreamCreationFailed(let url), .outputStreamCreationFailed(let url), - .outputStreamFileAlreadyExists(let url), .outputStreamURLInvalid(let url), - .bodyPartFileNotReachableWithError(let url, _), .bodyPartFileSizeQueryFailedWithError(let url, _): + 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 - default: + case .outputStreamWriteFailed, + .inputStreamReadFailed: return nil } } var underlyingError: Error? { switch self { - case .bodyPartFileNotReachableWithError(_, let error), .bodyPartFileSizeQueryFailedWithError(_, let error), - .outputStreamWriteFailed(let error), .inputStreamReadFailed(let error): + case let .bodyPartFileNotReachableWithError(_, error), + let .bodyPartFileSizeQueryFailedWithError(_, error), + let .outputStreamWriteFailed(error), + let .inputStreamReadFailed(error): return error - default: + case .bodyPartURLInvalid, + .bodyPartFilenameInvalid, + .bodyPartFileNotReachable, + .bodyPartFileIsDirectory, + .bodyPartFileSizeNotAvailable, + .bodyPartInputStreamCreationFailed, + .outputStreamCreationFailed, + .outputStreamFileAlreadyExists, + .outputStreamURLInvalid: return nil } } @@ -298,27 +503,52 @@ extension AFError.MultipartEncodingFailureReason { extension AFError.ResponseValidationFailureReason { var acceptableContentTypes: [String]? { switch self { - case .missingContentType(let types), .unacceptableContentType(let types, _): + case let .missingContentType(types), + let .unacceptableContentType(types, _): return types - default: + case .dataFileNil, + .dataFileReadFailed, + .unacceptableStatusCode, + .customValidationFailed: return nil } } var responseContentType: String? { switch self { - case .unacceptableContentType(_, let responseType): + case let .unacceptableContentType(_, responseType): return responseType - default: + case .dataFileNil, + .dataFileReadFailed, + .missingContentType, + .unacceptableStatusCode, + .customValidationFailed: return nil } } var responseCode: Int? { switch self { - case .unacceptableStatusCode(let code): + case let .unacceptableStatusCode(code): return code - default: + 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 } } @@ -327,18 +557,73 @@ extension AFError.ResponseValidationFailureReason { extension AFError.ResponseSerializationFailureReason { var failedStringEncoding: String.Encoding? { switch self { - case .stringSerializationFailed(let encoding): + case let .stringSerializationFailed(encoding): return encoding - default: + 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 + } + } +} + +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 .jsonSerializationFailed(let error), .propertyListSerializationFailed(let error): + case let .customEvaluationFailed(error): return error - default: + case let .trustEvaluationFailed(error): + return error + case .noRequiredEvaluator, + .noCertificatesFound, + .noPublicKeysFound, + .policyApplicationFailed, + .settingAnchorCertificatesFailed, + .revocationPolicyCreationFailed, + .defaultEvaluationFailed, + .hostValidationFailed, + .revocationCheckFailed, + .certificatePinningFailed, + .publicKeyPinningFailed: return nil } } @@ -349,16 +634,46 @@ extension AFError.ResponseSerializationFailureReason { extension AFError: LocalizedError { public var errorDescription: String? { switch self { - case .invalidURL(let url): + case .explicitlyCancelled: + return "Request explicitly cancelled." + case let .invalidURL(url): return "URL is not valid: \(url)" - case .parameterEncodingFailed(let reason): + case let .parameterEncodingFailed(reason): + return reason.localizedDescription + case let .parameterEncoderFailed(reason): return reason.localizedDescription - case .multipartEncodingFailed(let reason): + case let .multipartEncodingFailed(reason): return reason.localizedDescription - case .responseValidationFailed(let reason): + case let .requestAdaptationFailed(error): + return "Request adaption failed with error: \(error.localizedDescription)" + case let .responseValidationFailed(reason): return reason.localizedDescription - case .responseSerializationFailed(let reason): + 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.")" + case let .serverTrustEvaluationFailed(reason): + return "Server trust evaluation failed due to reason: \(reason.localizedDescription)" + 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)" } } } @@ -368,10 +683,21 @@ extension AFError.ParameterEncodingFailureReason { switch self { case .missingURL: return "URL request to encode was missing a URL" - case .jsonEncodingFailed(let error): + case let .jsonEncodingFailed(error): return "JSON could not be encoded because of error:\n\(error.localizedDescription)" - case .propertyListEncodingFailed(let error): - return "PropertyList 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)" } } } @@ -379,37 +705,39 @@ extension AFError.ParameterEncodingFailureReason { extension AFError.MultipartEncodingFailureReason { var localizedDescription: String { switch self { - case .bodyPartURLInvalid(let url): + case let .bodyPartURLInvalid(url): return "The URL provided is not a file URL: \(url)" - case .bodyPartFilenameInvalid(let url): + case let .bodyPartFilenameInvalid(url): return "The URL provided does not have a valid filename: \(url)" - case .bodyPartFileNotReachable(let url): + case let .bodyPartFileNotReachable(url): return "The URL provided is not reachable: \(url)" - case .bodyPartFileNotReachableWithError(let url, let error): - return ( - "The system returned an error while checking the provided URL for " + - "reachability.\nURL: \(url)\nError: \(error)" - ) - case .bodyPartFileIsDirectory(let 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 .bodyPartFileSizeNotAvailable(let url): + case let .bodyPartFileSizeNotAvailable(url): return "Could not fetch the file size from the provided URL: \(url)" - case .bodyPartFileSizeQueryFailedWithError(let url, let error): - return ( - "The system returned an error while attempting to fetch the file size from the " + - "provided URL.\nURL: \(url)\nError: \(error)" - ) - case .bodyPartInputStreamCreationFailed(let 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 .outputStreamCreationFailed(let url): + case let .outputStreamCreationFailed(url): return "Failed to create an OutputStream for URL: \(url)" - case .outputStreamFileAlreadyExists(let url): + case let .outputStreamFileAlreadyExists(url): return "A file already exists at the provided URL: \(url)" - case .outputStreamURLInvalid(let url): + case let .outputStreamURLInvalid(url): return "The provided OutputStream URL is invalid: \(url)" - case .outputStreamWriteFailed(let error): + case let .outputStreamWriteFailed(error): return "OutputStream write failed with error: \(error)" - case .inputStreamReadFailed(let error): + case let .inputStreamReadFailed(error): return "InputStream read failed with error: \(error)" } } @@ -418,20 +746,25 @@ extension AFError.MultipartEncodingFailureReason { extension AFError.ResponseSerializationFailureReason { var localizedDescription: String { switch self { - case .inputDataNil: - return "Response could not be serialized, input data was nil." 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 .inputFileReadFailed(let url): + case let .inputFileReadFailed(url): return "Response could not be serialized, input file could not be read: \(url)." - case .stringSerializationFailed(let encoding): + case let .stringSerializationFailed(encoding): return "String could not be serialized with encoding: \(encoding)." - case .jsonSerializationFailed(let error): + case let .jsonSerializationFailed(error): return "JSON could not be serialized because of error:\n\(error.localizedDescription)" - case .propertyListSerializationFailed(let error): - return "PropertyList 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)" } } } @@ -441,20 +774,67 @@ extension AFError.ResponseValidationFailureReason { switch self { case .dataFileNil: return "Response could not be validated, data file was nil." - case .dataFileReadFailed(let url): + case let .dataFileReadFailed(url): return "Response could not be validated, data file could not be read: \(url)." - case .missingContentType(let types): - return ( - "Response Content-Type was missing and acceptable content types " + - "(\(types.joined(separator: ","))) do not match \"*/*\"." - ) - case .unacceptableContentType(let acceptableTypes, let responseType): - return ( - "Response Content-Type \"\(responseType)\" does not match any acceptable types: " + - "\(acceptableTypes.joined(separator: ","))." - ) - case .unacceptableStatusCode(let code): + 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)" + } + } +} + +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)" + } + } +} + +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)) + """ } } } diff --git a/Example/Pods/Alamofire/Source/Alamofire.swift b/Example/Pods/Alamofire/Source/Alamofire.swift index 20c3672..7f2ca5b 100644 --- a/Example/Pods/Alamofire/Source/Alamofire.swift +++ b/Example/Pods/Alamofire/Source/Alamofire.swift @@ -1,7 +1,7 @@ // // Alamofire.swift // -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) +// 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 @@ -22,444 +22,8 @@ // THE SOFTWARE. // -import Foundation +/// Reference to `Session.default` for quick bootstrapping and examples. +public let AF = Session.default -/// Types adopting the `URLConvertible` protocol can be used to construct URLs, which are then used to construct -/// URL requests. -public protocol URLConvertible { - /// Returns a URL that conforms to RFC 2396 or throws an `Error`. - /// - /// - throws: An `Error` if the type cannot be converted to a `URL`. - /// - /// - returns: A URL or throws an `Error`. - func asURL() throws -> URL -} - -extension String: URLConvertible { - /// Returns a URL if `self` represents a valid URL string that conforms to RFC 2396 or throws an `AFError`. - /// - /// - throws: An `AFError.invalidURL` if `self` is not a valid URL string. - /// - /// - returns: A URL or throws an `AFError`. - 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 { return self } -} - -extension URLComponents: URLConvertible { - /// Returns a URL if `url` is not nil, otherwise throws an `Error`. - /// - /// - throws: An `AFError.invalidURL` if `url` is `nil`. - /// - /// - returns: A URL or throws an `AFError`. - 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 construct URL requests. -public protocol URLRequestConvertible { - /// Returns a URL request or throws if an `Error` was encountered. - /// - /// - throws: An `Error` if the underlying `URLRequest` is `nil`. - /// - /// - returns: A URL request. - func asURLRequest() throws -> URLRequest -} - -extension URLRequestConvertible { - /// The URL request. - public var urlRequest: URLRequest? { return try? asURLRequest() } -} - -extension URLRequest: URLRequestConvertible { - /// Returns a URL request or throws if an `Error` was encountered. - public func asURLRequest() throws -> URLRequest { return self } -} - -// MARK: - - -extension URLRequest { - /// Creates an instance with the specified `method`, `urlString` and `headers`. - /// - /// - parameter url: The URL. - /// - parameter method: The HTTP method. - /// - parameter headers: The HTTP headers. `nil` by default. - /// - /// - returns: The new `URLRequest` instance. - public init(url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws { - let url = try url.asURL() - - self.init(url: url) - - httpMethod = method.rawValue - - if let headers = headers { - for (headerField, headerValue) in headers { - setValue(headerValue, forHTTPHeaderField: headerField) - } - } - } - - func adapt(using adapter: RequestAdapter?) throws -> URLRequest { - guard let adapter = adapter else { return self } - return try adapter.adapt(self) - } -} - -// MARK: - Data Request - -/// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, -/// `method`, `parameters`, `encoding` and `headers`. -/// -/// - parameter url: The URL. -/// - parameter method: The HTTP method. `.get` by default. -/// - parameter parameters: The parameters. `nil` by default. -/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. -/// - parameter headers: The HTTP headers. `nil` by default. -/// -/// - returns: The created `DataRequest`. -@discardableResult -public func request( - _ url: URLConvertible, - method: HTTPMethod = .get, - parameters: Parameters? = nil, - encoding: ParameterEncoding = URLEncoding.default, - headers: HTTPHeaders? = nil) - -> DataRequest -{ - return SessionManager.default.request( - url, - method: method, - parameters: parameters, - encoding: encoding, - headers: headers - ) -} - -/// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of a URL based on the -/// specified `urlRequest`. -/// -/// - parameter urlRequest: The URL request -/// -/// - returns: The created `DataRequest`. -@discardableResult -public func request(_ urlRequest: URLRequestConvertible) -> DataRequest { - return SessionManager.default.request(urlRequest) -} - -// MARK: - Download Request - -// MARK: URL Request - -/// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, -/// `method`, `parameters`, `encoding`, `headers` and save them to the `destination`. -/// -/// If `destination` is not specified, the contents will remain in the temporary location determined by the -/// underlying URL session. -/// -/// - parameter url: The URL. -/// - parameter method: The HTTP method. `.get` by default. -/// - parameter parameters: The parameters. `nil` by default. -/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. -/// - parameter headers: The HTTP headers. `nil` by default. -/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. -/// -/// - returns: The created `DownloadRequest`. -@discardableResult -public func download( - _ url: URLConvertible, - method: HTTPMethod = .get, - parameters: Parameters? = nil, - encoding: ParameterEncoding = URLEncoding.default, - headers: HTTPHeaders? = nil, - to destination: DownloadRequest.DownloadFileDestination? = nil) - -> DownloadRequest -{ - return SessionManager.default.download( - url, - method: method, - parameters: parameters, - encoding: encoding, - headers: headers, - to: destination - ) -} - -/// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of a URL based on the -/// specified `urlRequest` and save them to the `destination`. -/// -/// If `destination` is not specified, the contents will remain in the temporary location determined by the -/// underlying URL session. -/// -/// - parameter urlRequest: The URL request. -/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. -/// -/// - returns: The created `DownloadRequest`. -@discardableResult -public func download( - _ urlRequest: URLRequestConvertible, - to destination: DownloadRequest.DownloadFileDestination? = nil) - -> DownloadRequest -{ - return SessionManager.default.download(urlRequest, to: destination) -} - -// MARK: Resume Data - -/// Creates a `DownloadRequest` using the default `SessionManager` from the `resumeData` produced from a -/// previous request cancellation to retrieve the contents of the original request and save them to the `destination`. -/// -/// If `destination` is not specified, the contents will remain in the temporary location determined by the -/// underlying URL session. -/// -/// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `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 following Stack Overflow post: -/// -/// - http://stackoverflow.com/a/39347461/1342462 -/// -/// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` -/// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for additional -/// information. -/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. -/// -/// - returns: The created `DownloadRequest`. -@discardableResult -public func download( - resumingWith resumeData: Data, - to destination: DownloadRequest.DownloadFileDestination? = nil) - -> DownloadRequest -{ - return SessionManager.default.download(resumingWith: resumeData, to: destination) -} - -// MARK: - Upload Request - -// MARK: File - -/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` -/// for uploading the `file`. -/// -/// - parameter file: The file to upload. -/// - parameter url: The URL. -/// - parameter method: The HTTP method. `.post` by default. -/// - parameter headers: The HTTP headers. `nil` by default. -/// -/// - returns: The created `UploadRequest`. -@discardableResult -public func upload( - _ fileURL: URL, - to url: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil) - -> UploadRequest -{ - return SessionManager.default.upload(fileURL, to: url, method: method, headers: headers) -} - -/// Creates a `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for -/// uploading the `file`. -/// -/// - parameter file: The file to upload. -/// - parameter urlRequest: The URL request. -/// -/// - returns: The created `UploadRequest`. -@discardableResult -public func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { - return SessionManager.default.upload(fileURL, with: urlRequest) -} - -// MARK: Data - -/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` -/// for uploading the `data`. -/// -/// - parameter data: The data to upload. -/// - parameter url: The URL. -/// - parameter method: The HTTP method. `.post` by default. -/// - parameter headers: The HTTP headers. `nil` by default. -/// -/// - returns: The created `UploadRequest`. -@discardableResult -public func upload( - _ data: Data, - to url: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil) - -> UploadRequest -{ - return SessionManager.default.upload(data, to: url, method: method, headers: headers) -} - -/// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for -/// uploading the `data`. -/// -/// - parameter data: The data to upload. -/// - parameter urlRequest: The URL request. -/// -/// - returns: The created `UploadRequest`. -@discardableResult -public func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { - return SessionManager.default.upload(data, with: urlRequest) -} - -// MARK: InputStream - -/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` -/// for uploading the `stream`. -/// -/// - parameter stream: The stream to upload. -/// - parameter url: The URL. -/// - parameter method: The HTTP method. `.post` by default. -/// - parameter headers: The HTTP headers. `nil` by default. -/// -/// - returns: The created `UploadRequest`. -@discardableResult -public func upload( - _ stream: InputStream, - to url: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil) - -> UploadRequest -{ - return SessionManager.default.upload(stream, to: url, method: method, headers: headers) -} - -/// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for -/// uploading the `stream`. -/// -/// - parameter urlRequest: The URL request. -/// - parameter stream: The stream to upload. -/// -/// - returns: The created `UploadRequest`. -@discardableResult -public func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { - return SessionManager.default.upload(stream, with: urlRequest) -} - -// MARK: MultipartFormData - -/// Encodes `multipartFormData` using `encodingMemoryThreshold` with the default `SessionManager` and calls -/// `encodingCompletion` with new `UploadRequest` using the `url`, `method` and `headers`. -/// -/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative -/// 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. -/// -/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. -/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. -/// `multipartFormDataEncodingMemoryThreshold` by default. -/// - parameter url: The URL. -/// - parameter method: The HTTP method. `.post` by default. -/// - parameter headers: The HTTP headers. `nil` by default. -/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. -public func upload( - multipartFormData: @escaping (MultipartFormData) -> Void, - usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, - to url: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil, - encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) -{ - return SessionManager.default.upload( - multipartFormData: multipartFormData, - usingThreshold: encodingMemoryThreshold, - to: url, - method: method, - headers: headers, - encodingCompletion: encodingCompletion - ) -} - -/// Encodes `multipartFormData` using `encodingMemoryThreshold` and the default `SessionManager` and -/// calls `encodingCompletion` with new `UploadRequest` using the `urlRequest`. -/// -/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative -/// 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. -/// -/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. -/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. -/// `multipartFormDataEncodingMemoryThreshold` by default. -/// - parameter urlRequest: The URL request. -/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. -public func upload( - multipartFormData: @escaping (MultipartFormData) -> Void, - usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, - with urlRequest: URLRequestConvertible, - encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) -{ - return SessionManager.default.upload( - multipartFormData: multipartFormData, - usingThreshold: encodingMemoryThreshold, - with: urlRequest, - encodingCompletion: encodingCompletion - ) -} - -#if !os(watchOS) - -// MARK: - Stream Request - -// MARK: Hostname and Port - -/// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `hostname` -/// and `port`. -/// -/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. -/// -/// - parameter hostName: The hostname of the server to connect to. -/// - parameter port: The port of the server to connect to. -/// -/// - returns: The created `StreamRequest`. -@discardableResult -@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) -public func stream(withHostName hostName: String, port: Int) -> StreamRequest { - return SessionManager.default.stream(withHostName: hostName, port: port) -} - -// MARK: NetService - -/// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `netService`. -/// -/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. -/// -/// - parameter netService: The net service used to identify the endpoint. -/// -/// - returns: The created `StreamRequest`. -@discardableResult -@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) -public func stream(with netService: NetService) -> StreamRequest { - return SessionManager.default.stream(with: netService) -} - -#endif +/// Current Alamofire version. Necessary since SPM doesn't use dynamic libraries. Plus this will be more accurate. +let version = "5.0.2" diff --git a/Example/Pods/Alamofire/Source/AlamofireExtended.swift b/Example/Pods/Alamofire/Source/AlamofireExtended.swift new file mode 100644 index 0000000..cb9eccf --- /dev/null +++ b/Example/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 { + /// 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.Type { get set } + /// Instance Alamofire extension point. + var af: AlamofireExtension { get set } +} + +public extension AlamofireExtended { + /// Static Alamofire extension point. + static var af: AlamofireExtension.Type { + get { return AlamofireExtension.self } + set {} + } + + /// Instance Alamofire extension point. + var af: AlamofireExtension { + get { return AlamofireExtension(self) } + set {} + } +} diff --git a/Example/Pods/Alamofire/Source/CachedResponseHandler.swift b/Example/Pods/Alamofire/Source/CachedResponseHandler.swift new file mode 100644 index 0000000..b6e0d4b --- /dev/null +++ b/Example/Pods/Alamofire/Source/CachedResponseHandler.swift @@ -0,0 +1,91 @@ +// +// 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 follow `Behavior`. + public static let cache = ResponseCacher(behavior: .cache) + /// Returns a `ResponseCacher` with a do not follow `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) + } + } +} diff --git a/Example/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift b/Example/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift index a54673c..10cd273 100644 --- a/Example/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift +++ b/Example/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift @@ -1,7 +1,7 @@ // // DispatchQueue+Alamofire.swift // -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) +// 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 @@ -26,11 +26,11 @@ import Dispatch import Foundation extension DispatchQueue { - static var userInteractive: DispatchQueue { return DispatchQueue.global(qos: .userInteractive) } - static var userInitiated: DispatchQueue { return DispatchQueue.global(qos: .userInitiated) } - static var utility: DispatchQueue { return DispatchQueue.global(qos: .utility) } - static var background: DispatchQueue { return DispatchQueue.global(qos: .background) } - + /// 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) } diff --git a/Example/Pods/Alamofire/Source/EventMonitor.swift b/Example/Pods/Alamofire/Source/EventMonitor.swift new file mode 100644 index 0000000..4363828 --- /dev/null +++ b/Example/Pods/Alamofire/Source/EventMonitor.swift @@ -0,0 +1,844 @@ +// +// 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` value without calling a `ResponseSerializer`. + func request(_ request: DataRequest, didParseResponse response: DataResponse) + + /// Event called when a `DataRequest` calls a `ResponseSerializer` and creates a generic `DataResponse`. + func request(_ request: DataRequest, didParseResponse response: DataResponse) + + // 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) + + /// 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` without calling a `ResponseSerializer`. + func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) + + /// Event called when a `DownloadRequest` calls a `DownloadResponseSerializer` and creates a generic `DownloadResponse` + func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) +} + +extension EventMonitor { + /// The default queue on which `CompositeEventMonitor`s will call the `EventMonitor` methods. `.main` by default. + public var queue: DispatchQueue { return .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) {} + public func request(_ request: DataRequest, didParseResponse response: DataResponse) {} + 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) {} + 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) {} + public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) {} +} + +/// 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: .background) + + 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) { + performEvent { $0.request(request, didParseResponse: response) } + } + + public func request(_ request: DataRequest, didParseResponse response: DataResponse) { + performEvent { $0.request(request, didParseResponse: response) } + } + + 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) { + 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) { + performEvent { $0.request(request, didParseResponse: response) } + } + + public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) { + 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) -> 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) -> 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) -> 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) { + requestDidParseResponse?(request, response) + } + + 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) { + 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) { + requestDidParseDownloadResponse?(request, response) + } +} diff --git a/Example/Pods/Alamofire/Source/HTTPHeaders.swift b/Example/Pods/Alamofire/Source/HTTPHeaders.swift new file mode 100644 index 0000000..641087c --- /dev/null +++ b/Example/Pods/Alamofire/Source/HTTPHeaders.swift @@ -0,0 +1,445 @@ +// +// 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. + public mutating func sort() { + headers.sort { $0.name < $1.name } + } + + /// Returns an instance sorted by header name. + /// + /// - Returns: A copy of the current instance sorted by name. + public func sorted() -> HTTPHeaders { + return HTTPHeaders(headers.sorted { $0.name < $1.name }) + } + + /// 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 { return 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]> { + return headers.makeIterator() + } +} + +extension HTTPHeaders: Collection { + public var startIndex: Int { + return headers.startIndex + } + + public var endIndex: Int { + return headers.endIndex + } + + public subscript(position: Int) -> HTTPHeader { + return headers[position] + } + + public func index(after i: Int) -> Int { + return headers.index(after: i) + } +} + +extension HTTPHeaders: CustomStringConvertible { + public var description: String { + return headers.map { $0.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 { + return "\(name): \(value)" + } +} + +extension HTTPHeader { + /// Returns an `Accept` header. + /// + /// - Parameter value: The `Accept` value. + /// - Returns: The header. + public static func accept(_ value: String) -> HTTPHeader { + return 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 { + return 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 { + return 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 { + return 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 { + return 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 { + return 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 { + return 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 { + return 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 { + return 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 + +public extension HTTPHeaders { + /// The default set of `HTTPHeaders` used by Alamofire. Includes `Accept-Encoding`, `Accept-Language`, and + /// `User-Agent`. + 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 userAgent: String = { + if let info = Bundle.main.infoDictionary { + let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" + let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" + let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown" + let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown" + + let osNameVersion: String = { + let version = ProcessInfo.processInfo.operatingSystemVersion + let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" + // swiftformat:disable indent + let osName: String = { + #if os(iOS) + return "iOS" + #elseif os(watchOS) + return "watchOS" + #elseif os(tvOS) + return "tvOS" + #elseif os(macOS) + return "macOS" + #elseif os(Linux) + return "Linux" + #else + return "Unknown" + #endif + }() + // swiftformat:enable indent + + return "\(osName) \(versionString)" + }() + + let alamofireVersion = "Alamofire/\(version)" + + return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)" + } + + return "Alamofire" + }() + + return .userAgent(userAgent) + }() +} + +extension Collection where Element == String { + func qualityEncoded() -> String { + return 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 { return allHTTPHeaderFields.map(HTTPHeaders.init) ?? HTTPHeaders() } + set { allHTTPHeaderFields = newValue.dictionary } + } +} + +extension HTTPURLResponse { + /// Returns `allHeaderFields` as `HTTPHeaders`. + public var headers: HTTPHeaders { + return (allHeaderFields as? [String: String]).map(HTTPHeaders.init) ?? HTTPHeaders() + } +} + +public extension URLSessionConfiguration { + /// Returns `httpAdditionalHeaders` as `HTTPHeaders`. + var headers: HTTPHeaders { + get { return (httpAdditionalHeaders as? [String: String]).map(HTTPHeaders.init) ?? HTTPHeaders() } + set { httpAdditionalHeaders = newValue.dictionary } + } +} diff --git a/Example/Pods/Alamofire/Source/HTTPMethod.swift b/Example/Pods/Alamofire/Source/HTTPMethod.swift new file mode 100644 index 0000000..4867c1e --- /dev/null +++ b/Example/Pods/Alamofire/Source/HTTPMethod.swift @@ -0,0 +1,54 @@ +// +// 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") + /// `TRACE` method. + public static let trace = HTTPMethod(rawValue: "TRACE") + + public let rawValue: String + + public init(rawValue: String) { + self.rawValue = rawValue + } +} diff --git a/Example/Pods/Alamofire/Source/MultipartFormData.swift b/Example/Pods/Alamofire/Source/MultipartFormData.swift index b840138..4ef54aa 100644 --- a/Example/Pods/Alamofire/Source/MultipartFormData.swift +++ b/Example/Pods/Alamofire/Source/MultipartFormData.swift @@ -1,7 +1,7 @@ // // MultipartFormData.swift // -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) +// 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 @@ -43,7 +43,6 @@ import CoreServices /// - 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 struct EncodingCharacters { @@ -71,7 +70,7 @@ open class MultipartFormData { boundaryText = "\(EncodingCharacters.crlf)--\(boundary)--\(EncodingCharacters.crlf)" } - return boundaryText.data(using: String.Encoding.utf8, allowLossyConversion: false)! + return Data(boundaryText.utf8) } } @@ -91,6 +90,9 @@ open class MultipartFormData { // 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)" @@ -98,7 +100,9 @@ open class MultipartFormData { public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } } /// The boundary used to separate the body parts in the encoded form data. - public var boundary: String + public let boundary: String + + let fileManager: FileManager private var bodyParts: [BodyPart] private var bodyPartError: AFError? @@ -106,63 +110,27 @@ open class MultipartFormData { // MARK: - Lifecycle - /// Creates a multipart form data object. + /// Creates an instance. /// - /// - returns: The multipart form data object. - public init() { - self.boundary = BoundaryGenerator.randomBoundary() - self.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 - /// - - self.streamBufferSize = 1024 + /// - 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 multipart form data object. - /// - /// The body part data will be encoded using the following format: - /// - /// - `Content-Disposition: form-data; name=#{name}` (HTTP Header) - /// - Encoded data - /// - Multipart form boundary - /// - /// - parameter data: The data to encode into the multipart form data. - /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. - public func append(_ data: Data, withName name: String) { - let headers = contentHeaders(withName: name) - let stream = InputStream(data: data) - let length = UInt64(data.count) - - append(stream, withLength: length, headers: headers) - } - - /// Creates a body part from the data and appends it to the multipart form data object. - /// - /// The body part data will be encoded using the following format: - /// - /// - `Content-Disposition: form-data; name=#{name}` (HTTP Header) - /// - `Content-Type: #{generated mimeType}` (HTTP Header) - /// - Encoded data - /// - Multipart form boundary - /// - /// - parameter data: The data to encode into the multipart form data. - /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. - /// - parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header. - public func append(_ data: Data, withName name: String, mimeType: String) { - let headers = contentHeaders(withName: name, mimeType: mimeType) - let stream = InputStream(data: data) - let length = UInt64(data.count) - - append(stream, withLength: length, headers: headers) - } - - /// Creates a body part from the data and appends it to the multipart form data object. + /// Creates a body part from the data and appends it to the instance. /// /// The body part data will be encoded using the following format: /// @@ -171,11 +139,12 @@ open class MultipartFormData { /// - Encoded file data /// - Multipart form boundary /// - /// - parameter data: The data to encode into the multipart form data. - /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. - /// - parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header. - /// - parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header. - public func append(_ data: Data, withName name: String, fileName: String, mimeType: String) { + /// - 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) @@ -183,7 +152,7 @@ open class MultipartFormData { append(stream, withLength: length, headers: headers) } - /// Creates a body part from the file and appends it to the multipart form data object. + /// Creates a body part from the file and appends it to the instance. /// /// The body part data will be encoded using the following format: /// @@ -196,8 +165,9 @@ open class MultipartFormData { /// `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the /// system associated MIME type. /// - /// - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. - /// - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. + /// - 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 @@ -210,7 +180,7 @@ open class MultipartFormData { } } - /// Creates a body part from the file and appends it to the multipart form data object. + /// Creates a body part from the file and appends it to the instance. /// /// The body part data will be encoded using the following format: /// @@ -219,10 +189,11 @@ open class MultipartFormData { /// - Encoded file data /// - Multipart form boundary /// - /// - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. - /// - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. - /// - parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header. - /// - parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header. + /// - 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) @@ -257,7 +228,7 @@ open class MultipartFormData { var isDirectory: ObjCBool = false let path = fileURL.path - guard FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) && !isDirectory.boolValue else { + guard fileManager.fileExists(atPath: path, isDirectory: &isDirectory) && !isDirectory.boolValue else { setBodyPartError(withReason: .bodyPartFileIsDirectory(at: fileURL)) return } @@ -269,14 +240,13 @@ open class MultipartFormData { let bodyContentLength: UInt64 do { - guard let fileSize = try FileManager.default.attributesOfItem(atPath: path)[.size] as? NSNumber else { + guard let fileSize = try fileManager.attributesOfItem(atPath: path)[.size] as? NSNumber else { setBodyPartError(withReason: .bodyPartFileSizeNotAvailable(at: fileURL)) return } bodyContentLength = fileSize.uint64Value - } - catch { + } catch { setBodyPartError(withReason: .bodyPartFileSizeQueryFailedWithError(forURL: fileURL, error: error)) return } @@ -293,7 +263,7 @@ open class MultipartFormData { append(stream, withLength: bodyContentLength, headers: headers) } - /// Creates a body part from the stream and appends it to the multipart form data object. + /// Creates a body part from the stream and appends it to the instance. /// /// The body part data will be encoded using the following format: /// @@ -302,23 +272,22 @@ open class MultipartFormData { /// - Encoded stream data /// - Multipart form boundary /// - /// - parameter stream: The input stream to encode in the multipart form data. - /// - parameter length: The content length of the stream. - /// - parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header. - /// - parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header. - /// - parameter mimeType: The 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) - { + /// - 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 headers, stream and length and appends it to the multipart form data object. + /// 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: /// @@ -326,9 +295,10 @@ open class MultipartFormData { /// - Encoded stream data /// - Multipart form boundary /// - /// - parameter stream: The input stream to encode in the multipart form data. - /// - parameter length: The content length of the stream. - /// - parameter headers: The HTTP headers for the body part. + /// - 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) @@ -336,15 +306,14 @@ open class MultipartFormData { // MARK: - Data Encoding - /// Encodes all the appended body parts into a single `Data` value. - /// - /// It is important to note that 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 `writeEncodedDataToDisk(fileURL:completionHandler:)` method. + /// Encodes all appended body parts into a single `Data` value. /// - /// - throws: An `AFError` if encoding encounters an error. + /// - 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. + /// - 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 @@ -363,20 +332,19 @@ open class MultipartFormData { return encoded } - /// Writes the appended body parts into the given file URL. + /// 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: The file URL to write the multipart form data into. - /// - /// - throws: An `AFError` if encoding encounters an error. + /// - 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.default.fileExists(atPath: fileURL.path) { + if fileManager.fileExists(atPath: fileURL.path) { throw AFError.multipartEncodingFailed(reason: .outputStreamFileAlreadyExists(at: fileURL)) } else if !fileURL.isFileURL { throw AFError.multipartEncodingFailed(reason: .outputStreamURLInvalid(url: fileURL)) @@ -389,10 +357,10 @@ open class MultipartFormData { outputStream.open() defer { outputStream.close() } - self.bodyParts.first?.hasInitialBoundary = true - self.bodyParts.last?.hasFinalBoundary = true + bodyParts.first?.hasInitialBoundary = true + bodyParts.last?.hasFinalBoundary = true - for bodyPart in self.bodyParts { + for bodyPart in bodyParts { try write(bodyPart, to: outputStream) } } @@ -419,14 +387,11 @@ open class MultipartFormData { } private func encodeHeaders(for bodyPart: BodyPart) -> Data { - var headerText = "" - - for (key, value) in bodyPart.headers { - headerText += "\(key): \(value)\(EncodingCharacters.crlf)" - } - headerText += EncodingCharacters.crlf + let headerText = bodyPart.headers.map { "\($0.name): \($0.value)\(EncodingCharacters.crlf)" } + .joined() + + EncodingCharacters.crlf - return headerText.data(using: String.Encoding.utf8, allowLossyConversion: false)! + return Data(headerText.utf8) } private func encodeBodyStream(for bodyPart: BodyPart) throws -> Data { @@ -537,8 +502,7 @@ open class MultipartFormData { private func mimeType(forPathExtension pathExtension: String) -> String { if let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), - let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() - { + let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() { return contentType as String } @@ -547,12 +511,12 @@ open class MultipartFormData { // MARK: - Private - Content Headers - private func contentHeaders(withName name: String, fileName: String? = nil, mimeType: String? = nil) -> [String: String] { + 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 = ["Content-Disposition": disposition] - if let mimeType = mimeType { headers["Content-Type"] = mimeType } + var headers: HTTPHeaders = [.contentDisposition(disposition)] + if let mimeType = mimeType { headers.add(.contentType(mimeType)) } return headers } diff --git a/Example/Pods/Alamofire/Source/MultipartUpload.swift b/Example/Pods/Alamofire/Source/MultipartUpload.swift new file mode 100644 index 0000000..4772c30 --- /dev/null +++ b/Example/Pods/Alamofire/Source/MultipartUpload.swift @@ -0,0 +1,87 @@ +// +// 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() } + + let isInBackgroundSession: Bool + let multipartFormData: MultipartFormData + let encodingMemoryThreshold: UInt64 + let request: URLRequestConvertible + let fileManager: FileManager + + init(isInBackgroundSession: Bool, + encodingMemoryThreshold: UInt64, + request: URLRequestConvertible, + multipartFormData: MultipartFormData) { + self.isInBackgroundSession = isInBackgroundSession + self.encodingMemoryThreshold = encodingMemoryThreshold + self.request = request + fileManager = multipartFormData.fileManager + self.multipartFormData = multipartFormData + } + + func build() throws -> (request: URLRequest, uploadable: UploadRequest.Uploadable) { + var urlRequest = try request.asURLRequest() + urlRequest.setValue(multipartFormData.contentType, forHTTPHeaderField: "Content-Type") + + let uploadable: UploadRequest.Uploadable + if multipartFormData.contentLength < encodingMemoryThreshold && !isInBackgroundSession { + let data = try multipartFormData.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.writeEncodedData(to: fileURL) + } catch { + // Cleanup after attempted write if it fails. + try? fileManager.removeItem(at: fileURL) + } + + uploadable = .file(fileURL, shouldRemove: true) + } + + return (request: urlRequest, uploadable: uploadable) + } +} + +extension MultipartUpload: UploadConvertible { + func asURLRequest() throws -> URLRequest { + return try result.get().request + } + + func createUploadable() throws -> UploadRequest.Uploadable { + return try result.get().uploadable + } +} diff --git a/Example/Pods/Alamofire/Source/NetworkReachabilityManager.swift b/Example/Pods/Alamofire/Source/NetworkReachabilityManager.swift index 398ca82..a07aa1d 100644 --- a/Example/Pods/Alamofire/Source/NetworkReachabilityManager.swift +++ b/Example/Pods/Alamofire/Source/NetworkReachabilityManager.swift @@ -1,7 +1,7 @@ // // NetworkReachabilityManager.swift // -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) +// 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 @@ -22,12 +22,12 @@ // THE SOFTWARE. // -#if !os(watchOS) +#if !(os(watchOS) || os(Linux)) import Foundation import SystemConfiguration -/// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and +/// 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 @@ -35,102 +35,116 @@ import SystemConfiguration /// 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. - /// - /// - unknown: It is unknown whether the network is reachable. - /// - notReachable: The network is not reachable. - /// - reachable: The network is reachable. 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) - } - /// Defines the various connection types detected by reachability flags. - /// - /// - ethernetOrWiFi: The connection type is either over Ethernet or WiFi. - /// - wwan: The connection type is a WWAN connection. - public enum ConnectionType { - case ethernetOrWiFi - case wwan + 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 { return isReachableOnWWAN || isReachableOnEthernetOrWiFi } + open var isReachable: Bool { return isReachableOnCellular || isReachableOnEthernetOrWiFi } - /// Whether the network is currently reachable over the WWAN interface. - open var isReachableOnWWAN: Bool { return networkReachabilityStatus == .reachable(.wwan) } + /// 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 { return status == .reachable(.cellular) } /// Whether the network is currently reachable over Ethernet or WiFi interface. - open var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .reachable(.ethernetOrWiFi) } + open var isReachableOnEthernetOrWiFi: Bool { return status == .reachable(.ethernetOrWiFi) } - /// The current network reachability status. - open var networkReachabilityStatus: NetworkReachabilityStatus { - guard let flags = self.flags else { return .unknown } - return networkReachabilityStatusForFlags(flags) - } - - /// The dispatch queue to execute the `listener` closure on. - open var listenerQueue: DispatchQueue = DispatchQueue.main - - /// A closure executed when the network reachability status changes. - open var listener: Listener? + /// `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() - if SCNetworkReachabilityGetFlags(reachability, &flags) { - return flags - } + return (SCNetworkReachabilityGetFlags(reachability, &flags)) ? flags : nil + } - return nil + /// The current network reachability status. + open var status: NetworkReachabilityStatus { + return 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 - open var previousFlags: SCNetworkReachabilityFlags + + /// Protected storage for mutable state. + private let mutableState = Protector(MutableState()) // MARK: - Initialization - /// Creates a `NetworkReachabilityManager` instance with the specified host. + /// Creates an instance with the specified host. /// - /// - parameter host: The host used to evaluate network reachability. + /// - Note: The `host` value must *not* contain a scheme, just the hostname. /// - /// - returns: The new `NetworkReachabilityManager` instance. + /// - 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 a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0. + /// 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. - /// - /// - returns: The new `NetworkReachabilityManager` instance. public convenience init?() { - var address = sockaddr_in() - address.sin_len = UInt8(MemoryLayout.size) - address.sin_family = sa_family_t(AF_INET) + var zero = sockaddr() + zero.sa_len = UInt8(MemoryLayout.size) + zero.sa_family = sa_family_t(AF_INET) - guard let reachability = withUnsafePointer(to: &address, { pointer in - return pointer.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout.size) { - return SCNetworkReachabilityCreateWithAddress(nil, $0) - } - }) else { return nil } + guard let reachability = SCNetworkReachabilityCreateWithAddress(nil, &zero) else { return nil } self.init(reachability: reachability) } private init(reachability: SCNetworkReachability) { self.reachability = reachability - - // Set the previous flags to an unreserved value to represent unknown status - self.previousFlags = SCNetworkReachabilityFlags(rawValue: 1 << 30) } deinit { @@ -141,70 +155,77 @@ open class NetworkReachabilityManager { /// Starts listening for changes in network reachability status. /// - /// - returns: `true` if listening was started successfully, `false` otherwise. + /// - 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() -> Bool { - var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) - context.info = Unmanaged.passUnretained(self).toOpaque() + open func startListening(onQueue queue: DispatchQueue = .main, + onUpdatePerforming listener: @escaping Listener) -> Bool { + stopListening() - let callbackEnabled = SCNetworkReachabilitySetCallback( - reachability, - { (_, flags, info) in - let reachability = Unmanaged.fromOpaque(info!).takeUnretainedValue() - reachability.notifyListener(flags) - }, - &context - ) + mutableState.write { state in + state.listenerQueue = queue + state.listener = listener + } - let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue) + var context = SCNetworkReachabilityContext(version: 0, + info: Unmanaged.passRetained(self).toOpaque(), + retain: nil, + release: nil, + copyDescription: nil) + let callback: SCNetworkReachabilityCallBack = { _, flags, info in + guard let info = info else { return } - listenerQueue.async { - self.previousFlags = SCNetworkReachabilityFlags(rawValue: 1 << 30) + let instance = Unmanaged.fromOpaque(info).takeUnretainedValue() + instance.notifyListener(flags) + } - guard let flags = self.flags else { return } + let queueAdded = SCNetworkReachabilitySetDispatchQueue(reachability, reachabilityQueue) + let callbackAdded = SCNetworkReachabilitySetCallback(reachability, callback, &context) - self.notifyListener(flags) + // Manually call listener to give initial state, since the framework may not. + if let currentFlags = flags { + reachabilityQueue.async { + self.notifyListener(currentFlags) + } } - return callbackEnabled && queueEnabled + 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) { - guard previousFlags != flags else { return } - previousFlags = flags - - listener?(networkReachabilityStatusForFlags(flags)) - } - - // MARK: - Internal - Network Reachability Status - - func networkReachabilityStatusForFlags(_ flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus { - guard isNetworkReachable(with: flags) else { return .notReachable } + let newStatus = NetworkReachabilityStatus(flags) - var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi) - - #if os(iOS) - if flags.contains(.isWWAN) { networkStatus = .reachable(.wwan) } - #endif - - return networkStatus - } + mutableState.write { state in + guard state.previousStatus != newStatus else { return } - func isNetworkReachable(with flags: SCNetworkReachabilityFlags) -> Bool { - let isReachable = flags.contains(.reachable) - let needsConnection = flags.contains(.connectionRequired) - let canConnectAutomatically = flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic) - let canConnectWithoutUserInteraction = canConnectAutomatically && !flags.contains(.interventionRequired) + state.previousStatus = newStatus - return isReachable && (!needsConnection || canConnectWithoutUserInteraction) + let listener = state.listener + state.listenerQueue?.async { listener?(newStatus) } + } } } @@ -212,27 +233,34 @@ open class NetworkReachabilityManager { extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} -/// Returns whether the two network reachability status values are equal. -/// -/// - parameter lhs: The left-hand side value to compare. -/// - parameter rhs: The right-hand side value to compare. -/// -/// - returns: `true` if the two values are equal, `false` otherwise. -public func ==( - lhs: NetworkReachabilityManager.NetworkReachabilityStatus, - rhs: NetworkReachabilityManager.NetworkReachabilityStatus) - -> Bool -{ - switch (lhs, rhs) { - case (.unknown, .unknown): - return true - case (.notReachable, .notReachable): - return true - case let (.reachable(lhsConnectionType), .reachable(rhsConnectionType)): - return lhsConnectionType == rhsConnectionType - default: +extension SCNetworkReachabilityFlags { + var isReachable: Bool { return contains(.reachable) } + var isConnectionRequired: Bool { return contains(.connectionRequired) } + var canConnectAutomatically: Bool { return contains(.connectionOnDemand) || contains(.connectionOnTraffic) } + var canConnectWithoutUserInteraction: Bool { return canConnectAutomatically && !contains(.interventionRequired) } + var isActuallyReachable: Bool { return 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 diff --git a/Example/Pods/Alamofire/Source/Notifications.swift b/Example/Pods/Alamofire/Source/Notifications.swift index e1ac31b..4a4b25a 100644 --- a/Example/Pods/Alamofire/Source/Notifications.swift +++ b/Example/Pods/Alamofire/Source/Notifications.swift @@ -1,7 +1,7 @@ // // Notifications.swift // -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) +// 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 @@ -24,32 +24,92 @@ import Foundation -extension Notification.Name { - /// Used as a namespace for all `URLSessionTask` related notifications. - public struct Task { - /// Posted when a `URLSessionTask` is resumed. The notification `object` contains the resumed `URLSessionTask`. - public static let DidResume = Notification.Name(rawValue: "org.alamofire.notification.name.task.didResume") +public extension Request { + /// Posted when a `Request` is resumed. The `Notification` contains the resumed `Request`. + static let didResumeNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didResume") + /// Posted when a `Request` is suspended. The `Notification` contains the suspended `Request`. + static let didSuspendNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didSuspend") + /// Posted when a `Request` is cancelled. The `Notification` contains the cancelled `Request`. + static let didCancelNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didCancel") + /// Posted when a `Request` is finished. The `Notification` contains the completed `Request`. + static let didFinishNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didFinish") - /// Posted when a `URLSessionTask` is suspended. The notification `object` contains the suspended `URLSessionTask`. - public static let DidSuspend = Notification.Name(rawValue: "org.alamofire.notification.name.task.didSuspend") + /// Posted when a `URLSessionTask` is resumed. The `Notification` contains the `Request` associated with the `URLSessionTask`. + 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`. + 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`. + 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`. + static let didCompleteTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didCompleteTask") +} + +// MARK: - - /// Posted when a `URLSessionTask` is cancelled. The notification `object` contains the cancelled `URLSessionTask`. - public static let DidCancel = Notification.Name(rawValue: "org.alamofire.notification.name.task.didCancel") +extension Notification { + /// The `Request` contained by the instance's `userInfo`, `nil` otherwise. + public var request: Request? { + return userInfo?[String.requestKey] as? Request + } - /// Posted when a `URLSessionTask` is completed. The notification `object` contains the completed `URLSessionTask`. - public static let DidComplete = Notification.Name(rawValue: "org.alamofire.notification.name.task.didComplete") + /// 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]) } } -// MARK: - +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 Notification { - /// Used as a namespace for all `Notification` user info dictionary keys. - public struct Key { - /// User info dictionary key representing the `URLSessionTask` associated with the notification. - public static let Task = "org.alamofire.notification.key.task" +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) + } - /// User info dictionary key representing the responseData associated with the notification. - public static let ResponseData = "org.alamofire.notification.key.responseData" + public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) { + NotificationCenter.default.postNotification(named: Request.didCompleteTaskNotification, with: request) } } diff --git a/Example/Pods/Alamofire/Source/OperationQueue+Alamofire.swift b/Example/Pods/Alamofire/Source/OperationQueue+Alamofire.swift new file mode 100644 index 0000000..b06a0cc --- /dev/null +++ b/Example/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 + } +} diff --git a/Example/Pods/Alamofire/Source/ParameterEncoder.swift b/Example/Pods/Alamofire/Source/ParameterEncoder.swift new file mode 100644 index 0000000..1e5c70a --- /dev/null +++ b/Example/Pods/Alamofire/Source/ParameterEncoder.swift @@ -0,0 +1,184 @@ +// +// 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: 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 { return 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: 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 + } +} + +/// 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 { return 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: 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 { 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 { try encoder.encode(parameters) } + .mapError { AFError.parameterEncoderFailed(reason: .encoderFailed(error: $0)) }.get() + } + + return request + } +} diff --git a/Example/Pods/Alamofire/Source/ParameterEncoding.swift b/Example/Pods/Alamofire/Source/ParameterEncoding.swift index 6195809..fbf1701 100644 --- a/Example/Pods/Alamofire/Source/ParameterEncoding.swift +++ b/Example/Pods/Alamofire/Source/ParameterEncoding.swift @@ -1,7 +1,7 @@ // // ParameterEncoding.swift // -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) +// 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 @@ -24,36 +24,19 @@ import Foundation -/// HTTP method definitions. -/// -/// See https://tools.ietf.org/html/rfc7231#section-4.3 -public enum HTTPMethod: String { - case options = "OPTIONS" - case get = "GET" - case head = "HEAD" - case post = "POST" - case put = "PUT" - case patch = "PATCH" - case delete = "DELETE" - case trace = "TRACE" - case connect = "CONNECT" -} - -// MARK: - - /// 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 URL request by encoding parameters and applying them onto an existing request. + /// Creates a `URLRequest` by encoding parameters and applying them on the passed request. /// - /// - parameter urlRequest: The request to have parameters applied. - /// - parameter parameters: The parameters to apply. + /// - Parameters: + /// - urlRequest: `URLRequestConvertible` value onto which parameters will be encoded. + /// - parameters: `Parameters` to encode onto the request. /// - /// - throws: An `AFError.parameterEncodingFailed` error if encoding fails. - /// - /// - returns: The encoded request. + /// - Returns: The encoded `URLRequest`. + /// - Throws: Any `Error` produced during parameter encoding. func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest } @@ -74,27 +57,34 @@ public protocol ParameterEncoding { /// `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. - /// - /// - methodDependent: 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. - /// - queryString: Sets or appends encoded query string result to existing query string. - /// - httpBody: Sets encoded query string result as the HTTP body of the URL request. public enum Destination { - case methodDependent, queryString, httpBody + /// 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. - /// - /// - brackets: An empty set of square brackets is appended to the key for every value. - /// This is the default behavior. - /// - noBrackets: No brackets are appended. The key is encoded as is. public enum ArrayEncoding { - case brackets, noBrackets + /// 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 func encode(key: String) -> String { switch self { @@ -107,11 +97,11 @@ public struct URLEncoding: ParameterEncoding { } /// Configures how `Bool` parameters are encoded. - /// - /// - numeric: Encode `true` as `1` and `false` as `0`. This is the default behavior. - /// - literal: Encode `true` and `false` as string literals. public enum BoolEncoding { - case numeric, literal + /// 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 { @@ -125,12 +115,9 @@ public struct URLEncoding: ParameterEncoding { // MARK: Properties - /// Returns a default `URLEncoding` instance. + /// Returns a default `URLEncoding` instance with a `.methodDependent` destination. public static var `default`: URLEncoding { return URLEncoding() } - /// Returns a `URLEncoding` instance with a `.methodDependent` destination. - public static var methodDependent: URLEncoding { return URLEncoding() } - /// Returns a `URLEncoding` instance with a `.queryString` destination. public static var queryString: URLEncoding { return URLEncoding(destination: .queryString) } @@ -148,14 +135,16 @@ public struct URLEncoding: ParameterEncoding { // MARK: Initialization - /// Creates a `URLEncoding` instance using the specified destination. - /// - /// - parameter destination: The destination defining where the encoded query string is to be applied. - /// - parameter arrayEncoding: The encoding to use for `Array` parameters. - /// - parameter boolEncoding: The encoding to use for `Bool` parameters. + /// Creates an instance using the specified parameters. /// - /// - returns: The new `URLEncoding` instance. - public init(destination: Destination = .methodDependent, arrayEncoding: ArrayEncoding = .brackets, boolEncoding: BoolEncoding = .numeric) { + /// - 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 @@ -163,20 +152,12 @@ public struct URLEncoding: ParameterEncoding { // MARK: Encoding - /// Creates a URL request by encoding parameters and applying them onto an existing request. - /// - /// - parameter urlRequest: The request to have parameters applied. - /// - parameter parameters: The parameters to apply. - /// - /// - throws: An `Error` if the encoding process encounters an error. - /// - /// - returns: The encoded request. 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 = HTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: method) { + if let method = urlRequest.method, destination.encodesParametersInURL(for: method) { guard let url = urlRequest.url else { throw AFError.parameterEncodingFailed(reason: .missingURL) } @@ -191,18 +172,19 @@ public struct URLEncoding: ParameterEncoding { urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") } - urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false) + urlRequest.httpBody = Data(query(parameters).utf8) } return urlRequest } - /// Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion. + /// Creates a percent-escaped, URL encoded query string components from the given key-value pair recursively. /// - /// - parameter key: The key of the query component. - /// - parameter value: The value of the query component. + /// - Parameters: + /// - key: Key of the query component. + /// - value: Value of the query component. /// - /// - returns: The percent-escaped, URL encoded query string components. + /// - Returns: The percent-escaped, URL encoded query string components. public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] { var components: [(String, String)] = [] @@ -229,60 +211,13 @@ public struct URLEncoding: ParameterEncoding { return components } - /// Returns a percent-escaped string following RFC 3986 for a query string key or value. - /// - /// RFC 3986 states that the following characters are "reserved" characters. - /// - /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/" - /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" + /// Creates a percent-escaped string following RFC 3986 for a query string key or value. /// - /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow - /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" - /// should be percent-escaped in the query string. + /// - Parameter string: `String` to be percent-escaped. /// - /// - parameter string: The string to be percent-escaped. - /// - /// - returns: The percent-escaped string. + /// - Returns: The percent-escaped `String`. public func escape(_ string: String) -> String { - let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 - let subDelimitersToEncode = "!$&'()*+,;=" - - var allowedCharacterSet = CharacterSet.urlQueryAllowed - allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") - - var escaped = "" - - //========================================================================================================== - // - // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few - // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no - // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more - // info, please refer to: - // - // - https://github.com/Alamofire/Alamofire/issues/206 - // - //========================================================================================================== - - if #available(iOS 8.3, *) { - escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string - } else { - let batchSize = 50 - var index = string.startIndex - - while index != string.endIndex { - let startIndex = index - let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex - let range = startIndex.. String { @@ -294,24 +229,6 @@ public struct URLEncoding: ParameterEncoding { } return components.map { "\($0)=\($1)" }.joined(separator: "&") } - - private func encodesParametersInURL(with method: HTTPMethod) -> Bool { - switch destination { - case .queryString: - return true - case .httpBody: - return false - default: - break - } - - switch method { - case .get, .head, .delete: - return true - default: - return false - } - } } // MARK: - @@ -319,7 +236,6 @@ public struct URLEncoding: ParameterEncoding { /// 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 { - // MARK: Properties /// Returns a `JSONEncoding` instance with default writing options. @@ -333,25 +249,15 @@ public struct JSONEncoding: ParameterEncoding { // MARK: Initialization - /// Creates a `JSONEncoding` instance using the specified options. + /// Creates an instance using the specified `WritingOptions`. /// - /// - parameter options: The options for writing the parameters as JSON data. - /// - /// - returns: The new `JSONEncoding` instance. + /// - Parameter options: `JSONSerialization.WritingOptions` to use. public init(options: JSONSerialization.WritingOptions = []) { self.options = options } // MARK: Encoding - /// Creates a URL request by encoding parameters and applying them onto an existing request. - /// - /// - parameter urlRequest: The request to have parameters applied. - /// - parameter parameters: The parameters to apply. - /// - /// - throws: An `Error` if the encoding process encounters an error. - /// - /// - returns: The encoded request. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() @@ -372,14 +278,14 @@ public struct JSONEncoding: ParameterEncoding { return urlRequest } - /// Creates a URL request by encoding the JSON object and setting the resulting data on the HTTP body. - /// - /// - parameter urlRequest: The request to apply the JSON object to. - /// - parameter jsonObject: The JSON object to apply to the request. + /// Encodes any JSON compatible object into a `URLRequest`. /// - /// - throws: An `Error` if the encoding process encounters an error. + /// - 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 request. + /// - 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() @@ -403,81 +309,6 @@ public struct JSONEncoding: ParameterEncoding { // MARK: - -/// Uses `PropertyListSerialization` to create a plist representation of the parameters object, according to the -/// associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header -/// field of an encoded request is set to `application/x-plist`. -public struct PropertyListEncoding: ParameterEncoding { - - // MARK: Properties - - /// Returns a default `PropertyListEncoding` instance. - public static var `default`: PropertyListEncoding { return PropertyListEncoding() } - - /// Returns a `PropertyListEncoding` instance with xml formatting and default writing options. - public static var xml: PropertyListEncoding { return PropertyListEncoding(format: .xml) } - - /// Returns a `PropertyListEncoding` instance with binary formatting and default writing options. - public static var binary: PropertyListEncoding { return PropertyListEncoding(format: .binary) } - - /// The property list serialization format. - public let format: PropertyListSerialization.PropertyListFormat - - /// The options for writing the parameters as plist data. - public let options: PropertyListSerialization.WriteOptions - - // MARK: Initialization - - /// Creates a `PropertyListEncoding` instance using the specified format and options. - /// - /// - parameter format: The property list serialization format. - /// - parameter options: The options for writing the parameters as plist data. - /// - /// - returns: The new `PropertyListEncoding` instance. - public init( - format: PropertyListSerialization.PropertyListFormat = .xml, - options: PropertyListSerialization.WriteOptions = 0) - { - self.format = format - self.options = options - } - - // MARK: Encoding - - /// Creates a URL request by encoding parameters and applying them onto an existing request. - /// - /// - parameter urlRequest: The request to have parameters applied. - /// - parameter parameters: The parameters to apply. - /// - /// - throws: An `Error` if the encoding process encounters an error. - /// - /// - returns: The encoded request. - public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { - var urlRequest = try urlRequest.asURLRequest() - - guard let parameters = parameters else { return urlRequest } - - do { - let data = try PropertyListSerialization.data( - fromPropertyList: parameters, - format: format, - options: options - ) - - if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { - urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") - } - - urlRequest.httpBody = data - } catch { - throw AFError.parameterEncodingFailed(reason: .propertyListEncodingFailed(error: error)) - } - - return urlRequest - } -} - -// MARK: - - extension NSNumber { fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) } } diff --git a/Example/Pods/Alamofire/Source/Protector.swift b/Example/Pods/Alamofire/Source/Protector.swift new file mode 100644 index 0000000..3e42a53 --- /dev/null +++ b/Example/Pods/Alamofire/Source/Protector.swift @@ -0,0 +1,167 @@ +// +// Protector.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: - + +/// An `os_unfair_lock` wrapper. +final class UnfairLock { + 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() + } + + private func lock() { + os_unfair_lock_lock(unfairLock) + } + + private func unlock() { + os_unfair_lock_unlock(unfairLock) + } + + /// Executes a closure returning a value while acquiring the lock. + /// + /// - Parameter closure: The closure to run. + /// + /// - Returns: The value the closure generated. + func around(_ closure: () -> T) -> T { + lock(); defer { unlock() } + return closure() + } + + /// Execute a closure while acquiring the lock. + /// + /// - Parameter closure: The closure to run. + func around(_ closure: () -> Void) { + lock(); defer { unlock() } + return closure() + } +} + +/// A thread-safe wrapper around a value. +final class Protector { + private let lock = UnfairLock() + private var value: T + + init(_ value: T) { + self.value = value + } + + /// The contained value. Unsafe for anything more than direct read or write. + var directValue: T { + get { return lock.around { value } } + set { lock.around { value = newValue } } + } + + /// Synchronously read or transform the contained value. + /// + /// - Parameter closure: The closure to execute. + /// + /// - Returns: The return value of the closure passed. + func read(_ closure: (T) -> U) -> U { + return lock.around { closure(self.value) } + } + + /// Synchronously modify the protected value. + /// + /// - Parameter closure: The closure to execute. + /// + /// - Returns: The modified value. + @discardableResult + func write(_ closure: (inout T) -> U) -> U { + return lock.around { closure(&self.value) } + } +} + +extension Protector where T: RangeReplaceableCollection { + /// Adds a new element to the end of this protected collection. + /// + /// - Parameter newElement: The `Element` to append. + func append(_ newElement: T.Element) { + write { (ward: inout T) in + ward.append(newElement) + } + } + + /// Adds the elements of a sequence to the end of this protected collection. + /// + /// - Parameter newElements: The `Sequence` to append. + func append(contentsOf newElements: S) where S.Element == T.Element { + write { (ward: inout T) in + ward.append(contentsOf: newElements) + } + } + + /// Add the elements of a collection to the end of the protected collection. + /// + /// - Parameter newElements: The `Collection` to append. + func append(contentsOf newElements: C) where C.Element == T.Element { + write { (ward: inout T) in + ward.append(contentsOf: newElements) + } + } +} + +extension Protector where T == Data? { + /// Adds the contents of a `Data` value to the end of the protected `Data`. + /// + /// - Parameter data: The `Data` to be appended. + func append(_ data: Data) { + write { (ward: inout T) in + ward?.append(data) + } + } +} + +extension Protector 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 { + return 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) } + } +} diff --git a/Example/Pods/Alamofire/Source/RedirectHandler.swift b/Example/Pods/Alamofire/Source/RedirectHandler.swift new file mode 100644 index 0000000..b6c069c --- /dev/null +++ b/Example/Pods/Alamofire/Source/RedirectHandler.swift @@ -0,0 +1,95 @@ +// +// 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) + } + } +} diff --git a/Example/Pods/Alamofire/Source/Request.swift b/Example/Pods/Alamofire/Source/Request.swift index 2be2ce0..6398d96 100644 --- a/Example/Pods/Alamofire/Source/Request.swift +++ b/Example/Pods/Alamofire/Source/Request.swift @@ -1,7 +1,7 @@ // // Request.swift // -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) +// 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 @@ -24,272 +24,824 @@ import Foundation -/// 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 if necessary and returns the result. +/// `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? + /// Closure called when the `Request` is able to create a cURL description of itself. + var cURLHandler: ((String) -> 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? + } + + /// Protected `MutableState` value that provides thread-safe access to state values. + fileprivate let protectedMutableState: Protector = Protector(MutableState()) + + /// `State` of the `Request`. + public var state: State { return protectedMutableState.directValue.state } + /// Returns whether `state` is `.initialized`. + public var isInitialized: Bool { return state == .initialized } + /// Returns whether `state is `.resumed`. + public var isResumed: Bool { return state == .resumed } + /// Returns whether `state` is `.suspended`. + public var isSuspended: Bool { return state == .suspended } + /// Returns whether `state` is `.cancelled`. + public var isCancelled: Bool { return state == .cancelled } + /// Returns whether `state` is `.finished`. + public var isFinished: Bool { return 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`. + fileprivate var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? { + get { return protectedMutableState.directValue.uploadProgressHandler } + set { protectedMutableState.write { $0.uploadProgressHandler = newValue } } + } + + /// `ProgressHandler` called when `downloadProgress` is updated, on the provided `DispatchQueue`. + fileprivate var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? { + get { return protectedMutableState.directValue.downloadProgressHandler } + set { protectedMutableState.write { $0.downloadProgressHandler = newValue } } + } + + // MARK: Redirect Handling + + /// `RedirectHandler` set on the instance. + public private(set) var redirectHandler: RedirectHandler? { + get { return protectedMutableState.directValue.redirectHandler } + set { protectedMutableState.write { $0.redirectHandler = newValue } } + } + + // MARK: Cached Response Handling + + /// `CachedResponseHandler` set on the instance. + public private(set) var cachedResponseHandler: CachedResponseHandler? { + get { return protectedMutableState.directValue.cachedResponseHandler } + set { protectedMutableState.write { $0.cachedResponseHandler = newValue } } + } + + // MARK: URLCredential + + /// `URLCredential` used for authentication challenges. Created by calling one of the `authenticate` methods. + public private(set) var credential: URLCredential? { + get { return protectedMutableState.directValue.credential } + set { protectedMutableState.write { $0.credential = newValue } } + } + + // MARK: Validators + + /// `Validator` callback closures that store the validation calls enqueued. + fileprivate var protectedValidators: Protector<[() -> Void]> = Protector([]) + + // MARK: URLRequests + + /// All `URLRequests` created on behalf of the `Request`, including original and adapted requests. + public var requests: [URLRequest] { return protectedMutableState.directValue.requests } + /// First `URLRequest` created on behalf of the `Request`. May not be the first one actually executed. + public var firstRequest: URLRequest? { return requests.first } + /// Last `URLRequest` created on behalf of the `Request`. + public var lastRequest: URLRequest? { return requests.last } + /// Current `URLRequest` created on behalf of the `Request`. + public var request: URLRequest? { return 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] { + return protectedMutableState.read { $0.tasks.compactMap { $0.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? { return lastTask?.response as? HTTPURLResponse } + + // MARK: Tasks + + /// All `URLSessionTask`s created on behalf of the `Request`. + public var tasks: [URLSessionTask] { return protectedMutableState.directValue.tasks } + /// First `URLSessionTask` created on behalf of the `Request`. + public var firstTask: URLSessionTask? { return tasks.first } + /// Last `URLSessionTask` crated on behalf of the `Request`. + public var lastTask: URLSessionTask? { return tasks.last } + /// Current `URLSessionTask` created on behalf of the `Request`. + public var task: URLSessionTask? { return lastTask } + + // MARK: Metrics + + /// All `URLSessionTaskMetrics` gathered on behalf of the `Request`. Should correspond to the `tasks` created. + public var allMetrics: [URLSessionTaskMetrics] { return protectedMutableState.directValue.metrics } + /// First `URLSessionTaskMetrics` gathered on behalf of the `Request`. + public var firstMetrics: URLSessionTaskMetrics? { return allMetrics.first } + /// Last `URLSessionTaskMetrics` gathered on behalf of the `Request`. + public var lastMetrics: URLSessionTaskMetrics? { return allMetrics.last } + /// Current `URLSessionTaskMetrics` gathered on behalf of the `Request`. + public var metrics: URLSessionTaskMetrics? { return lastMetrics } + + // MARK: Retry Count + + /// Number of times the `Request` has been retried. + public var retryCount: Int { return protectedMutableState.directValue.retryCount } + + // MARK: Error + + /// `Error` returned from Alamofire internally, from the network request directly, or any validators executed. + public fileprivate(set) var error: AFError? { + get { return protectedMutableState.directValue.error } + set { protectedMutableState.write { $0.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 urlRequest: The URL request to adapt. + /// - Parameter request: The `URLRequest` created. + func didCreateInitialURLRequest(_ request: URLRequest) { + protectedMutableState.write { $0.requests.append(request) } + + eventMonitor?.request(self, didCreateInitialURLRequest: request) + } + + /// Called when initial `URLRequest` creation has failed, typically through a `URLRequestConvertible`. /// - /// - throws: An `Error` if the adaptation encounters an error. + /// - Note: Triggers retry. /// - /// - returns: The adapted `URLRequest`. - func adapt(_ urlRequest: URLRequest) throws -> URLRequest -} + /// - Parameter error: `AFError` thrown from the failed creation. + func didFailToCreateURLRequest(with error: AFError) { + self.error = error + + eventMonitor?.request(self, didFailToCreateURLRequestWithError: error) -// MARK: - + callCURLHandlerIfNecessary() -/// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not. -public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void + 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) { + protectedMutableState.write { $0.requests.append(adaptedRequest) } -/// 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. + eventMonitor?.request(self, didAdaptInitialRequest: initialRequest, to: adaptedRequest) + } + + /// Called when a `RequestAdapter` fails to adapt a `URLRequest`. /// - /// 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. + /// - Note: Triggers retry. /// - /// - parameter manager: The session manager the request was executed on. - /// - parameter request: The request that failed due to the encountered error. - /// - parameter error: The error encountered when executing the request. - /// - parameter completion: The completion closure to be executed when retry decision has been determined. - func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) -} + /// - Parameters: + /// - request: The `URLRequest` the adapter was called with. + /// - error: The `AFError` returned by the `RequestAdapter`. + func didFailToAdaptURLRequest(_ request: URLRequest, withError error: AFError) { + self.error = error -// MARK: - + eventMonitor?.request(self, didFailToAdaptURLRequest: request, withError: error) -protocol TaskConvertible { - func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask -} + callCURLHandlerIfNecessary() -/// A dictionary of headers to apply to a `URLRequest`. -public typealias HTTPHeaders = [String: String] + retryOrFinish(error: error) + } -// MARK: - + /// Final `URLRequest` has been created for the instance. + /// + /// - Parameter request: The `URLRequest` created. + func didCreateURLRequest(_ request: URLRequest) { + eventMonitor?.request(self, didCreateURLRequest: request) -/// Responsible for sending a request and receiving the response and associated data from the server, as well as -/// managing its underlying `URLSessionTask`. -open class Request { + callCURLHandlerIfNecessary() + } - // MARK: Helper Types + /// Asynchronously calls any stored `cURLHandler` and then removes it from `mutableState`. + private func callCURLHandlerIfNecessary() { + protectedMutableState.write { mutableState in + guard let cURLHandler = mutableState.cURLHandler else { return } - /// A closure executed when monitoring upload or download progress of a request. - public typealias ProgressHandler = (Progress) -> Void + self.underlyingQueue.async { cURLHandler(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) { + protectedMutableState.write { $0.tasks.append(task) } + + eventMonitor?.request(self, didCreateTask: task) + } + + /// Called when resumption is completed. + func didResume() { + eventMonitor?.requestDidResume(self) + } + + /// Called when a `URLSessionTask` is resumed on behalf of the instance. + /// + /// - Parameter task: The `URLSessionTask` resumed. + func didResumeTask(_ task: URLSessionTask) { + eventMonitor?.request(self, didResumeTask: task) + } + + /// Called when suspension is completed. + func didSuspend() { + eventMonitor?.requestDidSuspend(self) + } + + /// Called when a `URLSessionTask` is suspended on behalf of the instance. + /// + /// - Parameter task: The `URLSessionTask` suspended. + func didSuspendTask(_ task: URLSessionTask) { + eventMonitor?.request(self, didSuspendTask: task) + } + + /// Called when cancellation is completed, sets `error` to `AFError.explicitlyCancelled`. + func didCancel() { + 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) { + 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) { + protectedMutableState.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) { + 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?) { + self.error = self.error ?? error + protectedValidators.directValue.forEach { $0() } + + eventMonitor?.request(self, didCompleteTask: task, with: error) - enum RequestTask { - case data(TaskConvertible?, URLSessionTask?) - case download(TaskConvertible?, URLSessionTask?) - case upload(TaskConvertible?, URLSessionTask?) - case stream(TaskConvertible?, URLSessionTask?) + retryOrFinish(error: self.error) } - // MARK: Properties + /// Called when the `RequestDelegate` is going to retry this `Request`. Calls `reset()`. + func prepareForRetry() { + protectedMutableState.write { $0.retryCount += 1 } + + reset() - /// The delegate for the underlying task. - open internal(set) var delegate: TaskDelegate { - get { - taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } - return taskDelegate + 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?) { + guard 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) + } } - set { - taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } - taskDelegate = newValue + } + + /// Finishes this `Request` and starts the response serializers. + /// + /// - Parameter error: The possible `Error` with which the instance will finish. + func finish(error: AFError? = nil) { + 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) { + protectedMutableState.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() } } + } } } - /// The underlying task. - open var task: URLSessionTask? { return delegate.task } + /// 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)? - /// The session belonging to the underlying task. - public let session: URLSession + protectedMutableState.write { mutableState in + let responseSerializerIndex = mutableState.responseSerializerCompletions.count - /// The request sent or to be sent to the server. - open var request: URLRequest? { return task?.originalRequest } + if responseSerializerIndex < mutableState.responseSerializers.count { + responseSerializer = mutableState.responseSerializers[responseSerializerIndex] + } + } - /// The response received from the server, if any. - open var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse } + return responseSerializer + } - /// The number of times the request has been retried. - open internal(set) var retryCount: UInt = 0 + /// 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] = [] - let originalTask: TaskConvertible? + protectedMutableState.write { mutableState in + completions = mutableState.responseSerializerCompletions - var startTime: CFAbsoluteTime? - var endTime: CFAbsoluteTime? + // 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() - var validations: [() -> Void] = [] + if mutableState.state.canTransitionTo(.finished) { + mutableState.state = .finished + } - private var taskDelegate: TaskDelegate - private var taskDelegateLock = NSLock() + mutableState.responseSerializerProcessingFinished = true + } - // MARK: Lifecycle + completions.forEach { $0() } - init(session: URLSession, requestTask: RequestTask, error: Error? = nil) { - self.session = session + // Cleanup the request + cleanup() - switch requestTask { - case .data(let originalTask, let task): - taskDelegate = DataTaskDelegate(task: task) - self.originalTask = originalTask - case .download(let originalTask, let task): - taskDelegate = DownloadTaskDelegate(task: task) - self.originalTask = originalTask - case .upload(let originalTask, let task): - taskDelegate = UploadTaskDelegate(task: task) - self.originalTask = originalTask - case .stream(let originalTask, let task): - taskDelegate = TaskDelegate(task: task) - self.originalTask = originalTask + return } - delegate.error = error - delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() } + 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) { + protectedMutableState.write { $0.responseSerializerCompletions.append(completion) } + processNextResponseSerializer() } - // MARK: Authentication + /// Resets all task and response serializer related state for retry. + func reset() { + error = nil - /// Associates an HTTP Basic credential with the request. + uploadProgress.totalUnitCount = 0 + uploadProgress.completedUnitCount = 0 + downloadProgress.totalUnitCount = 0 + downloadProgress.completedUnitCount = 0 + + protectedMutableState.write { $0.responseSerializerCompletions = [] } + } + + /// Called when updating the upload progress. /// - /// - parameter user: The user. - /// - parameter password: The password. - /// - parameter persistence: The URL credential persistence. `.ForSession` by default. + /// - 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. /// - /// - returns: The request. - @discardableResult - open func authenticate( - user: String, - password: String, - persistence: URLCredential.Persistence = .forSession) - -> Self - { - let credential = URLCredential(user: user, password: password, persistence: persistence) - return authenticate(usingCredential: credential) + /// - Parameter perform: The closure to perform. + func withState(perform: (State) -> Void) { + protectedMutableState.withState(perform: perform) } - /// Associates a specified credential with the request. + // 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`. /// - /// - parameter credential: The credential. + /// - 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 request. + /// - Returns: The instance. @discardableResult - open func authenticate(usingCredential credential: URLCredential) -> Self { - delegate.credential = credential + public func cancel() -> Self { + protectedMutableState.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 } - /// Returns a base64 encoded basic authentication credential as an authorization header tuple. - /// - /// - parameter user: The user. - /// - parameter password: The password. + /// Suspends the instance. /// - /// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise. - open class func authorizationHeader(user: String, password: String) -> (key: String, value: String)? { - guard let data = "\(user):\(password)".data(using: .utf8) else { return nil } + /// - Returns: The instance. + @discardableResult + public func suspend() -> Self { + protectedMutableState.write { mutableState in + guard mutableState.state.canTransitionTo(.suspended) else { return } - let credential = data.base64EncodedString(options: []) + mutableState.state = .suspended - return (key: "Authorization", value: "Basic \(credential)") + underlyingQueue.async { self.didSuspend() } + + guard let task = mutableState.tasks.last, task.state != .completed else { return } + + task.suspend() + underlyingQueue.async { self.didSuspendTask(task) } + } + + return self } - // MARK: State + /// Resumes the instance. + /// + /// - Returns: The instance. + @discardableResult + public func resume() -> Self { + protectedMutableState.write { mutableState in + guard mutableState.state.canTransitionTo(.resumed) else { return } - /// Resumes the request. - open func resume() { - guard let task = task else { delegate.queue.isSuspended = false ; return } + mutableState.state = .resumed - if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } + underlyingQueue.async { self.didResume() } - task.resume() + guard let task = mutableState.tasks.last, task.state != .completed else { return } - NotificationCenter.default.post( - name: Notification.Name.Task.DidResume, - object: self, - userInfo: [Notification.Key.Task: task] - ) + task.resume() + underlyingQueue.async { self.didResumeTask(task) } + } + + return self } - /// Suspends the request. - open func suspend() { - guard let task = task else { return } + // MARK: - Closure API - task.suspend() + /// 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) - NotificationCenter.default.post( - name: Notification.Name.Task.DidSuspend, - object: self, - userInfo: [Notification.Key.Task: task] - ) + return authenticate(with: credential) } - /// Cancels the request. - open func cancel() { - guard let task = task else { return } + /// Associates the provided credential with the instance. + /// + /// - Parameter credential: The `URLCredential`. + /// + /// - Returns: The instance. + @discardableResult + public func authenticate(with credential: URLCredential) -> Self { + protectedMutableState.write { $0.credential = credential } - task.cancel() + 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 { + protectedMutableState.write { $0.downloadProgressHandler = (handler: closure, queue: queue) } - NotificationCenter.default.post( - name: Notification.Name.Task.DidCancel, - object: self, - userInfo: [Notification.Key.Task: task] - ) + return self } -} -// MARK: - CustomStringConvertible + /// 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 { + protectedMutableState.write { $0.uploadProgressHandler = (handler: closure, queue: queue) } -extension Request: CustomStringConvertible { - /// The textual representation used when written to an output stream, which includes the HTTP method and URL, as - /// well as the response status code if a response has been received. - open var description: String { - var components: [String] = [] + return self + } - if let HTTPMethod = request?.httpMethod { - components.append(HTTPMethod) + // 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 { + protectedMutableState.write { mutableState in + precondition(mutableState.redirectHandler == nil, "Redirect handler has already been set.") + mutableState.redirectHandler = handler } - if let urlString = request?.url?.absoluteString { - components.append(urlString) + 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 { + protectedMutableState.write { mutableState in + precondition(mutableState.cachedResponseHandler == nil, "Cached response handler has already been set.") + mutableState.cachedResponseHandler = handler } - if let response = response { - components.append("(\(response.statusCode))") + 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. + /// + /// - Returns: The instance. + @discardableResult + public func cURLDescription(calling handler: @escaping (String) -> Void) -> Self { + protectedMutableState.write { mutableState in + if mutableState.requests.last != nil { + underlyingQueue.async { handler(self.cURLDescription()) } + } else { + mutableState.cURLHandler = handler + } } - return components.joined(separator: " ") + return self + } + + // MARK: Cleanup + + /// Final cleanup step executed when the instance finishes response serialization. + func cleanup() { + delegate?.cleanup(after: self) + // No-op: override in subclass } } -// MARK: - CustomDebugStringConvertible +// MARK: - Protocol Conformances -extension Request: CustomDebugStringConvertible { - /// The textual representation used when written to an output stream, in the form of a cURL command. - open var debugDescription: String { - return cURLRepresentation() +extension Request: Equatable { + public static func ==(lhs: Request, rhs: Request) -> Bool { + return lhs.id == rhs.id } +} - func cURLRepresentation() -> String { - var components = ["$ curl -v"] +extension Request: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(id) + } +} - guard let request = self.request, - let url = request.url, - let host = url.host - else { - return "$ curl command could not be created" - } +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." } - if let httpMethod = request.httpMethod, httpMethod != "GET" { - components.append("-X \(httpMethod)") - } + 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"] - if let credentialStorage = self.session.configuration.urlCredentialStorage { - let protectionSpace = URLProtectionSpace( - host: host, - port: url.port ?? 0, - protocol: url.scheme, - realm: host, - authenticationMethod: NSURLAuthenticationMethodHTTPBasic - ) + 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 { @@ -297,42 +849,41 @@ extension Request: CustomDebugStringConvertible { components.append("-u \(user):\(password)") } } else { - if let credential = delegate.credential, let user = credential.user, let password = credential.password { + if let credential = credential, let user = credential.user, let password = credential.password { components.append("-u \(user):\(password)") } } } - if session.configuration.httpShouldSetCookies { + if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies { if - let cookieStorage = session.configuration.httpCookieStorage, - let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty - { - let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" } - - #if swift(>=3.2) - components.append("-b \"\(string[.. Void) - func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { - do { - let urlRequest = try self.urlRequest.adapt(using: adapter) - return queue.sync { session.dataTask(with: urlRequest) } - } catch { - throw AdaptError(error: error) - } - } - } + /// 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: Properties +// MARK: - Subclasses - /// The request sent or to be sent to the server. - open override var request: URLRequest? { - if let request = super.request { return request } - if let requestable = originalTask as? Requestable { return requestable.urlRequest } +// MARK: - DataRequest - return nil - } +/// `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? { return protectedData.directValue } - /// The progress of fetching the response data from the server for the request. - open var progress: Progress { return dataDelegate.progress } + /// Protected storage for the `Data` read by the instance. + private var protectedData: Protector = Protector(nil) - var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate } + /// 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) + } - // MARK: Stream + override func reset() { + super.reset() - /// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server. - /// - /// This closure returns the bytes most recently received from the server, not including data from previous calls. - /// If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is - /// also important to note that the server data in any `Response` object will be `nil`. + protectedData.directValue = nil + } + + /// Called when `Data` is received by this instance. /// - /// - parameter closure: The code to be executed periodically during the lifecycle of the request. + /// - Note: Also calls `updateDownloadProgress`. /// - /// - returns: The request. - @discardableResult - open func stream(closure: ((Data) -> Void)? = nil) -> Self { - dataDelegate.dataStream = closure - return self + /// - Parameter data: The `Data` received. + func didReceive(data: Data) { + if self.data == nil { + protectedData.directValue = data + } else { + protectedData.append(data) + } + + updateDownloadProgress() } - // MARK: Progress + override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + let copiedRequest = request + return session.dataTask(with: copiedRequest) + } + + /// Called to updated 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 - /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. + 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 queue: The dispatch queue to execute the closure on. - /// - parameter closure: The code to be executed periodically as data is read from the server. + /// - Parameter validation: `Validation` closure used to validate the response. /// - /// - returns: The request. + /// - Returns: The instance. @discardableResult - open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { - dataDelegate.progressHandler = (closure, queue) - return self - } -} + public func validate(_ validation: @escaping Validation) -> Self { + let validator: () -> Void = { [unowned self] in + guard self.error == nil, let response = self.response else { return } -// MARK: - + let result = validation(self.request, response, self.data) -/// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`. -open class DownloadRequest: Request { + if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) } - // MARK: Helper Types + self.eventMonitor?.request(self, + didValidateRequest: self.request, + response: response, + data: self.data, + withResult: result) + } + + protectedValidators.append(validator) + + return self + } +} - /// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the - /// destination URL. - public struct DownloadOptions: OptionSet { - /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol. - public let rawValue: UInt +// MARK: - DownloadRequest - /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified. - public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0) +/// `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) - /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified. - public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1) + public let rawValue: Int - /// Creates a `DownloadFileDestinationOptions` instance with the specified raw value. - /// - /// - parameter rawValue: The raw bitmask value for the option. - /// - /// - returns: A new log level instance. - public init(rawValue: UInt) { + public init(rawValue: Int) { self.rawValue = rawValue } } - /// A closure executed once a download request has successfully completed in order to determine where to move the + // 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 URL response, and returns a two arguments: the file URL where the temporary file should be moved and /// the options defining how the file should be moved. - public typealias DownloadFileDestination = ( - _ temporaryURL: URL, - _ response: HTTPURLResponse) - -> (destinationURL: URL, options: DownloadOptions) + public typealias Destination = (_ temporaryURL: URL, + _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options) - enum Downloadable: TaskConvertible { - case request(URLRequest) - case resumeData(Data) + /// 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 { + return { temporaryURL, response in + let directoryURLs = FileManager.default.urls(for: directory, in: domain) + let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL - func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { - do { - let task: URLSessionTask + return (url, options) + } + } - switch self { - case let .request(urlRequest): - let urlRequest = try urlRequest.adapt(using: adapter) - task = queue.sync { session.downloadTask(with: urlRequest) } - case let .resumeData(resumeData): - task = queue.sync { session.downloadTask(withResumeData: resumeData) } - } + /// 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 + let filename = "Alamofire_\(url.lastPathComponent)" + let destination = url.deletingLastPathComponent().appendingPathComponent(filename) - return task - } catch { - throw AdaptError(error: error) - } - } + return (destination, []) } - // MARK: Properties + // MARK: Downloadable - /// The request sent or to be sent to the server. - open override var request: URLRequest? { - if let request = super.request { return request } + /// 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) + } - if let downloadable = originalTask as? Downloadable, case let .request(urlRequest) = downloadable { - return urlRequest - } + // MARK: Mutable State - return nil + /// 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? } - /// The resume data of the underlying download task if available after a failure. - open var resumeData: Data? { return downloadDelegate.resumeData } + /// Protected mutable state specific to `DownloadRequest`. + private let protectedDownloadMutableState: Protector = Protector(DownloadRequestMutableState()) - /// The progress of downloading the response data from the server for the request. - open var progress: Progress { return downloadDelegate.progress } + /// If the download is resumable and eventually cancelled, 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? { return protectedDownloadMutableState.directValue.resumeData } + /// If the download is successful, the `URL` where the file was downloaded. + public var fileURL: URL? { return protectedDownloadMutableState.directValue.fileURL } - var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate } + // MARK: Initial State - // MARK: State + /// `Downloadable` value used for this instance. + public let downloadable: Downloadable + /// The `Destination` to which the downloaded file is moved. + let destination: Destination - /// Cancels the request. - override open func cancel() { - cancel(createResumeData: true) + /// 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) } - /// Cancels the request. + override func reset() { + super.reset() + + protectedDownloadMutableState.write { + $0.resumeData = nil + $0.fileURL = nil + } + } + + /// Called when a download has finished. /// - /// - parameter createResumeData: Determines whether resume data is created via the underlying download task or not. - open func cancel(createResumeData: Bool) { - if createResumeData { - downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 } - } else { - downloadDelegate.downloadTask.cancel() + /// - Parameters: + /// - task: `URLSessionTask` that finished the download. + /// - result: `Result` of the automatic move to `destination`. + func didFinishDownloading(using task: URLSessionTask, with result: Result) { + eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result) + + switch result { + case let .success(url): protectedDownloadMutableState.write { $0.fileURL = url } + case let .failure(error): self.error = error } + } - NotificationCenter.default.post( - name: Notification.Name.Task.DidCancel, - object: self, - userInfo: [Notification.Key.Task: task as Any] - ) + /// 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) } } - // MARK: Progress + override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + return session.downloadTask(with: request) + } - /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. + /// Creates a `URLSessionTask` from the provided resume data. /// - /// - parameter queue: The dispatch queue to execute the closure on. - /// - parameter closure: The code to be executed periodically as data is read from the server. + /// - Parameters: + /// - data: `Data` used to resume the download. + /// - session: `URLSession` used to create the `URLSessionTask`. /// - /// - returns: The request. + /// - Returns: The `URLSessionTask` created. + public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask { + return 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 - open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { - downloadDelegate.progressHandler = (closure, queue) - return self + public override func cancel() -> Self { + return cancel(producingResumeData: false) } - // MARK: Destination + /// 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 { + return cancel(optionallyProducingResumeData: shouldProduceResumeData ? { _ in } : nil) + } - /// 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. + /// Cancels the instance while producing resume data. Once cancelled, a `DownloadRequest` can no longer be resumed + /// or suspended. /// - /// - parameter directory: The search path directory. `.DocumentDirectory` by default. - /// - parameter domain: The search path domain mask. `.UserDomainMask` by default. + /// - Note: The resume data passed to the completion handler will also be available on the instance's `resumeData` + /// property. /// - /// - returns: A download file destination closure. - open class func suggestedDownloadDestination( - for directory: FileManager.SearchPathDirectory = .documentDirectory, - in domain: FileManager.SearchPathDomainMask = .userDomainMask) - -> DownloadFileDestination - { - return { temporaryURL, response in - let directoryURLs = FileManager.default.urls(for: directory, in: domain) + /// - 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 { + return 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 { + protectedMutableState.write { mutableState in + guard mutableState.state.canTransitionTo(.cancelled) else { return } + + mutableState.state = .cancelled + + underlyingQueue.async { self.didCancel() } - if !directoryURLs.isEmpty { - return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), []) + guard let task = mutableState.tasks.last as? URLSessionDownloadTask, task.state != .completed else { + underlyingQueue.async { self.finish() } + return } - return (temporaryURL, []) + if let completionHandler = completionHandler { + // Resume to ensure metrics are gathered. + task.resume() + task.cancel { resumeData in + self.protectedDownloadMutableState.write { $0.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) + } + + protectedValidators.append(validator) + + return self } } -// MARK: - +// 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) + } -/// Specific type of `Request` that manages an underlying `URLSessionUploadTask`. -open class UploadRequest: DataRequest { + // MARK: Initial State - // MARK: Helper Types + /// The `UploadableConvertible` value used to produce the `Uploadable` value for this instance. + public let upload: UploadableConvertible - enum Uploadable: TaskConvertible { - case data(Data, URLRequest) - case file(URL, URLRequest) - case stream(InputStream, URLRequest) + /// `FileManager` used to perform cleanup tasks, including the removal of multipart form encoded payloads written + /// to disk. + public let fileManager: FileManager - func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { - do { - let task: URLSessionTask + // MARK: Mutable State - switch self { - case let .data(data, urlRequest): - let urlRequest = try urlRequest.adapt(using: adapter) - task = queue.sync { session.uploadTask(with: urlRequest, from: data) } - case let .file(url, urlRequest): - let urlRequest = try urlRequest.adapt(using: adapter) - task = queue.sync { session.uploadTask(with: urlRequest, fromFile: url) } - case let .stream(_, urlRequest): - let urlRequest = try urlRequest.adapt(using: adapter) - task = queue.sync { session.uploadTask(withStreamedRequest: urlRequest) } - } + /// `Uploadable` value used by the instance. + public var uploadable: Uploadable? - return task - } catch { - throw AdaptError(error: error) - } - } + /// 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. + /// - 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) } - // MARK: Properties + /// 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) - /// The request sent or to be sent to the server. - open override var request: URLRequest? { - if let request = super.request { return request } + retryOrFinish(error: error) + } - guard let uploadable = originalTask as? Uploadable else { return nil } + 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 .data(_, let urlRequest), .file(_, let urlRequest), .stream(_, let urlRequest): - return urlRequest + 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) } } - /// The progress of uploading the payload to the server for the upload request. - open var uploadProgress: Progress { return uploadDelegate.uploadProgress } + /// 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.") + } - var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate } + guard case let .stream(stream) = uploadable else { + fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.") + } - // MARK: Upload Progress + eventMonitor?.request(self, didProvideInputStream: stream) - /// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to - /// the server. - /// - /// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress - /// of data being read from the server. - /// - /// - parameter queue: The dispatch queue to execute the closure on. - /// - parameter closure: The code to be executed periodically as data is sent to the server. - /// - /// - returns: The request. - @discardableResult - open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { - uploadDelegate.uploadProgressHandler = (closure, queue) - return self + return stream } -} -// MARK: - + public override func cleanup() { + defer { super.cleanup() } -#if !os(watchOS) + guard + let uploadable = self.uploadable, + case let .file(url, shouldRemove) = uploadable, + shouldRemove + else { return } -/// Specific type of `Request` that manages an underlying `URLSessionStreamTask`. -@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) -open class StreamRequest: Request { - enum Streamable: TaskConvertible { - case stream(hostName: String, port: Int) - case netService(NetService) - - func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { - let task: URLSessionTask + try? fileManager.removeItem(at: url) + } +} - switch self { - case let .stream(hostName, port): - task = queue.sync { session.streamTask(withHostName: hostName, port: port) } - case let .netService(netService): - task = queue.sync { session.streamTask(with: netService) } - } +/// 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 +} - return task - } +extension UploadRequest.Uploadable: UploadableConvertible { + public func createUploadable() throws -> UploadRequest.Uploadable { + return self } } -#endif +/// A type that can be converted to an upload, whether from an `UploadRequest.Uploadable` or `URLRequestConvertible`. +public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible {} diff --git a/Example/Pods/Alamofire/Source/RequestInterceptor.swift b/Example/Pods/Alamofire/Source/RequestInterceptor.swift new file mode 100644 index 0000000..09ba4ee --- /dev/null +++ b/Example/Pods/Alamofire/Source/RequestInterceptor.swift @@ -0,0 +1,243 @@ +// +// 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 + +/// 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) -> Void) +} + +// 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) -> 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) -> 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) -> Void) { + adaptHandler(urlRequest, session, completion) + } +} + +// 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) + } +} + +// 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. + public init(adapters: [RequestAdapter] = [], retriers: [RequestRetrier] = []) { + self.adapters = adapters + self.retriers = retriers + } + + open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { + adapt(urlRequest, for: session, using: adapters, completion: completion) + } + + private func adapt(_ urlRequest: URLRequest, + for session: Session, + using adapters: [RequestAdapter], + completion: @escaping (Result) -> 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 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) + } + } + } +} diff --git a/Example/Pods/Alamofire/Source/RequestTaskMap.swift b/Example/Pods/Alamofire/Source/RequestTaskMap.swift new file mode 100644 index 0000000..8d4f33d --- /dev/null +++ b/Example/Pods/Alamofire/Source/RequestTaskMap.swift @@ -0,0 +1,136 @@ +// +// 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 var tasksToRequests: [URLSessionTask: Request] + private var requestsToTasks: [Request: URLSessionTask] + private var taskEvents: [URLSessionTask: (completed: Bool, metricsGathered: Bool)] + + var requests: [Request] { + return 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 { return 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 { return 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) { + 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) + case (true, false): self[task] = nil + } + } + + mutating func disassociateIfNecessaryAfterCompletingTask(_ task: URLSessionTask) { + 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.") + case (false, false): taskEvents[task] = (completed: true, metricsGathered: false) + case (false, true): self[task] = nil + } + } +} diff --git a/Example/Pods/Alamofire/Source/Response.swift b/Example/Pods/Alamofire/Source/Response.swift index d05cfb0..5874b28 100644 --- a/Example/Pods/Alamofire/Source/Response.swift +++ b/Example/Pods/Alamofire/Source/Response.swift @@ -1,7 +1,7 @@ // // Response.swift // -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) +// 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 @@ -24,8 +24,13 @@ import Foundation -/// Used to store all data associated with an non-serialized response of a data or upload request. -public struct DefaultDataResponse { +/// Default type of `DataResponse` returned by Alamofire, with an `AFError` `Failure` type. +public typealias AFDataResponse = DataResponse +/// Default type of `DownloadResponse` returned by Alamofire, with an `AFError` `Failure` type. +public typealias AFDownloadResponse = DownloadResponse + +/// Type used to store all values associated with a serialized response of a `DataRequest` or `UploadRequest`. +public struct DataResponse { /// The URL request sent to the server. public let request: URLRequest? @@ -35,87 +40,42 @@ public struct DefaultDataResponse { /// The data returned by the server. public let data: Data? - /// The error encountered while executing or validating the request. - public let error: Error? - - /// The timeline of the complete lifecycle of the request. - public let timeline: Timeline - - var _metrics: AnyObject? + /// The final metrics of the response. + public let metrics: URLSessionTaskMetrics? - /// Creates a `DefaultDataResponse` instance from the specified parameters. - /// - /// - Parameters: - /// - request: The URL request sent to the server. - /// - response: The server's response to the URL request. - /// - data: The data returned by the server. - /// - error: The error encountered while executing or validating the request. - /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. - /// - metrics: The task metrics containing the request / response statistics. `nil` by default. - public init( - request: URLRequest?, - response: HTTPURLResponse?, - data: Data?, - error: Error?, - timeline: Timeline = Timeline(), - metrics: AnyObject? = nil) - { - self.request = request - self.response = response - self.data = data - self.error = error - self.timeline = timeline - } -} - -// MARK: - - -/// Used to store all data associated with a serialized response of a data or upload request. -public struct DataResponse { - /// 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 time taken to serialize the response. + public let serializationDuration: TimeInterval /// The result of response serialization. - public let result: Result - - /// The timeline of the complete lifecycle of the request. - public let timeline: Timeline + public let result: Result /// Returns the associated value of the result if it is a success, `nil` otherwise. - public var value: Value? { return result.value } + public var value: Success? { return result.success } /// Returns the associated error value if the result if it is a failure, `nil` otherwise. - public var error: Error? { return result.error } - - var _metrics: AnyObject? - - /// Creates a `DataResponse` instance with the specified parameters derived from response serialization. - /// - /// - parameter request: The URL request sent to the server. - /// - parameter response: The server's response to the URL request. - /// - parameter data: The data returned by the server. - /// - parameter result: The result of response serialization. - /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. - /// - /// - returns: The new `DataResponse` instance. - public init( - request: URLRequest?, - response: HTTPURLResponse?, - data: Data?, - result: Result, - timeline: Timeline = Timeline()) - { + public var error: Failure? { return 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) { self.request = request self.response = response self.data = data + self.metrics = metrics + self.serializationDuration = serializationDuration self.result = result - self.timeline = timeline } } @@ -125,24 +85,36 @@ 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 { - return result.debugDescription + return "\(result)" } /// The debug textual representation used when written to an output stream, which includes the URL request, the URL - /// response, the server data, the response serialization result and the timeline. + /// response, the server data, the duration of the network and serialization actions, and the response serialization + /// result. public var debugDescription: String { - let requestDescription = request.map { "\($0.httpMethod ?? "GET") \($0)"} ?? "nil" + let requestDescription = request.map { "\($0.httpMethod!) \($0)" } ?? "nil" let requestBody = request?.httpBody.map { String(decoding: $0, as: UTF8.self) } ?? "None" - let responseDescription = response.map { "\($0)" } ?? "nil" + let responseDescription = response.map { response in + let sortedHeaders = response.headers.sorted() + + return """ + [Status Code]: \(response.statusCode) + [Headers]: + \(sortedHeaders) + """ + } ?? "nil" let responseBody = data.map { String(decoding: $0, as: UTF8.self) } ?? "None" + let metricsDescription = metrics.map { "\($0.taskInterval.duration)s" } ?? "None" return """ [Request]: \(requestDescription) [Request Body]: \n\(requestBody) - [Response]: \(responseDescription) + [Response]: \n\(responseDescription) [Response Body]: \n\(responseBody) + [Data]: \(data?.description ?? "None") + [Network Duration]: \(metricsDescription) + [Serialization Duration]: \(serializationDuration)s [Result]: \(result) - [Timeline]: \(timeline.debugDescription) """ } } @@ -162,27 +134,22 @@ extension DataResponse { /// /// - 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(_ transform: (Value) -> T) -> DataResponse { - var response = DataResponse( - request: request, - response: self.response, - data: data, - result: result.map(transform), - timeline: timeline - ) - - response._metrics = _metrics - - return response + public func map(_ transform: (Success) -> NewSuccess) -> DataResponse { + return DataResponse(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 `flatMap` method with a closure that may throw an error. For example: + /// Use the `tryMap` method with a closure that may throw an error. For example: /// /// let possibleData: DataResponse = ... - /// let possibleObject = possibleData.flatMap { + /// let possibleObject = possibleData.tryMap { /// try JSONSerialization.jsonObject(with: $0) /// } /// @@ -190,18 +157,13 @@ extension DataResponse { /// /// - 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 flatMap(_ transform: (Value) throws -> T) -> DataResponse { - var response = DataResponse( - request: request, - response: self.response, - data: data, - result: result.flatMap(transform), - timeline: timeline - ) - - response._metrics = _metrics - - return response + public func tryMap(_ transform: (Success) throws -> NewSuccess) -> DataResponse { + return DataResponse(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. @@ -212,166 +174,95 @@ extension DataResponse { /// 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(_ transform: (Error) -> E) -> DataResponse { - var response = DataResponse( - request: request, - response: self.response, - data: data, - result: result.mapError(transform), - timeline: timeline - ) - - response._metrics = _metrics - - return response + public func mapError(_ transform: (Failure) -> NewFailure) -> DataResponse { + return DataResponse(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 `flatMapError` function with a closure that may throw an error. For example: + /// Use the `tryMapError` function with a closure that may throw an error. For example: /// /// let possibleData: DataResponse = ... - /// let possibleObject = possibleData.flatMapError { + /// 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 flatMapError(_ transform: (Error) throws -> E) -> DataResponse { - var response = DataResponse( - request: request, - response: self.response, - data: data, - result: result.flatMapError(transform), - timeline: timeline - ) - - response._metrics = _metrics - - return response + public func tryMapError(_ transform: (Failure) throws -> NewFailure) -> DataResponse { + return DataResponse(request: request, + response: response, + data: data, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.tryMapError(transform)) } } // MARK: - -/// Used to store all data associated with an non-serialized response of a download request. -public struct DefaultDownloadResponse { +/// Used to store all data associated with a serialized response of a download request. +public struct DownloadResponse { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? - /// The temporary destination URL of the data returned from the server. - public let temporaryURL: URL? - - /// The final destination URL of the data returned from the server if it was moved. - public let destinationURL: URL? + /// 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 error encountered while executing or validating the request. - public let error: Error? + /// The final metrics of the response. + public let metrics: URLSessionTaskMetrics? - /// The timeline of the complete lifecycle of the request. - public let timeline: Timeline - - var _metrics: AnyObject? - - /// Creates a `DefaultDownloadResponse` instance from the specified parameters. - /// - /// - Parameters: - /// - request: The URL request sent to the server. - /// - response: The server's response to the URL request. - /// - temporaryURL: The temporary destination URL of the data returned from the server. - /// - destinationURL: The final destination URL of the data returned from the server if it was moved. - /// - resumeData: The resume data generated if the request was cancelled. - /// - error: The error encountered while executing or validating the request. - /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. - /// - metrics: The task metrics containing the request / response statistics. `nil` by default. - public init( - request: URLRequest?, - response: HTTPURLResponse?, - temporaryURL: URL?, - destinationURL: URL?, - resumeData: Data?, - error: Error?, - timeline: Timeline = Timeline(), - metrics: AnyObject? = nil) - { - self.request = request - self.response = response - self.temporaryURL = temporaryURL - self.destinationURL = destinationURL - self.resumeData = resumeData - self.error = error - self.timeline = timeline - } -} - -// MARK: - - -/// Used to store all data associated with a serialized response of a download request. -public struct DownloadResponse { - /// The URL request sent to the server. - public let request: URLRequest? - - /// The server's response to the URL request. - public let response: HTTPURLResponse? - - /// The temporary destination URL of the data returned from the server. - public let temporaryURL: URL? - - /// The final destination URL of the data returned from the server if it was moved. - public let destinationURL: URL? - - /// The resume data generated if the request was cancelled. - public let resumeData: Data? + /// The time taken to serialize the response. + public let serializationDuration: TimeInterval /// The result of response serialization. - public let result: Result - - /// The timeline of the complete lifecycle of the request. - public let timeline: Timeline + public let result: Result /// Returns the associated value of the result if it is a success, `nil` otherwise. - public var value: Value? { return result.value } + public var value: Success? { return result.success } /// Returns the associated error value if the result if it is a failure, `nil` otherwise. - public var error: Error? { return result.error } - - var _metrics: AnyObject? + public var error: Failure? { return result.failure } /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization. /// - /// - parameter request: The URL request sent to the server. - /// - parameter response: The server's response to the URL request. - /// - parameter temporaryURL: The temporary destination URL of the data returned from the server. - /// - parameter destinationURL: The final destination URL of the data returned from the server if it was moved. - /// - parameter resumeData: The resume data generated if the request was cancelled. - /// - parameter result: The result of response serialization. - /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. - /// - /// - returns: The new `DownloadResponse` instance. - public init( - request: URLRequest?, - response: HTTPURLResponse?, - temporaryURL: URL?, - destinationURL: URL?, - resumeData: Data?, - result: Result, - timeline: Timeline = Timeline()) - { + /// - Parameters: + /// - request: The `URLRequest` sent to the server. + /// - response: The `HTTPURLResponse` from the server. + /// - temporaryURL: The temporary destination `URL` of the data returned from the server. + /// - destinationURL: The final destination `URL` of the data returned from the server, if it was 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) { self.request = request self.response = response - self.temporaryURL = temporaryURL - self.destinationURL = destinationURL + self.fileURL = fileURL self.resumeData = resumeData + self.metrics = metrics + self.serializationDuration = serializationDuration self.result = result - self.timeline = timeline } } @@ -381,26 +272,36 @@ extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertibl /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { - return result.debugDescription + return "\(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 response serialization result and the - /// timeline. + /// 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 { - let requestDescription = request.map { "\($0.httpMethod ?? "GET") \($0)"} ?? "nil" + let requestDescription = request.map { "\($0.httpMethod!) \($0)" } ?? "nil" let requestBody = request?.httpBody.map { String(decoding: $0, as: UTF8.self) } ?? "None" - let responseDescription = response.map { "\($0)" } ?? "nil" + let responseDescription = response.map { response in + let sortedHeaders = response.headers.sorted() + + return """ + [Status Code]: \(response.statusCode) + [Headers]: + \(sortedHeaders) + """ + } ?? "nil" + let metricsDescription = metrics.map { "\($0.taskInterval.duration)s" } ?? "None" + let resumeDataDescription = resumeData.map { "\($0)" } ?? "None" return """ [Request]: \(requestDescription) [Request Body]: \n\(requestBody) - [Response]: \(responseDescription) - [TemporaryURL]: \(temporaryURL?.path ?? "nil") - [DestinationURL]: \(destinationURL?.path ?? "nil") - [ResumeData]: \(resumeData?.count ?? 0) bytes + [Response]: \n\(responseDescription) + [File URL]: \(fileURL?.path ?? "nil") + [ResumeData]: \(resumeDataDescription) + [Network Duration]: \(metricsDescription) + [Serialization Duration]: \(serializationDuration)s [Result]: \(result) - [Timeline]: \(timeline.debugDescription) """ } } @@ -420,29 +321,23 @@ extension DownloadResponse { /// /// - 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(_ transform: (Value) -> T) -> DownloadResponse { - var response = DownloadResponse( - request: request, - response: self.response, - temporaryURL: temporaryURL, - destinationURL: destinationURL, - resumeData: resumeData, - result: result.map(transform), - timeline: timeline - ) - - response._metrics = _metrics - - return response + public func map(_ transform: (Success) -> NewSuccess) -> DownloadResponse { + return DownloadResponse(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 `flatMap` method with a closure that may throw an error. For example: + /// Use the `tryMap` method with a closure that may throw an error. For example: /// /// let possibleData: DownloadResponse = ... - /// let possibleObject = possibleData.flatMap { + /// let possibleObject = possibleData.tryMap { /// try JSONSerialization.jsonObject(with: $0) /// } /// @@ -450,20 +345,14 @@ extension DownloadResponse { /// /// - 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 flatMap(_ transform: (Value) throws -> T) -> DownloadResponse { - var response = DownloadResponse( - request: request, - response: self.response, - temporaryURL: temporaryURL, - destinationURL: destinationURL, - resumeData: resumeData, - result: result.flatMap(transform), - timeline: timeline - ) - - response._metrics = _metrics - - return response + public func tryMap(_ transform: (Success) throws -> NewSuccess) -> DownloadResponse { + return DownloadResponse(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. @@ -474,101 +363,37 @@ extension DownloadResponse { /// 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(_ transform: (Error) -> E) -> DownloadResponse { - var response = DownloadResponse( - request: request, - response: self.response, - temporaryURL: temporaryURL, - destinationURL: destinationURL, - resumeData: resumeData, - result: result.mapError(transform), - timeline: timeline - ) - - response._metrics = _metrics - - return response + public func mapError(_ transform: (Failure) -> NewFailure) -> DownloadResponse { + return DownloadResponse(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 `flatMapError` function with a closure that may throw an error. For example: + /// Use the `tryMapError` function with a closure that may throw an error. For example: /// /// let possibleData: DownloadResponse = ... - /// let possibleObject = possibleData.flatMapError { + /// 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 flatMapError(_ transform: (Error) throws -> E) -> DownloadResponse { - var response = DownloadResponse( - request: request, - response: self.response, - temporaryURL: temporaryURL, - destinationURL: destinationURL, - resumeData: resumeData, - result: result.flatMapError(transform), - timeline: timeline - ) - - response._metrics = _metrics - - return response + public func tryMapError(_ transform: (Failure) throws -> NewFailure) -> DownloadResponse { + return DownloadResponse(request: request, + response: response, + fileURL: fileURL, + resumeData: resumeData, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.tryMapError(transform)) } } - -// MARK: - - -protocol Response { - /// The task metrics containing the request / response statistics. - var _metrics: AnyObject? { get set } - mutating func add(_ metrics: AnyObject?) -} - -extension Response { - mutating func add(_ metrics: AnyObject?) { - #if !os(watchOS) - guard #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) else { return } - guard let metrics = metrics as? URLSessionTaskMetrics else { return } - - _metrics = metrics - #endif - } -} - -// MARK: - - -@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) -extension DefaultDataResponse: Response { -#if !os(watchOS) - /// The task metrics containing the request / response statistics. - public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } -#endif -} - -@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) -extension DataResponse: Response { -#if !os(watchOS) - /// The task metrics containing the request / response statistics. - public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } -#endif -} - -@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) -extension DefaultDownloadResponse: Response { -#if !os(watchOS) - /// The task metrics containing the request / response statistics. - public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } -#endif -} - -@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) -extension DownloadResponse: Response { -#if !os(watchOS) - /// The task metrics containing the request / response statistics. - public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } -#endif -} diff --git a/Example/Pods/Alamofire/Source/ResponseSerialization.swift b/Example/Pods/Alamofire/Source/ResponseSerialization.swift index 9cc105a..61b2cd5 100644 --- a/Example/Pods/Alamofire/Source/ResponseSerialization.swift +++ b/Example/Pods/Alamofire/Source/ResponseSerialization.swift @@ -1,7 +1,7 @@ // // ResponseSerialization.swift // -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) +// 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 @@ -24,80 +24,144 @@ import Foundation -/// The type in which all data response serializers must conform to in order to serialize a response. +// 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 by this `DataResponseSerializerType`. + /// The type of serialized object to be created. associatedtype SerializedObject - /// A closure used by response handlers that takes a request, response, data and error and returns a result. - var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result { get } + /// 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 } -// MARK: - - -/// A generic `DataResponseSerializerType` used to serialize a request, response, and data into a serialized object. -public struct DataResponseSerializer: DataResponseSerializerProtocol { - /// The type of serialized object to be created by this `DataResponseSerializer`. - public typealias SerializedObject = Value - - /// A closure used by response handlers that takes a request, response, data and error and returns a result. - public var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result +/// 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 - /// Initializes the `ResponseSerializer` instance with the given serialize response closure. + /// Serialize the downloaded response `Data` from disk into the provided type.. /// - /// - parameter serializeResponse: The closure used to serialize the response. + /// - 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 new generic response serializer instance. - public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result) { - self.serializeResponse = serializeResponse - } + /// - Returns: The `SerializedObject`. + /// - Throws: Any `Error` produced during serialization. + func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> SerializedObject } -// MARK: - +/// 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 { get } + /// HTTP response codes for which empty response bodies are considered appropriate. + var emptyResponseCodes: Set { get } +} -/// The type in which all download response serializers must conform to in order to serialize a response. -public protocol DownloadResponseSerializerProtocol { - /// The type of serialized object to be created by this `DownloadResponseSerializerType`. - associatedtype SerializedObject +/// 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 { return data } +} + +/// `DataPreprocessor` that trims Google's typical `)]}',\n` XSSI JSON header. +public struct GoogleXSSIPreprocessor: DataPreprocessor { + public init() {} - /// A closure used by response handlers that takes a request, response, url and error and returns a result. - var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result { get } + public func preprocess(_ data: Data) throws -> Data { + return (data.prefix(6) == Data(")]}',\n".utf8)) ? data.dropFirst(6) : data + } } -// MARK: - +extension ResponseSerializer { + /// Default `DataPreprocessor`. `PassthroughPreprocessor` by default. + public static var defaultDataPreprocessor: DataPreprocessor { return PassthroughPreprocessor() } + /// Default `HTTPMethod`s for which empty response bodies are considered appropriate. `[.head]` by default. + public static var defaultEmptyRequestMethods: Set { return [.head] } + /// HTTP response codes for which empty response bodies are considered appropriate. `[204, 205]` by default. + public static var defaultEmptyResponseCodes: Set { return [204, 205] } + + public var dataPreprocessor: DataPreprocessor { return Self.defaultDataPreprocessor } + public var emptyRequestMethods: Set { return Self.defaultEmptyRequestMethods } + public var emptyResponseCodes: Set { return Self.defaultEmptyResponseCodes } -/// A generic `DownloadResponseSerializerType` used to serialize a request, response, and data into a serialized object. -public struct DownloadResponseSerializer: DownloadResponseSerializerProtocol { - /// The type of serialized object to be created by this `DownloadResponseSerializer`. - public typealias SerializedObject = Value + /// 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? { + return request.flatMap { $0.httpMethod } + .flatMap(HTTPMethod.init) + .map { emptyRequestMethods.contains($0) } + } - /// A closure used by response handlers that takes a request, response, url and error and returns a result. - public var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result + /// 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? { + return response.flatMap { $0.statusCode } + .map { emptyResponseCodes.contains($0) } + } - /// Initializes the `ResponseSerializer` instance with the given serialize response closure. + /// Determines whether `request` and `response` allow empty response bodies. /// - /// - parameter serializeResponse: The closure used to serialize the response. + /// - Parameters: + /// - request: `URLRequest` to evaluate. + /// - response: `HTTPURLResponse` to evaluate. /// - /// - returns: The new generic response serializer instance. - public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result) { - self.serializeResponse = serializeResponse + /// - Returns: `true` if `request` or `response` allow empty bodies, `false` otherwise. + public func emptyResponseAllowed(forRequest request: URLRequest?, response: HTTPURLResponse?) -> Bool { + return (requestAllowsEmptyResponseData(request) == true) || (responseAllowsEmptyResponseData(response) == true) } } -// MARK: - Timeline +/// 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. +public extension DownloadResponseSerializerProtocol where Self: DataResponseSerializerProtocol { + func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> Self.SerializedObject { + guard error == nil else { throw error! } -extension Request { - var timeline: Timeline { - let requestStartTime = self.startTime ?? CFAbsoluteTimeGetCurrent() - let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent() - let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime + 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)) + } - return Timeline( - requestStartTime: requestStartTime, - initialResponseTime: initialResponseTime, - requestCompletedTime: requestCompletedTime, - serializationCompletedTime: CFAbsoluteTimeGetCurrent() - ) + do { + return try serialize(request: request, response: response, data: data, error: error) + } catch { + throw error + } } } @@ -106,25 +170,29 @@ extension Request { extension DataRequest { /// Adds a handler to be called once the request has finished. /// - /// - parameter queue: The queue on which the completion handler is dispatched. - /// - parameter completionHandler: The code to be executed 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. + /// - Returns: The request. @discardableResult - public func response(queue: DispatchQueue? = nil, completionHandler: @escaping (DefaultDataResponse) -> Void) -> Self { - delegate.queue.addOperation { - (queue ?? DispatchQueue.main).async { - var dataResponse = DefaultDataResponse( - request: self.request, - response: self.response, - data: self.delegate.data, - error: self.delegate.error, - timeline: self.timeline - ) - - dataResponse.add(self.delegate.metrics) - - completionHandler(dataResponse) + public func response(queue: DispatchQueue = .main, completionHandler: @escaping (AFDataResponse) -> Void) -> Self { + appendResponseSerializer { + // Start work that should be on the serialization queue. + let result = AFResult(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) } } } } @@ -133,38 +201,77 @@ extension DataRequest { /// Adds a handler to be called once the request has finished. /// - /// - parameter queue: The queue on which the completion handler is dispatched. - /// - parameter responseSerializer: The response serializer responsible for serializing the request, response, - /// and data. - /// - parameter completionHandler: The code to be executed 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. + /// - Returns: The request. @discardableResult - public func response( - queue: DispatchQueue? = nil, - responseSerializer: T, - completionHandler: @escaping (DataResponse) -> Void) - -> Self - { - delegate.queue.addOperation { - let result = responseSerializer.serializeResponse( - self.request, - self.response, - self.delegate.data, - self.delegate.error - ) - - var dataResponse = DataResponse( - request: self.request, - response: self.response, - data: self.delegate.data, - result: result, - timeline: self.timeline - ) - - dataResponse.add(self.delegate.metrics) - - (queue ?? DispatchQueue.main).async { completionHandler(dataResponse) } + public func response(queue: DispatchQueue = .main, + responseSerializer: Serializer, + completionHandler: @escaping (AFDataResponse) -> Void) + -> Self { + appendResponseSerializer { + // Start work that should be on the serialization queue. + let start = CFAbsoluteTimeGetCurrent() + let result: AFResult = 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 = CFAbsoluteTimeGetCurrent() + // 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 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 = .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 @@ -174,31 +281,32 @@ extension DataRequest { extension DownloadRequest { /// Adds a handler to be called once the request has finished. /// - /// - parameter queue: The queue on which the completion handler is dispatched. - /// - parameter completionHandler: The code to be executed 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. + /// - Returns: The request. @discardableResult - public func response( - queue: DispatchQueue? = nil, - completionHandler: @escaping (DefaultDownloadResponse) -> Void) - -> Self - { - delegate.queue.addOperation { - (queue ?? DispatchQueue.main).async { - var downloadResponse = DefaultDownloadResponse( - request: self.request, - response: self.response, - temporaryURL: self.downloadDelegate.temporaryURL, - destinationURL: self.downloadDelegate.destinationURL, - resumeData: self.downloadDelegate.resumeData, - error: self.downloadDelegate.error, - timeline: self.timeline - ) - - downloadResponse.add(self.delegate.metrics) - - completionHandler(downloadResponse) + public func response(queue: DispatchQueue = .main, + completionHandler: @escaping (AFDownloadResponse) -> Void) + -> Self { + appendResponseSerializer { + // Start work that should be on the serialization queue. + let result = AFResult(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) } } } } @@ -207,40 +315,79 @@ extension DownloadRequest { /// Adds a handler to be called once the request has finished. /// - /// - parameter queue: The queue on which the completion handler is dispatched. - /// - parameter responseSerializer: The response serializer responsible for serializing the request, response, - /// and data contained in the destination url. - /// - parameter completionHandler: The code to be executed 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. + /// - Returns: The request. @discardableResult - public func response( - queue: DispatchQueue? = nil, - responseSerializer: T, - completionHandler: @escaping (DownloadResponse) -> Void) - -> Self - { - delegate.queue.addOperation { - let result = responseSerializer.serializeResponse( - self.request, - self.response, - self.downloadDelegate.fileURL, - self.downloadDelegate.error - ) - - var downloadResponse = DownloadResponse( - request: self.request, - response: self.response, - temporaryURL: self.downloadDelegate.temporaryURL, - destinationURL: self.downloadDelegate.destinationURL, - resumeData: self.downloadDelegate.resumeData, - result: result, - timeline: self.timeline - ) - - downloadResponse.add(self.delegate.metrics) - - (queue ?? DispatchQueue.main).async { completionHandler(downloadResponse) } + public func response(queue: DispatchQueue = .main, + responseSerializer: Serializer, + completionHandler: @escaping (AFDownloadResponse) -> Void) + -> Self { + appendResponseSerializer { + // Start work that should be on the serialization queue. + let start = CFAbsoluteTimeGetCurrent() + let result: AFResult = 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 = CFAbsoluteTimeGetCurrent() + // 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 = .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 @@ -249,467 +396,405 @@ extension DownloadRequest { // MARK: - Data -extension Request { - /// Returns a result data type that contains the response data as-is. - /// - /// - parameter response: The response from the server. - /// - parameter data: The data returned from the server. - /// - parameter error: The error already encountered if it exists. - /// - /// - returns: The result data type. - public static func serializeResponseData(response: HTTPURLResponse?, data: Data?, error: Error?) -> Result { - guard error == nil else { return .failure(error!) } - - if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(Data()) } - - guard let validData = data else { - return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) - } - - return .success(validData) - } -} - extension DataRequest { - /// Creates a response serializer that returns the associated data as-is. - /// - /// - returns: A data response serializer. - public static func dataResponseSerializer() -> DataResponseSerializer { - return DataResponseSerializer { _, response, data, error in - return Request.serializeResponseData(response: response, data: data, error: error) - } - } - /// Adds a handler to be called once the request has finished. /// - /// - parameter completionHandler: The code to be executed 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. + /// - Returns: The request. @discardableResult - public func responseData( - queue: DispatchQueue? = nil, - completionHandler: @escaping (DataResponse) -> Void) - -> Self - { - return response( - queue: queue, - responseSerializer: DataRequest.dataResponseSerializer(), - completionHandler: completionHandler - ) + public func responseData(queue: DispatchQueue = .main, + completionHandler: @escaping (AFDataResponse) -> Void) + -> Self { + return response(queue: queue, + responseSerializer: DataResponseSerializer(), + completionHandler: completionHandler) } } -extension DownloadRequest { - /// Creates a response serializer that returns the associated data as-is. - /// - /// - returns: A data response serializer. - public static func dataResponseSerializer() -> DownloadResponseSerializer { - return DownloadResponseSerializer { _, response, fileURL, error in - guard error == nil else { return .failure(error!) } +/// 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 response is has a status code valid for +/// empty responses (`204`, `205`), then an empty `Data` value is returned. +public final class DataResponseSerializer: ResponseSerializer { + public let dataPreprocessor: DataPreprocessor + public let emptyResponseCodes: Set + public let emptyRequestMethods: Set + + /// Creates an instance using 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. + public init(dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) { + self.dataPreprocessor = dataPreprocessor + self.emptyResponseCodes = emptyResponseCodes + self.emptyRequestMethods = emptyRequestMethods + } - guard let fileURL = fileURL else { - return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) - } + public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Data { + guard error == nil else { throw error! } - do { - let data = try Data(contentsOf: fileURL) - return Request.serializeResponseData(response: response, data: data, error: error) - } catch { - return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + 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 } +} +extension DownloadRequest { /// Adds a handler to be called once the request has finished. /// - /// - parameter completionHandler: The code to be executed 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. + /// - Returns: The request. @discardableResult - public func responseData( - queue: DispatchQueue? = nil, - completionHandler: @escaping (DownloadResponse) -> Void) - -> Self - { - return response( - queue: queue, - responseSerializer: DownloadRequest.dataResponseSerializer(), - completionHandler: completionHandler - ) + public func responseData(queue: DispatchQueue = .main, + completionHandler: @escaping (AFDownloadResponse) -> Void) + -> Self { + return response(queue: queue, + responseSerializer: DataResponseSerializer(), + completionHandler: completionHandler) } } // MARK: - String -extension Request { - /// Returns a result string type initialized from the response data with the specified string encoding. - /// - /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server - /// response, falling back to the default HTTP default character set, ISO-8859-1. - /// - parameter response: The response from the server. - /// - parameter data: The data returned from the server. - /// - parameter error: The error already encountered if it exists. - /// - /// - returns: The result data type. - public static func serializeResponseString( - encoding: String.Encoding?, - response: HTTPURLResponse?, - data: Data?, - error: Error?) - -> Result - { - guard error == nil else { return .failure(error!) } - - if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success("") } - - guard let validData = data else { - return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) +/// 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 response is has a status code valid for empty responses (`204`, `205`), +/// 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 + public let emptyRequestMethods: Set + + /// 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 = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = 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 as CFString?, convertedEncoding == nil { - convertedEncoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding( - CFStringConvertIANACharSetNameToEncoding(encodingName)) - ) + let ianaCharSet = CFStringConvertIANACharSetNameToEncoding(encodingName) + let nsStringEncoding = CFStringConvertEncodingToNSStringEncoding(ianaCharSet) + convertedEncoding = String.Encoding(rawValue: nsStringEncoding) } let actualEncoding = convertedEncoding ?? .isoLatin1 - if let string = String(data: validData, encoding: actualEncoding) { - return .success(string) - } else { - return .failure(AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding))) + guard let string = String(data: data, encoding: actualEncoding) else { + throw AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding)) } + + return string } } extension DataRequest { - /// Creates a response serializer that returns a result string type initialized from the response data with - /// the specified string encoding. - /// - /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server - /// response, falling back to the default HTTP default character set, ISO-8859-1. - /// - /// - returns: A string response serializer. - public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DataResponseSerializer { - return DataResponseSerializer { _, response, data, error in - return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error) - } - } - /// Adds a handler to be called once the request has finished. /// - /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the - /// server response, falling back to the default HTTP default character set, - /// ISO-8859-1. - /// - parameter completionHandler: A closure to be executed once the request has finished. + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` 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`. + /// - completionHandler: A closure to be executed once the request has finished. /// - /// - returns: The request. + /// - Returns: The request. @discardableResult - public func responseString( - queue: DispatchQueue? = nil, - encoding: String.Encoding? = nil, - completionHandler: @escaping (DataResponse) -> Void) - -> Self - { - return response( - queue: queue, - responseSerializer: DataRequest.stringResponseSerializer(encoding: encoding), - completionHandler: completionHandler - ) + public func responseString(queue: DispatchQueue = .main, + encoding: String.Encoding? = nil, + completionHandler: @escaping (AFDataResponse) -> Void) -> Self { + return response(queue: queue, + responseSerializer: StringResponseSerializer(encoding: encoding), + completionHandler: completionHandler) } } extension DownloadRequest { - /// Creates a response serializer that returns a result string type initialized from the response data with - /// the specified string encoding. - /// - /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server - /// response, falling back to the default HTTP default character set, ISO-8859-1. - /// - /// - returns: A string response serializer. - public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DownloadResponseSerializer { - return DownloadResponseSerializer { _, response, fileURL, error in - guard error == nil else { return .failure(error!) } - - guard let fileURL = fileURL else { - return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) - } - - do { - let data = try Data(contentsOf: fileURL) - return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error) - } catch { - return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) - } - } - } - /// Adds a handler to be called once the request has finished. /// - /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the - /// server response, falling back to the default HTTP default character set, - /// ISO-8859-1. - /// - parameter completionHandler: A closure to be executed once the request has finished. + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` 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`. + /// - completionHandler: A closure to be executed once the request has finished. /// - /// - returns: The request. + /// - Returns: The request. @discardableResult - public func responseString( - queue: DispatchQueue? = nil, - encoding: String.Encoding? = nil, - completionHandler: @escaping (DownloadResponse) -> Void) - -> Self - { - return response( - queue: queue, - responseSerializer: DownloadRequest.stringResponseSerializer(encoding: encoding), - completionHandler: completionHandler - ) + public func responseString(queue: DispatchQueue = .main, + encoding: String.Encoding? = nil, + completionHandler: @escaping (AFDownloadResponse) -> Void) + -> Self { + return response(queue: queue, + responseSerializer: StringResponseSerializer(encoding: encoding), + completionHandler: completionHandler) } } // MARK: - JSON -extension Request { - /// Returns a JSON object contained in a result type constructed from the response data using `JSONSerialization` - /// with the specified reading options. - /// - /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. - /// - parameter response: The response from the server. - /// - parameter data: The data returned from the server. - /// - parameter error: The error already encountered if it exists. - /// - /// - returns: The result data type. - public static func serializeResponseJSON( - options: JSONSerialization.ReadingOptions, - response: HTTPURLResponse?, - data: Data?, - error: Error?) - -> Result - { - guard error == nil else { return .failure(error!) } - - if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } - - guard let validData = data, validData.count > 0 else { - return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) +/// 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 response is has a status code valid for empty responses +/// (`204`, `205`), then an `NSNull` value is returned. +public final class JSONResponseSerializer: ResponseSerializer { + public let dataPreprocessor: DataPreprocessor + public let emptyResponseCodes: Set + public let emptyRequestMethods: Set + /// `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 = JSONResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = 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 { - let json = try JSONSerialization.jsonObject(with: validData, options: options) - return .success(json) + return try JSONSerialization.jsonObject(with: data, options: options) } catch { - return .failure(AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error))) + throw AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error)) } } } extension DataRequest { - /// Creates a response serializer that returns a JSON object result type constructed from the response data using - /// `JSONSerialization` with the specified reading options. - /// - /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. - /// - /// - returns: A JSON object response serializer. - public static func jsonResponseSerializer( - options: JSONSerialization.ReadingOptions = .allowFragments) - -> DataResponseSerializer - { - return DataResponseSerializer { _, response, data, error in - return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) - } - } - /// Adds a handler to be called once the request has finished. /// - /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. - /// - parameter completionHandler: A closure to be executed once the request has finished. + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - options: The JSON serialization reading options. `.allowFragments` by default. + /// - completionHandler: A closure to be executed once the request has finished. /// - /// - returns: The request. + /// - Returns: The request. @discardableResult - public func responseJSON( - queue: DispatchQueue? = nil, - options: JSONSerialization.ReadingOptions = .allowFragments, - completionHandler: @escaping (DataResponse) -> Void) - -> Self - { - return response( - queue: queue, - responseSerializer: DataRequest.jsonResponseSerializer(options: options), - completionHandler: completionHandler - ) + public func responseJSON(queue: DispatchQueue = .main, + options: JSONSerialization.ReadingOptions = .allowFragments, + completionHandler: @escaping (AFDataResponse) -> Void) -> Self { + return response(queue: queue, + responseSerializer: JSONResponseSerializer(options: options), + completionHandler: completionHandler) } } extension DownloadRequest { - /// Creates a response serializer that returns a JSON object result type constructed from the response data using - /// `JSONSerialization` with the specified reading options. + /// Adds a handler to be called once the request has finished. /// - /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - options: The JSON serialization reading options. `.allowFragments` by default. + /// - completionHandler: A closure to be executed once the request has finished. /// - /// - returns: A JSON object response serializer. - public static func jsonResponseSerializer( - options: JSONSerialization.ReadingOptions = .allowFragments) - -> DownloadResponseSerializer - { - return DownloadResponseSerializer { _, response, fileURL, error in - guard error == nil else { return .failure(error!) } - - guard let fileURL = fileURL else { - return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) - } - - do { - let data = try Data(contentsOf: fileURL) - return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) - } catch { - return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) - } - } + /// - Returns: The request. + @discardableResult + public func responseJSON(queue: DispatchQueue = .main, + options: JSONSerialization.ReadingOptions = .allowFragments, + completionHandler: @escaping (AFDownloadResponse) -> Void) + -> Self { + return response(queue: queue, + responseSerializer: JSONResponseSerializer(options: options), + completionHandler: completionHandler) } +} - /// Adds a handler to be called once the request has finished. - /// - /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. - /// - parameter completionHandler: A closure to be executed once the request has finished. +// MARK: - Empty + +/// Protocol representing an empty response. Use `T.emptyValue()` to get an instance. +public protocol EmptyResponse { + /// Empty value for the conforming type. /// - /// - returns: The request. - @discardableResult - public func responseJSON( - queue: DispatchQueue? = nil, - options: JSONSerialization.ReadingOptions = .allowFragments, - completionHandler: @escaping (DownloadResponse) -> Void) - -> Self - { - return response( - queue: queue, - responseSerializer: DownloadRequest.jsonResponseSerializer(options: options), - completionHandler: completionHandler - ) + /// - Returns: Value of `Self` to use for empty values. + static func emptyValue() -> Self +} + +/// Type representing an empty response. Use `Empty.value` to get the static instance. +public struct Empty: Decodable { + /// Static `Empty` instance used for all `Empty` responses. + public static let value = Empty() +} + +extension Empty: EmptyResponse { + public static func emptyValue() -> Empty { + return value } } -// MARK: - Property List +// MARK: - DataDecoder Protocol -extension Request { - /// Returns a plist object contained in a result type constructed from the response data using - /// `PropertyListSerialization` with the specified reading options. +/// Any type which can decode `Data` into a `Decodable` type. +public protocol DataDecoder { + /// Decode `Data` into the provided type. /// - /// - parameter options: The property list reading options. Defaults to `[]`. - /// - parameter response: The response from the server. - /// - parameter data: The data returned from the server. - /// - parameter error: The error already encountered if it exists. + /// - Parameters: + /// - type: The `Type` to be decoded. + /// - data: The `Data` to be decoded. /// - /// - returns: The result data type. - public static func serializeResponsePropertyList( - options: PropertyListSerialization.ReadOptions, - response: HTTPURLResponse?, - data: Data?, - error: Error?) - -> Result - { - guard error == nil else { return .failure(error!) } + /// - Returns: The decoded value of type `D`. + /// - Throws: Any error that occurs during decode. + func decode(_ type: D.Type, from data: Data) throws -> D +} + +/// `JSONDecoder` automatically conforms to `DataDecoder`. +extension JSONDecoder: 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 response is has a status code valid for empty responses (`204`, `205`), then +/// the `Empty.value` value is returned. +public final class DecodableResponseSerializer: ResponseSerializer { + public let dataPreprocessor: DataPreprocessor + /// The `DataDecoder` instance used to decode responses. + public let decoder: DataDecoder + public let emptyResponseCodes: Set + public let emptyRequestMethods: Set + + /// 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 = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = 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! } - if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } + guard var data = data, !data.isEmpty else { + guard emptyResponseAllowed(forRequest: request, response: response) else { + throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) + } - guard let validData = data, validData.count > 0 else { - return .failure(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 { - let plist = try PropertyListSerialization.propertyList(from: validData, options: options, format: nil) - return .success(plist) + return try decoder.decode(T.self, from: data) } catch { - return .failure(AFError.responseSerializationFailed(reason: .propertyListSerializationFailed(error: error))) + throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error)) } } } extension DataRequest { - /// Creates a response serializer that returns an object constructed from the response data using - /// `PropertyListSerialization` with the specified reading options. - /// - /// - parameter options: The property list reading options. Defaults to `[]`. - /// - /// - returns: A property list object response serializer. - public static func propertyListResponseSerializer( - options: PropertyListSerialization.ReadOptions = []) - -> DataResponseSerializer - { - return DataResponseSerializer { _, response, data, error in - return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) - } - } - /// Adds a handler to be called once the request has finished. /// - /// - parameter options: The property list reading options. Defaults to `[]`. - /// - parameter completionHandler: A closure to be executed 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. + /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default. + /// - completionHandler: A closure to be executed once the request has finished. /// - /// - returns: The request. + /// - Returns: The request. @discardableResult - public func responsePropertyList( - queue: DispatchQueue? = nil, - options: PropertyListSerialization.ReadOptions = [], - completionHandler: @escaping (DataResponse) -> Void) - -> Self - { - return response( - queue: queue, - responseSerializer: DataRequest.propertyListResponseSerializer(options: options), - completionHandler: completionHandler - ) + public func responseDecodable(of type: T.Type = T.self, + queue: DispatchQueue = .main, + decoder: DataDecoder = JSONDecoder(), + completionHandler: @escaping (AFDataResponse) -> Void) -> Self { + return response(queue: queue, + responseSerializer: DecodableResponseSerializer(decoder: decoder), + completionHandler: completionHandler) } } extension DownloadRequest { - /// Creates a response serializer that returns an object constructed from the response data using - /// `PropertyListSerialization` with the specified reading options. - /// - /// - parameter options: The property list reading options. Defaults to `[]`. - /// - /// - returns: A property list object response serializer. - public static func propertyListResponseSerializer( - options: PropertyListSerialization.ReadOptions = []) - -> DownloadResponseSerializer - { - return DownloadResponseSerializer { _, response, fileURL, error in - guard error == nil else { return .failure(error!) } - - guard let fileURL = fileURL else { - return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) - } - - do { - let data = try Data(contentsOf: fileURL) - return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) - } catch { - return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) - } - } - } - /// Adds a handler to be called once the request has finished. /// - /// - parameter options: The property list reading options. Defaults to `[]`. - /// - parameter completionHandler: A closure to be executed 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. + /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default. + /// - completionHandler: A closure to be executed once the request has finished. /// - /// - returns: The request. + /// - Returns: The request. @discardableResult - public func responsePropertyList( - queue: DispatchQueue? = nil, - options: PropertyListSerialization.ReadOptions = [], - completionHandler: @escaping (DownloadResponse) -> Void) - -> Self - { - return response( - queue: queue, - responseSerializer: DownloadRequest.propertyListResponseSerializer(options: options), - completionHandler: completionHandler - ) + public func responseDecodable(of type: T.Type = T.self, + queue: DispatchQueue = .main, + decoder: DataDecoder = JSONDecoder(), + completionHandler: @escaping (AFDownloadResponse) -> Void) -> Self { + return response(queue: queue, + responseSerializer: DecodableResponseSerializer(decoder: decoder), + completionHandler: completionHandler) } } - -/// A set of HTTP response status code that do not contain response data. -private let emptyDataStatusCodes: Set = [204, 205] diff --git a/Example/Pods/Alamofire/Source/Result+Alamofire.swift b/Example/Pods/Alamofire/Source/Result+Alamofire.swift new file mode 100644 index 0000000..60b35f8 --- /dev/null +++ b/Example/Pods/Alamofire/Source/Result+Alamofire.swift @@ -0,0 +1,109 @@ +// +// 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 = Result + +// MARK: - Internal APIs + +extension Result { + /// 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 = .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(_ transform: (Success) throws -> NewSuccess) -> Result { + 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 = .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(_ transform: (Failure) throws -> NewFailure) -> Result { + switch self { + case let .failure(error): + do { + return try .failure(transform(error)) + } catch { + return .failure(error) + } + case let .success(value): + return .success(value) + } + } +} diff --git a/Example/Pods/Alamofire/Source/Result.swift b/Example/Pods/Alamofire/Source/Result.swift deleted file mode 100644 index e092808..0000000 --- a/Example/Pods/Alamofire/Source/Result.swift +++ /dev/null @@ -1,300 +0,0 @@ -// -// Result.swift -// -// Copyright (c) 2014 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 - -/// Used to represent whether a request was successful or encountered an error. -/// -/// - success: The request and all post processing operations were successful resulting in the serialization of the -/// provided associated value. -/// -/// - failure: The request encountered an error resulting in a failure. The associated values are the original data -/// provided by the server as well as the error that caused the failure. -public enum Result { - case success(Value) - case failure(Error) - - /// Returns `true` if the result is a success, `false` otherwise. - public var isSuccess: Bool { - switch self { - case .success: - return true - case .failure: - return false - } - } - - /// Returns `true` if the result is a failure, `false` otherwise. - public var isFailure: Bool { - return !isSuccess - } - - /// Returns the associated value if the result is a success, `nil` otherwise. - public var value: Value? { - switch self { - case .success(let value): - return value - case .failure: - return nil - } - } - - /// Returns the associated error value if the result is a failure, `nil` otherwise. - public var error: Error? { - switch self { - case .success: - return nil - case .failure(let error): - return error - } - } -} - -// MARK: - CustomStringConvertible - -extension Result: CustomStringConvertible { - /// The textual representation used when written to an output stream, which includes whether the result was a - /// success or failure. - public var description: String { - switch self { - case .success: - return "SUCCESS" - case .failure: - return "FAILURE" - } - } -} - -// MARK: - CustomDebugStringConvertible - -extension Result: CustomDebugStringConvertible { - /// The debug textual representation used when written to an output stream, which includes whether the result was a - /// success or failure in addition to the value or error. - public var debugDescription: String { - switch self { - case .success(let value): - return "SUCCESS: \(value)" - case .failure(let error): - return "FAILURE: \(error)" - } - } -} - -// MARK: - Functional APIs - -extension Result { - /// Creates a `Result` instance from the result of a closure. - /// - /// A failure result is created when the closure throws, and a success result is created when the closure - /// succeeds without throwing an error. - /// - /// func someString() throws -> String { ... } - /// - /// let result = Result(value: { - /// return try someString() - /// }) - /// - /// // The type of result is Result - /// - /// The trailing closure syntax is also supported: - /// - /// let result = Result { try someString() } - /// - /// - parameter value: The closure to execute and create the result for. - public init(value: () throws -> Value) { - do { - self = try .success(value()) - } catch { - self = .failure(error) - } - } - - /// Returns the success value, or throws the failure error. - /// - /// let possibleString: Result = .success("success") - /// try print(possibleString.unwrap()) - /// // Prints "success" - /// - /// let noString: Result = .failure(error) - /// try print(noString.unwrap()) - /// // Throws error - public func unwrap() throws -> Value { - switch self { - case .success(let value): - return value - case .failure(let error): - throw error - } - } - - /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. - /// - /// Use the `map` method with a closure that does not throw. For example: - /// - /// let possibleData: Result = .success(Data()) - /// let possibleInt = possibleData.map { $0.count } - /// try print(possibleInt.unwrap()) - /// // Prints "0" - /// - /// let noData: Result = .failure(error) - /// let noInt = noData.map { $0.count } - /// try print(noInt.unwrap()) - /// // Throws error - /// - /// - parameter transform: A closure that takes the success value of the `Result` instance. - /// - /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the - /// same failure. - public func map(_ transform: (Value) -> T) -> Result { - switch self { - case .success(let value): - return .success(transform(value)) - case .failure(let error): - return .failure(error) - } - } - - /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. - /// - /// Use the `flatMap` method with a closure that may throw an error. For example: - /// - /// let possibleData: Result = .success(Data(...)) - /// let possibleObject = possibleData.flatMap { - /// 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. - public func flatMap(_ transform: (Value) throws -> T) -> Result { - switch self { - case .success(let value): - do { - return try .success(transform(value)) - } catch { - return .failure(error) - } - case .failure(let error): - return .failure(error) - } - } - - /// Evaluates the specified closure when the `Result` 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: Result = .failure(someError) - /// let withMyError: Result = possibleData.mapError { MyError.error($0) } - /// - /// - Parameter transform: A 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 instance. - public func mapError(_ transform: (Error) -> T) -> Result { - switch self { - case .failure(let error): - return .failure(transform(error)) - case .success: - return self - } - } - - /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. - /// - /// Use the `flatMapError` function with a closure that may throw an error. For example: - /// - /// let possibleData: Result = .success(Data(...)) - /// let possibleObject = possibleData.flatMapError { - /// 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 instance. - public func flatMapError(_ transform: (Error) throws -> T) -> Result { - switch self { - case .failure(let error): - do { - return try .failure(transform(error)) - } catch { - return .failure(error) - } - case .success: - return self - } - } - - /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. - /// - /// Use the `withValue` function to evaluate the passed closure without modifying the `Result` instance. - /// - /// - Parameter closure: A closure that takes the success value of this instance. - /// - Returns: This `Result` instance, unmodified. - @discardableResult - public func withValue(_ closure: (Value) throws -> Void) rethrows -> Result { - if case let .success(value) = self { try closure(value) } - - return self - } - - /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. - /// - /// Use the `withError` function to evaluate the passed closure without modifying the `Result` instance. - /// - /// - Parameter closure: A closure that takes the success value of this instance. - /// - Returns: This `Result` instance, unmodified. - @discardableResult - public func withError(_ closure: (Error) throws -> Void) rethrows -> Result { - if case let .failure(error) = self { try closure(error) } - - return self - } - - /// Evaluates the specified closure when the `Result` is a success. - /// - /// Use the `ifSuccess` function to evaluate the passed closure without modifying the `Result` instance. - /// - /// - Parameter closure: A `Void` closure. - /// - Returns: This `Result` instance, unmodified. - @discardableResult - public func ifSuccess(_ closure: () throws -> Void) rethrows -> Result { - if isSuccess { try closure() } - - return self - } - - /// Evaluates the specified closure when the `Result` is a failure. - /// - /// Use the `ifFailure` function to evaluate the passed closure without modifying the `Result` instance. - /// - /// - Parameter closure: A `Void` closure. - /// - Returns: This `Result` instance, unmodified. - @discardableResult - public func ifFailure(_ closure: () throws -> Void) rethrows -> Result { - if isFailure { try closure() } - - return self - } -} diff --git a/Example/Pods/Alamofire/Source/RetryPolicy.swift b/Example/Pods/Alamofire/Source/RetryPolicy.swift new file mode 100644 index 0000000..7400718 --- /dev/null +++ b/Example/Pods/Alamofire/Source/RetryPolicy.swift @@ -0,0 +1,363 @@ +// +// RetryPolicy.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 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 = [.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 = [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 = [// [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 + + /// The HTTP status codes that are automatically retried by the policy. + public let retryableHTTPStatusCodes: Set + + /// The URL error codes that are automatically retried by the policy. + public let retryableURLErrorCodes: Set + + /// Creates an `ExponentialBackoffRetryPolicy` 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 = RetryPolicy.defaultRetryableHTTPMethods, + retryableHTTPStatusCodes: Set = RetryPolicy.defaultRetryableHTTPStatusCodes, + retryableURLErrorCodes: Set = 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, + let httpMethod = request.request?.method, + retryableHTTPMethods.contains(httpMethod), + shouldRetry(response: request.response, error: error) { + let timeDelay = pow(Double(exponentialBackoffBase), Double(request.retryCount)) * exponentialBackoffScale + completion(.retryWithDelay(timeDelay)) + } else { + completion(.doNotRetry) + } + } + + private func shouldRetry(response: HTTPURLResponse?, error: Error) -> Bool { + if let statusCode = response?.statusCode, retryableHTTPStatusCodes.contains(statusCode) { + return true + } else if let errorCode = (error as? URLError)?.code, retryableURLErrorCodes.contains(errorCode) { + return true + } + + return false + } +} + +// 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 = RetryPolicy.defaultRetryableHTTPMethods) { + super.init(retryLimit: retryLimit, + exponentialBackoffBase: exponentialBackoffBase, + exponentialBackoffScale: exponentialBackoffScale, + retryableHTTPMethods: retryableHTTPMethods, + retryableHTTPStatusCodes: [], + retryableURLErrorCodes: [.networkConnectionLost]) + } +} diff --git a/Example/Pods/Alamofire/Source/ServerTrustEvaluation.swift b/Example/Pods/Alamofire/Source/ServerTrustEvaluation.swift new file mode 100644 index 0000000..e3af5ed --- /dev/null +++ b/Example/Pods/Alamofire/Source/ServerTrustEvaluation.swift @@ -0,0 +1,606 @@ +// +// 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 + } + + /// 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 + } +} + +/// A protocol describing the API used to evaluate server trusts. +public protocol ServerTrustEvaluating { + #if os(Linux) + // Implement this once Linux 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 + +/// 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`. + /// + /// - 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)) + } + } + } +} + +/// 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`. + /// + /// - 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)) + } + } +} + +/// 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`. + /// + /// - 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)) + } + } +} + +/// 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`. + /// + /// - 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) + } +} + +/// Disables all evaluation which in turn will always consider any server trust as valid. +/// +/// **THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION!** +public final class DisabledEvaluator: ServerTrustEvaluating { + /// Creates an instance. + public init() {} + + public func evaluate(_ trust: SecTrust, forHost host: String) throws {} +} + +// MARK: - Extensions + +public extension Array where Element == ServerTrustEvaluating { + #if os(Linux) + // Add this same convenience method for Linux. + #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`. + func evaluate(_ trust: SecTrust, forHost host: String) throws { + for evaluator in self { + try evaluator.evaluate(trust, forHost: host) + } + } + #endif +} + +extension Bundle: AlamofireExtended {} +public extension AlamofireExtension where ExtendedType: Bundle { + /// Returns all valid `cer`, `crt`, and `der` certificates in the bundle. + var certificates: [SecCertificate] { + return 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. + var publicKeys: [SecKey] { + return 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. + func paths(forResourcesOfTypes types: [String]) -> [String] { + return Array(Set(types.flatMap { type.paths(forResourcesOfType: $0, inDirectory: nil) })) + } +} + +extension SecTrust: AlamofireExtended {} +public 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, *) + 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:)") + 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. + 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, *) + 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()") + 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. + 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)) + } + + // Reenable system anchor certificates. + let systemStatus = SecTrustSetAnchorCertificatesOnly(type, true) + guard systemStatus.af.isSuccess else { + throw AFError.serverTrustEvaluationFailed(reason: .settingAnchorCertificatesFailed(status: systemStatus, + certificates: certificates)) + } + } + + /// The public keys contained in `self`. + var publicKeys: [SecKey] { + return certificates.af.publicKeys + } + + /// The `SecCertificate`s contained i `self`. + var certificates: [SecCertificate] { + return (0.. SecPolicy { + return 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. + 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 {} +public extension AlamofireExtension where ExtendedType == [SecCertificate] { + /// All `Data` values for the contained `SecCertificate`s. + var data: [Data] { + return type.map { SecCertificateCopyData($0) as Data } + } + + /// All public `SecKey` values for the contained `SecCertificate`s. + var publicKeys: [SecKey] { + return type.compactMap { $0.af.publicKey } + } +} + +extension SecCertificate: AlamofireExtended {} +public extension AlamofireExtension where ExtendedType == SecCertificate { + /// The public key for `self`, if it can be extracted. + var publicKey: SecKey? { + let policy = SecPolicyCreateBasicX509() + var trust: SecTrust? + let trustCreationStatus = SecTrustCreateWithCertificates(type, policy, &trust) + + guard let createdTrust = trust, trustCreationStatus == errSecSuccess else { return nil } + + return SecTrustCopyPublicKey(createdTrust) + } +} + +extension OSStatus: AlamofireExtended {} +public extension AlamofireExtension where ExtendedType == OSStatus { + /// Returns whether `self` is `errSecSuccess`. + var isSuccess: Bool { return type == errSecSuccess } +} + +extension SecTrustResultType: AlamofireExtended {} +public extension AlamofireExtension where ExtendedType == SecTrustResultType { + /// Returns whether `self is `.unspecified` or `.proceed`. + var isSuccess: Bool { + return (type == .unspecified || type == .proceed) + } +} diff --git a/Example/Pods/Alamofire/Source/ServerTrustPolicy.swift b/Example/Pods/Alamofire/Source/ServerTrustPolicy.swift deleted file mode 100644 index fccdc02..0000000 --- a/Example/Pods/Alamofire/Source/ServerTrustPolicy.swift +++ /dev/null @@ -1,310 +0,0 @@ -// -// ServerTrustPolicy.swift -// -// Copyright (c) 2014 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 `ServerTrustPolicy` objects to a given host. -open class ServerTrustPolicyManager { - /// The dictionary of policies mapped to a particular host. - public let policies: [String: ServerTrustPolicy] - - /// Initializes the `ServerTrustPolicyManager` instance with the given policies. - /// - /// Since different servers and web services can have different leaf certificates, intermediate and even root - /// certficates, 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. - /// - /// - parameter policies: A dictionary of all policies mapped to a particular host. - /// - /// - returns: The new `ServerTrustPolicyManager` instance. - public init(policies: [String: ServerTrustPolicy]) { - self.policies = policies - } - - /// Returns the `ServerTrustPolicy` for the given host if applicable. - /// - /// 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 server trust policy for the given host if found. - open func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? { - return policies[host] - } -} - -// MARK: - - -extension URLSession { - private struct AssociatedKeys { - static var managerKey = "URLSession.ServerTrustPolicyManager" - } - - var serverTrustPolicyManager: ServerTrustPolicyManager? { - get { - return objc_getAssociatedObject(self, &AssociatedKeys.managerKey) as? ServerTrustPolicyManager - } - set (manager) { - objc_setAssociatedObject(self, &AssociatedKeys.managerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) - } - } -} - -// MARK: - ServerTrustPolicy - -/// The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when -/// connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust -/// with a given set of criteria to determine whether the server trust is valid and the connection should be made. -/// -/// Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other -/// vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged -/// to route all communication over an HTTPS connection with pinning enabled. -/// -/// - performDefaultEvaluation: 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. -/// -/// - performRevokedEvaluation: 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. -/// -/// - pinCertificates: 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. -/// -/// - pinPublicKeys: 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. -/// -/// - disableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid. -/// -/// - customEvaluation: Uses the associated closure to evaluate the validity of the server trust. -public enum ServerTrustPolicy { - case performDefaultEvaluation(validateHost: Bool) - case performRevokedEvaluation(validateHost: Bool, revocationFlags: CFOptionFlags) - case pinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool) - case pinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool) - case disableEvaluation - case customEvaluation((_ serverTrust: SecTrust, _ host: String) -> Bool) - - // MARK: - Bundle Location - - /// Returns all certificates within the given bundle with a `.cer` file extension. - /// - /// - parameter bundle: The bundle to search for all `.cer` files. - /// - /// - returns: All certificates within the given bundle. - public static func certificates(in bundle: Bundle = Bundle.main) -> [SecCertificate] { - var certificates: [SecCertificate] = [] - - let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in - bundle.paths(forResourcesOfType: fileExtension, inDirectory: nil) - }.joined()) - - for path in paths { - if - let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData, - let certificate = SecCertificateCreateWithData(nil, certificateData) - { - certificates.append(certificate) - } - } - - return certificates - } - - /// Returns all public keys within the given bundle with a `.cer` file extension. - /// - /// - parameter bundle: The bundle to search for all `*.cer` files. - /// - /// - returns: All public keys within the given bundle. - public static func publicKeys(in bundle: Bundle = Bundle.main) -> [SecKey] { - var publicKeys: [SecKey] = [] - - for certificate in certificates(in: bundle) { - if let publicKey = publicKey(for: certificate) { - publicKeys.append(publicKey) - } - } - - return publicKeys - } - - // MARK: - Evaluation - - /// Evaluates whether the server trust is valid for the given host. - /// - /// - parameter serverTrust: The server trust to evaluate. - /// - parameter host: The host of the challenge protection space. - /// - /// - returns: Whether the server trust is valid. - public func evaluate(_ serverTrust: SecTrust, forHost host: String) -> Bool { - var serverTrustIsValid = false - - switch self { - case let .performDefaultEvaluation(validateHost): - let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) - SecTrustSetPolicies(serverTrust, policy) - - serverTrustIsValid = trustIsValid(serverTrust) - case let .performRevokedEvaluation(validateHost, revocationFlags): - let defaultPolicy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) - let revokedPolicy = SecPolicyCreateRevocation(revocationFlags) - SecTrustSetPolicies(serverTrust, [defaultPolicy, revokedPolicy] as CFTypeRef) - - serverTrustIsValid = trustIsValid(serverTrust) - case let .pinCertificates(pinnedCertificates, validateCertificateChain, validateHost): - if validateCertificateChain { - let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) - SecTrustSetPolicies(serverTrust, policy) - - SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates as CFArray) - SecTrustSetAnchorCertificatesOnly(serverTrust, true) - - serverTrustIsValid = trustIsValid(serverTrust) - } else { - let serverCertificatesDataArray = certificateData(for: serverTrust) - let pinnedCertificatesDataArray = certificateData(for: pinnedCertificates) - - outerLoop: for serverCertificateData in serverCertificatesDataArray { - for pinnedCertificateData in pinnedCertificatesDataArray { - if serverCertificateData == pinnedCertificateData { - serverTrustIsValid = true - break outerLoop - } - } - } - } - case let .pinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost): - var certificateChainEvaluationPassed = true - - if validateCertificateChain { - let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) - SecTrustSetPolicies(serverTrust, policy) - - certificateChainEvaluationPassed = trustIsValid(serverTrust) - } - - if certificateChainEvaluationPassed { - outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeys(for: serverTrust) as [AnyObject] { - for pinnedPublicKey in pinnedPublicKeys as [AnyObject] { - if serverPublicKey.isEqual(pinnedPublicKey) { - serverTrustIsValid = true - break outerLoop - } - } - } - } - case .disableEvaluation: - serverTrustIsValid = true - case let .customEvaluation(closure): - serverTrustIsValid = closure(serverTrust, host) - } - - return serverTrustIsValid - } - - // MARK: - Private - Trust Validation - - private func trustIsValid(_ trust: SecTrust) -> Bool { - var isValid = false - - if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { - isValid = SecTrustEvaluateWithError(trust, nil) - } else { - var result = SecTrustResultType.invalid - let status = SecTrustEvaluate(trust, &result) - - if status == errSecSuccess { - let unspecified = SecTrustResultType.unspecified - let proceed = SecTrustResultType.proceed - - isValid = result == unspecified || result == proceed - } - } - - return isValid - } - - // MARK: - Private - Certificate Data - - private func certificateData(for trust: SecTrust) -> [Data] { - var certificates: [SecCertificate] = [] - - for index in 0.. [Data] { - return certificates.map { SecCertificateCopyData($0) as Data } - } - - // MARK: - Private - Public Key Extraction - - private static func publicKeys(for trust: SecTrust) -> [SecKey] { - var publicKeys: [SecKey] = [] - - for index in 0.. SecKey? { - var publicKey: SecKey? - - let policy = SecPolicyCreateBasicX509() - var trust: SecTrust? - let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust) - - if let trust = trust, trustCreationStatus == errSecSuccess { - publicKey = SecTrustCopyPublicKey(trust) - } - - return publicKey - } -} diff --git a/Example/Pods/Alamofire/Source/Session.swift b/Example/Pods/Alamofire/Source/Session.swift new file mode 100644 index 0000000..c73cfc1 --- /dev/null +++ b/Example/Pods/Alamofire/Source/Session.swift @@ -0,0 +1,1039 @@ +// +// 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. + 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 = [] + + /// 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.") + + let delegateQueue = OperationQueue(maxConcurrentOperationCount: 1, underlyingQueue: rootQueue, name: "org.alamofire.session.sessionDelegateQueue") + let session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: delegateQueue) + + self.init(session: session, + delegate: delegate, + rootQueue: rootQueue, + startRequestsImmediately: startRequestsImmediately, + requestQueue: requestQueue, + serializationQueue: serializationQueue, + interceptor: interceptor, + serverTrustManager: serverTrustManager, + redirectHandler: redirectHandler, + cachedResponseHandler: cachedResponseHandler, + eventMonitors: eventMonitors) + } + + deinit { + finishRequestsForDeinit() + session.invalidateAndCancel() + } + + // MARK: - Cancellation + + /// 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) { + rootQueue.async { + self.activeRequests.forEach { $0.cancel() } + queue.async { completion?() } + } + } + + // MARK: - DataRequest + + struct RequestConvertible: URLRequestConvertible { + let url: URLConvertible + let method: HTTPMethod + let parameters: Parameters? + let encoding: ParameterEncoding + let headers: HTTPHeaders? + + func asURLRequest() throws -> URLRequest { + let request = try URLRequest(url: url, method: method, headers: headers) + 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. + /// + /// - 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) -> DataRequest { + let convertible = RequestConvertible(url: convertible, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers) + + return request(convertible, interceptor: interceptor) + } + + struct RequestEncodableConvertible: URLRequestConvertible { + let url: URLConvertible + let method: HTTPMethod + let parameters: Parameters? + let encoder: ParameterEncoder + let headers: HTTPHeaders? + + func asURLRequest() throws -> URLRequest { + let request = try URLRequest(url: url, method: method, headers: headers) + + 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. + /// + /// - Returns: The created `DataRequest`. + open func request(_ convertible: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil) -> DataRequest { + let convertible = RequestEncodableConvertible(url: convertible, + method: method, + parameters: parameters, + encoder: encoder, + headers: headers) + + 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: - 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. + /// - 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, + to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { + let convertible = RequestConvertible(url: convertible, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers) + + 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. + /// - 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, + encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { + let convertible = RequestEncodableConvertible(url: convertible, + method: method, + parameters: parameters, + encoder: encoder, + headers: headers) + + 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? + + func asURLRequest() throws -> URLRequest { + return try URLRequest(url: url, method: method, headers: headers) + } + } + + struct Upload: UploadConvertible { + let request: URLRequestConvertible + let uploadable: UploadableConvertible + + func createUploadable() throws -> UploadRequest.Uploadable { + return try uploadable.createUploadable() + } + + func asURLRequest() throws -> URLRequest { + return 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. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ data: Data, + to convertible: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: convertible, method: method, headers: headers) + + 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 { + return 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. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ fileURL: URL, + to convertible: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: convertible, method: method, headers: headers) + + 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 { + return 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. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ stream: InputStream, + to convertible: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: convertible, method: method, headers: headers) + + 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 { + return 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. + /// - convertible: `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. + /// + /// - 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) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: url, method: method, headers: headers) + + 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. + /// + /// - 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) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: url, method: method, headers: headers) + + let multipartUpload = MultipartUpload(isInBackgroundSession: session.configuration.identifier != nil, + 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(isInBackgroundSession: session.configuration.identifier != nil, + 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 + + /// Perform `Request`. + /// + /// - Note: Called during retry. + /// + /// - Parameter request: The `Request` to perform. + func perform(_ request: Request) { + switch request { + case let r as DataRequest: perform(r) + case let r as UploadRequest: perform(r) + case let r as DownloadRequest: perform(r) + default: fatalError("Attempted to perform unsupported Request subclass: \(type(of: request))") + } + } + + func perform(_ request: DataRequest) { + requestQueue.async { + guard !request.isCancelled else { return } + + self.activeRequests.insert(request) + + self.performSetupOperations(for: request, convertible: request.convertible) + } + } + + func perform(_ request: UploadRequest) { + requestQueue.async { + guard !request.isCancelled else { return } + + self.activeRequests.insert(request) + + do { + let uploadable = try request.upload.createUploadable() + self.rootQueue.async { request.didCreateUploadable(uploadable) } + + self.performSetupOperations(for: request, convertible: request.convertible) + } catch { + self.rootQueue.async { request.didFailToCreateUploadable(with: error.asAFError(or: .createUploadableFailed(error: error))) } + } + } + } + + func perform(_ request: DownloadRequest) { + requestQueue.async { + guard !request.isCancelled else { return } + + self.activeRequests.insert(request) + + switch request.downloadable { + case let .request(convertible): + self.performSetupOperations(for: request, convertible: convertible) + case let .resumeData(resumeData): + self.rootQueue.async { self.didReceiveResumeData(resumeData, for: request) } + } + } + } + + func performSetupOperations(for request: Request, convertible: URLRequestConvertible) { + 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 { + rootQueue.async { self.didCreateURLRequest(initialRequest, for: request) } + return + } + + adapter.adapt(initialRequest, for: self) { result in + do { + let adaptedRequest = try result.get() + try adaptedRequest.validate() + + self.rootQueue.async { + request.didAdaptInitialRequest(initialRequest, to: adaptedRequest) + 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) { + 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) { + 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) { + 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 { $0.finish(error: AFError.sessionDeinitialized) } + } +} + +// MARK: - RequestDelegate + +extension Session: RequestDelegate { + public var sessionConfiguration: URLSessionConfiguration { + return session.configuration + } + + public var startImmediately: Bool { return 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? { + return requestTaskMap[task] + } + + func didGatherMetricsForTask(_ task: URLSessionTask) { + requestTaskMap.disassociateIfNecessaryAfterGatheringMetricsForTask(task) + } + + func didCompleteTask(_ task: URLSessionTask) { + requestTaskMap.disassociateIfNecessaryAfterCompletingTask(task) + } + + func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential? { + return requestTaskMap[task]?.credential ?? + session.configuration.urlCredentialStorage?.defaultCredential(for: protectionSpace) + } + + func cancelRequestsForSessionInvalidation(with error: Error?) { + requestTaskMap.requests.forEach { $0.finish(error: AFError.sessionInvalidated(error: error)) } + } +} diff --git a/Example/Pods/Alamofire/Source/SessionDelegate.swift b/Example/Pods/Alamofire/Source/SessionDelegate.swift index 4964f1e..77f5379 100644 --- a/Example/Pods/Alamofire/Source/SessionDelegate.swift +++ b/Example/Pods/Alamofire/Source/SessionDelegate.swift @@ -1,7 +1,7 @@ // // SessionDelegate.swift // -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) +// 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 @@ -24,702 +24,303 @@ import Foundation -/// Responsible for handling all delegate callbacks for the underlying session. +/// Class which implements the various `URLSessionDelegate` methods to connect various Alamofire features. open class SessionDelegate: NSObject { + private let fileManager: FileManager - // MARK: URLSessionDelegate Overrides + weak var stateProvider: SessionStateProvider? + var eventMonitor: EventMonitor? - /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didBecomeInvalidWithError:)`. - open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)? - - /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`. - open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? - - /// Overrides all behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)` and requires the caller to call the `completionHandler`. - open var sessionDidReceiveChallengeWithCompletion: ((URLSession, URLAuthenticationChallenge, @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? - - /// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`. - open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)? - - // MARK: URLSessionTaskDelegate Overrides - - /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`. - open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? - - /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` and - /// requires the caller to call the `completionHandler`. - open var taskWillPerformHTTPRedirectionWithCompletion: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest, @escaping (URLRequest?) -> Void) -> Void)? - - /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)`. - open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? - - /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)` and - /// requires the caller to call the `completionHandler`. - open var taskDidReceiveChallengeWithCompletion: ((URLSession, URLSessionTask, URLAuthenticationChallenge, @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? - - /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)`. - open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? - - /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)` and - /// requires the caller to call the `completionHandler`. - open var taskNeedNewBodyStreamWithCompletion: ((URLSession, URLSessionTask, @escaping (InputStream?) -> Void) -> Void)? - - /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)`. - open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? - - /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didCompleteWithError:)`. - open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)? - - // MARK: URLSessionDataDelegate Overrides - - /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)`. - open var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? - - /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)` and - /// requires caller to call the `completionHandler`. - open var dataTaskDidReceiveResponseWithCompletion: ((URLSession, URLSessionDataTask, URLResponse, @escaping (URLSession.ResponseDisposition) -> Void) -> Void)? - - /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didBecome:)`. - open var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? - - /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:)`. - open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? - - /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`. - open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? - - /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)` and - /// requires caller to call the `completionHandler`. - open var dataTaskWillCacheResponseWithCompletion: ((URLSession, URLSessionDataTask, CachedURLResponse, @escaping (CachedURLResponse?) -> Void) -> Void)? - - // MARK: URLSessionDownloadDelegate Overrides - - /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didFinishDownloadingTo:)`. - open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)? - - /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)`. - open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? - - /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)`. - open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? - - // MARK: URLSessionStreamDelegate Overrides - -#if !os(watchOS) - - /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:readClosedFor:)`. - @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) - open var streamTaskReadClosed: ((URLSession, URLSessionStreamTask) -> Void)? { - get { - return _streamTaskReadClosed as? (URLSession, URLSessionStreamTask) -> Void - } - set { - _streamTaskReadClosed = newValue - } + /// 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 } - /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:writeClosedFor:)`. - @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) - open var streamTaskWriteClosed: ((URLSession, URLSessionStreamTask) -> Void)? { - get { - return _streamTaskWriteClosed as? (URLSession, URLSessionStreamTask) -> Void - } - set { - _streamTaskWriteClosed = newValue + /// 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(for task: URLSessionTask, as type: R.Type) -> R? { + guard let provider = stateProvider else { + assertionFailure("StateProvider is nil.") + return nil } - } - /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:betterRouteDiscoveredFor:)`. - @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) - open var streamTaskBetterRouteDiscovered: ((URLSession, URLSessionStreamTask) -> Void)? { - get { - return _streamTaskBetterRouteDiscovered as? (URLSession, URLSessionStreamTask) -> Void + guard let request = provider.request(for: task) as? R else { + fatalError("Returned Request is not of expected type: \(R.self).") } - set { - _streamTaskBetterRouteDiscovered = newValue - } - } - /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:streamTask:didBecome:outputStream:)`. - @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) - open var streamTaskDidBecomeInputAndOutputStreams: ((URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void)? { - get { - return _streamTaskDidBecomeInputStream as? (URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void - } - set { - _streamTaskDidBecomeInputStream = newValue - } + return request } +} - var _streamTaskReadClosed: Any? - var _streamTaskWriteClosed: Any? - var _streamTaskBetterRouteDiscovered: Any? - var _streamTaskDidBecomeInputStream: Any? +/// 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) + func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential? + func cancelRequestsForSessionInvalidation(with error: Error?) +} -#endif +// MARK: URLSessionDelegate - // MARK: Properties +extension SessionDelegate: URLSessionDelegate { + open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { + eventMonitor?.urlSession(session, didBecomeInvalidWithError: error) - var retrier: RequestRetrier? - weak var sessionManager: SessionManager? + stateProvider?.cancelRequestsForSessionInvalidation(with: error) + } +} - var requests: [Int: Request] = [:] - private let lock = NSLock() +// MARK: URLSessionTaskDelegate - /// Access the task delegate for the specified task in a thread-safe manner. - open subscript(task: URLSessionTask) -> Request? { - get { - lock.lock() ; defer { lock.unlock() } - return requests[task.taskIdentifier] - } - set { - lock.lock() ; defer { lock.unlock() } - requests[task.taskIdentifier] = newValue +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 NSURLAuthenticationMethodServerTrust: + evaluation = attemptServerTrustAuthentication(with: challenge) + case NSURLAuthenticationMethodHTTPBasic, NSURLAuthenticationMethodHTTPDigest, NSURLAuthenticationMethodNTLM, + NSURLAuthenticationMethodNegotiate, NSURLAuthenticationMethodClientCertificate: + evaluation = attemptCredentialAuthentication(for: challenge, belongingTo: task) + default: + evaluation = (.performDefaultHandling, nil, nil) } - } - // MARK: Lifecycle + if let error = evaluation.error { + stateProvider?.request(for: task)?.didFailTask(task, earlyWithError: error) + } - /// Initializes the `SessionDelegate` instance. - /// - /// - returns: The new `SessionDelegate` instance. - public override init() { - super.init() + completionHandler(evaluation.disposition, evaluation.credential) } - // MARK: NSObject Overrides - - /// Returns a `Bool` indicating whether the `SessionDelegate` implements or inherits a method that can respond - /// to a specified message. + /// Evaluates the server trust `URLAuthenticationChallenge` received. /// - /// - parameter selector: A selector that identifies a message. + /// - Parameter challenge: The `URLAuthenticationChallenge`. /// - /// - returns: `true` if the receiver implements or inherits a method that can respond to selector, otherwise `false`. - open override func responds(to selector: Selector) -> Bool { - #if !os(macOS) - if selector == #selector(URLSessionDelegate.urlSessionDidFinishEvents(forBackgroundURLSession:)) { - return sessionDidFinishEventsForBackgroundURLSession != nil - } - #endif - - #if !os(watchOS) - if #available(iOS 9.0, macOS 10.11, tvOS 9.0, *) { - switch selector { - case #selector(URLSessionStreamDelegate.urlSession(_:readClosedFor:)): - return streamTaskReadClosed != nil - case #selector(URLSessionStreamDelegate.urlSession(_:writeClosedFor:)): - return streamTaskWriteClosed != nil - case #selector(URLSessionStreamDelegate.urlSession(_:betterRouteDiscoveredFor:)): - return streamTaskBetterRouteDiscovered != nil - case #selector(URLSessionStreamDelegate.urlSession(_:streamTask:didBecome:outputStream:)): - return streamTaskDidBecomeInputAndOutputStreams != nil - default: - break - } - } - #endif - - switch selector { - case #selector(URLSessionDelegate.urlSession(_:didBecomeInvalidWithError:)): - return sessionDidBecomeInvalidWithError != nil - case #selector(URLSessionDelegate.urlSession(_:didReceive:completionHandler:)): - return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil) - case #selector(URLSessionTaskDelegate.urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)): - return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil) - case #selector(URLSessionDataDelegate.urlSession(_:dataTask:didReceive:completionHandler:)): - return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil) - default: - return type(of: self).instancesRespond(to: selector) + /// - 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) } - } -} -// MARK: - URLSessionDelegate + do { + guard let evaluator = try stateProvider?.serverTrustManager?.serverTrustEvaluator(forHost: host) else { + return (.performDefaultHandling, nil, nil) + } -extension SessionDelegate: URLSessionDelegate { - /// Tells the delegate that the session has been invalidated. - /// - /// - parameter session: The session object that was invalidated. - /// - parameter error: The error that caused invalidation, or nil if the invalidation was explicit. - open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { - sessionDidBecomeInvalidWithError?(session, error) + try evaluator.evaluate(trust, forHost: host) + + return (.useCredential, URLCredential(trust: trust), nil) + } catch { + return (.cancelAuthenticationChallenge, nil, error.asAFError(or: .serverTrustEvaluationFailed(reason: .customEvaluationFailed(error: error)))) + } } - /// Requests credentials from the delegate in response to a session-level authentication request from the - /// remote server. + /// Evaluates the credential-based authentication `URLAuthenticationChallenge` received for `task`. /// - /// - parameter session: The session containing the task that requested authentication. - /// - parameter challenge: An object that contains the request for authentication. - /// - parameter completionHandler: A handler that your delegate method must call providing the disposition - /// and credential. - open func urlSession( - _ session: URLSession, - didReceive challenge: URLAuthenticationChallenge, - completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) - { - guard sessionDidReceiveChallengeWithCompletion == nil else { - sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler) - return + /// - 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) } - var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling - var credential: URLCredential? - - if let sessionDidReceiveChallenge = sessionDidReceiveChallenge { - (disposition, credential) = sessionDidReceiveChallenge(session, challenge) - } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { - let host = challenge.protectionSpace.host - - if - let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host), - let serverTrust = challenge.protectionSpace.serverTrust - { - if serverTrustPolicy.evaluate(serverTrust, forHost: host) { - disposition = .useCredential - credential = URLCredential(trust: serverTrust) - } else { - disposition = .cancelAuthenticationChallenge - } - } + guard let credential = stateProvider?.credential(for: task, in: challenge.protectionSpace) else { + return (.performDefaultHandling, nil, nil) } - completionHandler(disposition, credential) + return (.useCredential, credential, nil) } -#if !os(macOS) - - /// Tells the delegate that all messages enqueued for a session have been delivered. - /// - /// - parameter session: The session that no longer has any outstanding requests. - open func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { - sessionDidFinishEventsForBackgroundURLSession?(session) + 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) } -#endif -} - -// MARK: - URLSessionTaskDelegate + open func urlSession(_ session: URLSession, + task: URLSessionTask, + needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) { + eventMonitor?.urlSession(session, taskNeedsNewBodyStream: task) -extension SessionDelegate: URLSessionTaskDelegate { - /// Tells the delegate that the remote server requested an HTTP redirect. - /// - /// - parameter session: The session containing the task whose request resulted in a redirect. - /// - parameter task: The task whose request resulted in a redirect. - /// - parameter response: An object containing the server’s response to the original request. - /// - parameter request: A URL request object filled out with the new location. - /// - parameter completionHandler: A closure that your handler should call with either the value of the request - /// parameter, a modified URL request object, or NULL to refuse the redirect and - /// return the body of the redirect response. - open func urlSession( - _ session: URLSession, - task: URLSessionTask, - willPerformHTTPRedirection response: HTTPURLResponse, - newRequest request: URLRequest, - completionHandler: @escaping (URLRequest?) -> Void) - { - guard taskWillPerformHTTPRedirectionWithCompletion == nil else { - taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler) + guard let request = request(for: task, as: UploadRequest.self) else { + assertionFailure("needNewBodyStream did not find UploadRequest.") + completionHandler(nil) return } - var redirectRequest: URLRequest? = request - - if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { - redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) - } - - completionHandler(redirectRequest) + completionHandler(request.inputStream()) } - /// Requests credentials from the delegate in response to an authentication request from the remote server. - /// - /// - parameter session: The session containing the task whose request requires authentication. - /// - parameter task: The task whose request requires authentication. - /// - parameter challenge: An object that contains the request for authentication. - /// - parameter completionHandler: A handler that your delegate method must call providing the disposition - /// and credential. - open func urlSession( - _ session: URLSession, - task: URLSessionTask, - didReceive challenge: URLAuthenticationChallenge, - completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) - { - guard taskDidReceiveChallengeWithCompletion == nil else { - taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler) - return - } + 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 taskDidReceiveChallenge = taskDidReceiveChallenge { - let result = taskDidReceiveChallenge(session, task, challenge) - completionHandler(result.0, result.1) - } else if let delegate = self[task]?.delegate { - delegate.urlSession( - session, - task: task, - didReceive: challenge, - completionHandler: completionHandler - ) + if let redirectHandler = stateProvider?.request(for: task)?.redirectHandler ?? stateProvider?.redirectHandler { + redirectHandler.task(task, willBeRedirectedTo: request, for: response, completion: completionHandler) } else { - urlSession(session, didReceive: challenge, completionHandler: completionHandler) - } - } - - /// Tells the delegate when a task requires a new request body stream to send to the remote server. - /// - /// - parameter session: The session containing the task that needs a new body stream. - /// - parameter task: The task that needs a new body stream. - /// - parameter completionHandler: A completion handler that your delegate method should call with the new body stream. - open func urlSession( - _ session: URLSession, - task: URLSessionTask, - needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) - { - guard taskNeedNewBodyStreamWithCompletion == nil else { - taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler) - return - } - - if let taskNeedNewBodyStream = taskNeedNewBodyStream { - completionHandler(taskNeedNewBodyStream(session, task)) - } else if let delegate = self[task]?.delegate { - delegate.urlSession(session, task: task, needNewBodyStream: completionHandler) + completionHandler(request) } } - /// Periodically informs the delegate of the progress of sending body content to the server. - /// - /// - parameter session: The session containing the data task. - /// - parameter task: The data task. - /// - parameter bytesSent: The number of bytes sent since the last time this delegate method was called. - /// - parameter totalBytesSent: The total number of bytes sent so far. - /// - parameter totalBytesExpectedToSend: The expected length of the body data. - open func urlSession( - _ session: URLSession, - task: URLSessionTask, - didSendBodyData bytesSent: Int64, - totalBytesSent: Int64, - totalBytesExpectedToSend: Int64) - { - if let taskDidSendBodyData = taskDidSendBodyData { - taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) - } else if let delegate = self[task]?.delegate as? UploadTaskDelegate { - delegate.URLSession( - session, - task: task, - didSendBodyData: bytesSent, - totalBytesSent: totalBytesSent, - totalBytesExpectedToSend: totalBytesExpectedToSend - ) - } - } + open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { + eventMonitor?.urlSession(session, task: task, didFinishCollecting: metrics) -#if !os(watchOS) + stateProvider?.request(for: task)?.didGatherMetrics(metrics) - /// Tells the delegate that the session finished collecting metrics for the task. - /// - /// - parameter session: The session collecting the metrics. - /// - parameter task: The task whose metrics have been collected. - /// - parameter metrics: The collected metrics. - @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) - @objc(URLSession:task:didFinishCollectingMetrics:) - open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { - self[task]?.delegate.metrics = metrics + stateProvider?.didGatherMetricsForTask(task) } -#endif - - /// Tells the delegate that the task finished transferring data. - /// - /// - parameter session: The session containing the task whose request finished transferring data. - /// - parameter task: The task whose request finished transferring data. - /// - parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil. open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { - /// Executed after it is determined that the request is not going to be retried - let completeTask: (URLSession, URLSessionTask, Error?) -> Void = { [weak self] session, task, error in - guard let strongSelf = self else { return } - - strongSelf.taskDidComplete?(session, task, error) + eventMonitor?.urlSession(session, task: task, didCompleteWithError: error) - strongSelf[task]?.delegate.urlSession(session, task: task, didCompleteWithError: error) + stateProvider?.request(for: task)?.didCompleteTask(task, with: error.map { $0.asAFError(or: .sessionTaskFailed(error: $0)) }) - var userInfo: [String: Any] = [Notification.Key.Task: task] + stateProvider?.didCompleteTask(task) + } - if let data = (strongSelf[task]?.delegate as? DataTaskDelegate)?.data { - userInfo[Notification.Key.ResponseData] = data - } + @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) + } +} - NotificationCenter.default.post( - name: Notification.Name.Task.DidComplete, - object: strongSelf, - userInfo: userInfo - ) +// MARK: URLSessionDataDelegate - strongSelf[task] = nil - } +extension SessionDelegate: URLSessionDataDelegate { + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + eventMonitor?.urlSession(session, dataTask: dataTask, didReceive: data) - guard let request = self[task], let sessionManager = sessionManager else { - completeTask(session, task, error) + guard let request = request(for: dataTask, as: DataRequest.self) else { + assertionFailure("dataTask did not find DataRequest.") return } - // Run all validations on the request before checking if an error occurred - request.validations.forEach { $0() } - - // Determine whether an error has occurred - var error: Error? = error - - if request.delegate.error != nil { - error = request.delegate.error - } - - /// If an error occurred and the retrier is set, asynchronously ask the retrier if the request - /// should be retried. Otherwise, complete the task by notifying the task delegate. - if let retrier = retrier, let error = error { - retrier.should(sessionManager, retry: request, with: error) { [weak self] shouldRetry, timeDelay in - guard shouldRetry else { completeTask(session, task, error) ; return } - - DispatchQueue.utility.after(timeDelay) { [weak self] in - guard let strongSelf = self else { return } + request.didReceive(data: data) + } - let retrySucceeded = strongSelf.sessionManager?.retry(request) ?? false + open func urlSession(_ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse, + completionHandler: @escaping (CachedURLResponse?) -> Void) { + eventMonitor?.urlSession(session, dataTask: dataTask, willCacheResponse: proposedResponse) - if retrySucceeded, let task = request.task { - strongSelf[task] = request - return - } else { - completeTask(session, task, error) - } - } - } + if let handler = stateProvider?.request(for: dataTask)?.cachedResponseHandler ?? stateProvider?.cachedResponseHandler { + handler.dataTask(dataTask, willCacheResponse: proposedResponse, completion: completionHandler) } else { - completeTask(session, task, error) + completionHandler(proposedResponse) } } } -// MARK: - URLSessionDataDelegate +// MARK: URLSessionDownloadDelegate -extension SessionDelegate: URLSessionDataDelegate { - /// Tells the delegate that the data task received the initial reply (headers) from the server. - /// - /// - parameter session: The session containing the data task that received an initial reply. - /// - parameter dataTask: The data task that received an initial reply. - /// - parameter response: A URL response object populated with headers. - /// - parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a - /// constant to indicate whether the transfer should continue as a data task or - /// should become a download task. - open func urlSession( - _ session: URLSession, - dataTask: URLSessionDataTask, - didReceive response: URLResponse, - completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) - { - guard dataTaskDidReceiveResponseWithCompletion == nil else { - dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler) +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 } - var disposition: URLSession.ResponseDisposition = .allow - - if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { - disposition = dataTaskDidReceiveResponse(session, dataTask, response) - } - - completionHandler(disposition) + downloadRequest.updateDownloadProgress(bytesWritten: fileOffset, + totalBytesExpectedToWrite: expectedTotalBytes) } - /// Tells the delegate that the data task was changed to a download task. - /// - /// - parameter session: The session containing the task that was replaced by a download task. - /// - parameter dataTask: The data task that was replaced by a download task. - /// - parameter downloadTask: The new download task that replaced the data task. - open func urlSession( - _ session: URLSession, - dataTask: URLSessionDataTask, - didBecome downloadTask: URLSessionDownloadTask) - { - if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask { - dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask) - } else { - self[downloadTask]?.delegate = DownloadTaskDelegate(task: downloadTask) - } - } - - /// Tells the delegate that the data task has received some of the expected data. - /// - /// - parameter session: The session containing the data task that provided data. - /// - parameter dataTask: The data task that provided data. - /// - parameter data: A data object containing the transferred data. - open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { - if let dataTaskDidReceiveData = dataTaskDidReceiveData { - dataTaskDidReceiveData(session, dataTask, data) - } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { - delegate.urlSession(session, dataTask: dataTask, didReceive: data) - } - } - - /// Asks the delegate whether the data (or upload) task should store the response in the cache. - /// - /// - parameter session: The session containing the data (or upload) task. - /// - parameter dataTask: The data (or upload) task. - /// - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current - /// caching policy and the values of certain received headers, such as the Pragma - /// and Cache-Control headers. - /// - parameter completionHandler: A block that your handler must call, providing either the original proposed - /// response, a modified version of that response, or NULL to prevent caching the - /// response. If your delegate implements this method, it must call this completion - /// handler; otherwise, your app leaks memory. - open func urlSession( - _ session: URLSession, - dataTask: URLSessionDataTask, - willCacheResponse proposedResponse: CachedURLResponse, - completionHandler: @escaping (CachedURLResponse?) -> Void) - { - guard dataTaskWillCacheResponseWithCompletion == nil else { - dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler) + 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 } - if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { - completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) - } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { - delegate.urlSession( - session, - dataTask: dataTask, - willCacheResponse: proposedResponse, - completionHandler: completionHandler - ) - } else { - completionHandler(proposedResponse) - } + downloadRequest.updateDownloadProgress(bytesWritten: bytesWritten, + totalBytesExpectedToWrite: totalBytesExpectedToWrite) } -} -// MARK: - URLSessionDownloadDelegate + open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { + eventMonitor?.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) -extension SessionDelegate: URLSessionDownloadDelegate { - /// Tells the delegate that a download task has finished downloading. - /// - /// - parameter session: The session containing the download task that finished. - /// - parameter downloadTask: The download task that finished. - /// - parameter location: A file URL for the temporary file. Because the file is temporary, you must either - /// open the file for reading or move it to a permanent location in your app’s sandbox - /// container directory before returning from this delegate method. - open func urlSession( - _ session: URLSession, - downloadTask: URLSessionDownloadTask, - didFinishDownloadingTo location: URL) - { - if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { - downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) - } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { - delegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) - } - } - - /// Periodically informs the delegate about the download’s progress. - /// - /// - parameter session: The session containing the download task. - /// - parameter downloadTask: The download task. - /// - parameter bytesWritten: The number of bytes transferred since the last time this delegate - /// method was called. - /// - parameter totalBytesWritten: The total number of bytes transferred so far. - /// - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length - /// header. If this header was not provided, the value is - /// `NSURLSessionTransferSizeUnknown`. - open func urlSession( - _ session: URLSession, - downloadTask: URLSessionDownloadTask, - didWriteData bytesWritten: Int64, - totalBytesWritten: Int64, - totalBytesExpectedToWrite: Int64) - { - if let downloadTaskDidWriteData = downloadTaskDidWriteData { - downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) - } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { - delegate.urlSession( - session, - downloadTask: downloadTask, - didWriteData: bytesWritten, - totalBytesWritten: totalBytesWritten, - totalBytesExpectedToWrite: totalBytesExpectedToWrite - ) + guard let request = request(for: downloadTask, as: DownloadRequest.self) else { + assertionFailure("downloadTask did not find DownloadRequest.") + return } - } - /// Tells the delegate that the download task has resumed downloading. - /// - /// - parameter session: The session containing the download task that finished. - /// - parameter downloadTask: The download task that resumed. See explanation in the discussion. - /// - parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the - /// existing content, then this value is zero. Otherwise, this value is an - /// integer representing the number of bytes on disk that do not need to be - /// retrieved again. - /// - parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header. - /// If this header was not provided, the value is NSURLSessionTransferSizeUnknown. - open func urlSession( - _ session: URLSession, - downloadTask: URLSessionDownloadTask, - didResumeAtOffset fileOffset: Int64, - expectedTotalBytes: Int64) - { - if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { - downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) - } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { - delegate.urlSession( - session, - downloadTask: downloadTask, - didResumeAtOffset: fileOffset, - expectedTotalBytes: expectedTotalBytes - ) + guard let response = request.response else { + fatalError("URLSessionDownloadTask finished downloading with no response.") } - } -} -// MARK: - URLSessionStreamDelegate + let (destination, options) = (request.destination)(location, response) -#if !os(watchOS) + eventMonitor?.request(request, didCreateDestinationURL: destination) -@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) -extension SessionDelegate: URLSessionStreamDelegate { - /// Tells the delegate that the read side of the connection has been closed. - /// - /// - parameter session: The session. - /// - parameter streamTask: The stream task. - open func urlSession(_ session: URLSession, readClosedFor streamTask: URLSessionStreamTask) { - streamTaskReadClosed?(session, streamTask) - } + do { + if options.contains(.removePreviousFile), fileManager.fileExists(atPath: destination.path) { + try fileManager.removeItem(at: destination) + } - /// Tells the delegate that the write side of the connection has been closed. - /// - /// - parameter session: The session. - /// - parameter streamTask: The stream task. - open func urlSession(_ session: URLSession, writeClosedFor streamTask: URLSessionStreamTask) { - streamTaskWriteClosed?(session, streamTask) - } + if options.contains(.createIntermediateDirectories) { + let directory = destination.deletingLastPathComponent() + try fileManager.createDirectory(at: directory, withIntermediateDirectories: true) + } - /// Tells the delegate that the system has determined that a better route to the host is available. - /// - /// - parameter session: The session. - /// - parameter streamTask: The stream task. - open func urlSession(_ session: URLSession, betterRouteDiscoveredFor streamTask: URLSessionStreamTask) { - streamTaskBetterRouteDiscovered?(session, streamTask) - } + try fileManager.moveItem(at: location, to: destination) - /// Tells the delegate that the stream task has been completed and provides the unopened stream objects. - /// - /// - parameter session: The session. - /// - parameter streamTask: The stream task. - /// - parameter inputStream: The new input stream. - /// - parameter outputStream: The new output stream. - open func urlSession( - _ session: URLSession, - streamTask: URLSessionStreamTask, - didBecome inputStream: InputStream, - outputStream: OutputStream) - { - streamTaskDidBecomeInputAndOutputStreams?(session, streamTask, inputStream, outputStream) + request.didFinishDownloading(using: downloadTask, with: .success(destination)) + } catch { + request.didFinishDownloading(using: downloadTask, with: .failure(.downloadedFileMoveFailed(error: error, source: location, destination: destination))) + } } } - -#endif diff --git a/Example/Pods/Alamofire/Source/SessionManager.swift b/Example/Pods/Alamofire/Source/SessionManager.swift deleted file mode 100644 index 02c36a7..0000000 --- a/Example/Pods/Alamofire/Source/SessionManager.swift +++ /dev/null @@ -1,899 +0,0 @@ -// -// SessionManager.swift -// -// Copyright (c) 2014 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 creating and managing `Request` objects, as well as their underlying `NSURLSession`. -open class SessionManager { - - // MARK: - Helper Types - - /// Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as - /// associated values. - /// - /// - Success: Represents a successful `MultipartFormData` encoding and contains the new `UploadRequest` along with - /// streaming information. - /// - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding - /// error. - public enum MultipartFormDataEncodingResult { - case success(request: UploadRequest, streamingFromDisk: Bool, streamFileURL: URL?) - case failure(Error) - } - - // MARK: - Properties - - /// A default instance of `SessionManager`, used by top-level Alamofire request methods, and suitable for use - /// directly for any ad hoc requests. - public static let `default`: SessionManager = { - let configuration = URLSessionConfiguration.default - configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders - - return SessionManager(configuration: configuration) - }() - - /// Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. - public static let defaultHTTPHeaders: HTTPHeaders = { - // Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3 - let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5" - - // Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5 - let acceptLanguage = Locale.preferredLanguages.prefix(6).enumerated().map { index, languageCode in - let quality = 1.0 - (Double(index) * 0.1) - return "\(languageCode);q=\(quality)" - }.joined(separator: ", ") - - // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 - // Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0` - let userAgent: String = { - if let info = Bundle.main.infoDictionary { - let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" - let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" - let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown" - let appBuild = info[kCFBundleVersionKey as String] 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) - return "iOS" - #elseif os(watchOS) - return "watchOS" - #elseif os(tvOS) - return "tvOS" - #elseif os(macOS) - return "OS X" - #elseif os(Linux) - return "Linux" - #else - return "Unknown" - #endif - }() - - return "\(osName) \(versionString)" - }() - - let alamofireVersion: String = { - guard - let afInfo = Bundle(for: SessionManager.self).infoDictionary, - let build = afInfo["CFBundleShortVersionString"] - else { return "Unknown" } - - return "Alamofire/\(build)" - }() - - return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)" - } - - return "Alamofire" - }() - - return [ - "Accept-Encoding": acceptEncoding, - "Accept-Language": acceptLanguage, - "User-Agent": userAgent - ] - }() - - /// Default memory threshold used when encoding `MultipartFormData` in bytes. - public static let multipartFormDataEncodingMemoryThreshold: UInt64 = 10_000_000 - - /// The underlying session. - public let session: URLSession - - /// The session delegate handling all the task and session delegate callbacks. - public let delegate: SessionDelegate - - /// Whether to start requests immediately after being constructed. `true` by default. - open var startRequestsImmediately: Bool = true - - /// The request adapter called each time a new request is created. - open var adapter: RequestAdapter? - - /// The request retrier called each time a request encounters an error to determine whether to retry the request. - open var retrier: RequestRetrier? { - get { return delegate.retrier } - set { delegate.retrier = newValue } - } - - /// The background completion handler closure provided by the UIApplicationDelegate - /// `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background - /// completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation - /// will automatically call the handler. - /// - /// If you need to handle your own events before the handler is called, then you need to override the - /// SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished. - /// - /// `nil` by default. - open var backgroundCompletionHandler: (() -> Void)? - - let queue = DispatchQueue(label: "org.alamofire.session-manager." + UUID().uuidString) - - // MARK: - Lifecycle - - /// Creates an instance with the specified `configuration`, `delegate` and `serverTrustPolicyManager`. - /// - /// - parameter configuration: The configuration used to construct the managed session. - /// `URLSessionConfiguration.default` by default. - /// - parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by - /// default. - /// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust - /// challenges. `nil` by default. - /// - /// - returns: The new `SessionManager` instance. - public init( - configuration: URLSessionConfiguration = URLSessionConfiguration.default, - delegate: SessionDelegate = SessionDelegate(), - serverTrustPolicyManager: ServerTrustPolicyManager? = nil) - { - self.delegate = delegate - self.session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) - - commonInit(serverTrustPolicyManager: serverTrustPolicyManager) - } - - /// Creates an instance with the specified `session`, `delegate` and `serverTrustPolicyManager`. - /// - /// - parameter session: The URL session. - /// - parameter delegate: The delegate of the URL session. Must equal the URL session's delegate. - /// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust - /// challenges. `nil` by default. - /// - /// - returns: The new `SessionManager` instance if the URL session's delegate matches; `nil` otherwise. - public init?( - session: URLSession, - delegate: SessionDelegate, - serverTrustPolicyManager: ServerTrustPolicyManager? = nil) - { - guard delegate === session.delegate else { return nil } - - self.delegate = delegate - self.session = session - - commonInit(serverTrustPolicyManager: serverTrustPolicyManager) - } - - private func commonInit(serverTrustPolicyManager: ServerTrustPolicyManager?) { - session.serverTrustPolicyManager = serverTrustPolicyManager - - delegate.sessionManager = self - - delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in - guard let strongSelf = self else { return } - DispatchQueue.main.async { strongSelf.backgroundCompletionHandler?() } - } - } - - deinit { - session.invalidateAndCancel() - } - - // MARK: - Data Request - - /// Creates a `DataRequest` to retrieve the contents of the specified `url`, `method`, `parameters`, `encoding` - /// and `headers`. - /// - /// - parameter url: The URL. - /// - parameter method: The HTTP method. `.get` by default. - /// - parameter parameters: The parameters. `nil` by default. - /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. - /// - parameter headers: The HTTP headers. `nil` by default. - /// - /// - returns: The created `DataRequest`. - @discardableResult - open func request( - _ url: URLConvertible, - method: HTTPMethod = .get, - parameters: Parameters? = nil, - encoding: ParameterEncoding = URLEncoding.default, - headers: HTTPHeaders? = nil) - -> DataRequest - { - var originalRequest: URLRequest? - - do { - originalRequest = try URLRequest(url: url, method: method, headers: headers) - let encodedURLRequest = try encoding.encode(originalRequest!, with: parameters) - return request(encodedURLRequest) - } catch { - return request(originalRequest, failedWith: error) - } - } - - /// Creates a `DataRequest` to retrieve the contents of a URL based on the specified `urlRequest`. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter urlRequest: The URL request. - /// - /// - returns: The created `DataRequest`. - @discardableResult - open func request(_ urlRequest: URLRequestConvertible) -> DataRequest { - var originalRequest: URLRequest? - - do { - originalRequest = try urlRequest.asURLRequest() - let originalTask = DataRequest.Requestable(urlRequest: originalRequest!) - - let task = try originalTask.task(session: session, adapter: adapter, queue: queue) - let request = DataRequest(session: session, requestTask: .data(originalTask, task)) - - delegate[task] = request - - if startRequestsImmediately { request.resume() } - - return request - } catch { - return request(originalRequest, failedWith: error) - } - } - - // MARK: Private - Request Implementation - - private func request(_ urlRequest: URLRequest?, failedWith error: Error) -> DataRequest { - var requestTask: Request.RequestTask = .data(nil, nil) - - if let urlRequest = urlRequest { - let originalTask = DataRequest.Requestable(urlRequest: urlRequest) - requestTask = .data(originalTask, nil) - } - - let underlyingError = error.underlyingAdaptError ?? error - let request = DataRequest(session: session, requestTask: requestTask, error: underlyingError) - - if let retrier = retrier, error is AdaptError { - allowRetrier(retrier, toRetry: request, with: underlyingError) - } else { - if startRequestsImmediately { request.resume() } - } - - return request - } - - // MARK: - Download Request - - // MARK: URL Request - - /// Creates a `DownloadRequest` to retrieve the contents the specified `url`, `method`, `parameters`, `encoding`, - /// `headers` and save them to the `destination`. - /// - /// If `destination` is not specified, the contents will remain in the temporary location determined by the - /// underlying URL session. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter url: The URL. - /// - parameter method: The HTTP method. `.get` by default. - /// - parameter parameters: The parameters. `nil` by default. - /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. - /// - parameter headers: The HTTP headers. `nil` by default. - /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. - /// - /// - returns: The created `DownloadRequest`. - @discardableResult - open func download( - _ url: URLConvertible, - method: HTTPMethod = .get, - parameters: Parameters? = nil, - encoding: ParameterEncoding = URLEncoding.default, - headers: HTTPHeaders? = nil, - to destination: DownloadRequest.DownloadFileDestination? = nil) - -> DownloadRequest - { - do { - let urlRequest = try URLRequest(url: url, method: method, headers: headers) - let encodedURLRequest = try encoding.encode(urlRequest, with: parameters) - return download(encodedURLRequest, to: destination) - } catch { - return download(nil, to: destination, failedWith: error) - } - } - - /// Creates a `DownloadRequest` to retrieve the contents of a URL based on the specified `urlRequest` and save - /// them to the `destination`. - /// - /// If `destination` is not specified, the contents will remain in the temporary location determined by the - /// underlying URL session. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter urlRequest: The URL request - /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. - /// - /// - returns: The created `DownloadRequest`. - @discardableResult - open func download( - _ urlRequest: URLRequestConvertible, - to destination: DownloadRequest.DownloadFileDestination? = nil) - -> DownloadRequest - { - do { - let urlRequest = try urlRequest.asURLRequest() - return download(.request(urlRequest), to: destination) - } catch { - return download(nil, to: destination, failedWith: error) - } - } - - // MARK: Resume Data - - /// Creates a `DownloadRequest` from the `resumeData` produced from a previous request cancellation to retrieve - /// the contents of the original request and save them to the `destination`. - /// - /// If `destination` is not specified, the contents will remain in the temporary location determined by the - /// underlying URL session. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `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 following Stack Overflow post: - /// - /// - http://stackoverflow.com/a/39347461/1342462 - /// - /// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` - /// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for - /// additional information. - /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. - /// - /// - returns: The created `DownloadRequest`. - @discardableResult - open func download( - resumingWith resumeData: Data, - to destination: DownloadRequest.DownloadFileDestination? = nil) - -> DownloadRequest - { - return download(.resumeData(resumeData), to: destination) - } - - // MARK: Private - Download Implementation - - private func download( - _ downloadable: DownloadRequest.Downloadable, - to destination: DownloadRequest.DownloadFileDestination?) - -> DownloadRequest - { - do { - let task = try downloadable.task(session: session, adapter: adapter, queue: queue) - let download = DownloadRequest(session: session, requestTask: .download(downloadable, task)) - - download.downloadDelegate.destination = destination - - delegate[task] = download - - if startRequestsImmediately { download.resume() } - - return download - } catch { - return download(downloadable, to: destination, failedWith: error) - } - } - - private func download( - _ downloadable: DownloadRequest.Downloadable?, - to destination: DownloadRequest.DownloadFileDestination?, - failedWith error: Error) - -> DownloadRequest - { - var downloadTask: Request.RequestTask = .download(nil, nil) - - if let downloadable = downloadable { - downloadTask = .download(downloadable, nil) - } - - let underlyingError = error.underlyingAdaptError ?? error - - let download = DownloadRequest(session: session, requestTask: downloadTask, error: underlyingError) - download.downloadDelegate.destination = destination - - if let retrier = retrier, error is AdaptError { - allowRetrier(retrier, toRetry: download, with: underlyingError) - } else { - if startRequestsImmediately { download.resume() } - } - - return download - } - - // MARK: - Upload Request - - // MARK: File - - /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `file`. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter file: The file to upload. - /// - parameter url: The URL. - /// - parameter method: The HTTP method. `.post` by default. - /// - parameter headers: The HTTP headers. `nil` by default. - /// - /// - returns: The created `UploadRequest`. - @discardableResult - open func upload( - _ fileURL: URL, - to url: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil) - -> UploadRequest - { - do { - let urlRequest = try URLRequest(url: url, method: method, headers: headers) - return upload(fileURL, with: urlRequest) - } catch { - return upload(nil, failedWith: error) - } - } - - /// Creates a `UploadRequest` from the specified `urlRequest` for uploading the `file`. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter file: The file to upload. - /// - parameter urlRequest: The URL request. - /// - /// - returns: The created `UploadRequest`. - @discardableResult - open func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { - do { - let urlRequest = try urlRequest.asURLRequest() - return upload(.file(fileURL, urlRequest)) - } catch { - return upload(nil, failedWith: error) - } - } - - // MARK: Data - - /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `data`. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter data: The data to upload. - /// - parameter url: The URL. - /// - parameter method: The HTTP method. `.post` by default. - /// - parameter headers: The HTTP headers. `nil` by default. - /// - /// - returns: The created `UploadRequest`. - @discardableResult - open func upload( - _ data: Data, - to url: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil) - -> UploadRequest - { - do { - let urlRequest = try URLRequest(url: url, method: method, headers: headers) - return upload(data, with: urlRequest) - } catch { - return upload(nil, failedWith: error) - } - } - - /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `data`. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter data: The data to upload. - /// - parameter urlRequest: The URL request. - /// - /// - returns: The created `UploadRequest`. - @discardableResult - open func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { - do { - let urlRequest = try urlRequest.asURLRequest() - return upload(.data(data, urlRequest)) - } catch { - return upload(nil, failedWith: error) - } - } - - // MARK: InputStream - - /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `stream`. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter stream: The stream to upload. - /// - parameter url: The URL. - /// - parameter method: The HTTP method. `.post` by default. - /// - parameter headers: The HTTP headers. `nil` by default. - /// - /// - returns: The created `UploadRequest`. - @discardableResult - open func upload( - _ stream: InputStream, - to url: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil) - -> UploadRequest - { - do { - let urlRequest = try URLRequest(url: url, method: method, headers: headers) - return upload(stream, with: urlRequest) - } catch { - return upload(nil, failedWith: error) - } - } - - /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `stream`. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter stream: The stream to upload. - /// - parameter urlRequest: The URL request. - /// - /// - returns: The created `UploadRequest`. - @discardableResult - open func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { - do { - let urlRequest = try urlRequest.asURLRequest() - return upload(.stream(stream, urlRequest)) - } catch { - return upload(nil, failedWith: error) - } - } - - // MARK: MultipartFormData - - /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new - /// `UploadRequest` using the `url`, `method` and `headers`. - /// - /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative - /// 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. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. - /// `multipartFormDataEncodingMemoryThreshold` by default. - /// - parameter url: The URL. - /// - parameter method: The HTTP method. `.post` by default. - /// - parameter headers: The HTTP headers. `nil` by default. - /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. - open func upload( - multipartFormData: @escaping (MultipartFormData) -> Void, - usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, - to url: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil, - queue: DispatchQueue? = nil, - encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) - { - do { - let urlRequest = try URLRequest(url: url, method: method, headers: headers) - - return upload( - multipartFormData: multipartFormData, - usingThreshold: encodingMemoryThreshold, - with: urlRequest, - queue: queue, - encodingCompletion: encodingCompletion - ) - } catch { - (queue ?? DispatchQueue.main).async { encodingCompletion?(.failure(error)) } - } - } - - /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new - /// `UploadRequest` using the `urlRequest`. - /// - /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative - /// 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. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. - /// `multipartFormDataEncodingMemoryThreshold` by default. - /// - parameter urlRequest: The URL request. - /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. - open func upload( - multipartFormData: @escaping (MultipartFormData) -> Void, - usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, - with urlRequest: URLRequestConvertible, - queue: DispatchQueue? = nil, - encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) - { - DispatchQueue.global(qos: .utility).async { - let formData = MultipartFormData() - multipartFormData(formData) - - var tempFileURL: URL? - - do { - var urlRequestWithContentType = try urlRequest.asURLRequest() - urlRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type") - - let isBackgroundSession = self.session.configuration.identifier != nil - - if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession { - let data = try formData.encode() - - let encodingResult = MultipartFormDataEncodingResult.success( - request: self.upload(data, with: urlRequestWithContentType), - streamingFromDisk: false, - streamFileURL: nil - ) - - (queue ?? DispatchQueue.main).async { encodingCompletion?(encodingResult) } - } else { - let fileManager = FileManager.default - let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory()) - let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data") - let fileName = UUID().uuidString - let fileURL = directoryURL.appendingPathComponent(fileName) - - tempFileURL = fileURL - - var directoryError: Error? - - // Create directory inside serial queue to ensure two threads don't do this in parallel - self.queue.sync { - do { - try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) - } catch { - directoryError = error - } - } - - if let directoryError = directoryError { throw directoryError } - - try formData.writeEncodedData(to: fileURL) - - let upload = self.upload(fileURL, with: urlRequestWithContentType) - - // Cleanup the temp file once the upload is complete - upload.delegate.queue.addOperation { - do { - try FileManager.default.removeItem(at: fileURL) - } catch { - // No-op - } - } - - (queue ?? DispatchQueue.main).async { - let encodingResult = MultipartFormDataEncodingResult.success( - request: upload, - streamingFromDisk: true, - streamFileURL: fileURL - ) - - encodingCompletion?(encodingResult) - } - } - } catch { - // Cleanup the temp file in the event that the multipart form data encoding failed - if let tempFileURL = tempFileURL { - do { - try FileManager.default.removeItem(at: tempFileURL) - } catch { - // No-op - } - } - - (queue ?? DispatchQueue.main).async { encodingCompletion?(.failure(error)) } - } - } - } - - // MARK: Private - Upload Implementation - - private func upload(_ uploadable: UploadRequest.Uploadable) -> UploadRequest { - do { - let task = try uploadable.task(session: session, adapter: adapter, queue: queue) - let upload = UploadRequest(session: session, requestTask: .upload(uploadable, task)) - - if case let .stream(inputStream, _) = uploadable { - upload.delegate.taskNeedNewBodyStream = { _, _ in inputStream } - } - - delegate[task] = upload - - if startRequestsImmediately { upload.resume() } - - return upload - } catch { - return upload(uploadable, failedWith: error) - } - } - - private func upload(_ uploadable: UploadRequest.Uploadable?, failedWith error: Error) -> UploadRequest { - var uploadTask: Request.RequestTask = .upload(nil, nil) - - if let uploadable = uploadable { - uploadTask = .upload(uploadable, nil) - } - - let underlyingError = error.underlyingAdaptError ?? error - let upload = UploadRequest(session: session, requestTask: uploadTask, error: underlyingError) - - if let retrier = retrier, error is AdaptError { - allowRetrier(retrier, toRetry: upload, with: underlyingError) - } else { - if startRequestsImmediately { upload.resume() } - } - - return upload - } - -#if !os(watchOS) - - // MARK: - Stream Request - - // MARK: Hostname and Port - - /// Creates a `StreamRequest` for bidirectional streaming using the `hostname` and `port`. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter hostName: The hostname of the server to connect to. - /// - parameter port: The port of the server to connect to. - /// - /// - returns: The created `StreamRequest`. - @discardableResult - @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) - open func stream(withHostName hostName: String, port: Int) -> StreamRequest { - return stream(.stream(hostName: hostName, port: port)) - } - - // MARK: NetService - - /// Creates a `StreamRequest` for bidirectional streaming using the `netService`. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter netService: The net service used to identify the endpoint. - /// - /// - returns: The created `StreamRequest`. - @discardableResult - @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) - open func stream(with netService: NetService) -> StreamRequest { - return stream(.netService(netService)) - } - - // MARK: Private - Stream Implementation - - @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) - private func stream(_ streamable: StreamRequest.Streamable) -> StreamRequest { - do { - let task = try streamable.task(session: session, adapter: adapter, queue: queue) - let request = StreamRequest(session: session, requestTask: .stream(streamable, task)) - - delegate[task] = request - - if startRequestsImmediately { request.resume() } - - return request - } catch { - return stream(failedWith: error) - } - } - - @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) - private func stream(failedWith error: Error) -> StreamRequest { - let stream = StreamRequest(session: session, requestTask: .stream(nil, nil), error: error) - if startRequestsImmediately { stream.resume() } - return stream - } - -#endif - - // MARK: - Internal - Retry Request - - func retry(_ request: Request) -> Bool { - guard let originalTask = request.originalTask else { return false } - - do { - let task = try originalTask.task(session: session, adapter: adapter, queue: queue) - - if let originalTask = request.task { - delegate[originalTask] = nil // removes the old request to avoid endless growth - } - - request.delegate.task = task // resets all task delegate data - - request.retryCount += 1 - request.startTime = CFAbsoluteTimeGetCurrent() - request.endTime = nil - - task.resume() - - return true - } catch { - request.delegate.error = error.underlyingAdaptError ?? error - return false - } - } - - private func allowRetrier(_ retrier: RequestRetrier, toRetry request: Request, with error: Error) { - DispatchQueue.utility.async { [weak self] in - guard let strongSelf = self else { return } - - retrier.should(strongSelf, retry: request, with: error) { shouldRetry, timeDelay in - guard let strongSelf = self else { return } - - guard shouldRetry else { - if strongSelf.startRequestsImmediately { request.resume() } - return - } - - DispatchQueue.utility.after(timeDelay) { - guard let strongSelf = self else { return } - - let retrySucceeded = strongSelf.retry(request) - - if retrySucceeded, let task = request.task { - strongSelf.delegate[task] = request - } else { - if strongSelf.startRequestsImmediately { request.resume() } - } - } - } - } - } -} diff --git a/Example/Pods/Alamofire/Source/TaskDelegate.swift b/Example/Pods/Alamofire/Source/TaskDelegate.swift deleted file mode 100644 index 5705737..0000000 --- a/Example/Pods/Alamofire/Source/TaskDelegate.swift +++ /dev/null @@ -1,466 +0,0 @@ -// -// TaskDelegate.swift -// -// Copyright (c) 2014 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 - -/// The task delegate is responsible for handling all delegate callbacks for the underlying task as well as -/// executing all operations attached to the serial operation queue upon task completion. -open class TaskDelegate: NSObject { - - // MARK: Properties - - /// The serial operation queue used to execute all operations after the task completes. - public let queue: OperationQueue - - /// The data returned by the server. - public var data: Data? { return nil } - - /// The error generated throughout the lifecyle of the task. - public var error: Error? - - var task: URLSessionTask? { - set { - taskLock.lock(); defer { taskLock.unlock() } - _task = newValue - } - get { - taskLock.lock(); defer { taskLock.unlock() } - return _task - } - } - - var initialResponseTime: CFAbsoluteTime? - var credential: URLCredential? - var metrics: AnyObject? // URLSessionTaskMetrics - - private var _task: URLSessionTask? { - didSet { reset() } - } - - private let taskLock = NSLock() - - // MARK: Lifecycle - - init(task: URLSessionTask?) { - _task = task - - self.queue = { - let operationQueue = OperationQueue() - - operationQueue.maxConcurrentOperationCount = 1 - operationQueue.isSuspended = true - operationQueue.qualityOfService = .utility - - return operationQueue - }() - } - - func reset() { - error = nil - initialResponseTime = nil - } - - // MARK: URLSessionTaskDelegate - - var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? - var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? - var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? - var taskDidCompleteWithError: ((URLSession, URLSessionTask, Error?) -> Void)? - - @objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:) - func urlSession( - _ session: URLSession, - task: URLSessionTask, - willPerformHTTPRedirection response: HTTPURLResponse, - newRequest request: URLRequest, - completionHandler: @escaping (URLRequest?) -> Void) - { - var redirectRequest: URLRequest? = request - - if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { - redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) - } - - completionHandler(redirectRequest) - } - - @objc(URLSession:task:didReceiveChallenge:completionHandler:) - func urlSession( - _ session: URLSession, - task: URLSessionTask, - didReceive challenge: URLAuthenticationChallenge, - completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) - { - var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling - var credential: URLCredential? - - if let taskDidReceiveChallenge = taskDidReceiveChallenge { - (disposition, credential) = taskDidReceiveChallenge(session, task, challenge) - } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { - let host = challenge.protectionSpace.host - - if - let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host), - let serverTrust = challenge.protectionSpace.serverTrust - { - if serverTrustPolicy.evaluate(serverTrust, forHost: host) { - disposition = .useCredential - credential = URLCredential(trust: serverTrust) - } else { - disposition = .cancelAuthenticationChallenge - } - } - } else { - if challenge.previousFailureCount > 0 { - disposition = .rejectProtectionSpace - } else { - credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace) - - if credential != nil { - disposition = .useCredential - } - } - } - - completionHandler(disposition, credential) - } - - @objc(URLSession:task:needNewBodyStream:) - func urlSession( - _ session: URLSession, - task: URLSessionTask, - needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) - { - var bodyStream: InputStream? - - if let taskNeedNewBodyStream = taskNeedNewBodyStream { - bodyStream = taskNeedNewBodyStream(session, task) - } - - completionHandler(bodyStream) - } - - @objc(URLSession:task:didCompleteWithError:) - func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { - if let taskDidCompleteWithError = taskDidCompleteWithError { - taskDidCompleteWithError(session, task, error) - } else { - if let error = error { - if self.error == nil { self.error = error } - - if - let downloadDelegate = self as? DownloadTaskDelegate, - let resumeData = (error as NSError).userInfo[NSURLSessionDownloadTaskResumeData] as? Data - { - downloadDelegate.resumeData = resumeData - } - } - - queue.isSuspended = false - } - } -} - -// MARK: - - -class DataTaskDelegate: TaskDelegate, URLSessionDataDelegate { - - // MARK: Properties - - var dataTask: URLSessionDataTask { return task as! URLSessionDataTask } - - override var data: Data? { - if dataStream != nil { - return nil - } else { - return mutableData - } - } - - var progress: Progress - var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? - - var dataStream: ((_ data: Data) -> Void)? - - private var totalBytesReceived: Int64 = 0 - private var mutableData: Data - - private var expectedContentLength: Int64? - - // MARK: Lifecycle - - override init(task: URLSessionTask?) { - mutableData = Data() - progress = Progress(totalUnitCount: 0) - - super.init(task: task) - } - - override func reset() { - super.reset() - - progress = Progress(totalUnitCount: 0) - totalBytesReceived = 0 - mutableData = Data() - expectedContentLength = nil - } - - // MARK: URLSessionDataDelegate - - var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? - var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? - var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? - var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? - - func urlSession( - _ session: URLSession, - dataTask: URLSessionDataTask, - didReceive response: URLResponse, - completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) - { - var disposition: URLSession.ResponseDisposition = .allow - - expectedContentLength = response.expectedContentLength - - if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { - disposition = dataTaskDidReceiveResponse(session, dataTask, response) - } - - completionHandler(disposition) - } - - func urlSession( - _ session: URLSession, - dataTask: URLSessionDataTask, - didBecome downloadTask: URLSessionDownloadTask) - { - dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask) - } - - func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { - if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } - - if let dataTaskDidReceiveData = dataTaskDidReceiveData { - dataTaskDidReceiveData(session, dataTask, data) - } else { - if let dataStream = dataStream { - dataStream(data) - } else { - mutableData.append(data) - } - - let bytesReceived = Int64(data.count) - totalBytesReceived += bytesReceived - let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown - - progress.totalUnitCount = totalBytesExpected - progress.completedUnitCount = totalBytesReceived - - if let progressHandler = progressHandler { - progressHandler.queue.async { progressHandler.closure(self.progress) } - } - } - } - - func urlSession( - _ session: URLSession, - dataTask: URLSessionDataTask, - willCacheResponse proposedResponse: CachedURLResponse, - completionHandler: @escaping (CachedURLResponse?) -> Void) - { - var cachedResponse: CachedURLResponse? = proposedResponse - - if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { - cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse) - } - - completionHandler(cachedResponse) - } -} - -// MARK: - - -class DownloadTaskDelegate: TaskDelegate, URLSessionDownloadDelegate { - - // MARK: Properties - - var downloadTask: URLSessionDownloadTask { return task as! URLSessionDownloadTask } - - var progress: Progress - var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? - - var resumeData: Data? - override var data: Data? { return resumeData } - - var destination: DownloadRequest.DownloadFileDestination? - - var temporaryURL: URL? - var destinationURL: URL? - - var fileURL: URL? { return destination != nil ? destinationURL : temporaryURL } - - // MARK: Lifecycle - - override init(task: URLSessionTask?) { - progress = Progress(totalUnitCount: 0) - super.init(task: task) - } - - override func reset() { - super.reset() - - progress = Progress(totalUnitCount: 0) - resumeData = nil - } - - // MARK: URLSessionDownloadDelegate - - var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> URL)? - var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? - var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? - - func urlSession( - _ session: URLSession, - downloadTask: URLSessionDownloadTask, - didFinishDownloadingTo location: URL) - { - temporaryURL = location - - guard - let destination = destination, - let response = downloadTask.response as? HTTPURLResponse - else { return } - - let result = destination(location, response) - let destinationURL = result.destinationURL - let options = result.options - - self.destinationURL = destinationURL - - do { - if options.contains(.removePreviousFile), FileManager.default.fileExists(atPath: destinationURL.path) { - try FileManager.default.removeItem(at: destinationURL) - } - - if options.contains(.createIntermediateDirectories) { - let directory = destinationURL.deletingLastPathComponent() - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) - } - - try FileManager.default.moveItem(at: location, to: destinationURL) - } catch { - self.error = error - } - } - - func urlSession( - _ session: URLSession, - downloadTask: URLSessionDownloadTask, - didWriteData bytesWritten: Int64, - totalBytesWritten: Int64, - totalBytesExpectedToWrite: Int64) - { - if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } - - if let downloadTaskDidWriteData = downloadTaskDidWriteData { - downloadTaskDidWriteData( - session, - downloadTask, - bytesWritten, - totalBytesWritten, - totalBytesExpectedToWrite - ) - } else { - progress.totalUnitCount = totalBytesExpectedToWrite - progress.completedUnitCount = totalBytesWritten - - if let progressHandler = progressHandler { - progressHandler.queue.async { progressHandler.closure(self.progress) } - } - } - } - - func urlSession( - _ session: URLSession, - downloadTask: URLSessionDownloadTask, - didResumeAtOffset fileOffset: Int64, - expectedTotalBytes: Int64) - { - if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { - downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) - } else { - progress.totalUnitCount = expectedTotalBytes - progress.completedUnitCount = fileOffset - } - } -} - -// MARK: - - -class UploadTaskDelegate: DataTaskDelegate { - - // MARK: Properties - - var uploadTask: URLSessionUploadTask { return task as! URLSessionUploadTask } - - var uploadProgress: Progress - var uploadProgressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? - - // MARK: Lifecycle - - override init(task: URLSessionTask?) { - uploadProgress = Progress(totalUnitCount: 0) - super.init(task: task) - } - - override func reset() { - super.reset() - uploadProgress = Progress(totalUnitCount: 0) - } - - // MARK: URLSessionTaskDelegate - - var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? - - func URLSession( - _ session: URLSession, - task: URLSessionTask, - didSendBodyData bytesSent: Int64, - totalBytesSent: Int64, - totalBytesExpectedToSend: Int64) - { - if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } - - if let taskDidSendBodyData = taskDidSendBodyData { - taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) - } else { - uploadProgress.totalUnitCount = totalBytesExpectedToSend - uploadProgress.completedUnitCount = totalBytesSent - - if let uploadProgressHandler = uploadProgressHandler { - uploadProgressHandler.queue.async { uploadProgressHandler.closure(self.uploadProgress) } - } - } - } -} diff --git a/Example/Pods/Alamofire/Source/Timeline.swift b/Example/Pods/Alamofire/Source/Timeline.swift deleted file mode 100644 index 596c1bd..0000000 --- a/Example/Pods/Alamofire/Source/Timeline.swift +++ /dev/null @@ -1,136 +0,0 @@ -// -// Timeline.swift -// -// Copyright (c) 2014 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 computing the timing metrics for the complete lifecycle of a `Request`. -public struct Timeline { - /// The time the request was initialized. - public let requestStartTime: CFAbsoluteTime - - /// The time the first bytes were received from or sent to the server. - public let initialResponseTime: CFAbsoluteTime - - /// The time when the request was completed. - public let requestCompletedTime: CFAbsoluteTime - - /// The time when the response serialization was completed. - public let serializationCompletedTime: CFAbsoluteTime - - /// The time interval in seconds from the time the request started to the initial response from the server. - public let latency: TimeInterval - - /// The time interval in seconds from the time the request started to the time the request completed. - public let requestDuration: TimeInterval - - /// The time interval in seconds from the time the request completed to the time response serialization completed. - public let serializationDuration: TimeInterval - - /// The time interval in seconds from the time the request started to the time response serialization completed. - public let totalDuration: TimeInterval - - /// Creates a new `Timeline` instance with the specified request times. - /// - /// - parameter requestStartTime: The time the request was initialized. Defaults to `0.0`. - /// - parameter initialResponseTime: The time the first bytes were received from or sent to the server. - /// Defaults to `0.0`. - /// - parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`. - /// - parameter serializationCompletedTime: The time when the response serialization was completed. Defaults - /// to `0.0`. - /// - /// - returns: The new `Timeline` instance. - public init( - requestStartTime: CFAbsoluteTime = 0.0, - initialResponseTime: CFAbsoluteTime = 0.0, - requestCompletedTime: CFAbsoluteTime = 0.0, - serializationCompletedTime: CFAbsoluteTime = 0.0) - { - self.requestStartTime = requestStartTime - self.initialResponseTime = initialResponseTime - self.requestCompletedTime = requestCompletedTime - self.serializationCompletedTime = serializationCompletedTime - - self.latency = initialResponseTime - requestStartTime - self.requestDuration = requestCompletedTime - requestStartTime - self.serializationDuration = serializationCompletedTime - requestCompletedTime - self.totalDuration = serializationCompletedTime - requestStartTime - } -} - -// MARK: - CustomStringConvertible - -extension Timeline: CustomStringConvertible { - /// The textual representation used when written to an output stream, which includes the latency, the request - /// duration and the total duration. - public var description: String { - let latency = String(format: "%.3f", self.latency) - let requestDuration = String(format: "%.3f", self.requestDuration) - let serializationDuration = String(format: "%.3f", self.serializationDuration) - let totalDuration = String(format: "%.3f", self.totalDuration) - - // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is - // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. - let timings = [ - "\"Latency\": " + latency + " secs", - "\"Request Duration\": " + requestDuration + " secs", - "\"Serialization Duration\": " + serializationDuration + " secs", - "\"Total Duration\": " + totalDuration + " secs" - ] - - return "Timeline: { " + timings.joined(separator: ", ") + " }" - } -} - -// MARK: - CustomDebugStringConvertible - -extension Timeline: CustomDebugStringConvertible { - /// The textual representation used when written to an output stream, which includes the request start time, the - /// initial response time, the request completed time, the serialization completed time, the latency, the request - /// duration and the total duration. - public var debugDescription: String { - let requestStartTime = String(format: "%.3f", self.requestStartTime) - let initialResponseTime = String(format: "%.3f", self.initialResponseTime) - let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime) - let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime) - let latency = String(format: "%.3f", self.latency) - let requestDuration = String(format: "%.3f", self.requestDuration) - let serializationDuration = String(format: "%.3f", self.serializationDuration) - let totalDuration = String(format: "%.3f", self.totalDuration) - - // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is - // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. - let timings = [ - "\"Request Start Time\": " + requestStartTime, - "\"Initial Response Time\": " + initialResponseTime, - "\"Request Completed Time\": " + requestCompletedTime, - "\"Serialization Completed Time\": " + serializationCompletedTime, - "\"Latency\": " + latency + " secs", - "\"Request Duration\": " + requestDuration + " secs", - "\"Serialization Duration\": " + serializationDuration + " secs", - "\"Total Duration\": " + totalDuration + " secs" - ] - - return "Timeline: { " + timings.joined(separator: ", ") + " }" - } -} diff --git a/Example/Pods/Alamofire/Source/URLConvertible+URLRequestConvertible.swift b/Example/Pods/Alamofire/Source/URLConvertible+URLRequestConvertible.swift new file mode 100644 index 0000000..9ac00ef --- /dev/null +++ b/Example/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 { return 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? { return try? asURLRequest() } +} + +extension URLRequest: URLRequestConvertible { + /// Returns `self`. + public func asURLRequest() throws -> URLRequest { return 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 + } +} diff --git a/Example/Pods/Alamofire/Source/URLEncodedFormEncoder.swift b/Example/Pods/Alamofire/Source/URLEncodedFormEncoder.swift new file mode 100644 index 0000000..8da3576 --- /dev/null +++ b/Example/Pods/Alamofire/Source/URLEncodedFormEncoder.swift @@ -0,0 +1,973 @@ +// +// 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 + + /// Encodes the key according to the encoding. + /// + /// - Parameter key: The `key` to encode. + /// - Returns: The encoded key. + func encode(_ key: String) -> String { + switch self { + case .brackets: return "\(key)[]" + case .noBrackets: return key + } + } + } + + /// 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 { + return convert(key, usingSeparator: "_") + } + + private func convertToKebabCase(_ key: String) -> String { + return convert(key, usingSeparator: "-") + } + + private func convert(_ key: String, usingSeparator separator: String) -> String { + guard !key.isEmpty else { return key } + + var words: [Range] = [] + // 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)..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.. 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] { return [:] } + + 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(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key: CodingKey { + let container = _URLEncodedFormEncoder.KeyedContainer(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding) + return KeyedEncodingContainer(container) + } + + func unkeyedContainer() -> UnkeyedEncodingContainer { + return _URLEncodedFormEncoder.UnkeyedContainer(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding) + } + + func singleValueContainer() -> SingleValueEncodingContainer { + return _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.count >= 1 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(_ 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 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] { + return 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(_ 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(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer where NestedKey: CodingKey { + let container = _URLEncodedFormEncoder.KeyedContainer(context: context, + codingPath: nestedCodingPath(for: key), + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding) + + return KeyedEncodingContainer(container) + } + + func superEncoder() -> Encoder { + return _URLEncodedFormEncoder(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding) + } + + func superEncoder(forKey key: Key) -> Encoder { + return _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(_ 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(_ 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) + default: + try attemptToEncode(value) + } + } + + private func attemptToEncode(_ 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] { + return 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(_ 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(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer where NestedKey: CodingKey { + defer { count += 1 } + let container = _URLEncodedFormEncoder.KeyedContainer(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.map { component in + let keyPath = arrayEncoding.encode(key) + 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 { + return joined(separator: "&") + } +} + +public 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. + 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) + }() +} diff --git a/Example/Pods/Alamofire/Source/URLRequest+Alamofire.swift b/Example/Pods/Alamofire/Source/URLRequest+Alamofire.swift new file mode 100644 index 0000000..b198fe0 --- /dev/null +++ b/Example/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 + +public extension URLRequest { + /// Returns the `httpMethod` as Alamofire's `HTTPMethod` type. + var method: HTTPMethod? { + get { return httpMethod.flatMap(HTTPMethod.init) } + set { httpMethod = newValue?.rawValue } + } + + func validate() throws { + if method == .get, let bodyData = httpBody { + throw AFError.urlRequestValidationFailed(reason: .bodyDataInGETRequest(bodyData)) + } + } +} diff --git a/Example/Pods/Alamofire/Source/URLSessionConfiguration+Alamofire.swift b/Example/Pods/Alamofire/Source/URLSessionConfiguration+Alamofire.swift new file mode 100644 index 0000000..de3e290 --- /dev/null +++ b/Example/Pods/Alamofire/Source/URLSessionConfiguration+Alamofire.swift @@ -0,0 +1,37 @@ +// +// 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 + } +} diff --git a/Example/Pods/Alamofire/Source/Validation.swift b/Example/Pods/Alamofire/Source/Validation.swift index 59e0bbb..d0def32 100644 --- a/Example/Pods/Alamofire/Source/Validation.swift +++ b/Example/Pods/Alamofire/Source/Validation.swift @@ -1,7 +1,7 @@ // // Validation.swift // -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) +// 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 @@ -25,19 +25,12 @@ import Foundation extension Request { - // MARK: Helper Types fileprivate typealias ErrorReason = AFError.ResponseValidationFailureReason - /// Used to represent whether validation was successful or encountered an error resulting in a failure. - /// - /// - success: The validation was successful. - /// - failure: The validation failed encountering the provided error. - public enum ValidationResult { - case success - case failure(Error) - } + /// Used to represent whether a validation succeeded or failed. + public typealias ValidationResult = Result fileprivate struct MIMEType { let type: String @@ -48,12 +41,7 @@ extension Request { init?(_ string: String) { let components: [String] = { let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines) - - #if swift(>=3.2) let split = stripped[..<(stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)] - #else - let split = stripped.substring(to: stripped.range(of: ";")?.lowerBound ?? stripped.endIndex) - #endif return split.components(separatedBy: "/") }() @@ -78,7 +66,7 @@ extension Request { // MARK: Properties - fileprivate var acceptableStatusCodes: [Int] { return Array(200..<300) } + fileprivate var acceptableStatusCodes: Range { return 200..<300 } fileprivate var acceptableContentTypes: [String] { if let accept = request?.value(forHTTPHeaderField: "Accept") { @@ -90,14 +78,12 @@ extension Request { // MARK: Status Code - fileprivate func validate( - statusCode acceptableStatusCodes: S, - response: HTTPURLResponse) + fileprivate func validate(statusCode acceptableStatusCodes: S, + response: HTTPURLResponse) -> ValidationResult - where S.Iterator.Element == Int - { + where S.Iterator.Element == Int { if acceptableStatusCodes.contains(response.statusCode) { - return .success + return .success(Void()) } else { let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode) return .failure(AFError.responseValidationFailed(reason: reason)) @@ -106,14 +92,12 @@ extension Request { // MARK: Content Type - fileprivate func validate( - contentType acceptableContentTypes: S, - response: HTTPURLResponse, - data: Data?) + fileprivate func validate(contentType acceptableContentTypes: S, + response: HTTPURLResponse, + data: Data?) -> ValidationResult - where S.Iterator.Element == String - { - guard let data = data, data.count > 0 else { return .success } + where S.Iterator.Element == String { + guard let data = data, !data.isEmpty else { return .success(Void()) } guard let responseContentType = response.mimeType, @@ -121,7 +105,7 @@ extension Request { else { for contentType in acceptableContentTypes { if let mimeType = MIMEType(contentType), mimeType.isWildcard { - return .success + return .success(Void()) } } @@ -135,15 +119,13 @@ extension Request { for contentType in acceptableContentTypes { if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) { - return .success + return .success(Void()) } } let error: AFError = { - let reason: ErrorReason = .unacceptableContentType( - acceptableContentTypes: Array(acceptableContentTypes), - responseContentType: responseContentType - ) + let reason: ErrorReason = .unacceptableContentType(acceptableContentTypes: Array(acceptableContentTypes), + responseContentType: responseContentType) return AFError.responseValidationFailed(reason: reason) }() @@ -159,30 +141,6 @@ extension DataRequest { /// request was valid. public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult - /// Validates the request, using the specified closure. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - parameter validation: A closure to validate the request. - /// - /// - returns: The request. - @discardableResult - public func validate(_ validation: @escaping Validation) -> Self { - let validationExecution: () -> Void = { [unowned self] in - if - let response = self.response, - self.delegate.error == nil, - case let .failure(error) = validation(self.request, response, self.delegate.data) - { - self.delegate.error = error - } - } - - validations.append(validationExecution) - - return self - } - /// 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. @@ -193,7 +151,7 @@ extension DataRequest { @discardableResult public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { return validate { [unowned self] _, response, _ in - return self.validate(statusCode: acceptableStatusCodes, response: response) + self.validate(statusCode: acceptableStatusCodes, response: response) } } @@ -205,9 +163,9 @@ extension DataRequest { /// /// - returns: The request. @discardableResult - public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { + public func validate(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String { return validate { [unowned self] _, response, data in - return self.validate(contentType: acceptableContentTypes, response: response, data: data) + self.validate(contentType: acceptableContentTypes(), response: response, data: data) } } @@ -219,7 +177,7 @@ extension DataRequest { /// - returns: The request. @discardableResult public func validate() -> Self { - let contentTypes = { [unowned self] in + let contentTypes: () -> [String] = { [unowned self] in self.acceptableContentTypes } return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) @@ -231,41 +189,11 @@ extension DataRequest { 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, - _ temporaryURL: URL?, - _ destinationURL: URL?) + public typealias Validation = (_ request: URLRequest?, + _ response: HTTPURLResponse, + _ fileURL: URL?) -> ValidationResult - /// Validates the request, using the specified closure. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - parameter validation: A closure to validate the request. - /// - /// - returns: The request. - @discardableResult - public func validate(_ validation: @escaping Validation) -> Self { - let validationExecution: () -> Void = { [unowned self] in - let request = self.request - let temporaryURL = self.downloadDelegate.temporaryURL - let destinationURL = self.downloadDelegate.destinationURL - - if - let response = self.response, - self.delegate.error == nil, - case let .failure(error) = validation(request, response, temporaryURL, destinationURL) - { - self.delegate.error = error - } - } - - validations.append(validationExecution) - - return self - } - /// 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. @@ -275,8 +203,8 @@ extension DownloadRequest { /// - returns: The request. @discardableResult public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { - return validate { [unowned self] _, response, _, _ in - return self.validate(statusCode: acceptableStatusCodes, response: response) + return validate { [unowned self] _, response, _ in + self.validate(statusCode: acceptableStatusCodes, response: response) } } @@ -288,17 +216,15 @@ extension DownloadRequest { /// /// - returns: The request. @discardableResult - public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { - return validate { [unowned self] _, response, _, _ in - let fileURL = self.downloadDelegate.fileURL - + public func validate(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String { + return 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) + return self.validate(contentType: acceptableContentTypes(), response: response, data: data) } catch { return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL))) } diff --git a/Example/Pods/Local Podspecs/ErrorHandler.podspec.json b/Example/Pods/Local Podspecs/ErrorHandler.podspec.json index 9d5649e..d83a192 100644 --- a/Example/Pods/Local Podspecs/ErrorHandler.podspec.json +++ b/Example/Pods/Local Podspecs/ErrorHandler.podspec.json @@ -1,6 +1,10 @@ { "name": "ErrorHandler", "version": "0.8.2", + "swift_versions": [ + "4.2", + "5.0" + ], "summary": "Elegant and flexible error handling for Swift", "description": "> Elegant and flexible error handling for Swift\n\nErrorHandler enables expressing complex error handling logic with a few lines of code using a memorable fluent API.", "homepage": "https://github.com/Workable/swift-error-handler", @@ -13,10 +17,10 @@ "Eleni Papanikolopoulou": "eleni.papanikolopoulou@gmail.com" }, "platforms": { - "ios": "8.0", - "osx": "10.10", - "watchos": "2.0", - "tvos": "9.0" + "ios": "10.0", + "osx": "10.12", + "tvos": "10.0", + "watchos": "3.0" }, "source": { "git": "https://github.com/Workable/swift-error-handler.git", @@ -34,12 +38,13 @@ "source_files": "ErrorHandler/Classes/Alamofire/**/*", "dependencies": { "Alamofire": [ - "~> 4.1" + "~> 5" ], "ErrorHandler/Core": [ ] } } - ] + ], + "swift_version": "5.0" } diff --git a/Example/Pods/Manifest.lock b/Example/Pods/Manifest.lock index d7625f7..f14bab8 100644 --- a/Example/Pods/Manifest.lock +++ b/Example/Pods/Manifest.lock @@ -1,9 +1,9 @@ PODS: - - Alamofire (4.9.1) + - Alamofire (5.0.2) - ErrorHandler (0.8.2): - ErrorHandler/Core (= 0.8.2) - ErrorHandler/Alamofire (0.8.2): - - Alamofire (~> 4.1) + - Alamofire (~> 5) - ErrorHandler/Core - ErrorHandler/Core (0.8.2) @@ -20,9 +20,9 @@ EXTERNAL SOURCES: :path: "../" SPEC CHECKSUMS: - Alamofire: 85e8a02c69d6020a0d734f6054870d7ecb75cf18 - ErrorHandler: 5184ce9905c80d20810cc1abcf2ebc3ea3d56021 + Alamofire: 3ba7a4db18b4f62c4a1c0e1cb39d7f3d52e10ada + ErrorHandler: 5b44764fe86ed8771f7b5e79599bd4d5fd753a4f -PODFILE CHECKSUM: 8e328fdbad084717f3c5a8e2ce8f3f3671d29c67 +PODFILE CHECKSUM: 1ecd38147b811789385bbac850686caa2f83077b -COCOAPODS: 1.8.3 +COCOAPODS: 1.8.4 diff --git a/Example/Pods/Pods.xcodeproj/project.pbxproj b/Example/Pods/Pods.xcodeproj/project.pbxproj index fe1429b..cf971c7 100644 --- a/Example/Pods/Pods.xcodeproj/project.pbxproj +++ b/Example/Pods/Pods.xcodeproj/project.pbxproj @@ -7,40 +7,56 @@ objects = { /* Begin PBXBuildFile section */ - 0C5E11DE24DAA737704B355F5F2F3426 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0D01BA8472F25D39F718F71557EDC8DD /* ParameterEncoding.swift */; }; - 132E0F619E4338E5D1B27E4C72076B3F /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = B06639F7A76DB8A9D0D0E41CDD7A6684 /* Notifications.swift */; }; + 00FA97D56201027AEB1C7692A2C3CF8B /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 8983361440DA703D7E1F9901F2657715 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0419772A87B16DB7DCF405A9E77D671F /* Protector.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1982A99EC0068FB848DB3B942CB83DB5 /* Protector.swift */; }; + 06507A26118BA5ACFBBC8C225776920E /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = D349810CA61917A72856F3114DE4DA68 /* Validation.swift */; }; + 0AE06C3AEA6CA45342BA703230ABD2CB /* CachedResponseHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33BB7D85C23DEE0174BE6AFD50EE6E41 /* CachedResponseHandler.swift */; }; + 0CC43FF0E31AA320ACFEB0FE6239DF34 /* ServerTrustEvaluation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7059C4CC67DC9BED886103B6F8540E89 /* ServerTrustEvaluation.swift */; }; + 13457FE4E607509A3B9527B0711033D5 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79356BB38DCE3AF0EE679B37B4436ED0 /* ResponseSerialization.swift */; }; 1452121F52C4B00BA9B1F25A13BBC6E9 /* NSErrorMatcher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75D1C9F69FE1A899D601FD64ABECF6BD /* NSErrorMatcher.swift */; }; - 1945CD5D63A1C164AEAAA9A33E85571E /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 341BDAD0026CDA8E7BCE35AC122E1C8C /* Alamofire-dummy.m */; }; - 1986B50C74F1697EA43F68335C93CEB3 /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = BFCE3D7EDCA41F256D471B40BBFD3FCE /* MultipartFormData.swift */; }; + 14AB7976E100075ADEA0AB1DB833E72D /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8842C3D78AC0E234008C8E176A413664 /* ParameterEncoding.swift */; }; + 17953A9CF2E354B3E69B9ABC2F367AD9 /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = B0B912D70323E7F86DCD780B2231C472 /* AFError.swift */; }; 1BDA1A76B43E152B1E91D24779E5E2EC /* Pods-ErrorHandler_Example-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = D4942566DB46CA1043F9870EFFA14EF1 /* Pods-ErrorHandler_Example-dummy.m */; }; - 2C61B040BA6A9A7AE66C4D9BA26D5520 /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = F640F61D5BEE8132009BAEAA65B587A4 /* SessionDelegate.swift */; }; - 3571F958A3907B3A806E62D50C2550D4 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5460AD0F6241621B45A17AB23A8E5B7 /* NetworkReachabilityManager.swift */; }; 366770F02F111A01BD07DFA937BA0420 /* AFErrorStatusCodeMatcher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 21384DBED434E3C4A6705484B9361921 /* AFErrorStatusCodeMatcher.swift */; }; 3984E35DA9D88FCBE6C223003A306AE2 /* ErrorHandler-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 24AB3F5394D085ED5897811C12783187 /* ErrorHandler-dummy.m */; }; - 53791F5E5F07400F92CFDFC89A432305 /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33115EC2A5164913C68F8BD170389EEE /* Validation.swift */; }; + 4082513A35C682F2193D002C80F72B79 /* Result+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 47152D714F71E858000F62A8A616FCAF /* Result+Alamofire.swift */; }; + 42CDB5C986C78BBC8E5C0185F746CABF /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = FED8657059CCC1AA8B884882B6C21DF3 /* SessionDelegate.swift */; }; + 44127C4B989C9CC6A90D78B66A929A5E /* AlamofireExtended.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1A6BA50BC9798E96A96694316FD7F19 /* AlamofireExtended.swift */; }; + 48D97BE7D5CAED273BD2341C239CC934 /* RequestTaskMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 96C2ABABCF96583B0736B746A886AECB /* RequestTaskMap.swift */; }; 5506C8CEA85FD1357428DD35A480BEB9 /* Pods-ErrorHandler_Tests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 0819F9DA1393E1A568CD02B496252C0C /* Pods-ErrorHandler_Tests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 643F961F1DC813AA34FBE6977183056A /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 69DAB41DE6AF59D8362CBC670CDF0EEC /* Foundation.framework */; }; - 64744C911253C3E01461FAD7C935C8D7 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD807F155301ECA538A2C1C296E1186D /* Result.swift */; }; + 56EC8ED1535DAB987F3D2B71D4C05773 /* HTTPHeaders.swift in Sources */ = {isa = PBXBuildFile; fileRef = 252E34E06DE82E4A96FF19DDAAB47C48 /* HTTPHeaders.swift */; }; + 5C4A0685B5A201436AB52EF25829B333 /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 60B0E4FA795EABD32357C1014201A8F9 /* MultipartFormData.swift */; }; + 5D12235D061AEE7459279AAF8C348DFE /* URLEncodedFormEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3472833109D10A6D1A67609593B695A /* URLEncodedFormEncoder.swift */; }; + 5D61C8ED0DDCC9F8B576B6514B19EE50 /* ParameterEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1F8926879B94ED50118A3EA9401E92DD /* ParameterEncoder.swift */; }; + 643F961F1DC813AA34FBE6977183056A /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3F401E181BEA002337E464DED414F440 /* Foundation.framework */; }; + 69ACE4EEE5A8C1C618B22CC1F7B8EF01 /* Session.swift in Sources */ = {isa = PBXBuildFile; fileRef = F832D5DCB54F4499206CA6D8DECB63DA /* Session.swift */; }; + 6A22C46CB1EDE471794D9AB2AC10327F /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = A6EF2A5FCF56EE72AA71A552A8D39A96 /* Request.swift */; }; + 70517C3BAC2D6614347DEAC15299EB84 /* URLConvertible+URLRequestConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = A93EE927BDAEF08BD7FED7F2C1D56707 /* URLConvertible+URLRequestConvertible.swift */; }; 707E3A5438CF654DCA6198028C2EEA15 /* Pods-ErrorHandler_Example-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = AAF2AB79FA266A1549C945925963F3A9 /* Pods-ErrorHandler_Example-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 7664FD4F59A0C00866CBAE60B0A3AD64 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 69DAB41DE6AF59D8362CBC670CDF0EEC /* Foundation.framework */; }; - 7A6B2405C104DBAC85F2D0F7E3797244 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 69DAB41DE6AF59D8362CBC670CDF0EEC /* Foundation.framework */; }; - 83956E20859CDBBE7BC38ABADE0170FB /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D5A0E300C04A6DF88D620788FE38780 /* AFError.swift */; }; - 85DB724E68E88029F67E2C0487A4C81B /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 69DAB41DE6AF59D8362CBC670CDF0EEC /* Foundation.framework */; }; - 931BBB8230A25161D5C37528A8F9FECF /* SessionManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D7E25E371731FAE44F46A9F392CB5D5 /* SessionManager.swift */; }; - 933FDA5970AA525D6CB92BFEBA2BAB4A /* Timeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = 32DB5272AD01ECD0B09A86818A7754C4 /* Timeline.swift */; }; - 98392A9F2FC1786E9863884D25E296A1 /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4B03B07DFA7C8BB60693AE1DE30731E2 /* Alamofire.framework */; }; - 98A929C8E9012AB167672714FFD2113C /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9D59E1AD3CC394A93392FF3DC8CF2961 /* Request.swift */; }; + 7A6B2405C104DBAC85F2D0F7E3797244 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3F401E181BEA002337E464DED414F440 /* Foundation.framework */; }; + 7CF8362BA31492053F5CB165637AE117 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = FC87D7C9C22946B653EC891AD65CA774 /* NetworkReachabilityManager.swift */; }; + 85DB724E68E88029F67E2C0487A4C81B /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3F401E181BEA002337E464DED414F440 /* Foundation.framework */; }; + 92811AC5CD9A5004116AE43C4E8FD955 /* OperationQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 906744E115B923BC81683FA8522951A8 /* OperationQueue+Alamofire.swift */; }; + 97A168DFB6DB61770CE2DBF4FD39AA8D /* CFNetwork.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 32BD7B93FEA70BDFD057550D07FA7961 /* CFNetwork.framework */; }; + 98392A9F2FC1786E9863884D25E296A1 /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D0FF301302A2A77E95697F2B5692FA5E /* Alamofire.framework */; }; 9C704A6D6F4D975941C98B60893D465C /* ErrorHandler-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 606BE8303EA7BEBCEEB352710830C84A /* ErrorHandler-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - AFC64B1097F7355FF423D6A73E9C7210 /* TaskDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75C759635F88377BD7E2DEDE04C23C62 /* TaskDelegate.swift */; }; + AD9899986955B2EC1EC20818C860C971 /* RequestInterceptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 955C7B41827018BB1B59E447A617F1A6 /* RequestInterceptor.swift */; }; + AF92602937CA016548022C600B8CDC16 /* URLSessionConfiguration+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2598222A405D08F1B87C0463420492F3 /* URLSessionConfiguration+Alamofire.swift */; }; + B1C58F6CED7B3E45170711D9ADF878AF /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = CA569E409E59A3A7C43E582FFFECC049 /* Alamofire-dummy.m */; }; + B23E9A5CDA31534491226F4C2EE8F8E6 /* HTTPMethod.swift in Sources */ = {isa = PBXBuildFile; fileRef = 774B0CF83AA71BBED2A70E4A0AE6D9CD /* HTTPMethod.swift */; }; + B788B3354CCEBE56DFDB963CAFD7F6C2 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C6818CB68941B73559573DB4F55FF2F /* Alamofire.swift */; }; BB2A13AB68F25C138862DFA625D1DC66 /* ErrorHandler+AFExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A182FD1146398A40411ACBF0BF48485 /* ErrorHandler+AFExtensions.swift */; }; - BEE6B677416CA71C981D1D3F60B18C96 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C15C076B531E2E7744C358418A0C0B5 /* Alamofire.swift */; }; - D3D8C379C6E4FB487E5ABD6800AD7B7E /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = AFF7F7716086D54E6308EE52C8227B87 /* DispatchQueue+Alamofire.swift */; }; - D65C254F5ABF2CB5ECEE50FE8F8E1A80 /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = CCC6858C85690F7AFEA7F6542EE9A69A /* Response.swift */; }; + BE82AE980F8C7EE28A6448959194F93A /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3F401E181BEA002337E464DED414F440 /* Foundation.framework */; }; + C64AF152F7928CDB59385528DB65FE19 /* RedirectHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = CDE821E7D82EDB49E8CCB3F4281CB873 /* RedirectHandler.swift */; }; + C7369563F6946D8984124E1A546B6425 /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = A437F36AAA97B99103FBD62EA2687E78 /* Notifications.swift */; }; + CACBD166E573774FB5613C34AA6DA7A7 /* EventMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 76C3EEA63BB9145123705DFCADC8EE27 /* EventMonitor.swift */; }; + D6B2983389480F48F27A0704EEB5DC81 /* RetryPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 96ED5BF61D38354434EEDC4FD6779584 /* RetryPolicy.swift */; }; DD8A41A1CCD8CF3FA496C9F1258B6182 /* Pods-ErrorHandler_Tests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 57F21E981916F5AADCE7E5ADCBB09243 /* Pods-ErrorHandler_Tests-dummy.m */; }; + E07BD425C4EA9ADF15DDFCDB10D0B2FB /* MultipartUpload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7BDE34987683B80FE97BBE5736A439B6 /* MultipartUpload.swift */; }; E12F5BCBD9948B00022ADC5C3F975A5E /* ErrorHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2948CB95C564872E4F2DBC4A36E71528 /* ErrorHandler.swift */; }; - E3747EC31FCCA97D75A81FC700CF7E24 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B03859BDC36782899379E222720A297 /* ResponseSerialization.swift */; }; - F13F2AA7F2E6D95A181CAB99B900D531 /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4453BE339B79900FDC53E34FE5589CB /* ServerTrustPolicy.swift */; }; - F7B74645E07C39771156A1FA413B98D4 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = D54AEF5647A987180EDAD7E1CEF7387B /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + E4E12208D5246E64B7E6CCAE987ADB03 /* URLRequest+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = D578A4BA4B36B12F7C081E8ED1215837 /* URLRequest+Alamofire.swift */; }; + E9A5AC2F471699CCA516952A5FEB990B /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 77E408574C32514C9D9055B5A00125B4 /* DispatchQueue+Alamofire.swift */; }; + F71789DC91A75033EFB79DB828676451 /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 325AADD7113A629C5C8D34CF07909EFD /* Response.swift */; }; FF68907DAF7C201181FF626958CFA361 /* Matchers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83E0C1BCD85D78BF7D8167A40CF9D19C /* Matchers.swift */; }; /* End PBXBuildFile section */ @@ -80,62 +96,78 @@ 0819F9DA1393E1A568CD02B496252C0C /* Pods-ErrorHandler_Tests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-ErrorHandler_Tests-umbrella.h"; sourceTree = ""; }; 08DAAAE6A10FC81DFABDA013A3570FBB /* Pods-ErrorHandler_Tests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-ErrorHandler_Tests.release.xcconfig"; sourceTree = ""; }; 0A95765082C23CD7BDAC48A2916C138B /* Pods-ErrorHandler_Example.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-ErrorHandler_Example.release.xcconfig"; sourceTree = ""; }; - 0D01BA8472F25D39F718F71557EDC8DD /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; 165B0310C0578682A0DDBA8E19C162C8 /* ErrorHandler.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = ErrorHandler.xcconfig; sourceTree = ""; }; + 1982A99EC0068FB848DB3B942CB83DB5 /* Protector.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Protector.swift; path = Source/Protector.swift; sourceTree = ""; }; 1A182FD1146398A40411ACBF0BF48485 /* ErrorHandler+AFExtensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ErrorHandler+AFExtensions.swift"; path = "ErrorHandler/Classes/Alamofire/ErrorHandler+AFExtensions.swift"; sourceTree = ""; }; - 1C15C076B531E2E7744C358418A0C0B5 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; + 1C6818CB68941B73559573DB4F55FF2F /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; + 1F8926879B94ED50118A3EA9401E92DD /* ParameterEncoder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoder.swift; path = Source/ParameterEncoder.swift; sourceTree = ""; }; 21384DBED434E3C4A6705484B9361921 /* AFErrorStatusCodeMatcher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AFErrorStatusCodeMatcher.swift; path = ErrorHandler/Classes/Alamofire/AFErrorStatusCodeMatcher.swift; sourceTree = ""; }; 24AB3F5394D085ED5897811C12783187 /* ErrorHandler-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "ErrorHandler-dummy.m"; sourceTree = ""; }; + 252E34E06DE82E4A96FF19DDAAB47C48 /* HTTPHeaders.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HTTPHeaders.swift; path = Source/HTTPHeaders.swift; sourceTree = ""; }; + 2598222A405D08F1B87C0463420492F3 /* URLSessionConfiguration+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLSessionConfiguration+Alamofire.swift"; path = "Source/URLSessionConfiguration+Alamofire.swift"; sourceTree = ""; }; 2948CB95C564872E4F2DBC4A36E71528 /* ErrorHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ErrorHandler.swift; path = ErrorHandler/Classes/Core/ErrorHandler.swift; sourceTree = ""; }; - 32DB5272AD01ECD0B09A86818A7754C4 /* Timeline.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeline.swift; path = Source/Timeline.swift; sourceTree = ""; }; - 33115EC2A5164913C68F8BD170389EEE /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; - 341BDAD0026CDA8E7BCE35AC122E1C8C /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; - 3D7E25E371731FAE44F46A9F392CB5D5 /* SessionManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionManager.swift; path = Source/SessionManager.swift; sourceTree = ""; }; + 325AADD7113A629C5C8D34CF07909EFD /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; + 32BD7B93FEA70BDFD057550D07FA7961 /* CFNetwork.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CFNetwork.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/CFNetwork.framework; sourceTree = DEVELOPER_DIR; }; + 33BB7D85C23DEE0174BE6AFD50EE6E41 /* CachedResponseHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CachedResponseHandler.swift; path = Source/CachedResponseHandler.swift; sourceTree = ""; }; + 3F401E181BEA002337E464DED414F440 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + 47152D714F71E858000F62A8A616FCAF /* Result+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Result+Alamofire.swift"; path = "Source/Result+Alamofire.swift"; sourceTree = ""; }; 48B9CBBB57D1CE70A75641FBBAE448AF /* Pods-ErrorHandler_Tests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-ErrorHandler_Tests-acknowledgements.markdown"; sourceTree = ""; }; - 4B03B07DFA7C8BB60693AE1DE30731E2 /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 4F380A974DB08A3A5AAA4F22694A85B3 /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; 56D3A01F8E3A2E0EF027DFA04F94FDC9 /* Pods-ErrorHandler_Example-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-ErrorHandler_Example-acknowledgements.markdown"; sourceTree = ""; }; 57F21E981916F5AADCE7E5ADCBB09243 /* Pods-ErrorHandler_Tests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-ErrorHandler_Tests-dummy.m"; sourceTree = ""; }; + 5C4A2EA954452FABDC9746857D19ED7D /* Alamofire-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Alamofire-Info.plist"; sourceTree = ""; }; 5D797E9A5C5782CE845840781FA1CC81 /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Alamofire.framework; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 606BE8303EA7BEBCEEB352710830C84A /* ErrorHandler-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "ErrorHandler-umbrella.h"; sourceTree = ""; }; - 69DAB41DE6AF59D8362CBC670CDF0EEC /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + 60B0E4FA795EABD32357C1014201A8F9 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; + 6AC6C2A47145FA1261B6E8425F2262E1 /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; 6D7DAF5C864E74B2C4D817811DD9D0F2 /* Pods-ErrorHandler_Example-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-ErrorHandler_Example-acknowledgements.plist"; sourceTree = ""; }; - 75C759635F88377BD7E2DEDE04C23C62 /* TaskDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TaskDelegate.swift; path = Source/TaskDelegate.swift; sourceTree = ""; }; + 7059C4CC67DC9BED886103B6F8540E89 /* ServerTrustEvaluation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustEvaluation.swift; path = Source/ServerTrustEvaluation.swift; sourceTree = ""; }; 75D1C9F69FE1A899D601FD64ABECF6BD /* NSErrorMatcher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NSErrorMatcher.swift; path = ErrorHandler/Classes/Core/NSErrorMatcher.swift; sourceTree = ""; }; - 7B03859BDC36782899379E222720A297 /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; + 76C3EEA63BB9145123705DFCADC8EE27 /* EventMonitor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EventMonitor.swift; path = Source/EventMonitor.swift; sourceTree = ""; }; + 774B0CF83AA71BBED2A70E4A0AE6D9CD /* HTTPMethod.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HTTPMethod.swift; path = Source/HTTPMethod.swift; sourceTree = ""; }; + 77E408574C32514C9D9055B5A00125B4 /* DispatchQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Alamofire.swift"; path = "Source/DispatchQueue+Alamofire.swift"; sourceTree = ""; }; + 79356BB38DCE3AF0EE679B37B4436ED0 /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; + 7BDE34987683B80FE97BBE5736A439B6 /* MultipartUpload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartUpload.swift; path = Source/MultipartUpload.swift; sourceTree = ""; }; 804611608ED5CE39BEEC79C3FCB96FAE /* Pods-ErrorHandler_Example-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-ErrorHandler_Example-frameworks.sh"; sourceTree = ""; }; 83E0C1BCD85D78BF7D8167A40CF9D19C /* Matchers.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Matchers.swift; path = ErrorHandler/Classes/Core/Matchers.swift; sourceTree = ""; }; 85D459C75CCB190940916C74DDB17E00 /* Pods-ErrorHandler_Tests-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-ErrorHandler_Tests-Info.plist"; sourceTree = ""; }; + 8842C3D78AC0E234008C8E176A413664 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; + 8983361440DA703D7E1F9901F2657715 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; 8AA622A1744632068031D60282391A2A /* Pods-ErrorHandler_Tests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-ErrorHandler_Tests.modulemap"; sourceTree = ""; }; - 8D5A0E300C04A6DF88D620788FE38780 /* AFError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AFError.swift; path = Source/AFError.swift; sourceTree = ""; }; + 906744E115B923BC81683FA8522951A8 /* OperationQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "OperationQueue+Alamofire.swift"; path = "Source/OperationQueue+Alamofire.swift"; sourceTree = ""; }; 93BF6B222D9268B71EDABF1336161676 /* Pods_ErrorHandler_Example.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_ErrorHandler_Example.framework; path = "Pods-ErrorHandler_Example.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; - 985417470B9341C92A5160D4B2FF2B08 /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; - 9D59E1AD3CC394A93392FF3DC8CF2961 /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; + 955C7B41827018BB1B59E447A617F1A6 /* RequestInterceptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestInterceptor.swift; path = Source/RequestInterceptor.swift; sourceTree = ""; }; + 96C2ABABCF96583B0736B746A886AECB /* RequestTaskMap.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestTaskMap.swift; path = Source/RequestTaskMap.swift; sourceTree = ""; }; + 96ED5BF61D38354434EEDC4FD6779584 /* RetryPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RetryPolicy.swift; path = Source/RetryPolicy.swift; sourceTree = ""; }; 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; indentWidth = 2; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; tabWidth = 2; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + A437F36AAA97B99103FBD62EA2687E78 /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; + A6EF2A5FCF56EE72AA71A552A8D39A96 /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; + A93EE927BDAEF08BD7FED7F2C1D56707 /* URLConvertible+URLRequestConvertible.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLConvertible+URLRequestConvertible.swift"; path = "Source/URLConvertible+URLRequestConvertible.swift"; sourceTree = ""; }; AAF2AB79FA266A1549C945925963F3A9 /* Pods-ErrorHandler_Example-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-ErrorHandler_Example-umbrella.h"; sourceTree = ""; }; ACC20AD19CD774FD3776BF683936F7AA /* README.md */ = {isa = PBXFileReference; includeInIndex = 1; path = README.md; sourceTree = ""; }; - AD8710F26B62AABFF387E9CA4F6899A4 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Alamofire.modulemap; sourceTree = ""; }; ADF12CCE83AA13C21340E9B75F59BA64 /* ErrorHandler.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = ErrorHandler.modulemap; sourceTree = ""; }; AF586B3890CD756CE713E553C5E04D9F /* ErrorHandler.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = ErrorHandler.framework; path = ErrorHandler.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - AFF7F7716086D54E6308EE52C8227B87 /* DispatchQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Alamofire.swift"; path = "Source/DispatchQueue+Alamofire.swift"; sourceTree = ""; }; - B06639F7A76DB8A9D0D0E41CDD7A6684 /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; + B0B912D70323E7F86DCD780B2231C472 /* AFError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AFError.swift; path = Source/AFError.swift; sourceTree = ""; }; B0F95C1D1992D0009780BF51CB0DDD77 /* Pods_ErrorHandler_Tests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_ErrorHandler_Tests.framework; path = "Pods-ErrorHandler_Tests.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; BBF9EF5370BAB7C621872D272CA2901D /* ErrorHandler.podspec */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; indentWidth = 2; lastKnownFileType = text; path = ErrorHandler.podspec; sourceTree = ""; tabWidth = 2; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; - BFCE3D7EDCA41F256D471B40BBFD3FCE /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; C2D5EA14B8E5D0C38F70E51C9E89E93C /* Pods-ErrorHandler_Tests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-ErrorHandler_Tests-acknowledgements.plist"; sourceTree = ""; }; - C4453BE339B79900FDC53E34FE5589CB /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; - C9C3EF964FFA8A9F78851B59A8D4FFBC /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; + CA569E409E59A3A7C43E582FFFECC049 /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; CA9CC7B827F90F8D4476BBE62EB2D8B8 /* Pods-ErrorHandler_Example.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-ErrorHandler_Example.debug.xcconfig"; sourceTree = ""; }; - CCC6858C85690F7AFEA7F6542EE9A69A /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; + CDE821E7D82EDB49E8CCB3F4281CB873 /* RedirectHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RedirectHandler.swift; path = Source/RedirectHandler.swift; sourceTree = ""; }; + D0FF301302A2A77E95697F2B5692FA5E /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; D18062075C863D7A7F9AC31F86E6E890 /* Pods-ErrorHandler_Tests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-ErrorHandler_Tests.debug.xcconfig"; sourceTree = ""; }; + D1A6BA50BC9798E96A96694316FD7F19 /* AlamofireExtended.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AlamofireExtended.swift; path = Source/AlamofireExtended.swift; sourceTree = ""; }; + D2D875F7C044C8B217EF5F195FE38EF6 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Alamofire.modulemap; sourceTree = ""; }; + D3472833109D10A6D1A67609593B695A /* URLEncodedFormEncoder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = URLEncodedFormEncoder.swift; path = Source/URLEncodedFormEncoder.swift; sourceTree = ""; }; + D349810CA61917A72856F3114DE4DA68 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; D4942566DB46CA1043F9870EFFA14EF1 /* Pods-ErrorHandler_Example-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-ErrorHandler_Example-dummy.m"; sourceTree = ""; }; - D54AEF5647A987180EDAD7E1CEF7387B /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; + D578A4BA4B36B12F7C081E8ED1215837 /* URLRequest+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLRequest+Alamofire.swift"; path = "Source/URLRequest+Alamofire.swift"; sourceTree = ""; }; DA59CC3A311625B872DF3D9F0D5A7F57 /* ErrorHandler-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "ErrorHandler-Info.plist"; sourceTree = ""; }; DAA5AD46B641FE7498406D9860EA2056 /* Pods-ErrorHandler_Example-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-ErrorHandler_Example-Info.plist"; sourceTree = ""; }; - DD807F155301ECA538A2C1C296E1186D /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; - DE36AED4DF687B2D37BD230D9D2F69B6 /* Alamofire-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Alamofire-Info.plist"; sourceTree = ""; }; F4CD742C829079BBF81B89646477CAAE /* LICENSE */ = {isa = PBXFileReference; includeInIndex = 1; path = LICENSE; sourceTree = ""; }; - F5460AD0F6241621B45A17AB23A8E5B7 /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; - F640F61D5BEE8132009BAEAA65B587A4 /* SessionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDelegate.swift; path = Source/SessionDelegate.swift; sourceTree = ""; }; + F832D5DCB54F4499206CA6D8DECB63DA /* Session.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Session.swift; path = Source/Session.swift; sourceTree = ""; }; + FC87D7C9C22946B653EC891AD65CA774 /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; + FED8657059CCC1AA8B884882B6C21DF3 /* SessionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDelegate.swift; path = Source/SessionDelegate.swift; sourceTree = ""; }; FF2A38EF36D5EAE306E1E699F6CB550F /* ErrorHandler-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "ErrorHandler-prefix.pch"; sourceTree = ""; }; /* End PBXFileReference section */ @@ -148,11 +180,12 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 090C1D63463ACF622287EFF9D5C9392D /* Frameworks */ = { + 8B0D8633F410345F93419B8C3D7B6916 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 7664FD4F59A0C00866CBAE60B0A3AD64 /* Foundation.framework in Frameworks */, + 97A168DFB6DB61770CE2DBF4FD39AA8D /* CFNetwork.framework in Frameworks */, + BE82AE980F8C7EE28A6448959194F93A /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -176,6 +209,14 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 08C3CADBFE7473C8C2720B971358481C /* Pods */ = { + isa = PBXGroup; + children = ( + CC1ED248BA98F2E22521DA618B8E5953 /* Alamofire */, + ); + name = Pods; + sourceTree = ""; + }; 0F0741B94793F1428A4528E5EA331C86 /* Alamofire */ = { isa = PBXGroup; children = ( @@ -213,15 +254,6 @@ name = "Development Pods"; sourceTree = ""; }; - 2F2A6FCCD7293377A61DF5D10894ACF2 /* Frameworks */ = { - isa = PBXGroup; - children = ( - 4B03B07DFA7C8BB60693AE1DE30731E2 /* Alamofire.framework */, - DBBD239EB7C1C83EA80124D1A53485AB /* iOS */, - ); - name = Frameworks; - sourceTree = ""; - }; 31184162346D02ED0102E25BE7B3140B /* ErrorHandler */ = { isa = PBXGroup; children = ( @@ -250,6 +282,15 @@ path = "Target Support Files/Pods-ErrorHandler_Tests"; sourceTree = ""; }; + 4BF62439A2FE1F58E9E704216CF2CE03 /* iOS */ = { + isa = PBXGroup; + children = ( + 32BD7B93FEA70BDFD057550D07FA7961 /* CFNetwork.framework */, + 3F401E181BEA002337E464DED414F440 /* Foundation.framework */, + ); + name = iOS; + sourceTree = ""; + }; 5584A95CB53E5DE346B0DD15BAA221D6 /* Support Files */ = { isa = PBXGroup; children = ( @@ -264,26 +305,13 @@ path = "Example/Pods/Target Support Files/ErrorHandler"; sourceTree = ""; }; - 5C26875CAEBEFEDA19F66418CD7AE5DB /* Support Files */ = { + 8B7A79262BFE6D94671D449787F3AAA9 /* Frameworks */ = { isa = PBXGroup; children = ( - AD8710F26B62AABFF387E9CA4F6899A4 /* Alamofire.modulemap */, - 985417470B9341C92A5160D4B2FF2B08 /* Alamofire.xcconfig */, - 341BDAD0026CDA8E7BCE35AC122E1C8C /* Alamofire-dummy.m */, - DE36AED4DF687B2D37BD230D9D2F69B6 /* Alamofire-Info.plist */, - C9C3EF964FFA8A9F78851B59A8D4FFBC /* Alamofire-prefix.pch */, - D54AEF5647A987180EDAD7E1CEF7387B /* Alamofire-umbrella.h */, + D0FF301302A2A77E95697F2B5692FA5E /* Alamofire.framework */, + 4BF62439A2FE1F58E9E704216CF2CE03 /* iOS */, ); - name = "Support Files"; - path = "../Target Support Files/Alamofire"; - sourceTree = ""; - }; - 90FDDC7F5D24472360CA259A8D40AE98 /* Pods */ = { - isa = PBXGroup; - children = ( - ABBD6121E62B33A53CF07892A75F2030 /* Alamofire */, - ); - name = Pods; + name = Frameworks; sourceTree = ""; }; 94B91277A251CF11155B49D9BD8310C1 /* Pods-ErrorHandler_Example */ = { @@ -313,27 +341,42 @@ name = Core; sourceTree = ""; }; - ABBD6121E62B33A53CF07892A75F2030 /* Alamofire */ = { + CC1ED248BA98F2E22521DA618B8E5953 /* Alamofire */ = { isa = PBXGroup; children = ( - 8D5A0E300C04A6DF88D620788FE38780 /* AFError.swift */, - 1C15C076B531E2E7744C358418A0C0B5 /* Alamofire.swift */, - AFF7F7716086D54E6308EE52C8227B87 /* DispatchQueue+Alamofire.swift */, - BFCE3D7EDCA41F256D471B40BBFD3FCE /* MultipartFormData.swift */, - F5460AD0F6241621B45A17AB23A8E5B7 /* NetworkReachabilityManager.swift */, - B06639F7A76DB8A9D0D0E41CDD7A6684 /* Notifications.swift */, - 0D01BA8472F25D39F718F71557EDC8DD /* ParameterEncoding.swift */, - 9D59E1AD3CC394A93392FF3DC8CF2961 /* Request.swift */, - CCC6858C85690F7AFEA7F6542EE9A69A /* Response.swift */, - 7B03859BDC36782899379E222720A297 /* ResponseSerialization.swift */, - DD807F155301ECA538A2C1C296E1186D /* Result.swift */, - C4453BE339B79900FDC53E34FE5589CB /* ServerTrustPolicy.swift */, - F640F61D5BEE8132009BAEAA65B587A4 /* SessionDelegate.swift */, - 3D7E25E371731FAE44F46A9F392CB5D5 /* SessionManager.swift */, - 75C759635F88377BD7E2DEDE04C23C62 /* TaskDelegate.swift */, - 32DB5272AD01ECD0B09A86818A7754C4 /* Timeline.swift */, - 33115EC2A5164913C68F8BD170389EEE /* Validation.swift */, - 5C26875CAEBEFEDA19F66418CD7AE5DB /* Support Files */, + B0B912D70323E7F86DCD780B2231C472 /* AFError.swift */, + 1C6818CB68941B73559573DB4F55FF2F /* Alamofire.swift */, + D1A6BA50BC9798E96A96694316FD7F19 /* AlamofireExtended.swift */, + 33BB7D85C23DEE0174BE6AFD50EE6E41 /* CachedResponseHandler.swift */, + 77E408574C32514C9D9055B5A00125B4 /* DispatchQueue+Alamofire.swift */, + 76C3EEA63BB9145123705DFCADC8EE27 /* EventMonitor.swift */, + 252E34E06DE82E4A96FF19DDAAB47C48 /* HTTPHeaders.swift */, + 774B0CF83AA71BBED2A70E4A0AE6D9CD /* HTTPMethod.swift */, + 60B0E4FA795EABD32357C1014201A8F9 /* MultipartFormData.swift */, + 7BDE34987683B80FE97BBE5736A439B6 /* MultipartUpload.swift */, + FC87D7C9C22946B653EC891AD65CA774 /* NetworkReachabilityManager.swift */, + A437F36AAA97B99103FBD62EA2687E78 /* Notifications.swift */, + 906744E115B923BC81683FA8522951A8 /* OperationQueue+Alamofire.swift */, + 1F8926879B94ED50118A3EA9401E92DD /* ParameterEncoder.swift */, + 8842C3D78AC0E234008C8E176A413664 /* ParameterEncoding.swift */, + 1982A99EC0068FB848DB3B942CB83DB5 /* Protector.swift */, + CDE821E7D82EDB49E8CCB3F4281CB873 /* RedirectHandler.swift */, + A6EF2A5FCF56EE72AA71A552A8D39A96 /* Request.swift */, + 955C7B41827018BB1B59E447A617F1A6 /* RequestInterceptor.swift */, + 96C2ABABCF96583B0736B746A886AECB /* RequestTaskMap.swift */, + 325AADD7113A629C5C8D34CF07909EFD /* Response.swift */, + 79356BB38DCE3AF0EE679B37B4436ED0 /* ResponseSerialization.swift */, + 47152D714F71E858000F62A8A616FCAF /* Result+Alamofire.swift */, + 96ED5BF61D38354434EEDC4FD6779584 /* RetryPolicy.swift */, + 7059C4CC67DC9BED886103B6F8540E89 /* ServerTrustEvaluation.swift */, + F832D5DCB54F4499206CA6D8DECB63DA /* Session.swift */, + FED8657059CCC1AA8B884882B6C21DF3 /* SessionDelegate.swift */, + A93EE927BDAEF08BD7FED7F2C1D56707 /* URLConvertible+URLRequestConvertible.swift */, + D3472833109D10A6D1A67609593B695A /* URLEncodedFormEncoder.swift */, + D578A4BA4B36B12F7C081E8ED1215837 /* URLRequest+Alamofire.swift */, + 2598222A405D08F1B87C0463420492F3 /* URLSessionConfiguration+Alamofire.swift */, + D349810CA61917A72856F3114DE4DA68 /* Validation.swift */, + E54E43FD3458F5DE8FE802AE2526AF81 /* Support Files */, ); name = Alamofire; path = Alamofire; @@ -344,19 +387,25 @@ children = ( 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */, 2DAF0B3C6398E3DC1E493D68A71F2D55 /* Development Pods */, - 2F2A6FCCD7293377A61DF5D10894ACF2 /* Frameworks */, - 90FDDC7F5D24472360CA259A8D40AE98 /* Pods */, + 8B7A79262BFE6D94671D449787F3AAA9 /* Frameworks */, + 08C3CADBFE7473C8C2720B971358481C /* Pods */, 2D43A654797EF9F1935D0AF6A9541BD4 /* Products */, 14A1F683CFCDF5FC5E555F04D17F0632 /* Targets Support Files */, ); sourceTree = ""; }; - DBBD239EB7C1C83EA80124D1A53485AB /* iOS */ = { + E54E43FD3458F5DE8FE802AE2526AF81 /* Support Files */ = { isa = PBXGroup; children = ( - 69DAB41DE6AF59D8362CBC670CDF0EEC /* Foundation.framework */, + D2D875F7C044C8B217EF5F195FE38EF6 /* Alamofire.modulemap */, + 4F380A974DB08A3A5AAA4F22694A85B3 /* Alamofire.xcconfig */, + CA569E409E59A3A7C43E582FFFECC049 /* Alamofire-dummy.m */, + 5C4A2EA954452FABDC9746857D19ED7D /* Alamofire-Info.plist */, + 6AC6C2A47145FA1261B6E8425F2262E1 /* Alamofire-prefix.pch */, + 8983361440DA703D7E1F9901F2657715 /* Alamofire-umbrella.h */, ); - name = iOS; + name = "Support Files"; + path = "../Target Support Files/Alamofire"; sourceTree = ""; }; EE45138EBA5F7D78391C420992032622 /* Pod */ = { @@ -372,19 +421,19 @@ /* End PBXGroup section */ /* Begin PBXHeadersBuildPhase section */ - 2582784E4FA6A1AC5D23FC53AC3F6EE2 /* Headers */ = { + AB496FBE6F87A83D742136D4F89C8E77 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - F7B74645E07C39771156A1FA413B98D4 /* Alamofire-umbrella.h in Headers */, + 707E3A5438CF654DCA6198028C2EEA15 /* Pods-ErrorHandler_Example-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; - AB496FBE6F87A83D742136D4F89C8E77 /* Headers */ = { + ADDF288DD930A46B5F0F198C225895C9 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - 707E3A5438CF654DCA6198028C2EEA15 /* Pods-ErrorHandler_Example-umbrella.h in Headers */, + 00FA97D56201027AEB1C7692A2C3CF8B /* Alamofire-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -467,12 +516,12 @@ }; EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */ = { isa = PBXNativeTarget; - buildConfigurationList = E4A5194ABAF7A4780609E0E581DA6B54 /* Build configuration list for PBXNativeTarget "Alamofire" */; + buildConfigurationList = 6B2B8EC7E21CDBFF2BDA26B1B4AC4C0D /* Build configuration list for PBXNativeTarget "Alamofire" */; buildPhases = ( - 2582784E4FA6A1AC5D23FC53AC3F6EE2 /* Headers */, - 2DDFD9AC10F181CD7130BDF5F9E0502B /* Sources */, - 090C1D63463ACF622287EFF9D5C9392D /* Frameworks */, - 473D3E892ABB6C798CFF290644259B34 /* Resources */, + ADDF288DD930A46B5F0F198C225895C9 /* Headers */, + 7349DB0E9BEBE664696F1DCC25226F26 /* Sources */, + 8B0D8633F410345F93419B8C3D7B6916 /* Frameworks */, + 28FC0024B79C28A420D7C4FEBB9E3AEB /* Resources */, ); buildRules = ( ); @@ -513,7 +562,7 @@ /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ - 473D3E892ABB6C798CFF290644259B34 /* Resources */ = { + 28FC0024B79C28A420D7C4FEBB9E3AEB /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( @@ -544,36 +593,51 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ - 2DDFD9AC10F181CD7130BDF5F9E0502B /* Sources */ = { + 49080AE988D2AC6FB3760E0EEBF43785 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 83956E20859CDBBE7BC38ABADE0170FB /* AFError.swift in Sources */, - 1945CD5D63A1C164AEAAA9A33E85571E /* Alamofire-dummy.m in Sources */, - BEE6B677416CA71C981D1D3F60B18C96 /* Alamofire.swift in Sources */, - D3D8C379C6E4FB487E5ABD6800AD7B7E /* DispatchQueue+Alamofire.swift in Sources */, - 1986B50C74F1697EA43F68335C93CEB3 /* MultipartFormData.swift in Sources */, - 3571F958A3907B3A806E62D50C2550D4 /* NetworkReachabilityManager.swift in Sources */, - 132E0F619E4338E5D1B27E4C72076B3F /* Notifications.swift in Sources */, - 0C5E11DE24DAA737704B355F5F2F3426 /* ParameterEncoding.swift in Sources */, - 98A929C8E9012AB167672714FFD2113C /* Request.swift in Sources */, - D65C254F5ABF2CB5ECEE50FE8F8E1A80 /* Response.swift in Sources */, - E3747EC31FCCA97D75A81FC700CF7E24 /* ResponseSerialization.swift in Sources */, - 64744C911253C3E01461FAD7C935C8D7 /* Result.swift in Sources */, - F13F2AA7F2E6D95A181CAB99B900D531 /* ServerTrustPolicy.swift in Sources */, - 2C61B040BA6A9A7AE66C4D9BA26D5520 /* SessionDelegate.swift in Sources */, - 931BBB8230A25161D5C37528A8F9FECF /* SessionManager.swift in Sources */, - AFC64B1097F7355FF423D6A73E9C7210 /* TaskDelegate.swift in Sources */, - 933FDA5970AA525D6CB92BFEBA2BAB4A /* Timeline.swift in Sources */, - 53791F5E5F07400F92CFDFC89A432305 /* Validation.swift in Sources */, + DD8A41A1CCD8CF3FA496C9F1258B6182 /* Pods-ErrorHandler_Tests-dummy.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; - 49080AE988D2AC6FB3760E0EEBF43785 /* Sources */ = { + 7349DB0E9BEBE664696F1DCC25226F26 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - DD8A41A1CCD8CF3FA496C9F1258B6182 /* Pods-ErrorHandler_Tests-dummy.m in Sources */, + 17953A9CF2E354B3E69B9ABC2F367AD9 /* AFError.swift in Sources */, + B1C58F6CED7B3E45170711D9ADF878AF /* Alamofire-dummy.m in Sources */, + B788B3354CCEBE56DFDB963CAFD7F6C2 /* Alamofire.swift in Sources */, + 44127C4B989C9CC6A90D78B66A929A5E /* AlamofireExtended.swift in Sources */, + 0AE06C3AEA6CA45342BA703230ABD2CB /* CachedResponseHandler.swift in Sources */, + E9A5AC2F471699CCA516952A5FEB990B /* DispatchQueue+Alamofire.swift in Sources */, + CACBD166E573774FB5613C34AA6DA7A7 /* EventMonitor.swift in Sources */, + 56EC8ED1535DAB987F3D2B71D4C05773 /* HTTPHeaders.swift in Sources */, + B23E9A5CDA31534491226F4C2EE8F8E6 /* HTTPMethod.swift in Sources */, + 5C4A0685B5A201436AB52EF25829B333 /* MultipartFormData.swift in Sources */, + E07BD425C4EA9ADF15DDFCDB10D0B2FB /* MultipartUpload.swift in Sources */, + 7CF8362BA31492053F5CB165637AE117 /* NetworkReachabilityManager.swift in Sources */, + C7369563F6946D8984124E1A546B6425 /* Notifications.swift in Sources */, + 92811AC5CD9A5004116AE43C4E8FD955 /* OperationQueue+Alamofire.swift in Sources */, + 5D61C8ED0DDCC9F8B576B6514B19EE50 /* ParameterEncoder.swift in Sources */, + 14AB7976E100075ADEA0AB1DB833E72D /* ParameterEncoding.swift in Sources */, + 0419772A87B16DB7DCF405A9E77D671F /* Protector.swift in Sources */, + C64AF152F7928CDB59385528DB65FE19 /* RedirectHandler.swift in Sources */, + 6A22C46CB1EDE471794D9AB2AC10327F /* Request.swift in Sources */, + AD9899986955B2EC1EC20818C860C971 /* RequestInterceptor.swift in Sources */, + 48D97BE7D5CAED273BD2341C239CC934 /* RequestTaskMap.swift in Sources */, + F71789DC91A75033EFB79DB828676451 /* Response.swift in Sources */, + 13457FE4E607509A3B9527B0711033D5 /* ResponseSerialization.swift in Sources */, + 4082513A35C682F2193D002C80F72B79 /* Result+Alamofire.swift in Sources */, + D6B2983389480F48F27A0704EEB5DC81 /* RetryPolicy.swift in Sources */, + 0CC43FF0E31AA320ACFEB0FE6239DF34 /* ServerTrustEvaluation.swift in Sources */, + 69ACE4EEE5A8C1C618B22CC1F7B8EF01 /* Session.swift in Sources */, + 42CDB5C986C78BBC8E5C0185F746CABF /* SessionDelegate.swift in Sources */, + 70517C3BAC2D6614347DEAC15299EB84 /* URLConvertible+URLRequestConvertible.swift in Sources */, + 5D12235D061AEE7459279AAF8C348DFE /* URLEncodedFormEncoder.swift in Sources */, + E4E12208D5246E64B7E6CCAE987ADB03 /* URLRequest+Alamofire.swift in Sources */, + AF92602937CA016548022C600B8CDC16 /* URLSessionConfiguration+Alamofire.swift in Sources */, + 06507A26118BA5ACFBBC8C225776920E /* Validation.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -628,134 +692,11 @@ /* End PBXTargetDependency section */ /* Begin XCBuildConfiguration section */ - 23EBCFDBCD6C2B77AA1A6ECF422DC6EE /* Debug */ = { + 00319A2330DC739FCBFBB6CFB0C5F58D /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 165B0310C0578682A0DDBA8E19C162C8 /* ErrorHandler.xcconfig */; - buildSettings = { - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - GCC_PREFIX_HEADER = "Target Support Files/ErrorHandler/ErrorHandler-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/ErrorHandler/ErrorHandler-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/ErrorHandler/ErrorHandler.modulemap"; - PRODUCT_MODULE_NAME = ErrorHandler; - PRODUCT_NAME = ErrorHandler; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; - 37604B635A6B9C24F2D1C22019254EB9 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = CA9CC7B827F90F8D4476BBE62EB2D8B8 /* Pods-ErrorHandler_Example.debug.xcconfig */; - buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - INFOPLIST_FILE = "Target Support Files/Pods-ErrorHandler_Example/Pods-ErrorHandler_Example-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.3; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-ErrorHandler_Example/Pods-ErrorHandler_Example.modulemap"; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; - 60A7F9B4A8E92A5B16CC2AA887D9FE07 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_NO_COMMON_BLOCKS = YES; - GCC_PREPROCESSOR_DEFINITIONS = ( - "POD_CONFIGURATION_RELEASE=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 8.3; - MTL_ENABLE_DEBUG_INFO = NO; - MTL_FAST_MATH = YES; - PRODUCT_NAME = "$(TARGET_NAME)"; - STRIP_INSTALLED_PRODUCT = NO; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_OPTIMIZATION_LEVEL = "-O"; - SWIFT_VERSION = 5.0; - SYMROOT = "${SRCROOT}/../build"; - }; - name = Release; - }; - 75BBB760DFD877E344322B54D29DFE64 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 985417470B9341C92A5160D4B2FF2B08 /* Alamofire.xcconfig */; + baseConfigurationReference = 4F380A974DB08A3A5AAA4F22694A85B3 /* Alamofire.xcconfig */; buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; @@ -768,7 +709,7 @@ GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; INFOPLIST_FILE = "Target Support Files/Alamofire/Alamofire-Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; PRODUCT_MODULE_NAME = Alamofire; @@ -783,7 +724,7 @@ }; name = Debug; }; - 7E1F3D358966F24610AD782F313B4C40 /* Debug */ = { + 196DFA3E4A09A28224918543529A1885 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; @@ -834,7 +775,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 8.3; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; MTL_FAST_MATH = YES; ONLY_ACTIVE_ARCH = YES; @@ -847,11 +788,11 @@ }; name = Debug; }; - 9EE01EE769C0B4445EB64C673CDDEC11 /* Debug */ = { + 34BF57C020688FBB4F3821AD9E23253D /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = D18062075C863D7A7F9AC31F86E6E890 /* Pods-ErrorHandler_Tests.debug.xcconfig */; + baseConfigurationReference = 165B0310C0578682A0DDBA8E19C162C8 /* ErrorHandler.xcconfig */; buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; @@ -861,29 +802,30 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - INFOPLIST_FILE = "Target Support Files/Pods-ErrorHandler_Tests/Pods-ErrorHandler_Tests-Info.plist"; + GCC_PREFIX_HEADER = "Target Support Files/ErrorHandler/ErrorHandler-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/ErrorHandler/ErrorHandler-Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.3; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-ErrorHandler_Tests/Pods-ErrorHandler_Tests.modulemap"; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + MODULEMAP_FILE = "Target Support Files/ErrorHandler/ErrorHandler.modulemap"; + PRODUCT_MODULE_NAME = ErrorHandler; + PRODUCT_NAME = ErrorHandler; SDKROOT = iphoneos; SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; - name = Debug; + name = Release; }; - B4DFBFB3A83521EDA20D0F50F7EB8B6D /* Release */ = { + 42CD662B95BB834C4C7B60249352C5B0 /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 165B0310C0578682A0DDBA8E19C162C8 /* ErrorHandler.xcconfig */; buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; @@ -896,7 +838,7 @@ GCC_PREFIX_HEADER = "Target Support Files/ErrorHandler/ErrorHandler-prefix.pch"; INFOPLIST_FILE = "Target Support Files/ErrorHandler/ErrorHandler-Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MODULEMAP_FILE = "Target Support Files/ErrorHandler/ErrorHandler.modulemap"; PRODUCT_MODULE_NAME = ErrorHandler; @@ -906,17 +848,51 @@ SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; - name = Release; + name = Debug; }; - C6A1A82C8E467D0BE859E25CE38AAF1F /* Release */ = { + 7D9400A6D62CD867B80615D7DD01F8B3 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = CA9CC7B827F90F8D4476BBE62EB2D8B8 /* Pods-ErrorHandler_Example.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-ErrorHandler_Example/Pods-ErrorHandler_Example-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-ErrorHandler_Example/Pods-ErrorHandler_Example.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 91F5CB6957C696E6CBECA84107ED08CE /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 08DAAAE6A10FC81DFABDA013A3570FBB /* Pods-ErrorHandler_Tests.release.xcconfig */; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; @@ -928,7 +904,7 @@ DYLIB_INSTALL_NAME_BASE = "@rpath"; INFOPLIST_FILE = "Target Support Files/Pods-ErrorHandler_Tests/Pods-ErrorHandler_Tests-Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.3; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MACH_O_TYPE = staticlib; MODULEMAP_FILE = "Target Support Files/Pods-ErrorHandler_Tests/Pods-ErrorHandler_Tests.modulemap"; @@ -946,10 +922,12 @@ }; name = Release; }; - F94FD07C591B17B7E61A1528AB9BCB3B /* Release */ = { + 9D23FB134C7F67803BEBFBF6D7929F2F /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 985417470B9341C92A5160D4B2FF2B08 /* Alamofire.xcconfig */; + baseConfigurationReference = 0A95765082C23CD7BDAC48A2916C138B /* Pods-ErrorHandler_Example.release.xcconfig */; buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; @@ -959,18 +937,19 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Alamofire/Alamofire-Info.plist"; + INFOPLIST_FILE = "Target Support Files/Pods-ErrorHandler_Example/Pods-ErrorHandler_Example-Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; - PRODUCT_MODULE_NAME = Alamofire; - PRODUCT_NAME = Alamofire; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-ErrorHandler_Example/Pods-ErrorHandler_Example.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; SDKROOT = iphoneos; SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_VERSION = 5.1; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; @@ -978,11 +957,72 @@ }; name = Release; }; - FC737405B5570BBBF8D3D510DF30D54F /* Release */ = { + B01D14FDC83DCF9D4BE53066BEA96D05 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 0A95765082C23CD7BDAC48A2916C138B /* Pods-ErrorHandler_Example.release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_RELEASE=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRIP_INSTALLED_PRODUCT = NO; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + SWIFT_VERSION = 5.0; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Release; + }; + F2EDC57A181AEADD08D945F056BD91D7 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = D18062075C863D7A7F9AC31F86E6E890 /* Pods-ErrorHandler_Tests.debug.xcconfig */; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; @@ -992,12 +1032,12 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - INFOPLIST_FILE = "Target Support Files/Pods-ErrorHandler_Example/Pods-ErrorHandler_Example-Info.plist"; + INFOPLIST_FILE = "Target Support Files/Pods-ErrorHandler_Tests/Pods-ErrorHandler_Tests-Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.3; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-ErrorHandler_Example/Pods-ErrorHandler_Example.modulemap"; + MODULEMAP_FILE = "Target Support Files/Pods-ErrorHandler_Tests/Pods-ErrorHandler_Tests.modulemap"; OTHER_LDFLAGS = ""; OTHER_LIBTOOLFLAGS = ""; PODS_ROOT = "$(SRCROOT)"; @@ -1006,6 +1046,38 @@ SDKROOT = iphoneos; SKIP_INSTALL = YES; TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + F659822BFF3B3C20B29B76B89800A5E9 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 4F380A974DB08A3A5AAA4F22694A85B3 /* Alamofire.xcconfig */; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Alamofire-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + PRODUCT_MODULE_NAME = Alamofire; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.1; + TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; @@ -1018,8 +1090,8 @@ 12B00D361C6BCC33C1C55B1FB1CCF470 /* Build configuration list for PBXNativeTarget "ErrorHandler" */ = { isa = XCConfigurationList; buildConfigurations = ( - 23EBCFDBCD6C2B77AA1A6ECF422DC6EE /* Debug */, - B4DFBFB3A83521EDA20D0F50F7EB8B6D /* Release */, + 42CD662B95BB834C4C7B60249352C5B0 /* Debug */, + 34BF57C020688FBB4F3821AD9E23253D /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; @@ -1027,8 +1099,8 @@ 22248BB055FA811AC81C9B9D04EEEC6E /* Build configuration list for PBXNativeTarget "Pods-ErrorHandler_Tests" */ = { isa = XCConfigurationList; buildConfigurations = ( - 9EE01EE769C0B4445EB64C673CDDEC11 /* Debug */, - C6A1A82C8E467D0BE859E25CE38AAF1F /* Release */, + F2EDC57A181AEADD08D945F056BD91D7 /* Debug */, + 91F5CB6957C696E6CBECA84107ED08CE /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; @@ -1036,26 +1108,26 @@ 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */ = { isa = XCConfigurationList; buildConfigurations = ( - 7E1F3D358966F24610AD782F313B4C40 /* Debug */, - 60A7F9B4A8E92A5B16CC2AA887D9FE07 /* Release */, + 196DFA3E4A09A28224918543529A1885 /* Debug */, + B01D14FDC83DCF9D4BE53066BEA96D05 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 7ED285772333FDCC3389F33514347BAF /* Build configuration list for PBXNativeTarget "Pods-ErrorHandler_Example" */ = { + 6B2B8EC7E21CDBFF2BDA26B1B4AC4C0D /* Build configuration list for PBXNativeTarget "Alamofire" */ = { isa = XCConfigurationList; buildConfigurations = ( - 37604B635A6B9C24F2D1C22019254EB9 /* Debug */, - FC737405B5570BBBF8D3D510DF30D54F /* Release */, + 00319A2330DC739FCBFBB6CFB0C5F58D /* Debug */, + F659822BFF3B3C20B29B76B89800A5E9 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - E4A5194ABAF7A4780609E0E581DA6B54 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { + 7ED285772333FDCC3389F33514347BAF /* Build configuration list for PBXNativeTarget "Pods-ErrorHandler_Example" */ = { isa = XCConfigurationList; buildConfigurations = ( - 75BBB760DFD877E344322B54D29DFE64 /* Debug */, - F94FD07C591B17B7E61A1528AB9BCB3B /* Release */, + 7D9400A6D62CD867B80615D7DD01F8B3 /* Debug */, + 9D23FB134C7F67803BEBFBF6D7929F2F /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; diff --git a/Example/Pods/Target Support Files/Alamofire/Alamofire-Info.plist b/Example/Pods/Target Support Files/Alamofire/Alamofire-Info.plist index 0dbae30..b8fc464 100644 --- a/Example/Pods/Target Support Files/Alamofire/Alamofire-Info.plist +++ b/Example/Pods/Target Support Files/Alamofire/Alamofire-Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 4.9.1 + 5.0.2 CFBundleSignature ???? CFBundleVersion diff --git a/Example/Pods/Target Support Files/Alamofire/Alamofire.xcconfig b/Example/Pods/Target Support Files/Alamofire/Alamofire.xcconfig index 243af4f..385cdcf 100644 --- a/Example/Pods/Target Support Files/Alamofire/Alamofire.xcconfig +++ b/Example/Pods/Target Support Files/Alamofire/Alamofire.xcconfig @@ -1,5 +1,6 @@ CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Alamofire GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_LDFLAGS = $(inherited) -framework "CFNetwork" OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS PODS_BUILD_DIR = ${BUILD_DIR} PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) diff --git a/Example/Pods/Target Support Files/Pods-ErrorHandler_Example/Pods-ErrorHandler_Example-acknowledgements.markdown b/Example/Pods/Target Support Files/Pods-ErrorHandler_Example/Pods-ErrorHandler_Example-acknowledgements.markdown index 0292957..7f5ddb1 100644 --- a/Example/Pods/Target Support Files/Pods-ErrorHandler_Example/Pods-ErrorHandler_Example-acknowledgements.markdown +++ b/Example/Pods/Target Support Files/Pods-ErrorHandler_Example/Pods-ErrorHandler_Example-acknowledgements.markdown @@ -3,7 +3,7 @@ This application makes use of the following third party libraries: ## Alamofire -Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) +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 diff --git a/Example/Pods/Target Support Files/Pods-ErrorHandler_Example/Pods-ErrorHandler_Example-acknowledgements.plist b/Example/Pods/Target Support Files/Pods-ErrorHandler_Example/Pods-ErrorHandler_Example-acknowledgements.plist index e474087..79a5349 100644 --- a/Example/Pods/Target Support Files/Pods-ErrorHandler_Example/Pods-ErrorHandler_Example-acknowledgements.plist +++ b/Example/Pods/Target Support Files/Pods-ErrorHandler_Example/Pods-ErrorHandler_Example-acknowledgements.plist @@ -14,7 +14,7 @@ FooterText - Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) + 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 diff --git a/Example/Pods/Target Support Files/Pods-ErrorHandler_Example/Pods-ErrorHandler_Example.debug.xcconfig b/Example/Pods/Target Support Files/Pods-ErrorHandler_Example/Pods-ErrorHandler_Example.debug.xcconfig index 94154c7..9fb94da 100644 --- a/Example/Pods/Target Support Files/Pods-ErrorHandler_Example/Pods-ErrorHandler_Example.debug.xcconfig +++ b/Example/Pods/Target Support Files/Pods-ErrorHandler_Example/Pods-ErrorHandler_Example.debug.xcconfig @@ -3,7 +3,7 @@ FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/ErrorHandler/ErrorHandler.framework/Headers" LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' -OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "ErrorHandler" -framework "Foundation" +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "ErrorHandler" -framework "Foundation" OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS PODS_BUILD_DIR = ${BUILD_DIR} PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) diff --git a/Example/Pods/Target Support Files/Pods-ErrorHandler_Example/Pods-ErrorHandler_Example.release.xcconfig b/Example/Pods/Target Support Files/Pods-ErrorHandler_Example/Pods-ErrorHandler_Example.release.xcconfig index 94154c7..9fb94da 100644 --- a/Example/Pods/Target Support Files/Pods-ErrorHandler_Example/Pods-ErrorHandler_Example.release.xcconfig +++ b/Example/Pods/Target Support Files/Pods-ErrorHandler_Example/Pods-ErrorHandler_Example.release.xcconfig @@ -3,7 +3,7 @@ FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/ErrorHandler/ErrorHandler.framework/Headers" LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' -OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "ErrorHandler" -framework "Foundation" +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "ErrorHandler" -framework "Foundation" OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS PODS_BUILD_DIR = ${BUILD_DIR} PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) diff --git a/Example/Pods/Target Support Files/Pods-ErrorHandler_Tests/Pods-ErrorHandler_Tests.debug.xcconfig b/Example/Pods/Target Support Files/Pods-ErrorHandler_Tests/Pods-ErrorHandler_Tests.debug.xcconfig index 91d820c..bc982e0 100644 --- a/Example/Pods/Target Support Files/Pods-ErrorHandler_Tests/Pods-ErrorHandler_Tests.debug.xcconfig +++ b/Example/Pods/Target Support Files/Pods-ErrorHandler_Tests/Pods-ErrorHandler_Tests.debug.xcconfig @@ -1,7 +1,7 @@ FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/ErrorHandler" GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/ErrorHandler/ErrorHandler.framework/Headers" -OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "ErrorHandler" -framework "Foundation" +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "ErrorHandler" -framework "Foundation" PODS_BUILD_DIR = ${BUILD_DIR} PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_PODFILE_DIR_PATH = ${SRCROOT}/. diff --git a/Example/Pods/Target Support Files/Pods-ErrorHandler_Tests/Pods-ErrorHandler_Tests.release.xcconfig b/Example/Pods/Target Support Files/Pods-ErrorHandler_Tests/Pods-ErrorHandler_Tests.release.xcconfig index 91d820c..bc982e0 100644 --- a/Example/Pods/Target Support Files/Pods-ErrorHandler_Tests/Pods-ErrorHandler_Tests.release.xcconfig +++ b/Example/Pods/Target Support Files/Pods-ErrorHandler_Tests/Pods-ErrorHandler_Tests.release.xcconfig @@ -1,7 +1,7 @@ FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/ErrorHandler" GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/ErrorHandler/ErrorHandler.framework/Headers" -OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "ErrorHandler" -framework "Foundation" +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "ErrorHandler" -framework "Foundation" PODS_BUILD_DIR = ${BUILD_DIR} PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_PODFILE_DIR_PATH = ${SRCROOT}/.