diff --git a/WWCodeDFW/Podfile b/WWCodeDFW/Podfile index 0e3420b..5acec35 100644 --- a/WWCodeDFW/Podfile +++ b/WWCodeDFW/Podfile @@ -8,10 +8,10 @@ target 'WWCodeDFW' do # Pods for WWCodeDFW # SnapKit - pod 'SnapKit', '~> 3.0.0’ + pod 'SnapKit', '~> 5.0.0' # AlamoFire - pod 'Alamofire', '~> 4.5' + pod 'Alamofire', '~> 5.0.0-rc.2' # SwiftyJSON pod 'SwiftyJSON' diff --git a/WWCodeDFW/Podfile.lock b/WWCodeDFW/Podfile.lock index 40e6f25..d1792db 100644 --- a/WWCodeDFW/Podfile.lock +++ b/WWCodeDFW/Podfile.lock @@ -1,21 +1,28 @@ PODS: - - Alamofire (4.5.1) - - SnapKit (3.0.2) - - SwiftLint (0.23.0) - - SwiftyJSON (3.1.4) + - Alamofire (5.0.0-rc.2) + - SnapKit (5.0.1) + - SwiftLint (0.35.0) + - SwiftyJSON (5.0.0) DEPENDENCIES: - - Alamofire (~> 4.5) - - SnapKit (~> 3.0.0) + - Alamofire (~> 5.0.0-rc.2) + - SnapKit (~> 5.0.0) - SwiftLint - SwiftyJSON +SPEC REPOS: + https://github.com/cocoapods/specs.git: + - Alamofire + - SnapKit + - SwiftLint + - SwiftyJSON + SPEC CHECKSUMS: - Alamofire: 2d95912bf4c34f164fdfc335872e8c312acaea4a - SnapKit: 2e456761aa92d4d4067a7a5594c18769d451a8ad - SwiftLint: 6ddf7d305644c2239cb768a11d97cce804816691 - SwiftyJSON: c2842d878f95482ffceec5709abc3d05680c0220 + Alamofire: f9450d3c7f6bea2ad62e7a541c3e9b186c7991d6 + SnapKit: 97b92857e3df3a0c71833cce143274bf6ef8e5eb + SwiftLint: 5553187048b900c91aa03552807681bb6b027846 + SwiftyJSON: 36413e04c44ee145039d332b4f4e2d3e8d6c4db7 -PODFILE CHECKSUM: cf0dec5dff3c2a442745cbd029e92615aff683c5 +PODFILE CHECKSUM: 81ddc0dbf5ed57258b530b6d6fa1e55ccd268d73 -COCOAPODS: 1.3.1 +COCOAPODS: 1.7.5 diff --git a/WWCodeDFW/Pods/Alamofire/LICENSE b/WWCodeDFW/Pods/Alamofire/LICENSE index 1654602..2ec3cb1 100644 --- a/WWCodeDFW/Pods/Alamofire/LICENSE +++ b/WWCodeDFW/Pods/Alamofire/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2014-2017 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 diff --git a/WWCodeDFW/Pods/Alamofire/README.md b/WWCodeDFW/Pods/Alamofire/README.md index f190df9..da7503f 100644 --- a/WWCodeDFW/Pods/Alamofire/README.md +++ b/WWCodeDFW/Pods/Alamofire/README.md @@ -4,27 +4,30 @@ [![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)](http://twitter.com/AlamofireSF) +[![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. +**⚠️⚠️⚠️ WARNING ⚠️⚠️⚠️** This documentation is out of date during the Alamofire 5 beta process. + - [Features](#features) - [Component Libraries](#component-libraries) - [Requirements](#requirements) - [Migration Guides](#migration-guides) - [Communication](#communication) - [Installation](#installation) -- [Usage](#usage) - - **Intro -** [Making a Request](#making-a-request), [Response Handling](#response-handling), [Response Validation](#response-validation), [Response Caching](#response-caching) - - **HTTP -** [HTTP Methods](#http-methods), [Parameter Encoding](#parameter-encoding), [HTTP Headers](#http-headers), [Authentication](#authentication) - - **Large Data -** [Downloading Data to a File](#downloading-data-to-a-file), [Uploading Data to a Server](#uploading-data-to-a-server) - - **Tools -** [Statistical Metrics](#statistical-metrics), [cURL Command Output](#curl-command-output) -- [Advanced Usage](#advanced-usage) - - **URL Session -** [Session Manager](#session-manager), [Session Delegate](#session-delegate), [Request](#request) - - **Routing -** [Routing Requests](#routing-requests), [Adapting and Retrying Requests](#adapting-and-retrying-requests) - - **Model Objects -** [Custom Response Serialization](#custom-response-serialization) - - **Connection -** [Security](#security), [Network Reachability](#network-reachability) +- [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) + - **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) - [Open Radars](#open-radars) - [FAQ](#faq) - [Credits](#credits) @@ -56,82 +59,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 8.3+ -- Swift 3.1+ +- iOS 10.0+ / macOS 10.12+ / tvOS 10.0+ / watchOS 3.0+ +- Xcode 10.2+ +- Swift 5+ ## Migration Guides +- Alamofire 5.0 Migration Guide: To be written! - [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**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/alamofire). (Tag 'alamofire') -- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/alamofire). -- If you **found a bug**, open an issue. -- If you **have a feature request**, open an issue. +- If you **need help with making network requests** using Alamofire, use [Stack Overflow](https://stackoverflow.com/questions/tagged/alamofire) and tag `alamofire`. +- If you need to **find or understand an API**, check [our documentation](http://alamofire.github.io/Alamofire/) or [Apple's documentation for `URLSession`](https://developer.apple.com/documentation/foundation/url_loading_system), on top of which Alamofire is built. +- If you need **help with an Alamofire feature**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). +- If you'd like to **discuss Alamofire best practices**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). +- If you'd like to **discuss a feature request**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). +- If you **found a bug**, open an issue here on GitHub and follow the guide. The more detail the better! - If you **want to contribute**, submit a pull request. ## Installation ### CocoaPods -[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command: - -```bash -$ gem install cocoapods -``` - -> CocoaPods 1.1+ is required to build Alamofire 4.0+. - -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.5' -end -``` - -Then, run the following command: - -```bash -$ pod install +pod 'Alamofire', '~> 5.0.0-rc.2' ``` ### Carthage -[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. - -You can install Carthage with [Homebrew](http://brew.sh/) using the following command: - -```bash -$ brew update -$ brew install carthage -``` - -To integrate 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.5 +github "Alamofire/Alamofire" "5.0.0-rc.2" ``` -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 dependencies: [ - .Package(url: "https://github.com/Alamofire/Alamofire.git", majorVersion: 4) + .package(url: "https://github.com/Alamofire/Alamofire.git", from: "5.0.0-rc.2") ] ``` @@ -147,7 +121,7 @@ If you prefer not to use any of the aforementioned dependency managers, you can $ git init ``` -- Add Alamofire as a git [submodule](http://git-scm.com/docs/git-submodule) by running the following command: +- Add Alamofire as a git [submodule](https://git-scm.com/docs/git-submodule) by running the following command: ```bash $ git submodule add https://github.com/Alamofire/Alamofire.git @@ -165,7 +139,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`. @@ -173,1668 +147,29 @@ If you prefer not to use any of the aforementioned dependency managers, you can > The `Alamofire.framework` is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device. ---- - -## Usage - -### Making a Request - -```swift -import Alamofire - -Alamofire.request("https://httpbin.org/get") -``` - -### Response Handling - -Handling the `Response` of a `Request` made in Alamofire involves chaining a response handler onto the `Request`. - -```swift -Alamofire.request("https://httpbin.org/get").responseJSON { response in - print("Request: \(String(describing: response.request))") // original url request - print("Response: \(String(describing: response.response))") // http url response - print("Result: \(response.result)") // response serialization result - - if let json = response.result.value { - print("JSON: \(json)") // serialized json response - } - - if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) { - print("Data: \(utf8Text)") // original server data as UTF8 string - } -} -``` - -In the above example, the `responseJSON` handler is appended to the `Request` to be executed once the `Request` is complete. Rather than blocking execution to wait for a response from the server, a [callback](http://en.wikipedia.org/wiki/Callback_%28computer_programming%29) in the form of a closure is specified to handle the response once it's received. The result of a request is only available inside the scope of a response closure. Any execution contingent on the response or data received from the server must be done within a response closure. - -> Networking in Alamofire is done _asynchronously_. Asynchronous programming may be a source of frustration to programmers unfamiliar with the concept, but there are [very good reasons](https://developer.apple.com/library/ios/qa/qa1693/_index.html) for doing it this way. - -Alamofire contains five different response handlers by default including: - -```swift -// Response Handler - Unserialized Response -func response( - queue: DispatchQueue?, - completionHandler: @escaping (DefaultDataResponse) -> Void) - -> Self - -// Response Data Handler - Serialized into Data -func responseData( - queue: DispatchQueue?, - completionHandler: @escaping (DataResponse) -> Void) - -> Self - -// Response String Handler - Serialized into String -func responseString( - queue: DispatchQueue?, - encoding: String.Encoding?, - completionHandler: @escaping (DataResponse) -> Void) - -> Self - -// Response JSON Handler - Serialized into Any -func responseJSON( - queue: DispatchQueue?, - completionHandler: @escaping (DataResponse) -> Void) - -> Self - -// Response PropertyList (plist) Handler - Serialized into Any -func responsePropertyList( - queue: DispatchQueue?, - completionHandler: @escaping (DataResponse) -> Void)) - -> Self -``` - -None of the response handlers perform any validation of the `HTTPURLResponse` it gets back from the server. - -> For example, response status codes in the `400..<500` and `500..<600` ranges do NOT automatically trigger an `Error`. Alamofire uses [Response Validation](#response-validation) method chaining to achieve this. - -#### Response Handler - -The `response` handler does NOT evaluate any of the response data. It merely forwards on all information directly from the URL session delegate. It is the Alamofire equivalent of using `cURL` to execute a `Request`. - -```swift -Alamofire.request("https://httpbin.org/get").response { response in - print("Request: \(response.request)") - print("Response: \(response.response)") - print("Error: \(response.error)") - - if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) { - print("Data: \(utf8Text)") - } -} -``` - -> We strongly encourage you to leverage the other response serializers taking advantage of `Response` and `Result` types. - -#### Response Data Handler - -The `responseData` handler uses the `responseDataSerializer` (the object that serializes the server data into some other type) to extract the `Data` returned by the server. If no errors occur and `Data` is returned, the response `Result` will be a `.success` and the `value` will be of type `Data`. - -```swift -Alamofire.request("https://httpbin.org/get").responseData { response in - debugPrint("All Response Info: \(response)") - - if let data = response.result.value, let utf8Text = String(data: data, encoding: .utf8) { - print("Data: \(utf8Text)") - } -} -``` - -#### Response String Handler - -The `responseString` handler uses the `responseStringSerializer` to convert the `Data` returned by the server into a `String` with the specified encoding. If no errors occur and the server data is successfully serialized into a `String`, the response `Result` will be a `.success` and the `value` will be of type `String`. - -```swift -Alamofire.request("https://httpbin.org/get").responseString { response in - print("Success: \(response.result.isSuccess)") - print("Response String: \(response.result.value)") -} -``` - -> If no encoding is specified, Alamofire will use the text encoding specified in the `HTTPURLResponse` from the server. If the text encoding cannot be determined by the server response, it defaults to `.isoLatin1`. - -#### Response JSON Handler - -The `responseJSON` handler uses the `responseJSONSerializer` to convert the `Data` returned by the server into an `Any` type using the specified `JSONSerialization.ReadingOptions`. If no errors occur and the server data is successfully serialized into a JSON object, the response `Result` will be a `.success` and the `value` will be of type `Any`. - -```swift -Alamofire.request("https://httpbin.org/get").responseJSON { response in - debugPrint(response) - - if let json = response.result.value { - print("JSON: \(json)") - } -} -``` - -> All JSON serialization is handled by the `JSONSerialization` API in the `Foundation` framework. - -#### Chained Response Handlers - -Response handlers can even be chained: - -```swift -Alamofire.request("https://httpbin.org/get") - .responseString { response in - print("Response String: \(response.result.value)") - } - .responseJSON { response in - print("Response JSON: \(response.result.value)") - } -``` - -> It is important to note that using multiple response handlers on the same `Request` requires the server data to be serialized multiple times. Once for each response handler. - -#### Response Handler Queue - -Response handlers by default are executed on the main dispatch queue. However, a custom dispatch queue can be provided instead. - -```swift -let utilityQueue = DispatchQueue.global(qos: .utility) - -Alamofire.request("https://httpbin.org/get").responseJSON(queue: utilityQueue) { response in - print("Executing response handler on utility queue") -} -``` - -### Response Validation - -By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling `validate` before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type. - -#### Manual Validation - -```swift -Alamofire.request("https://httpbin.org/get") - .validate(statusCode: 200..<300) - .validate(contentType: ["application/json"]) - .responseData { response in - switch response.result { - case .success: - print("Validation Successful") - case .failure(let error): - print(error) - } - } -``` - -#### Automatic Validation - -Automatically validates status code within `200..<300` range, and that the `Content-Type` header of the response matches the `Accept` header of the request, if one is provided. - -```swift -Alamofire.request("https://httpbin.org/get").validate().responseJSON { response in - switch response.result { - case .success: - print("Validation Successful") - case .failure(let error): - print(error) - } -} -``` - -### Response Caching - -Response Caching is handled on the system framework level by [`URLCache`](https://developer.apple.com/reference/foundation/urlcache). It provides a composite in-memory and on-disk cache and lets you manipulate the sizes of both the in-memory and on-disk portions. - -> By default, Alamofire leverages the shared `URLCache`. In order to customize it, see the [Session Manager Configurations](#session-manager) section. - -### HTTP Methods - -The `HTTPMethod` enumeration lists the HTTP methods defined in [RFC 7231 §4.3](http://tools.ietf.org/html/rfc7231#section-4.3): - -```swift -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" -} -``` - -These values can be passed as the `method` argument to the `Alamofire.request` API: - -```swift -Alamofire.request("https://httpbin.org/get") // method defaults to `.get` - -Alamofire.request("https://httpbin.org/post", method: .post) -Alamofire.request("https://httpbin.org/put", method: .put) -Alamofire.request("https://httpbin.org/delete", method: .delete) -``` - -> The `Alamofire.request` method parameter defaults to `.get`. - -### Parameter Encoding - -Alamofire supports three types of parameter encoding including: `URL`, `JSON` and `PropertyList`. It can also support any custom encoding that conforms to the `ParameterEncoding` protocol. - -#### URL Encoding - -The `URLEncoding` type creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP body of the URL request. Whether the query string is set or appended to any existing URL query string or set as the HTTP body depends on the `Destination` of the encoding. The `Destination` enumeration has three cases: - -- `.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. - -The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification for how to encode collection types, 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`). - -##### GET Request With URL-Encoded Parameters - -```swift -let parameters: Parameters = ["foo": "bar"] - -// All three of these calls are equivalent -Alamofire.request("https://httpbin.org/get", parameters: parameters) // encoding defaults to `URLEncoding.default` -Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding.default) -Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding(destination: .methodDependent)) - -// https://httpbin.org/get?foo=bar -``` - -##### POST Request With URL-Encoded Parameters - -```swift -let parameters: Parameters = [ - "foo": "bar", - "baz": ["a", 1], - "qux": [ - "x": 1, - "y": 2, - "z": 3 - ] -] - -// All three of these calls are equivalent -Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters) -Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.default) -Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.httpBody) - -// HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3 -``` - -#### JSON Encoding - -The `JSONEncoding` type creates a JSON representation of the parameters object, which is set as the HTTP body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. - -##### POST Request with JSON-Encoded Parameters - -```swift -let parameters: Parameters = [ - "foo": [1,2,3], - "bar": [ - "baz": "qux" - ] -] - -// Both calls are equivalent -Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding.default) -Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding(options: [])) - -// HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}} -``` - -#### Property List Encoding - -The `PropertyListEncoding` 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`. - -#### Custom Encoding - -In the event that the provided `ParameterEncoding` types do not meet your needs, you can create your own custom encoding. Here's a quick example of how you could build a custom `JSONStringArrayEncoding` type to encode a JSON string array onto a `Request`. - -```swift -struct JSONStringArrayEncoding: ParameterEncoding { - private let array: [String] - - init(array: [String]) { - self.array = array - } - - func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { - var urlRequest = try urlRequest.asURLRequest() - - let data = try JSONSerialization.data(withJSONObject: array, options: []) - - if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { - urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") - } - - urlRequest.httpBody = data - - return urlRequest - } -} -``` - -#### Manual Parameter Encoding of a URLRequest - -The `ParameterEncoding` APIs can be used outside of making network requests. - -```swift -let url = URL(string: "https://httpbin.org/get")! -var urlRequest = URLRequest(url: url) - -let parameters: Parameters = ["foo": "bar"] -let encodedURLRequest = try URLEncoding.queryString.encode(urlRequest, with: parameters) -``` - -### HTTP Headers - -Adding a custom HTTP header to a `Request` is supported directly in the global `request` method. This makes it easy to attach HTTP headers to a `Request` that can be constantly changing. - -```swift -let headers: HTTPHeaders = [ - "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", - "Accept": "application/json" -] - -Alamofire.request("https://httpbin.org/headers", headers: headers).responseJSON { response in - debugPrint(response) -} -``` - -> For HTTP headers that do not change, it is recommended to set them on the `URLSessionConfiguration` so they are automatically applied to any `URLSessionTask` created by the underlying `URLSession`. For more information, see the [Session Manager Configurations](#session-manager) section. - -The default Alamofire `SessionManager` provides a default set of headers for every `Request`. These include: - -- `Accept-Encoding`, which defaults to `gzip;q=1.0, compress;q=0.5`, per [RFC 7230 §4.2.3](https://tools.ietf.org/html/rfc7230#section-4.2.3). -- `Accept-Language`, which defaults to up to the top 6 preferred languages on the system, formatted like `en;q=1.0`, per [RFC 7231 §5.3.5](https://tools.ietf.org/html/rfc7231#section-5.3.5). -- `User-Agent`, which contains versioning information about the current app. For example: `iOS Example/1.0 (com.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0`, per [RFC 7231 §5.5.3](https://tools.ietf.org/html/rfc7231#section-5.5.3). - -If you need to customize these headers, a custom `URLSessionConfiguration` should be created, the `defaultHTTPHeaders` property updated and the configuration applied to a new `SessionManager` instance. - -### Authentication - -Authentication is handled on the system framework level by [`URLCredential`](https://developer.apple.com/reference/foundation/nsurlcredential) and [`URLAuthenticationChallenge`](https://developer.apple.com/reference/foundation/urlauthenticationchallenge). - -**Supported Authentication Schemes** - -- [HTTP Basic](http://en.wikipedia.org/wiki/Basic_access_authentication) -- [HTTP Digest](http://en.wikipedia.org/wiki/Digest_access_authentication) -- [Kerberos](http://en.wikipedia.org/wiki/Kerberos_%28protocol%29) -- [NTLM](http://en.wikipedia.org/wiki/NT_LAN_Manager) - -#### HTTP Basic Authentication - -The `authenticate` method on a `Request` will automatically provide a `URLCredential` to a `URLAuthenticationChallenge` when appropriate: - -```swift -let user = "user" -let password = "password" - -Alamofire.request("https://httpbin.org/basic-auth/\(user)/\(password)") - .authenticate(user: user, password: password) - .responseJSON { response in - debugPrint(response) - } -``` - -Depending upon your server implementation, an `Authorization` header may also be appropriate: - -```swift -let user = "user" -let password = "password" - -var headers: HTTPHeaders = [:] - -if let authorizationHeader = Request.authorizationHeader(user: user, password: password) { - headers[authorizationHeader.key] = authorizationHeader.value -} - -Alamofire.request("https://httpbin.org/basic-auth/user/password", headers: headers) - .responseJSON { response in - debugPrint(response) - } -``` - -#### Authentication with URLCredential - -```swift -let user = "user" -let password = "password" - -let credential = URLCredential(user: user, password: password, persistence: .forSession) - -Alamofire.request("https://httpbin.org/basic-auth/\(user)/\(password)") - .authenticate(usingCredential: credential) - .responseJSON { response in - debugPrint(response) - } -``` - -> It is important to note that when using a `URLCredential` for authentication, the underlying `URLSession` will actually end up making two requests if a challenge is issued by the server. The first request will not include the credential which "may" trigger a challenge from the server. The challenge is then received by Alamofire, the credential is appended and the request is retried by the underlying `URLSession`. - -### Downloading Data to a File - -Requests made in Alamofire that fetch data from a server can download the data in-memory or on-disk. The `Alamofire.request` APIs used in all the examples so far always downloads the server data in-memory. This is great for smaller payloads because it's more efficient, but really bad for larger payloads because the download could run your entire application out-of-memory. Because of this, you can also use the `Alamofire.download` APIs to download the server data to a temporary file on-disk. - -> This will only work on `macOS` as is. Other platforms don't allow access to the filesystem outside of your app's sandbox. To download files on other platforms, see the [Download File Destination](#download-file-destination) section. - -```swift -Alamofire.download("https://httpbin.org/image/png").responseData { response in - if let data = response.result.value { - let image = UIImage(data: data) - } -} -``` - -> The `Alamofire.download` APIs should also be used if you need to download data while your app is in the background. For more information, please see the [Session Manager Configurations](#session-manager) section. - -#### Download File Destination - -You can also provide a `DownloadFileDestination` closure to move the file from the temporary directory to a final destination. Before the temporary file is actually moved to the `destinationURL`, the `DownloadOptions` specified in the closure will be executed. The two currently supported `DownloadOptions` are: - -- `.createIntermediateDirectories` - Creates intermediate directories for the destination URL if specified. -- `.removePreviousFile` - Removes a previous file from the destination URL if specified. - -```swift -let destination: DownloadRequest.DownloadFileDestination = { _, _ in - let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] - let fileURL = documentsURL.appendingPathComponent("pig.png") - - return (fileURL, [.removePreviousFile, .createIntermediateDirectories]) -} - -Alamofire.download(urlString, to: destination).response { response in - print(response) - - if response.error == nil, let imagePath = response.destinationURL?.path { - let image = UIImage(contentsOfFile: imagePath) - } -} -``` - -You can also use the suggested download destination API. - -```swift -let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory) -Alamofire.download("https://httpbin.org/image/png", to: destination) -``` - -#### Download Progress - -Many times it can be helpful to report download progress to the user. Any `DownloadRequest` can report download progress using the `downloadProgress` API. - -```swift -Alamofire.download("https://httpbin.org/image/png") - .downloadProgress { progress in - print("Download Progress: \(progress.fractionCompleted)") - } - .responseData { response in - if let data = response.result.value { - let image = UIImage(data: data) - } - } -``` - -The `downloadProgress` API also takes a `queue` parameter which defines which `DispatchQueue` the download progress closure should be called on. - -```swift -let utilityQueue = DispatchQueue.global(qos: .utility) - -Alamofire.download("https://httpbin.org/image/png") - .downloadProgress(queue: utilityQueue) { progress in - print("Download Progress: \(progress.fractionCompleted)") - } - .responseData { response in - if let data = response.result.value { - let image = UIImage(data: data) - } - } -``` - -#### Resuming a Download - -If a `DownloadRequest` is cancelled or interrupted, the underlying URL session may generate resume data for the active `DownloadRequest`. If this happens, the resume data can be re-used to restart the `DownloadRequest` where it left off. The resume data can be accessed through the download response, then reused when trying to restart the request. - -> **IMPORTANT:** 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 see this Stack Overflow [post](http://stackoverflow.com/a/39347461/1342462). - -```swift -class ImageRequestor { - private var resumeData: Data? - private var image: UIImage? - - func fetchImage(completion: (UIImage?) -> Void) { - guard image == nil else { completion(image) ; return } - - let destination: DownloadRequest.DownloadFileDestination = { _, _ in - let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] - let fileURL = documentsURL.appendingPathComponent("pig.png") - - return (fileURL, [.removePreviousFile, .createIntermediateDirectories]) - } - - let request: DownloadRequest - - if let resumeData = resumeData { - request = Alamofire.download(resumingWith: resumeData) - } else { - request = Alamofire.download("https://httpbin.org/image/png") - } - - request.responseData { response in - switch response.result { - case .success(let data): - self.image = UIImage(data: data) - case .failure: - self.resumeData = response.resumeData - } - } - } -} -``` - -### Uploading Data to a Server - -When sending relatively small amounts of data to a server using JSON or URL encoded parameters, the `Alamofire.request` APIs are usually sufficient. If you need to send much larger amounts of data from a file URL or an `InputStream`, then the `Alamofire.upload` APIs are what you want to use. - -> The `Alamofire.upload` APIs should also be used if you need to upload data while your app is in the background. For more information, please see the [Session Manager Configurations](#session-manager) section. - -#### Uploading Data - -```swift -let imageData = UIImagePNGRepresentation(image)! - -Alamofire.upload(imageData, to: "https://httpbin.org/post").responseJSON { response in - debugPrint(response) -} -``` - -#### Uploading a File - -```swift -let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov") - -Alamofire.upload(fileURL, to: "https://httpbin.org/post").responseJSON { response in - debugPrint(response) -} -``` - -#### Uploading Multipart Form Data - -```swift -Alamofire.upload( - multipartFormData: { multipartFormData in - multipartFormData.append(unicornImageURL, withName: "unicorn") - multipartFormData.append(rainbowImageURL, withName: "rainbow") - }, - to: "https://httpbin.org/post", - encodingCompletion: { encodingResult in - switch encodingResult { - case .success(let upload, _, _): - upload.responseJSON { response in - debugPrint(response) - } - case .failure(let encodingError): - print(encodingError) - } - } -) -``` - -#### Upload Progress +## Open Radars -While your user is waiting for their upload to complete, sometimes it can be handy to show the progress of the upload to the user. Any `UploadRequest` can report both upload progress and download progress of the response data using the `uploadProgress` and `downloadProgress` APIs. +The following radars have some effect on the current implementation of Alamofire. -```swift -let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov") +- [`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` -Alamofire.upload(fileURL, to: "https://httpbin.org/post") - .uploadProgress { progress in // main queue by default - print("Upload Progress: \(progress.fractionCompleted)") - } - .downloadProgress { progress in // main queue by default - print("Download Progress: \(progress.fractionCompleted)") - } - .responseJSON { response in - debugPrint(response) - } -``` +## Resolved Radars -### Statistical Metrics +The following radars have been resolved over time after being filed against the Alamofire project. -#### Timeline +- [`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 -Alamofire collects timings throughout the lifecycle of a `Request` and creates a `Timeline` object exposed as a property on all response types. - -```swift -Alamofire.request("https://httpbin.org/get").responseJSON { response in - print(response.timeline) -} -``` - -The above reports the following `Timeline` info: - -- `Latency`: 0.428 seconds -- `Request Duration`: 0.428 seconds -- `Serialization Duration`: 0.001 seconds -- `Total Duration`: 0.429 seconds - -#### URL Session Task Metrics - -In iOS and tvOS 10 and macOS 10.12, Apple introduced the new [URLSessionTaskMetrics](https://developer.apple.com/reference/foundation/urlsessiontaskmetrics) APIs. The task metrics encapsulate some fantastic statistical information about the request and response execution. The API is very similar to the `Timeline`, but provides many more statistics that Alamofire doesn't have access to compute. The metrics can be accessed through any response type. - -```swift -Alamofire.request("https://httpbin.org/get").responseJSON { response in - print(response.metrics) -} -``` - -It's important to note that these APIs are only available on iOS and tvOS 10 and macOS 10.12. Therefore, depending on your deployment target, you may need to use these inside availability checks: - -```swift -Alamofire.request("https://httpbin.org/get").responseJSON { response in - if #available(iOS 10.0, *) { - print(response.metrics) - } -} -``` - -### cURL Command Output - -Debugging platform issues can be frustrating. Thankfully, Alamofire `Request` objects conform to both the `CustomStringConvertible` and `CustomDebugStringConvertible` protocols to provide some VERY helpful debugging tools. - -#### CustomStringConvertible - -```swift -let request = Alamofire.request("https://httpbin.org/ip") - -print(request) -// GET https://httpbin.org/ip (200) -``` - -#### CustomDebugStringConvertible - -```swift -let request = Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"]) -debugPrint(request) -``` - -Outputs: - -```bash -$ curl -i \ - -H "User-Agent: Alamofire/4.0.0" \ - -H "Accept-Encoding: gzip;q=1.0, compress;q=0.5" \ - -H "Accept-Language: en;q=1.0,fr;q=0.9,de;q=0.8,zh-Hans;q=0.7,zh-Hant;q=0.6,ja;q=0.5" \ - "https://httpbin.org/get?foo=bar" -``` - ---- - -## Advanced Usage - -Alamofire is built on `URLSession` and the Foundation URL Loading System. To make the most of this framework, it is recommended that you be familiar with the concepts and capabilities of the underlying networking stack. - -**Recommended Reading** - -- [URL Loading System Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html) -- [URLSession Class Reference](https://developer.apple.com/reference/foundation/nsurlsession) -- [URLCache Class Reference](https://developer.apple.com/reference/foundation/urlcache) -- [URLAuthenticationChallenge Class Reference](https://developer.apple.com/reference/foundation/urlauthenticationchallenge) - -### Session Manager - -Top-level convenience methods like `Alamofire.request` use a default instance of `Alamofire.SessionManager`, which is configured with the default `URLSessionConfiguration`. - -As such, the following two statements are equivalent: - -```swift -Alamofire.request("https://httpbin.org/get") -``` - -```swift -let sessionManager = Alamofire.SessionManager.default -sessionManager.request("https://httpbin.org/get") -``` - -Applications can create session managers for background and ephemeral sessions, as well as new managers that customize the default session configuration, such as for default headers (`httpAdditionalHeaders`) or timeout interval (`timeoutIntervalForRequest`). - -#### Creating a Session Manager with Default Configuration - -```swift -let configuration = URLSessionConfiguration.default -let sessionManager = Alamofire.SessionManager(configuration: configuration) -``` - -#### Creating a Session Manager with Background Configuration - -```swift -let configuration = URLSessionConfiguration.background(withIdentifier: "com.example.app.background") -let sessionManager = Alamofire.SessionManager(configuration: configuration) -``` - -#### Creating a Session Manager with Ephemeral Configuration - -```swift -let configuration = URLSessionConfiguration.ephemeral -let sessionManager = Alamofire.SessionManager(configuration: configuration) -``` - -#### Modifying the Session Configuration - -```swift -var defaultHeaders = Alamofire.SessionManager.defaultHTTPHeaders -defaultHeaders["DNT"] = "1 (Do Not Track Enabled)" - -let configuration = URLSessionConfiguration.default -configuration.httpAdditionalHeaders = defaultHeaders - -let sessionManager = Alamofire.SessionManager(configuration: configuration) -``` - -> This is **not** recommended for `Authorization` or `Content-Type` headers. Instead, use the `headers` parameter in the top-level `Alamofire.request` APIs, `URLRequestConvertible` and `ParameterEncoding`, respectively. - -### Session Delegate - -By default, an Alamofire `SessionManager` instance creates a `SessionDelegate` object to handle all the various types of delegate callbacks that are generated by the underlying `URLSession`. The implementations of each delegate method handle the most common use cases for these types of calls abstracting the complexity away from the top-level APIs. However, advanced users may find the need to override the default functionality for various reasons. - -#### Override Closures - -The first way to customize the `SessionDelegate` behavior is through the use of the override closures. Each closure gives you the ability to override the implementation of the matching `SessionDelegate` API, yet still use the default implementation for all other APIs. This makes it easy to customize subsets of the delegate functionality. Here are a few examples of some of the override closures available: - -```swift -/// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`. -open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? - -/// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`. -open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)? - -/// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`. -open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? - -/// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`. -open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? -``` - -The following is a short example of how to use the `taskWillPerformHTTPRedirection` to avoid following redirects to any `apple.com` domains. - -```swift -let sessionManager = Alamofire.SessionManager(configuration: URLSessionConfiguration.default) -let delegate: Alamofire.SessionDelegate = sessionManager.delegate - -delegate.taskWillPerformHTTPRedirection = { session, task, response, request in - var finalRequest = request - - if - let originalRequest = task.originalRequest, - let urlString = originalRequest.url?.urlString, - urlString.contains("apple.com") - { - finalRequest = originalRequest - } - - return finalRequest -} -``` - -#### Subclassing - -Another way to override the default implementation of the `SessionDelegate` is to subclass it. Subclassing allows you completely customize the behavior of the API or to create a proxy for the API and still use the default implementation. Creating a proxy allows you to log events, emit notifications, provide pre and post hook implementations, etc. Here's a quick example of subclassing the `SessionDelegate` and logging a message when a redirect occurs. - -```swift -class LoggingSessionDelegate: SessionDelegate { - override func urlSession( - _ session: URLSession, - task: URLSessionTask, - willPerformHTTPRedirection response: HTTPURLResponse, - newRequest request: URLRequest, - completionHandler: @escaping (URLRequest?) -> Void) - { - print("URLSession will perform HTTP redirection to request: \(request)") - - super.urlSession( - session, - task: task, - willPerformHTTPRedirection: response, - newRequest: request, - completionHandler: completionHandler - ) - } -} -``` - -Generally speaking, either the default implementation or the override closures should provide the necessary functionality required. Subclassing should only be used as a last resort. - -> It is important to keep in mind that the `subdelegates` are initialized and destroyed in the default implementation. Be careful when subclassing to not introduce memory leaks. - -### Request - -The result of a `request`, `download`, `upload` or `stream` methods are a `DataRequest`, `DownloadRequest`, `UploadRequest` and `StreamRequest` which all inherit from `Request`. All `Request` instances are always created by an owning session manager, and never initialized directly. - -Each subclass has specialized methods such as `authenticate`, `validate`, `responseJSON` and `uploadProgress` that each return the caller instance in order to facilitate method chaining. - -Requests can be suspended, resumed and cancelled: - -- `suspend()`: Suspends the underlying task and dispatch queue. -- `resume()`: Resumes the underlying task and dispatch queue. If the owning manager does not have `startRequestsImmediately` set to `true`, the request must call `resume()` in order to start. -- `cancel()`: Cancels the underlying task, producing an error that is passed to any registered response handlers. - -### Routing Requests - -As apps grow in size, it's important to adopt common patterns as you build out your network stack. An important part of that design is how to route your requests. The Alamofire `URLConvertible` and `URLRequestConvertible` protocols along with the `Router` design pattern are here to help. - -#### URLConvertible - -Types adopting the `URLConvertible` protocol can be used to construct URLs, which are then used to construct URL requests internally. `String`, `URL`, and `URLComponents` conform to `URLConvertible` by default, allowing any of them to be passed as `url` parameters to the `request`, `upload`, and `download` methods: - -```swift -let urlString = "https://httpbin.org/post" -Alamofire.request(urlString, method: .post) - -let url = URL(string: urlString)! -Alamofire.request(url, method: .post) - -let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true)! -Alamofire.request(urlComponents, method: .post) -``` - -Applications interacting with web applications in a significant manner are encouraged to have custom types conform to `URLConvertible` as a convenient way to map domain-specific models to server resources. - -##### Type-Safe Routing - -```swift -extension User: URLConvertible { - static let baseURLString = "https://example.com" - - func asURL() throws -> URL { - let urlString = User.baseURLString + "/users/\(username)/" - return try urlString.asURL() - } -} -``` - -```swift -let user = User(username: "mattt") -Alamofire.request(user) // https://example.com/users/mattt -``` - -#### URLRequestConvertible - -Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. `URLRequest` conforms to `URLRequestConvertible` by default, allowing it to be passed into `request`, `upload`, and `download` methods directly (this is the recommended way to specify custom HTTP body for individual requests): - -```swift -let url = URL(string: "https://httpbin.org/post")! -var urlRequest = URLRequest(url: url) -urlRequest.httpMethod = "POST" - -let parameters = ["foo": "bar"] - -do { - urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: []) -} catch { - // No-op -} - -urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") - -Alamofire.request(urlRequest) -``` - -Applications interacting with web applications in a significant manner are encouraged to have custom types conform to `URLRequestConvertible` as a way to ensure consistency of requested endpoints. Such an approach can be used to abstract away server-side inconsistencies and provide type-safe routing, as well as manage authentication credentials and other state. - -##### API Parameter Abstraction - -```swift -enum Router: URLRequestConvertible { - case search(query: String, page: Int) - - static let baseURLString = "https://example.com" - static let perPage = 50 - - // MARK: URLRequestConvertible - - func asURLRequest() throws -> URLRequest { - let result: (path: String, parameters: Parameters) = { - switch self { - case let .search(query, page) where page > 0: - return ("/search", ["q": query, "offset": Router.perPage * page]) - case let .search(query, _): - return ("/search", ["q": query]) - } - }() - - let url = try Router.baseURLString.asURL() - let urlRequest = URLRequest(url: url.appendingPathComponent(result.path)) - - return try URLEncoding.default.encode(urlRequest, with: result.parameters) - } -} -``` - -```swift -Alamofire.request(Router.search(query: "foo bar", page: 1)) // https://example.com/search?q=foo%20bar&offset=50 -``` - -##### CRUD & Authorization - -```swift -import Alamofire - -enum Router: URLRequestConvertible { - case createUser(parameters: Parameters) - case readUser(username: String) - case updateUser(username: String, parameters: Parameters) - case destroyUser(username: String) - - static let baseURLString = "https://example.com" - - var method: HTTPMethod { - switch self { - case .createUser: - return .post - case .readUser: - return .get - case .updateUser: - return .put - case .destroyUser: - return .delete - } - } - - var path: String { - switch self { - case .createUser: - return "/users" - case .readUser(let username): - return "/users/\(username)" - case .updateUser(let username, _): - return "/users/\(username)" - case .destroyUser(let username): - return "/users/\(username)" - } - } - - // MARK: URLRequestConvertible - - func asURLRequest() throws -> URLRequest { - let url = try Router.baseURLString.asURL() - - var urlRequest = URLRequest(url: url.appendingPathComponent(path)) - urlRequest.httpMethod = method.rawValue - - switch self { - case .createUser(let parameters): - urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters) - case .updateUser(_, let parameters): - urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters) - default: - break - } - - return urlRequest - } -} -``` - -```swift -Alamofire.request(Router.readUser("mattt")) // GET https://example.com/users/mattt -``` - -### Adapting and Retrying Requests - -Most web services these days are behind some sort of authentication system. One of the more common ones today is OAuth. This generally involves generating an access token authorizing your application or user to call the various supported web services. While creating these initial access tokens can be laborsome, it can be even more complicated when your access token expires and you need to fetch a new one. There are many thread-safety issues that need to be considered. - -The `RequestAdapter` and `RequestRetrier` protocols were created to make it much easier to create a thread-safe authentication system for a specific set of web services. - -#### RequestAdapter - -The `RequestAdapter` protocol allows each `Request` made on a `SessionManager` to be inspected and adapted before being created. One very specific way to use an adapter is to append an `Authorization` header to requests behind a certain type of authentication. - -```swift -class AccessTokenAdapter: RequestAdapter { - private let accessToken: String - - init(accessToken: String) { - self.accessToken = accessToken - } - - func adapt(_ urlRequest: URLRequest) throws -> URLRequest { - var urlRequest = urlRequest - - if let urlString = urlRequest.url?.absoluteString, urlString.hasPrefix("https://httpbin.org") { - urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization") - } - - return urlRequest - } -} -``` - -```swift -let sessionManager = SessionManager() -sessionManager.adapter = AccessTokenAdapter(accessToken: "1234") - -sessionManager.request("https://httpbin.org/get") -``` - -#### RequestRetrier - -The `RequestRetrier` protocol allows a `Request` that encountered an `Error` while being executed to be retried. When using both the `RequestAdapter` and `RequestRetrier` protocols together, you can create credential refresh systems for OAuth1, OAuth2, Basic Auth and even exponential backoff retry policies. The possibilities are endless. Here's an example of how you could implement a refresh flow for OAuth2 access tokens. - -> **DISCLAIMER:** This is **NOT** a global `OAuth2` solution. It is merely an example demonstrating how one could use the `RequestAdapter` in conjunction with the `RequestRetrier` to create a thread-safe refresh system. - -> To reiterate, **do NOT copy** this sample code and drop it into a production application. This is merely an example. Each authentication system must be tailored to a particular platform and authentication type. - -```swift -class OAuth2Handler: RequestAdapter, RequestRetrier { - private typealias RefreshCompletion = (_ succeeded: Bool, _ accessToken: String?, _ refreshToken: String?) -> Void - - private let sessionManager: SessionManager = { - let configuration = URLSessionConfiguration.default - configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders - - return SessionManager(configuration: configuration) - }() - - private let lock = NSLock() - - private var clientID: String - private var baseURLString: String - private var accessToken: String - private var refreshToken: String - - private var isRefreshing = false - private var requestsToRetry: [RequestRetryCompletion] = [] - - // MARK: - Initialization - - public init(clientID: String, baseURLString: String, accessToken: String, refreshToken: String) { - self.clientID = clientID - self.baseURLString = baseURLString - self.accessToken = accessToken - self.refreshToken = refreshToken - } - - // MARK: - RequestAdapter - - func adapt(_ urlRequest: URLRequest) throws -> URLRequest { - if let urlString = urlRequest.url?.absoluteString, urlString.hasPrefix(baseURLString) { - var urlRequest = urlRequest - urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization") - return urlRequest - } - - return urlRequest - } - - // MARK: - RequestRetrier - - func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) { - lock.lock() ; defer { lock.unlock() } - - if let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401 { - requestsToRetry.append(completion) - - if !isRefreshing { - refreshTokens { [weak self] succeeded, accessToken, refreshToken in - guard let strongSelf = self else { return } - - strongSelf.lock.lock() ; defer { strongSelf.lock.unlock() } - - if let accessToken = accessToken, let refreshToken = refreshToken { - strongSelf.accessToken = accessToken - strongSelf.refreshToken = refreshToken - } - - strongSelf.requestsToRetry.forEach { $0(succeeded, 0.0) } - strongSelf.requestsToRetry.removeAll() - } - } - } else { - completion(false, 0.0) - } - } - - // MARK: - Private - Refresh Tokens - - private func refreshTokens(completion: @escaping RefreshCompletion) { - guard !isRefreshing else { return } - - isRefreshing = true - - let urlString = "\(baseURLString)/oauth2/token" - - let parameters: [String: Any] = [ - "access_token": accessToken, - "refresh_token": refreshToken, - "client_id": clientID, - "grant_type": "refresh_token" - ] - - sessionManager.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default) - .responseJSON { [weak self] response in - guard let strongSelf = self else { return } - - if - let json = response.result.value as? [String: Any], - let accessToken = json["access_token"] as? String, - let refreshToken = json["refresh_token"] as? String - { - completion(true, accessToken, refreshToken) - } else { - completion(false, nil, nil) - } - - strongSelf.isRefreshing = false - } - } -} -``` - -```swift -let baseURLString = "https://some.domain-behind-oauth2.com" - -let oauthHandler = OAuth2Handler( - clientID: "12345678", - baseURLString: baseURLString, - accessToken: "abcd1234", - refreshToken: "ef56789a" -) - -let sessionManager = SessionManager() -sessionManager.adapter = oauthHandler -sessionManager.retrier = oauthHandler - -let urlString = "\(baseURLString)/some/endpoint" - -sessionManager.request(urlString).validate().responseJSON { response in - debugPrint(response) -} -``` - -Once the `OAuth2Handler` is applied as both the `adapter` and `retrier` for the `SessionManager`, it will handle an invalid access token error by automatically refreshing the access token and retrying all failed requests in the same order they failed. - -> If you needed them to execute in the same order they were created, you could sort them by their task identifiers. - -The example above only checks for a `401` response code which is not nearly robust enough, but does demonstrate how one could check for an invalid access token error. In a production application, one would want to check the `realm` and most likely the `www-authenticate` header response although it depends on the OAuth2 implementation. - -Another important note is that this authentication system could be shared between multiple session managers. For example, you may need to use both a `default` and `ephemeral` session configuration for the same set of web services. The example above allows the same `oauthHandler` instance to be shared across multiple session managers to manage the single refresh flow. - -### Custom Response Serialization - -Alamofire provides built-in response serialization for data, strings, JSON, and property lists: - -```swift -Alamofire.request(...).responseData { (resp: DataResponse) in ... } -Alamofire.request(...).responseString { (resp: DataResponse) in ... } -Alamofire.request(...).responseJSON { (resp: DataResponse) in ... } -Alamofire.request(...).responsePropertyList { resp: DataResponse) in ... } -``` - -Those responses wrap deserialized *values* (Data, String, Any) or *errors* (network, validation errors), as well as *meta-data* (URL request, HTTP headers, status code, [metrics](#statistical-metrics), ...). - -You have several ways to customize all of those response elements: - -- [Response Mapping](#response-mapping) -- [Handling Errors](#handling-errors) -- [Creating a Custom Response Serializer](#creating-a-custom-response-serializer) -- [Generic Response Object Serialization](#generic-response-object-serialization) - -#### Response Mapping - -Response mapping is the simplest way to produce customized responses. It transforms the value of a response, while preserving eventual errors and meta-data. For example, you can turn a json response `DataResponse` into a response that holds an application model, such as `DataResponse`. You perform response mapping with the `DataResponse.map` method: - -```swift -Alamofire.request("https://example.com/users/mattt").responseJSON { (response: DataResponse) in - let userResponse = response.map { json in - // We assume an existing User(json: Any) initializer - return User(json: json) - } - - // Process userResponse, of type DataResponse: - if let user = userResponse.value { - print("User: { username: \(user.username), name: \(user.name) }") - } -} -``` - -When the transformation may throw an error, use `flatMap` instead: - -```swift -Alamofire.request("https://example.com/users/mattt").responseJSON { response in - let userResponse = response.flatMap { json in - try User(json: json) - } -} -``` - -Response mapping is a good fit for your custom completion handlers: - -```swift -@discardableResult -func loadUser(completionHandler: @escaping (DataResponse) -> Void) -> Alamofire.DataRequest { - return Alamofire.request("https://example.com/users/mattt").responseJSON { response in - let userResponse = response.flatMap { json in - try User(json: json) - } - - completionHandler(userResponse) - } -} - -loadUser { response in - if let user = response.value { - print("User: { username: \(user.username), name: \(user.name) }") - } -} -``` - -When the map/flatMap closure may process a big amount of data, make sure you execute it outside of the main thread: - -```swift -@discardableResult -func loadUser(completionHandler: @escaping (DataResponse) -> Void) -> Alamofire.DataRequest { - let utilityQueue = DispatchQueue.global(qos: .utility) - - return Alamofire.request("https://example.com/users/mattt").responseJSON(queue: utilityQueue) { response in - let userResponse = response.flatMap { json in - try User(json: json) - } - - DispatchQueue.main.async { - completionHandler(userResponse) - } - } -} -``` - -`map` and `flatMap` are also available for [download responses](#downloading-data-to-a-file). - -#### Handling Errors - -Before implementing custom response serializers or object serialization methods, it's important to consider how to handle any errors that may occur. There are two basic options: passing existing errors along unmodified, to be dealt with at response time; or, wrapping all errors in an `Error` type specific to your app. - -For example, here's a simple `BackendError` enum which will be used in later examples: - -```swift -enum BackendError: Error { - case network(error: Error) // Capture any underlying Error from the URLSession API - case dataSerialization(error: Error) - case jsonSerialization(error: Error) - case xmlSerialization(error: Error) - case objectSerialization(reason: String) -} -``` - -#### Creating a Custom Response Serializer - -Alamofire provides built-in response serialization for strings, JSON, and property lists, but others can be added in extensions on `Alamofire.DataRequest` and / or `Alamofire.DownloadRequest`. - -For example, here's how a response handler using [Ono](https://github.com/mattt/Ono) might be implemented: - -```swift -extension DataRequest { - static func xmlResponseSerializer() -> DataResponseSerializer { - return DataResponseSerializer { request, response, data, error in - // Pass through any underlying URLSession error to the .network case. - guard error == nil else { return .failure(BackendError.network(error: error!)) } - - // Use Alamofire's existing data serializer to extract the data, passing the error as nil, as it has - // already been handled. - let result = Request.serializeResponseData(response: response, data: data, error: nil) - - guard case let .success(validData) = result else { - return .failure(BackendError.dataSerialization(error: result.error! as! AFError)) - } - - do { - let xml = try ONOXMLDocument(data: validData) - return .success(xml) - } catch { - return .failure(BackendError.xmlSerialization(error: error)) - } - } - } - - @discardableResult - func responseXMLDocument( - queue: DispatchQueue? = nil, - completionHandler: @escaping (DataResponse) -> Void) - -> Self - { - return response( - queue: queue, - responseSerializer: DataRequest.xmlResponseSerializer(), - completionHandler: completionHandler - ) - } -} -``` - -#### Generic Response Object Serialization - -Generics can be used to provide automatic, type-safe response object serialization. - -```swift -protocol ResponseObjectSerializable { - init?(response: HTTPURLResponse, representation: Any) -} - -extension DataRequest { - func responseObject( - queue: DispatchQueue? = nil, - completionHandler: @escaping (DataResponse) -> Void) - -> Self - { - let responseSerializer = DataResponseSerializer { request, response, data, error in - guard error == nil else { return .failure(BackendError.network(error: error!)) } - - let jsonResponseSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments) - let result = jsonResponseSerializer.serializeResponse(request, response, data, nil) - - guard case let .success(jsonObject) = result else { - return .failure(BackendError.jsonSerialization(error: result.error!)) - } - - guard let response = response, let responseObject = T(response: response, representation: jsonObject) else { - return .failure(BackendError.objectSerialization(reason: "JSON could not be serialized: \(jsonObject)")) - } - - return .success(responseObject) - } - - return response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) - } -} -``` - -```swift -struct User: ResponseObjectSerializable, CustomStringConvertible { - let username: String - let name: String - - var description: String { - return "User: { username: \(username), name: \(name) }" - } - - init?(response: HTTPURLResponse, representation: Any) { - guard - let username = response.url?.lastPathComponent, - let representation = representation as? [String: Any], - let name = representation["name"] as? String - else { return nil } - - self.username = username - self.name = name - } -} -``` - -```swift -Alamofire.request("https://example.com/users/mattt").responseObject { (response: DataResponse) in - debugPrint(response) - - if let user = response.result.value { - print("User: { username: \(user.username), name: \(user.name) }") - } -} -``` - -The same approach can also be used to handle endpoints that return a representation of a collection of objects: - -```swift -protocol ResponseCollectionSerializable { - static func collection(from response: HTTPURLResponse, withRepresentation representation: Any) -> [Self] -} - -extension ResponseCollectionSerializable where Self: ResponseObjectSerializable { - static func collection(from response: HTTPURLResponse, withRepresentation representation: Any) -> [Self] { - var collection: [Self] = [] - - if let representation = representation as? [[String: Any]] { - for itemRepresentation in representation { - if let item = Self(response: response, representation: itemRepresentation) { - collection.append(item) - } - } - } - - return collection - } -} -``` - -```swift -extension DataRequest { - @discardableResult - func responseCollection( - queue: DispatchQueue? = nil, - completionHandler: @escaping (DataResponse<[T]>) -> Void) -> Self - { - let responseSerializer = DataResponseSerializer<[T]> { request, response, data, error in - guard error == nil else { return .failure(BackendError.network(error: error!)) } - - let jsonSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments) - let result = jsonSerializer.serializeResponse(request, response, data, nil) - - guard case let .success(jsonObject) = result else { - return .failure(BackendError.jsonSerialization(error: result.error!)) - } - - guard let response = response else { - let reason = "Response collection could not be serialized due to nil response." - return .failure(BackendError.objectSerialization(reason: reason)) - } - - return .success(T.collection(from: response, withRepresentation: jsonObject)) - } - - return response(responseSerializer: responseSerializer, completionHandler: completionHandler) - } -} -``` - -```swift -struct User: ResponseObjectSerializable, ResponseCollectionSerializable, CustomStringConvertible { - let username: String - let name: String - - var description: String { - return "User: { username: \(username), name: \(name) }" - } - - init?(response: HTTPURLResponse, representation: Any) { - guard - let username = response.url?.lastPathComponent, - let representation = representation as? [String: Any], - let name = representation["name"] as? String - else { return nil } - - self.username = username - self.name = name - } -} -``` - -```swift -Alamofire.request("https://example.com/users").responseCollection { (response: DataResponse<[User]>) in - debugPrint(response) - - if let users = response.result.value { - users.forEach { print("- \($0)") } - } -} -``` - -### Security - -Using a secure HTTPS connection when communicating with servers and web services is an important step in securing sensitive data. By default, Alamofire will evaluate the certificate chain provided by the server using Apple's built in validation provided by the Security framework. While this guarantees the certificate chain is valid, it does not prevent man-in-the-middle (MITM) attacks or other potential vulnerabilities. In order to mitigate MITM attacks, applications dealing with sensitive customer data or financial information should use certificate or public key pinning provided by the `ServerTrustPolicy`. - -#### ServerTrustPolicy - -The `ServerTrustPolicy` enumeration evaluates the server trust generally provided by an `URLAuthenticationChallenge` when connecting to a server over a secure HTTPS connection. - -```swift -let serverTrustPolicy = ServerTrustPolicy.pinCertificates( - certificates: ServerTrustPolicy.certificates(), - validateCertificateChain: true, - validateHost: true -) -``` - -There are many different cases of server trust evaluation giving you complete control over the validation process: - -* `performDefaultEvaluation`: Uses the default server trust evaluation while allowing you to control whether to validate the host provided by the challenge. -* `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. -* `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. -* `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 thus giving you complete control over the validation process. Use with caution. - -#### Server Trust Policy Manager - -The `ServerTrustPolicyManager` is responsible for storing an internal mapping of server trust policies to a particular host. This allows Alamofire to evaluate each host against a different server trust policy. - -```swift -let serverTrustPolicies: [String: ServerTrustPolicy] = [ - "test.example.com": .pinCertificates( - certificates: ServerTrustPolicy.certificates(), - validateCertificateChain: true, - validateHost: true - ), - "insecure.expired-apis.com": .disableEvaluation -] - -let sessionManager = SessionManager( - serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies) -) -``` - -> Make sure to keep a reference to the new `SessionManager` instance, otherwise your requests will all get cancelled when your `sessionManager` is deallocated. - -These server trust policies will result in the following behavior: - -- `test.example.com` will always use certificate pinning with certificate chain and host validation enabled thus requiring the following criteria to be met to allow the TLS handshake to succeed: - - Certificate chain MUST be valid. - - Certificate chain MUST include one of the pinned certificates. - - Challenge host MUST match the host in the certificate chain's leaf certificate. -- `insecure.expired-apis.com` will never evaluate the certificate chain and will always allow the TLS handshake to succeed. -- All other hosts will use the default evaluation provided by Apple. - -##### Subclassing Server Trust Policy Manager - -If you find yourself needing more flexible server trust policy matching behavior (i.e. wildcarded domains), then subclass the `ServerTrustPolicyManager` and override the `serverTrustPolicyForHost` method with your own custom implementation. - -```swift -class CustomServerTrustPolicyManager: ServerTrustPolicyManager { - override func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? { - var policy: ServerTrustPolicy? - - // Implement your custom domain matching behavior... - - return policy - } -} -``` - -#### Validating the Host - -The `.performDefaultEvaluation`, `.pinCertificates` and `.pinPublicKeys` server trust policies all take a `validateHost` parameter. Setting the value to `true` will cause the server trust evaluation to verify that hostname in the certificate matches the hostname of the challenge. If they do not match, evaluation will fail. A `validateHost` value of `false` will still evaluate the full certificate chain, but will not validate the hostname of the leaf certificate. - -> It is recommended that `validateHost` always be set to `true` in production environments. - -#### Validating the Certificate Chain - -Pinning certificates and public keys both have the option of validating the certificate chain using the `validateCertificateChain` parameter. By setting this value to `true`, the full certificate chain will be evaluated in addition to performing a byte equality check against the pinned certificates or public keys. A value of `false` will skip the certificate chain validation, but will still perform the byte equality check. - -There are several cases where it may make sense to disable certificate chain validation. The most common use cases for disabling validation are self-signed and expired certificates. The evaluation would always fail in both of these cases, but the byte equality check will still ensure you are receiving the certificate you expect from the server. - -> It is recommended that `validateCertificateChain` always be set to `true` in production environments. - -#### App Transport Security - -With the addition of App Transport Security (ATS) in iOS 9, it is possible that using a custom `ServerTrustPolicyManager` with several `ServerTrustPolicy` objects will have no effect. If you continuously see `CFNetwork SSLHandshake failed (-9806)` errors, you have probably run into this problem. Apple's ATS system overrides the entire challenge system unless you configure the ATS settings in your app's plist to disable enough of it to allow your app to evaluate the server trust. - -If you run into this problem (high probability with self-signed certificates), you can work around this issue by adding the following to your `Info.plist`. - -```xml - - NSAppTransportSecurity - - NSExceptionDomains - - example.com - - NSExceptionAllowsInsecureHTTPLoads - - NSExceptionRequiresForwardSecrecy - - NSIncludesSubdomains - - - NSTemporaryExceptionMinimumTLSVersion - TLSv1.2 - - - - -``` - -Whether you need to set the `NSExceptionRequiresForwardSecrecy` to `NO` depends on whether your TLS connection is using an allowed cipher suite. In certain cases, it will need to be set to `NO`. The `NSExceptionAllowsInsecureHTTPLoads` MUST be set to `YES` in order to allow the `SessionDelegate` to receive challenge callbacks. Once the challenge callbacks are being called, the `ServerTrustPolicyManager` will take over the server trust evaluation. You may also need to specify the `NSTemporaryExceptionMinimumTLSVersion` if you're trying to connect to a host that only supports TLS versions less than `1.2`. - -> It is recommended to always use valid certificates in production environments. - -### Network Reachability - -The `NetworkReachabilityManager` listens for reachability changes of hosts and addresses for both WWAN and WiFi network interfaces. - -```swift -let manager = NetworkReachabilityManager(host: "www.apple.com") - -manager?.listener = { status in - print("Network Status Changed: \(status)") -} - -manager?.startListening() -``` - -> Make sure to remember to retain the `manager` in the above example, or no status changes will be reported. -> Also, do not include the scheme in the `host` string or reachability won't function correctly. - -There are some important things to remember when using network reachability to determine what to do next. - -- **Do NOT** use Reachability to determine if a network request should be sent. - - You should **ALWAYS** send it. -- When Reachability is restored, use the event to retry failed network requests. - - Even though the network requests may still fail, this is a good moment to retry them. -- The network reachability status can be useful for determining why a network request may have failed. - - If a network request fails, it is more useful to tell the user that the network request failed due to being offline rather than a more technical error, such as "request timed out." - -> It is recommended to check out [WWDC 2012 Session 706, "Networking Best Practices"](https://developer.apple.com/videos/play/wwdc2012-706/) for more info. - ---- - -## Open Radars - -The following radars have some effect on the current implementation of Alamofire. - -- [`rdar://21349340`](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case -- `rdar://26870455` - Background URL Session Configurations do not work in the simulator -- `rdar://26849668` - Some URLProtocol APIs do not properly handle `URLRequest` - -## Resolved Radars - -The following radars have been resolved over time after being filed against the Alamofire project. - -- [`rdar://26761490`](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage (Resolved on 9/1/17 in Xcode 9 beta 6). - -## FAQ - -### What's the origin of the name Alamofire? +### 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. @@ -1845,17 +180,22 @@ 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 register 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. Donating to the ASF will enable us to: +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. +Donating to the ASF will enable us to: -- Pay our legal fees to register as a federal non-profit organization - Pay our yearly legal fees to keep the non-profit in good status - Pay for our mail servers to help us stay on top of all questions and security issues - Potentially fund test servers to make it easier for us to test the edge cases - Potentially fund developers to work on one of our projects full-time -The community adoption of the ASF libraries has been amazing. We are greatly humbled by your enthusiasm around the projects, and want to continue to do everything we can to move the needle forward. With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. If you use any of our libraries for work, see if your employers would be interested in donating. Our initial goal is to raise $1000 to get all our legal ducks in a row and kickstart this campaign. Any amount you can donate today to help us reach our goal would be greatly appreciated. +The community adoption of the ASF libraries has been amazing. +We are greatly humbled by your enthusiasm around the projects, and want to continue to do everything we can to move the needle forward. +With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. +If you use any of our libraries for work, see if your employers would be interested in donating. +Any amount you can donate today to help us reach our goal would be greatly appreciated. -Click here to lend your support to: Alamofire Software Foundation and make a donation at pledgie.com ! +[![paypal](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W34WPEE74APJQ) ## License diff --git a/WWCodeDFW/Pods/Alamofire/Source/AFError.swift b/WWCodeDFW/Pods/Alamofire/Source/AFError.swift index 585ae14..b8adbdc 100644 --- a/WWCodeDFW/Pods/Alamofire/Source/AFError.swift +++ b/WWCodeDFW/Pods/Alamofire/Source/AFError.swift @@ -1,7 +1,7 @@ // // AFError.swift // -// Copyright (c) 2014-2017 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,320 @@ 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 + /// 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 +347,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 .multipartEncodingFailed(let reason): + case let .parameterEncodingFailed(reason): return reason.underlyingError - case .responseSerializationFailed(let reason): + case let .parameterEncoderFailed(reason): + return reason.underlyingError + case let .requestAdaptationFailed(error): + return error + case let .requestRetryFailed(retryError, _): + return retryError + case let .responseValidationFailed(reason): return reason.underlyingError - default: + case let .responseSerializationFailed(reason): + return reason.underlyingError + case let .serverTrustEvaluationFailed(reason): + return reason.underlyingError + 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 .downloadedFileMoveFailed(_, let 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 +459,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 +501,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 +555,70 @@ 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, + .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 .noRequiredEvaluator, + .noCertificatesFound, + .noPublicKeysFound, + .policyApplicationFailed, + .settingAnchorCertificatesFailed, + .revocationPolicyCreationFailed, + .defaultEvaluationFailed, + .hostValidationFailed, + .revocationCheckFailed, + .certificatePinningFailed, + .publicKeyPinningFailed: return nil } } @@ -349,16 +629,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 .serverTrustEvaluationFailed: + return "Server trust evaluation failed." + 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 +678,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 +700,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 +741,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 +769,65 @@ 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 .defaultEvaluationFailed(output): + return "Default evaluation failed for host \(output.host)." + case let .hostValidationFailed(output): + return "Host validation failed for host \(output.host)." + case .revocationCheckFailed(let output, _): + return "Revocation check failed for host \(output.host)." + case .certificatePinningFailed(let host, _, _, _): + return "Certificate pinning failed for host \(host)." + case .publicKeyPinningFailed(let 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/WWCodeDFW/Pods/Alamofire/Source/Alamofire.swift b/WWCodeDFW/Pods/Alamofire/Source/Alamofire.swift index e971613..549922d 100644 --- a/WWCodeDFW/Pods/Alamofire/Source/Alamofire.swift +++ b/WWCodeDFW/Pods/Alamofire/Source/Alamofire.swift @@ -1,7 +1,7 @@ // // Alamofire.swift // -// Copyright (c) 2014-2017 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,442 +24,497 @@ import Foundation -/// 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 -} +/// Global namespace containing API for the `default` `Session` instance. +public enum AF { + /// Current Alamofire version. Necessary since SPM doesn't use dynamic libraries. Plus this will be more accurate. + static let version = "5.0.0-rc.2" -extension String: URLConvertible { - /// Returns a URL if `self` represents a valid URL string that conforms to RFC 2396 or throws an `AFError`. + // MARK: - Data Request + + /// Creates a `DataRequest` using `Session.default` to retrieve the contents of the specified `url` using the + /// `method`, `parameters`, `encoding`, and `headers` provided. /// - /// - throws: An `AFError.invalidURL` if `self` is not a valid URL string. + /// - Parameters: + /// - url: The `URLConvertible` value. + /// - method: The `HTTPMethod`, `.get` by default. + /// - parameters: The `Parameters`, `nil` by default. + /// - encoding: The `ParameterEncoding`, `URLEncoding.default` by default. + /// - headers: The `HTTPHeaders`, `nil` by default. + /// - interceptor: The `RequestInterceptor`, `nil` by default. /// - /// - 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 + /// - Returns: The created `DataRequest`. + public static func request(_ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil) -> DataRequest { + return Session.default.request(url, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers, + interceptor: interceptor) } -} - -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`. + /// Creates a `DataRequest` using `Session.default` to retrieve the contents of the specified `url` using the + /// `method`, `parameters`, `encoding`, and `headers` provided. /// - /// - throws: An `AFError.invalidURL` if `url` is `nil`. + /// - Parameters: + /// - url: The `URLConvertible` value. + /// - method: The `HTTPMethod`, `.get` by default. + /// - parameters: The `Encodable` parameters, `nil` by default. + /// - encoding: The `ParameterEncoder`, `URLEncodedFormParameterEncoder.default` by default. + /// - headers: The `HTTPHeaders`, `nil` by default. + /// - interceptor: The `RequestInterceptor`, `nil` by default. /// - /// - returns: A URL or throws an `AFError`. - public func asURL() throws -> URL { - guard let url = url else { throw AFError.invalidURL(url: self) } - return url + /// - Returns: The created `DataRequest`. + public static func request(_ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil) -> DataRequest { + return Session.default.request(url, + method: method, + parameters: parameters, + encoder: encoder, + headers: headers, + interceptor: interceptor) } -} - -// 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. + /// Creates a `DataRequest` using `Session.default` to execute the specified `urlRequest`. /// - /// - throws: An `Error` if the underlying `URLRequest` is `nil`. + /// - Parameters: + /// - urlRequest: The `URLRequestConvertible` value. + /// - interceptor: The `RequestInterceptor`, `nil` by default. /// - /// - 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 } -} + /// - Returns: The created `DataRequest`. + public static func request(_ urlRequest: URLRequestConvertible, interceptor: RequestInterceptor? = nil) -> DataRequest { + return Session.default.request(urlRequest, interceptor: interceptor) + } -// MARK: - + // MARK: - Download Request -extension URLRequest { - /// Creates an instance with the specified `method`, `urlString` and `headers`. + /// Creates a `DownloadRequest` using `Session.default` to download the contents of the specified `url` to + /// the provided `destination` using the `method`, `parameters`, `encoding`, and `headers` provided. /// - /// - parameter url: The URL. - /// - parameter method: The HTTP method. - /// - parameter headers: The HTTP headers. `nil` by default. + /// If `destination` is not specified, the download will be moved to a temporary location determined by Alamofire. /// - /// - 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) - } - } + /// - Parameters: + /// - url: The `URLConvertible` value. + /// - method: The `HTTPMethod`, `.get` by default. + /// - parameters: The `Parameters`, `nil` by default. + /// - encoding: The `ParameterEncoding`, `URLEncoding.default` by default. + /// - headers: The `HTTPHeaders`, `nil` by default. + /// - interceptor: The `RequestInterceptor`, `nil` by default. + /// - destination: The `DownloadRequest.Destination` closure used the determine the destination of the + /// downloaded file. `nil` by default. + /// + /// - Returns: The created `DownloadRequest`. + public static func download(_ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { + return Session.default.download(url, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers, + interceptor: interceptor, + to: destination) } - func adapt(using adapter: RequestAdapter?) throws -> URLRequest { - guard let adapter = adapter else { return self } - return try adapter.adapt(self) + /// Creates a `DownloadRequest` using `Session.default` to download the contents of the specified `url` to the + /// provided `destination` using the `method`, encodable `parameters`, `encoder`, and `headers` provided. + /// + /// - Note: If `destination` is not specified, the download will be moved to a temporary location determined by + /// Alamofire. + /// + /// - Parameters: + /// - url: The `URLConvertible` value. + /// - method: The `HTTPMethod`, `.get` by default. + /// - parameters: The `Encodable` parameters, `nil` by default. + /// - encoder: The `ParameterEncoder`, `URLEncodedFormParameterEncoder.default` by default. + /// - headers: The `HTTPHeaders`, `nil` by default. + /// - interceptor: The `RequestInterceptor`, `nil` by default. + /// - destination: The `DownloadRequest.Destination` closure used the determine the destination of the + /// downloaded file. `nil` by default. + /// + /// - Returns: The created `DownloadRequest`. + public static func download(_ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { + return Session.default.download(url, + method: method, + parameters: parameters, + encoder: encoder, + headers: headers, + interceptor: interceptor, + to: destination) } -} -// MARK: - Data Request + // MARK: URLRequest -/// 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 + /// Creates a `DownloadRequest` using `Session.default` to execute the specified `urlRequest` and download + /// the result to the provided `destination`. + /// + /// - Parameters: + /// - urlRequest: The `URLRequestConvertible` value. + /// - interceptor: The `RequestInterceptor`, `nil` by default. + /// - destination: The `DownloadRequest.Destination` closure used the determine the destination of the + /// downloaded file. `nil` by default. + /// + /// - Returns: The created `DownloadRequest`. + public static func download(_ urlRequest: URLRequestConvertible, + interceptor: RequestInterceptor? = nil, + to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { + return Session.default.download(urlRequest, interceptor: interceptor, to: destination) + } -// MARK: File + // MARK: Resume Data -/// 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 `DownloadRequest` using the `Session.default` from the `resumeData` produced from a previous + /// `DownloadRequest` cancellation to retrieve the contents of the original request and save them to the `destination`. + /// + /// - Note: If `destination` is not specified, the download will be moved to a temporary location determined by + /// Alamofire. + /// + /// - 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: + /// - resumeData: The resume `Data`. This is an opaque blob produced by `URLSessionDownloadTask` when a task is + /// cancelled. See [Apple's documentation](https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel) + /// for more information. + /// - interceptor: The `RequestInterceptor`, `nil` by default. + /// - destination: The `DownloadRequest.Destination` closure used to determine the destination of the downloaded + /// file. `nil` by default. + /// + /// - Returns: The created `DownloadRequest`. + public static func download(resumingWith resumeData: Data, + interceptor: RequestInterceptor? = nil, + to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { + return Session.default.download(resumingWith: resumeData, interceptor: interceptor, to: destination) + } -/// 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: - Upload Request -// MARK: Data + // 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) -} + /// 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`. + public static func upload(_ data: Data, + to convertible: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + return Session.default.upload(data, + to: convertible, + method: method, + headers: headers, + interceptor: interceptor, + fileManager: fileManager) + } -// MARK: InputStream + /// 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`. + public static func upload(_ data: Data, + with convertible: URLRequestConvertible, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + return Session.default.upload(data, with: convertible, interceptor: interceptor, fileManager: fileManager) + } -/// 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) -} + // MARK: File -/// 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) -} + /// 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`. + public static func upload(_ fileURL: URL, + to convertible: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + return Session.default.upload(fileURL, + to: convertible, + method: method, + headers: headers, + interceptor: interceptor, + fileManager: fileManager) + } -// MARK: MultipartFormData + /// 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`. + public static func upload(_ fileURL: URL, + with convertible: URLRequestConvertible, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + return Session.default.upload(fileURL, with: convertible, interceptor: interceptor, fileManager: fileManager) + } -/// 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 - ) -} + // MARK: InputStream -/// 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 - ) -} + /// 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`. + public static func upload(_ stream: InputStream, + to convertible: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + return Session.default.upload(stream, + to: convertible, + method: method, + headers: headers, + interceptor: interceptor, + fileManager: fileManager) + } -#if !os(watchOS) + /// 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`. + public static func upload(_ stream: InputStream, + with convertible: URLRequestConvertible, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + return Session.default.upload(stream, with: convertible, interceptor: interceptor, fileManager: fileManager) + } -// MARK: - Stream Request + // MARK: MultipartFormData -// MARK: Hostname and Port + /// 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`. + public static 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 { + return Session.default.upload(multipartFormData: multipartFormData, + to: url, + usingThreshold: encodingMemoryThreshold, + method: method, + headers: headers, + interceptor: interceptor, + fileManager: fileManager) + } -/// 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) -} + /// 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`. + public static func upload(multipartFormData: @escaping (MultipartFormData) -> Void, + with request: URLRequestConvertible, + usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + return Session.default.upload(multipartFormData: multipartFormData, + with: request, + usingThreshold: encodingMemoryThreshold, + interceptor: interceptor, + fileManager: fileManager) + } -// MARK: NetService + /// 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`. + public static 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 { + return Session.default.upload(multipartFormData: multipartFormData, + to: url, + usingThreshold: encodingMemoryThreshold, + method: method, + headers: headers, + interceptor: interceptor, + fileManager: fileManager) + } -/// 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) + /// 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`. + public static func upload(multipartFormData: MultipartFormData, + with request: URLRequestConvertible, + usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + return Session.default.upload(multipartFormData: multipartFormData, + with: request, + usingThreshold: encodingMemoryThreshold, + interceptor: interceptor, + fileManager: fileManager) + } } - -#endif diff --git a/WWCodeDFW/Pods/Alamofire/Source/AlamofireExtended.swift b/WWCodeDFW/Pods/Alamofire/Source/AlamofireExtended.swift new file mode 100644 index 0000000..3009e8b --- /dev/null +++ b/WWCodeDFW/Pods/Alamofire/Source/AlamofireExtended.swift @@ -0,0 +1,58 @@ +// +// 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 metatype of any extended type. + let type: ExtendedType + + 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/WWCodeDFW/Pods/Alamofire/Source/CachedResponseHandler.swift b/WWCodeDFW/Pods/Alamofire/Source/CachedResponseHandler.swift new file mode 100644 index 0000000..b6e0d4b --- /dev/null +++ b/WWCodeDFW/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/WWCodeDFW/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift b/WWCodeDFW/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift index 9031395..10cd273 100644 --- a/WWCodeDFW/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift +++ b/WWCodeDFW/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift @@ -1,7 +1,7 @@ // // DispatchQueue+Alamofire.swift // -// Copyright (c) 2014-2017 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/WWCodeDFW/Pods/Alamofire/Source/EventMonitor.swift b/WWCodeDFW/Pods/Alamofire/Source/EventMonitor.swift new file mode 100644 index 0000000..cc11133 --- /dev/null +++ b/WWCodeDFW/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 certificat 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` failes 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.componsiteEventMonitor", 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/WWCodeDFW/Pods/Alamofire/Source/HTTPHeaders.swift b/WWCodeDFW/Pods/Alamofire/Source/HTTPHeaders.swift new file mode 100644 index 0000000..c01e89b --- /dev/null +++ b/WWCodeDFW/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 supporte 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/\(AF.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/WWCodeDFW/Pods/Alamofire/Source/HTTPMethod.swift b/WWCodeDFW/Pods/Alamofire/Source/HTTPMethod.swift new file mode 100644 index 0000000..4867c1e --- /dev/null +++ b/WWCodeDFW/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/WWCodeDFW/Pods/Alamofire/Source/MultipartFormData.swift b/WWCodeDFW/Pods/Alamofire/Source/MultipartFormData.swift index ba02d24..4ef54aa 100644 --- a/WWCodeDFW/Pods/Alamofire/Source/MultipartFormData.swift +++ b/WWCodeDFW/Pods/Alamofire/Source/MultipartFormData.swift @@ -1,7 +1,7 @@ // // MultipartFormData.swift // -// Copyright (c) 2014-2017 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)" @@ -100,69 +102,35 @@ open class MultipartFormData { /// The boundary used to separate the body parts in the encoded form data. public let boundary: String + let fileManager: FileManager + private var bodyParts: [BodyPart] private var bodyPartError: AFError? private let streamBufferSize: Int // MARK: - Lifecycle - /// Creates 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/WWCodeDFW/Pods/Alamofire/Source/MultipartUpload.swift b/WWCodeDFW/Pods/Alamofire/Source/MultipartUpload.swift new file mode 100644 index 0000000..4772c30 --- /dev/null +++ b/WWCodeDFW/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/WWCodeDFW/Pods/Alamofire/Source/NetworkReachabilityManager.swift b/WWCodeDFW/Pods/Alamofire/Source/NetworkReachabilityManager.swift index cdb5a02..d2c4338 100644 --- a/WWCodeDFW/Pods/Alamofire/Source/NetworkReachabilityManager.swift +++ b/WWCodeDFW/Pods/Alamofire/Source/NetworkReachabilityManager.swift @@ -1,7 +1,7 @@ // // NetworkReachabilityManager.swift // -// Copyright (c) 2014-2017 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,113 +22,129 @@ // 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 /// network requests when a connection is established. It should not be used to prevent a user from initiating a network /// request, as it's possible that an initial request may be required to establish reachability. -public class NetworkReachabilityManager { +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. - public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi } + open var isReachable: Bool { return isReachableOnCellular || isReachableOnEthernetOrWiFi } - /// Whether the network is currently reachable over the WWAN interface. - public 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. - public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .reachable(.ethernetOrWiFi) } + open var isReachableOnEthernetOrWiFi: Bool { return status == .reachable(.ethernetOrWiFi) } - /// The current network reachability status. - public var networkReachabilityStatus: NetworkReachabilityStatus { - guard let flags = self.flags else { return .unknown } - return networkReachabilityStatusForFlags(flags) - } + /// `DispatchQueue` on which reachability will update. + public let reachabilityQueue = DispatchQueue(label: "org.alamofire.reachabilityQueue") - /// The dispatch queue to execute the `listener` closure on. - public var listenerQueue: DispatchQueue = DispatchQueue.main - - /// A closure executed when the network reachability status changes. - public var listener: Listener? - - private var flags: SCNetworkReachabilityFlags? { + /// 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 + } + + /// The current network reachability status. + open var status: NetworkReachabilityStatus { + return flags.map(NetworkReachabilityStatus.init) ?? .unknown + } - return nil + /// 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 - private 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 - self.previousFlags = SCNetworkReachabilityFlags() } deinit { @@ -139,67 +155,77 @@ public 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 - public func startListening() -> Bool { - var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) - context.info = Unmanaged.passUnretained(self).toOpaque() - - let callbackEnabled = SCNetworkReachabilitySetCallback( - reachability, - { (_, flags, info) in - let reachability = Unmanaged.fromOpaque(info!).takeUnretainedValue() - reachability.notifyListener(flags) - }, - &context - ) - - let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue) - - listenerQueue.async { - self.previousFlags = SCNetworkReachabilityFlags() - self.notifyListener(self.flags ?? SCNetworkReachabilityFlags()) + open func startListening(onQueue queue: DispatchQueue = .main, + onUpdatePerforming listener: @escaping Listener) -> Bool { + stopListening() + + mutableState.write { state in + state.listenerQueue = queue + state.listener = listener } - return callbackEnabled && queueEnabled + 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 } + + let instance = Unmanaged.fromOpaque(info).takeUnretainedValue() + instance.notifyListener(flags) + } + + let queueAdded = SCNetworkReachabilitySetDispatchQueue(reachability, reachabilityQueue) + let callbackAdded = SCNetworkReachabilitySetCallback(reachability, callback, &context) + + // Manually call listener to give initial state, since the framework may not. + if let currentFlags = flags { + reachabilityQueue.async { + self.notifyListener(currentFlags) + } + } + + return callbackAdded && queueAdded } /// Stops listening for changes in network reachability status. - public func stopListening() { + 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 + let newStatus = NetworkReachabilityStatus(flags) - func networkReachabilityStatusForFlags(_ flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus { - guard isNetworkReachable(with: flags) else { return .notReachable } + mutableState.write { state in + guard state.previousStatus != newStatus else { return } - var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi) + state.previousStatus = newStatus - #if os(iOS) - if flags.contains(.isWWAN) { networkStatus = .reachable(.wwan) } - #endif - - return networkStatus - } - - 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) - - return isReachable && (!needsConnection || canConnectWithoutUserInteraction) + let listener = state.listener + state.listenerQueue?.async { listener?(newStatus) } + } } } @@ -207,27 +233,34 @@ public 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/WWCodeDFW/Pods/Alamofire/Source/Notifications.swift b/WWCodeDFW/Pods/Alamofire/Source/Notifications.swift index df41505..4a4b25a 100644 --- a/WWCodeDFW/Pods/Alamofire/Source/Notifications.swift +++ b/WWCodeDFW/Pods/Alamofire/Source/Notifications.swift @@ -1,7 +1,7 @@ // // Notifications.swift // -// Copyright (c) 2014-2017 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,29 +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") +} - /// 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") +// MARK: - - /// 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") +extension Notification { + /// The `Request` contained by the instance's `userInfo`, `nil` otherwise. + public var request: Request? { + return userInfo?[String.requestKey] as? Request + } + + /// Convenience initializer for a `Notification` containing a `Request` payload. + /// + /// - Parameters: + /// - name: The name of the notification. + /// - request: The `Request` payload. + init(name: Notification.Name, request: Request) { + self.init(name: name, object: nil, userInfo: [String.requestKey: request]) } } -// 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) + } + + public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) { + NotificationCenter.default.postNotification(named: Request.didCompleteTaskNotification, with: request) } } diff --git a/WWCodeDFW/Pods/Alamofire/Source/OperationQueue+Alamofire.swift b/WWCodeDFW/Pods/Alamofire/Source/OperationQueue+Alamofire.swift new file mode 100644 index 0000000..b06a0cc --- /dev/null +++ b/WWCodeDFW/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/WWCodeDFW/Pods/Alamofire/Source/ParameterEncoder.swift b/WWCodeDFW/Pods/Alamofire/Source/ParameterEncoder.swift new file mode 100644 index 0000000..1e5c70a --- /dev/null +++ b/WWCodeDFW/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/WWCodeDFW/Pods/Alamofire/Source/ParameterEncoding.swift b/WWCodeDFW/Pods/Alamofire/Source/ParameterEncoding.swift index dabb562..fbf1701 100644 --- a/WWCodeDFW/Pods/Alamofire/Source/ParameterEncoding.swift +++ b/WWCodeDFW/Pods/Alamofire/Source/ParameterEncoding.swift @@ -1,7 +1,7 @@ // // ParameterEncoding.swift // -// Copyright (c) 2014-2017 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. - /// - /// - parameter urlRequest: The request to have parameters applied. - /// - parameter parameters: The parameters to apply. + /// Creates a `URLRequest` by encoding parameters and applying them on the passed request. /// - /// - throws: An `AFError.parameterEncodingFailed` error if encoding fails. + /// - Parameters: + /// - urlRequest: `URLRequestConvertible` value onto which parameters will be encoded. + /// - parameters: `Parameters` to encode onto the request. /// - /// - returns: The encoded request. + /// - Returns: The encoded `URLRequest`. + /// - Throws: Any `Error` produced during parameter encoding. func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest } @@ -64,32 +47,77 @@ public protocol ParameterEncoding { /// the HTTP body depends on the destination of the encoding. /// /// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to -/// `application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification for how to encode -/// collection types, 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`). +/// `application/x-www-form-urlencoded; charset=utf-8`. +/// +/// There is no published specification for how to encode collection types. By default the convention of appending +/// `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for +/// nested dictionary values (`foo[bar]=baz`) is used. Optionally, `ArrayEncoding` can be used to omit the +/// square brackets appended to array keys. +/// +/// `BoolEncoding` can be used to configure how boolean values are encoded. The default behavior is to encode +/// `true` as 1 and `false` as 0. public struct URLEncoding: ParameterEncoding { - // MARK: Helper Types /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the /// resulting URL request. - /// - /// - 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. + public enum ArrayEncoding { + /// An empty set of square brackets is appended to the key for every value. This is the default behavior. + case brackets + /// No brackets are appended. The key is encoded as is. + case noBrackets + + func encode(key: String) -> String { + switch self { + case .brackets: + return "\(key)[]" + case .noBrackets: + return key + } + } + } + + /// Configures how `Bool` parameters are encoded. + public enum BoolEncoding { + /// Encode `true` as `1` and `false` as `0`. This is the default behavior. + case numeric + /// Encode `true` and `false` as string literals. + case literal + + func encode(value: Bool) -> String { + switch self { + case .numeric: + return value ? "1" : "0" + case .literal: + return value ? "true" : "false" + } + } } // MARK: Properties - /// Returns a default `URLEncoding` instance. + /// 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) } @@ -99,33 +127,37 @@ public struct URLEncoding: ParameterEncoding { /// The destination defining where the encoded query string is to be applied to the URL request. public let destination: Destination + /// The encoding to use for `Array` parameters. + public let arrayEncoding: ArrayEncoding + + /// The encoding to use for `Bool` parameters. + public let boolEncoding: BoolEncoding + // MARK: Initialization - /// Creates a `URLEncoding` instance using the specified destination. + /// Creates an instance using the specified parameters. /// - /// - parameter destination: The destination defining where the encoded query string is to be applied. - /// - /// - returns: The new `URLEncoding` instance. - public init(destination: Destination = .methodDependent) { + /// - Parameters: + /// - destination: `Destination` defining where the encoded query string will be applied. `.methodDependent` by + /// default. + /// - arrayEncoding: `ArrayEncoding` to use. `.brackets` by default. + /// - boolEncoding: `BoolEncoding` to use. `.numeric` by default. + public init(destination: Destination = .methodDependent, + arrayEncoding: ArrayEncoding = .brackets, + boolEncoding: BoolEncoding = .numeric) { self.destination = destination + self.arrayEncoding = arrayEncoding + self.boolEncoding = boolEncoding } // MARK: Encoding - /// 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) } @@ -140,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)] = [] @@ -161,16 +194,16 @@ public struct URLEncoding: ParameterEncoding { } } else if let array = value as? [Any] { for value in array { - components += queryComponents(fromKey: "\(key)[]", value: value) + components += queryComponents(fromKey: arrayEncoding.encode(key: key), value: value) } } else if let value = value as? NSNumber { if value.isBool { - components.append((escape(key), escape((value.boolValue ? "1" : "0")))) + components.append((escape(key), escape(boolEncoding.encode(value: value.boolValue)))) } else { components.append((escape(key), escape("\(value)"))) } } else if let bool = value as? Bool { - components.append((escape(key), escape((bool ? "1" : "0")))) + components.append((escape(key), escape(boolEncoding.encode(value: bool)))) } else { components.append((escape(key), escape("\(value)"))) } @@ -178,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 { @@ -243,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: - @@ -268,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. @@ -282,25 +249,15 @@ public struct JSONEncoding: ParameterEncoding { // MARK: Initialization - /// Creates a `JSONEncoding` instance using the specified options. - /// - /// - parameter options: The options for writing the parameters as JSON data. + /// Creates an instance using the specified `WritingOptions`. /// - /// - 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() @@ -321,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. + /// Encodes any JSON compatible object into a `URLRequest`. /// - /// - parameter urlRequest: The request to apply the JSON object to. - /// - parameter jsonObject: The JSON object to apply to the request. + /// - 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. /// - /// - throws: An `Error` if the encoding process encounters an error. - /// - /// - 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() @@ -352,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/WWCodeDFW/Pods/Alamofire/Source/Protector.swift b/WWCodeDFW/Pods/Alamofire/Source/Protector.swift new file mode 100644 index 0000000..5987483 --- /dev/null +++ b/WWCodeDFW/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 transtion 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/WWCodeDFW/Pods/Alamofire/Source/RedirectHandler.swift b/WWCodeDFW/Pods/Alamofire/Source/RedirectHandler.swift new file mode 100644 index 0000000..5f35a92 --- /dev/null +++ b/WWCodeDFW/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 task whose request resulted in a redirect. + /// - request: The URL request object to the new location specified by the redirect response. + /// - response: The response containing the server's response to the original request. + /// - completion: The closure to execute containing the new request, a modified request, 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/WWCodeDFW/Pods/Alamofire/Source/Request.swift b/WWCodeDFW/Pods/Alamofire/Source/Request.swift index d93c52d..e640f61 100644 --- a/WWCodeDFW/Pods/Alamofire/Source/Request.swift +++ b/WWCodeDFW/Pods/Alamofire/Source/Request.swift @@ -1,7 +1,7 @@ // // Request.swift // -// Copyright (c) 2014-2017 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,818 @@ 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` prividing 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 threadsafe 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. /// - /// - parameter urlRequest: The URL request to adapt. + /// - 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 a initial `URLRequest` has been created on behalf of the instance. If a `RequestAdapter` is active, + /// the `URLRequest` will be adapted before being issued. /// - /// - throws: An `Error` if the adaptation encounters an error. + /// - 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`. /// - /// - returns: The adapted `URLRequest`. - func adapt(_ urlRequest: URLRequest) throws -> URLRequest -} + /// - Note: Triggers retry. + /// + /// - Parameter error: `AFError` thrown from the failed creation. + func didFailToCreateURLRequest(with error: AFError) { + self.error = error -// MARK: - + eventMonitor?.request(self, didFailToCreateURLRequestWithError: error) -/// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not. -public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void + callCURLHandlerIfNecessary() -/// 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. + retryOrFinish(error: error) + } + + /// Called when a `RequestAdapter` has successfully adapted 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. + /// - 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) } + + eventMonitor?.request(self, didAdaptInitialRequest: initialRequest, to: adaptedRequest) + } + + /// Called when a `RequestAdapter` fails to adapt a `URLRequest`. /// - /// - 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) -} + /// - Note: Triggers retry. + /// + /// - Parameters: + /// - request: The `URLRequest` the adapter was called with. + /// - error: The `AFError` returned by the `RequestAdapter`. + func didFailToAdaptURLRequest(_ request: URLRequest, withError error: AFError) { + 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) + } - enum RequestTask { - case data(TaskConvertible?, URLSessionTask?) - case download(TaskConvertible?, URLSessionTask?) - case upload(TaskConvertible?, URLSessionTask?) - case stream(TaskConvertible?, URLSessionTask?) + /// 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) } - // MARK: Properties + /// 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) } - /// The delegate for the underlying task. - open internal(set) var delegate: TaskDelegate { - get { - taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } - return taskDelegate + 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) + + retryOrFinish(error: self.error) + } + + /// Called when the `RequestDelegate` is going to retry this `Request`. Calls `reset()`. + func prepareForRetry() { + protectedMutableState.write { $0.retryCount += 1 } + + reset() + + eventMonitor?.requestIsRetrying(self) + } + + /// Called to determine whether retry will be triggered for the particular error, or whether the instance should + /// call `finish()`. + /// + /// - Parameter error: The possible `AFError` which may trigger retry. + func retryOrFinish(error: AFError?) { + 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. + /// + /// - 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() } + } } } - /// 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. - open 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() } } - // MARK: Authentication + /// Notifies the `Request` that the response serializer is complete. + /// + /// - Parameter completion: The completion handler provided with the response serilizer, called when all serializers + /// are complete. + func responseSerializerDidComplete(completion: @escaping () -> Void) { + protectedMutableState.write { $0.responseSerializerCompletions.append(completion) } + processNextResponseSerializer() + } + + /// Resets all task and response serializer related state for retry. + func reset() { + error = nil + + uploadProgress.totalUnitCount = 0 + uploadProgress.completedUnitCount = 0 + downloadProgress.totalUnitCount = 0 + downloadProgress.completedUnitCount = 0 - /// Associates an HTTP Basic credential with the request. + 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. /// - /// - parameter credential: The credential. + /// - Parameters: + /// - request: `URLRequest` to use to create the `URLSessionTask`. + /// - session: `URLSession` which creates the `URLSessionTask`. + /// + /// - Returns: The `URLSessionTask` created. + func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + fatalError("Subclasses must override.") + } + + // MARK: - Public API + + // These APIs are callable from any queue. + + // MARK: State + + /// Cancels the instance. Once cancelled, a `Request` can no longer be resumed or suspended. /// - /// - returns: The 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. + /// Suspends the instance. /// - /// - parameter user: The user. - /// - parameter password: The password. - /// - /// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise. - open static 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,31 +843,26 @@ 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) - struct Requestable: TaskConvertible { - let urlRequest: URLRequest + /// 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?) +} - 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) - } - } - } +// MARK: - Subclasses - // MARK: Properties +// MARK: - DataRequest - /// 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 } +/// `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 } - return nil - } + /// Protected storage for the `Data` read by the instance. + private var protectedData: Protector = Protector(nil) - /// The progress of fetching the response data from the server for the request. - open var progress: Progress { return dataDelegate.progress } + /// 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) + } - var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate } + override func reset() { + super.reset() - // MARK: Stream + protectedData.directValue = nil + } - /// 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`. + /// 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) + public func validate(_ validation: @escaping Validation) -> Self { + let validator: () -> Void = { [unowned self] in + guard self.error == nil, let response = self.response else { return } + + let result = validation(self.request, response, self.data) + + if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) } + + self.eventMonitor?.request(self, + didValidateRequest: self.request, + response: response, + data: self.data, + withResult: result) + } + + protectedValidators.append(validator) + return self } } -// MARK: - - -/// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`. -open class DownloadRequest: Request { +// MARK: - DownloadRequest - // MARK: Helper Types +/// `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 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 - - /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified. - public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0) + public let rawValue: Int - /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified. - public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1) - - /// 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 } } + // MARK: Destination + /// A closure executed once a download request 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) - - enum Downloadable: TaskConvertible { - case request(URLRequest) - case resumeData(Data) + public typealias Destination = (_ temporaryURL: URL, + _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options) - func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { - do { - let task: URLSessionTask + // MARK: Destination - 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) } - } + /// 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 - return task - } catch { - throw AdaptError(error: error) - } + return (url, options) } } - // MARK: Properties - - /// The request sent or to be sent to the server. - open override var request: URLRequest? { - if let request = super.request { return request } + /// 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) - if let downloadable = originalTask as? Downloadable, case let .request(urlRequest) = downloadable { - return urlRequest - } + return (destination, []) + } - return nil + /// 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) } - /// The resume data of the underlying download task if available after a failure. - open var resumeData: Data? { return downloadDelegate.resumeData } + // MARK: Mutable State - /// The progress of downloading the response data from the server for the request. - open var progress: Progress { return downloadDelegate.progress } + /// 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? + } - var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate } + /// Protected mutable state specific to `DownloadRequest`. + private let protectedDownloadMutableState: Protector = Protector(DownloadRequestMutableState()) - // MARK: State + /// 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 } + + // MARK: Initial State - /// Cancels the request. - open override func cancel() { - downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 } + /// `Downloadable` value used for this instance. + public let downloadable: Downloadable + /// The `Destination` to which the downloaded file is moved. + let destination: Destination - NotificationCenter.default.post( - name: Notification.Name.Task.DidCancel, - object: self, - userInfo: [Notification.Key.Task: task as Any] - ) + /// 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) } - // MARK: Progress + 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. + protectedDownloadMutableState.write { + $0.resumeData = nil + $0.fileURL = nil + } + } + + /// Called when a download has finished. /// - /// - 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: + /// - 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 + } + } + + /// Updates the `downloadProgress` using the provided values. /// - /// - returns: The request. - @discardableResult - open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { - downloadDelegate.progressHandler = (closure, queue) - return self + /// - 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: Destination + override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + return session.downloadTask(with: request) + } - /// 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. + /// Creates a `URLSessionTask` from the provided resume data. /// - /// - parameter directory: The search path directory. `.DocumentDirectory` by default. - /// - parameter domain: The search path domain mask. `.UserDomainMask` by default. + /// - Parameters: + /// - data: `Data` used to resume the download. + /// - session: `URLSession` used to create the `URLSessionTask`. /// - /// - 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) + /// - Returns: The `URLSessionTask` created. + public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask { + return session.downloadTask(withResumeData: data) + } - if !directoryURLs.isEmpty { - return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), []) - } + /// 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 + public override func cancel() -> Self { + return cancel(producingResumeData: false) + } - return (temporaryURL, []) - } + /// 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) } -} -// MARK: - + /// Cancels the instance while producing resume data. Once cancelled, a `DownloadRequest` can no longer be resumed + /// or suspended. + /// + /// - Note: The resume data passed to the completion handler will also be available on the instance's `resumeData` + /// property. + /// + /// - Parameter completionHandler: The completion handler that is called when the download has been successfully + /// cancelled. It is not guaranteed to be called on a particular queue, so you may + /// want use an appropriate queue to perform your work. + /// + /// - Returns: The instance. + @discardableResult + public func cancel(byProducingResumeData completionHandler: @escaping (_ data: Data?) -> Void) -> Self { + return cancel(optionallyProducingResumeData: completionHandler) + } -/// Specific type of `Request` that manages an underlying `URLSessionUploadTask`. -open class UploadRequest: DataRequest { + /// 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 } - // MARK: Helper Types + mutableState.state = .cancelled - enum Uploadable: TaskConvertible { - case data(Data, URLRequest) - case file(URL, URLRequest) - case stream(InputStream, URLRequest) + underlyingQueue.async { self.didCancel() } - func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { - do { - let task: URLSessionTask + guard let task = mutableState.tasks.last as? URLSessionDownloadTask, task.state != .completed else { + underlyingQueue.async { self.finish() } + return + } - 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) } + 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) } - - return task - } catch { - throw AdaptError(error: error) + } else { + // Resume to ensure metrics are gathered. + task.resume() + task.cancel() + self.underlyingQueue.async { self.didCancelTask(task) } } } + + return self } - // MARK: Properties + /// 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 } - /// The request sent or to be sent to the server. - open override var request: URLRequest? { - if let request = super.request { return request } + let result = validation(self.request, response, self.fileURL) - guard let uploadable = originalTask as? Uploadable else { return nil } + if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) } - switch uploadable { - case .data(_, let urlRequest), .file(_, let urlRequest), .stream(_, let urlRequest): - return urlRequest + self.eventMonitor?.request(self, + didValidateRequest: self.request, + response: response, + fileURL: self.fileURL, + withResult: result) } + + protectedValidators.append(validator) + + return self } +} - /// The progress of uploading the payload to the server for the upload request. - open var uploadProgress: Progress { return uploadDelegate.uploadProgress } +// 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) + } - var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate } + // MARK: Initial State - // MARK: Upload Progress + /// The `UploadableConvertible` value used to produce the `Uploadable` value for this instance. + public let upload: UploadableConvertible - /// 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. + /// `FileManager` used to perform cleanup tasks, including the removal of multipart form encoded payloads written + /// to disk. + public let fileManager: FileManager + + // MARK: Mutable State + + /// `Uploadable` value used by the instance. + public var uploadable: Uploadable? + + /// Creates an `UploadRequest` using the provided parameters. /// - /// - 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. + /// - 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`. /// - /// - returns: The request. - @discardableResult - open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { - uploadDelegate.uploadProgressHandler = (closure, queue) - return self + /// - Parameter uploadable: The `Uploadable` that was created. + func didCreateUploadable(_ uploadable: Uploadable) { + self.uploadable = uploadable + + eventMonitor?.request(self, didCreateUploadable: uploadable) } -} -// MARK: - + /// 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) -#if !os(watchOS) + retryOrFinish(error: error) + } -/// 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) + 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.") + } - func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { - let task: URLSessionTask + switch uploadable { + case let .data(data): return session.uploadTask(with: request, from: data) + case let .file(url, _): return session.uploadTask(with: request, fromFile: url) + case .stream: return session.uploadTask(withStreamedRequest: request) + } + } - 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) } - } + /// 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.") + } - return task + guard case let .stream(stream) = uploadable else { + fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.") } + + eventMonitor?.request(self, didProvideInputStream: stream) + + return stream + } + + public override func cleanup() { + defer { super.cleanup() } + + guard + let uploadable = self.uploadable, + case let .file(url, shouldRemove) = uploadable, + shouldRemove + else { return } + + try? fileManager.removeItem(at: url) + } +} + +/// A type that can produce an `UploadRequest.Uploadable` value. +public protocol UploadableConvertible { + /// Produces an `UploadRequest.Uploadable` value from the instance. + /// + /// - Returns: The `UploadRequest.Uploadable`. + /// - Throws: Any `Error` produced during creation. + func createUploadable() throws -> UploadRequest.Uploadable +} + +extension UploadRequest.Uploadable: UploadableConvertible { + public func createUploadable() throws -> UploadRequest.Uploadable { + 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/WWCodeDFW/Pods/Alamofire/Source/RequestInterceptor.swift b/WWCodeDFW/Pods/Alamofire/Source/RequestInterceptor.swift new file mode 100644 index 0000000..36590fc --- /dev/null +++ b/WWCodeDFW/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 `AFError`. + 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/WWCodeDFW/Pods/Alamofire/Source/RequestTaskMap.swift b/WWCodeDFW/Pods/Alamofire/Source/RequestTaskMap.swift new file mode 100644 index 0000000..8d4f33d --- /dev/null +++ b/WWCodeDFW/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/WWCodeDFW/Pods/Alamofire/Source/Response.swift b/WWCodeDFW/Pods/Alamofire/Source/Response.swift index 703eeb4..5874b28 100644 --- a/WWCodeDFW/Pods/Alamofire/Source/Response.swift +++ b/WWCodeDFW/Pods/Alamofire/Source/Response.swift @@ -1,7 +1,7 @@ // // Response.swift // -// Copyright (c) 2014-2017 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? - - /// 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 final metrics of the response. + public let metrics: URLSessionTaskMetrics? - /// 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,21 +85,37 @@ 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 { - var output: [String] = [] - - output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") - output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") - output.append("[Data]: \(data?.count ?? 0) bytes") - output.append("[Result]: \(result.debugDescription)") - output.append("[Timeline]: \(timeline.debugDescription)") - - return output.joined(separator: "\n") + let requestDescription = request.map { "\($0.httpMethod!) \($0)" } ?? "nil" + let requestBody = request?.httpBody.map { String(decoding: $0, as: UTF8.self) } ?? "None" + 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]: \n\(responseDescription) + [Response Body]: \n\(responseBody) + [Data]: \(data?.description ?? "None") + [Network Duration]: \(metricsDescription) + [Serialization Duration]: \(serializationDuration)s + [Result]: \(result) + """ } } @@ -158,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) /// } /// @@ -186,139 +157,112 @@ 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)) } -} - -// MARK: - - -/// Used to store all data associated with an non-serialized response of a download request. -public struct DefaultDownloadResponse { - /// 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 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? + /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `mapError` function with a closure that does not throw. For example: + /// + /// let possibleData: DataResponse = ... + /// 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: (Failure) -> NewFailure) -> DataResponse { + return DataResponse(request: request, + response: response, + data: data, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.mapError(transform)) + } - /// Creates a `DefaultDownloadResponse` instance from the specified parameters. + /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. /// - /// - 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 + /// Use the `tryMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleObject = possibleData.tryMapError { + /// try someFailableFunction(taking: $0) + /// } + /// + /// - Parameter transform: A throwing closure that takes the error of the instance. + /// + /// - Returns: A `DataResponse` instance containing the result of the transform. + public func tryMapError(_ 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 a serialized response of a download request. -public struct DownloadResponse { +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 result of response serialization. - public let result: Result + /// The final metrics of the response. + public let metrics: URLSessionTaskMetrics? + + /// The time taken to serialize the response. + public let serializationDuration: TimeInterval - /// The timeline of the complete lifecycle of the request. - public let timeline: Timeline + /// The result of response serialization. + 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 } } @@ -328,24 +272,37 @@ 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 { - var output: [String] = [] - - output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") - output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") - output.append("[TemporaryURL]: \(temporaryURL?.path ?? "nil")") - output.append("[DestinationURL]: \(destinationURL?.path ?? "nil")") - output.append("[ResumeData]: \(resumeData?.count ?? 0) bytes") - output.append("[Result]: \(result.debugDescription)") - output.append("[Timeline]: \(timeline.debugDescription)") - - return output.joined(separator: "\n") + let requestDescription = request.map { "\($0.httpMethod!) \($0)" } ?? "nil" + let requestBody = request?.httpBody.map { String(decoding: $0, as: UTF8.self) } ?? "None" + 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]: \n\(responseDescription) + [File URL]: \(fileURL?.path ?? "nil") + [ResumeData]: \(resumeDataDescription) + [Network Duration]: \(metricsDescription) + [Serialization Duration]: \(serializationDuration)s + [Result]: \(result) + """ } } @@ -364,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) /// } /// @@ -394,72 +345,55 @@ 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)) } -} - -// 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 + /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `mapError` function with a closure that does not throw. For example: + /// + /// let possibleData: DownloadResponse = ... + /// 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: (Failure) -> NewFailure) -> DownloadResponse { + return DownloadResponse(request: request, + response: response, + fileURL: fileURL, + resumeData: resumeData, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.mapError(transform)) } -} - -// 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 + /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `tryMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleObject = possibleData.tryMapError { + /// try someFailableFunction(taking: $0) + /// } + /// + /// - Parameter transform: A throwing closure that takes the error of the instance. + /// + /// - Returns: A `DownloadResponse` instance containing the result of the transform. + public func tryMapError(_ transform: (Failure) throws -> NewFailure) -> DownloadResponse { + return DownloadResponse(request: request, + response: response, + fileURL: fileURL, + resumeData: resumeData, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.tryMapError(transform)) + } } diff --git a/WWCodeDFW/Pods/Alamofire/Source/ResponseSerialization.swift b/WWCodeDFW/Pods/Alamofire/Source/ResponseSerialization.swift index 1f29ed8..fd235f2 100644 --- a/WWCodeDFW/Pods/Alamofire/Source/ResponseSerialization.swift +++ b/WWCodeDFW/Pods/Alamofire/Source/ResponseSerialization.swift @@ -1,7 +1,7 @@ // // ResponseSerialization.swift // -// Copyright (c) 2014-2017 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: T, + 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,384 @@ 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)) - ) + if let encodingName = response?.textEncodingName as CFString?, convertedEncoding == nil { + let ianaCharSet = CFStringConvertIANACharSetNameToEncoding(encodingName) + let nsStringEncoding = CFStringConvertEncodingToNSStringEncoding(ianaCharSet) + convertedEncoding = String.Encoding(rawValue: nsStringEncoding) } - let actualEncoding = convertedEncoding ?? String.Encoding.isoLatin1 + 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. - /// - /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. - /// - /// - 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))) - } - } - } - /// 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 (DownloadResponse) -> Void) - -> Self - { - return response( - queue: queue, - responseSerializer: DownloadRequest.jsonResponseSerializer(options: options), - completionHandler: completionHandler - ) + 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) } } -// MARK: - Property List +// MARK: - Empty -extension Request { - /// Returns a plist object contained in a result type constructed from the response data using - /// `PropertyListSerialization` with the specified reading options. - /// - /// - 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. +/// Protocol representing an empty response. Use `T.emptyValue()` to get an instance. +public protocol EmptyResponse { + /// Empty value for the conforming type. /// - /// - 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!) } - - if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } + /// - Returns: Value of `Self` to use for empty values. + static func emptyValue() -> Self +} - guard let validData = data, validData.count > 0 else { - return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) - } +/// 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() +} - do { - let plist = try PropertyListSerialization.propertyList(from: validData, options: options, format: nil) - return .success(plist) - } catch { - return .failure(AFError.responseSerializationFailed(reason: .propertyListSerializationFailed(error: error))) - } +extension Empty: EmptyResponse { + public static func emptyValue() -> Empty { + return value } } -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) - } - } +// MARK: - DataDecoder Protocol - /// Adds a handler to be called once the request has finished. +/// 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 completionHandler: A closure to be executed once the request has finished. + /// - Parameters: + /// - type: The `Type` to be decoded. + /// - data: The `Data` to be decoded. /// - /// - 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 - ) - } + /// - Returns: The decoded value of type `D`. + /// - Throws: Any error that occurs during decode. + func decode(_ type: D.Type, from data: Data) throws -> D } -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!) } +/// `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! } - guard let fileURL = fileURL else { - return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + guard var data = data, !data.isEmpty else { + guard emptyResponseAllowed(forRequest: request, response: response) else { + throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) } - 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))) + guard let emptyResponseType = T.self as? EmptyResponse.Type, let emptyValue = emptyResponseType.emptyValue() as? T else { + throw AFError.responseSerializationFailed(reason: .invalidEmptyResponse(type: "\(T.self)")) } + + return emptyValue + } + + data = try dataPreprocessor.preprocess(data) + + do { + return try decoder.decode(T.self, from: data) + } catch { + throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error)) } } +} +extension DataRequest { /// 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 (AFDataResponse) -> 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/WWCodeDFW/Pods/Alamofire/Source/Result+Alamofire.swift b/WWCodeDFW/Pods/Alamofire/Source/Result+Alamofire.swift new file mode 100644 index 0000000..60b35f8 --- /dev/null +++ b/WWCodeDFW/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/WWCodeDFW/Pods/Alamofire/Source/Result.swift b/WWCodeDFW/Pods/Alamofire/Source/Result.swift deleted file mode 100644 index bbd3c61..0000000 --- a/WWCodeDFW/Pods/Alamofire/Source/Result.swift +++ /dev/null @@ -1,300 +0,0 @@ -// -// Result.swift -// -// Copyright (c) 2014-2017 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) -> Void) -> Result { - if case let .success(value) = self { 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) -> Void) -> Result { - if case let .failure(error) = self { 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: () -> Void) -> Result { - if isSuccess { 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: () -> Void) -> Result { - if isFailure { closure() } - - return self - } -} diff --git a/WWCodeDFW/Pods/Alamofire/Source/RetryPolicy.swift b/WWCodeDFW/Pods/Alamofire/Source/RetryPolicy.swift new file mode 100644 index 0000000..7400718 --- /dev/null +++ b/WWCodeDFW/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/WWCodeDFW/Pods/Alamofire/Source/ServerTrustEvaluation.swift b/WWCodeDFW/Pods/Alamofire/Source/ServerTrustEvaluation.swift new file mode 100644 index 0000000..34a0445 --- /dev/null +++ b/WWCodeDFW/Pods/Alamofire/Source/ServerTrustEvaluation.swift @@ -0,0 +1,562 @@ +// +// 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 + /// 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. + /// + /// - Parameters: + /// - allHostsMustBeEvaluated: The value determining whether all hosts for this instance must be evaluated. `true` + /// by default. + /// - evaluators: A dictionary of evaluators mappend 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 `DefaultTrustEvalutor`. + /// + /// - 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) + } + + 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 evalute the trust. All `cer`, `crt`, and `der` + /// certificates in `Bundle.main` by default. + /// - acceptSelfSignedCertificates: Adds the provided certificates as anchors for the trust evaulation, 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 { + /// Attempts to validate `self` using the policy 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. + 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 + } + + /// 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. + 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/WWCodeDFW/Pods/Alamofire/Source/ServerTrustPolicy.swift b/WWCodeDFW/Pods/Alamofire/Source/ServerTrustPolicy.swift deleted file mode 100644 index 1ad3530..0000000 --- a/WWCodeDFW/Pods/Alamofire/Source/ServerTrustPolicy.swift +++ /dev/null @@ -1,307 +0,0 @@ -// -// ServerTrustPolicy.swift -// -// Copyright (c) 2014-2017 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. - open 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 - - 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/WWCodeDFW/Pods/Alamofire/Source/Session.swift b/WWCodeDFW/Pods/Alamofire/Source/Session.swift new file mode 100644 index 0000000..08114c2 --- /dev/null +++ b/WWCodeDFW/Pods/Alamofire/Source/Session.swift @@ -0,0 +1,1042 @@ +// +// 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:) intializer 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 (startRequestsImmediately, state) { + case (true, .initialized): + rootQueue.async { request.resume() } + case (false, .initialized): + // 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) } + case (_, .finished): + // Do nothing + break + } + } + } + + // 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 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/WWCodeDFW/Pods/Alamofire/Source/SessionDelegate.swift b/WWCodeDFW/Pods/Alamofire/Source/SessionDelegate.swift index d38c253..1cc2b3d 100644 --- a/WWCodeDFW/Pods/Alamofire/Source/SessionDelegate.swift +++ b/WWCodeDFW/Pods/Alamofire/Source/SessionDelegate.swift @@ -1,7 +1,7 @@ // // SessionDelegate.swift // -// Copyright (c) 2014-2017 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,696 +24,282 @@ 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)? + /// 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 URLSessionDownloadDelegate method `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)`. - open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? +/// 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?) +} - // MARK: URLSessionStreamDelegate Overrides +// MARK: URLSessionDelegate -#if !os(watchOS) +extension SessionDelegate: URLSessionDelegate { + open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { + eventMonitor?.urlSession(session, didBecomeInvalidWithError: error) - /// 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 - } + stateProvider?.cancelRequestsForSessionInvalidation(with: error) } +} - /// 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 - } - } +// MARK: URLSessionTaskDelegate - /// 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 - } - set { - _streamTaskBetterRouteDiscovered = 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: + evaluation = attemptHTTPAuthentication(for: challenge, belongingTo: task) + // case NSURLAuthenticationMethodClientCertificate: + // Alamofire doesn't currently support client certificate validation. + default: + evaluation = (.performDefaultHandling, nil, nil) } - } - /// 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 + if let error = evaluation.error { + stateProvider?.request(for: task)?.didFailTask(task, earlyWithError: error) } - } - - var _streamTaskReadClosed: Any? - var _streamTaskWriteClosed: Any? - var _streamTaskBetterRouteDiscovered: Any? - var _streamTaskDidBecomeInputStream: Any? - -#endif - - // MARK: Properties - - var retrier: RequestRetrier? - weak var sessionManager: SessionManager? - - private var requests: [Int: Request] = [:] - private let lock = NSLock() - /// 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 - } + completionHandler(evaluation.disposition, evaluation.credential) } - // MARK: Lifecycle - - /// Initializes the `SessionDelegate` instance. + /// Evaluates the server trust `URLAuthenticationChallenge` received. /// - /// - returns: The new `SessionDelegate` instance. - public override init() { - super.init() - } + /// - Parameter challenge: The `URLAuthenticationChallenge`. + /// + /// - Returns: The `ChallengeEvaluation`. + func attemptServerTrustAuthentication(with challenge: URLAuthenticationChallenge) -> ChallengeEvaluation { + let host = challenge.protectionSpace.host - // MARK: NSObject Overrides + guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, + let trust = challenge.protectionSpace.serverTrust + else { + return (.performDefaultHandling, nil, nil) + } - /// Returns a `Bool` indicating whether the `SessionDelegate` implements or inherits a method that can respond - /// to a specified message. - /// - /// - parameter selector: A selector that identifies a message. - /// - /// - 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 - } + do { + guard let evaluator = try stateProvider?.serverTrustManager?.serverTrustEvaluator(forHost: host) else { + return (.performDefaultHandling, nil, nil) } - #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) - } - } -} -// MARK: - URLSessionDelegate + try evaluator.evaluate(trust, forHost: host) -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) + 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 HTTP authentication `URLAuthenticationChallenge` received for `task`. + /// + /// - Parameters: + /// - challenge: The `URLAuthenticationChallenge`. + /// - task: The `URLSessionTask` which received the challenge. /// - /// - 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 + /// - Returns: The `ChallengeEvaluation`. + func attemptHTTPAuthentication(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 - -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) - return - } - - var redirectRequest: URLRequest? = request + open func urlSession(_ session: URLSession, + task: URLSessionTask, + needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) { + eventMonitor?.urlSession(session, taskNeedsNewBodyStream: task) - if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { - redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) + guard let request = stateProvider?.request(for: task) as? UploadRequest else { + fatalError("needNewBodyStream for request that isn't UploadRequest.") } - 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 } + eventMonitor?.urlSession(session, task: task, didCompleteWithError: error) - strongSelf.taskDidComplete?(session, task, error) + stateProvider?.request(for: task)?.didCompleteTask(task, with: error.map { $0.asAFError(or: .sessionTaskFailed(error: $0)) }) - strongSelf[task]?.delegate.urlSession(session, task: task, didCompleteWithError: error) - - NotificationCenter.default.post( - name: Notification.Name.Task.DidComplete, - object: strongSelf, - userInfo: [Notification.Key.Task: task] - ) - - strongSelf[task] = nil - } + stateProvider?.didCompleteTask(task) + } - guard let request = self[task], let sessionManager = sessionManager else { - completeTask(session, task, error) - return - } + @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) + } +} - // Run all validations on the request before checking if an error occurred - request.validations.forEach { $0() } +// MARK: URLSessionDataDelegate - // Determine whether an error has occurred - var error: Error? = error +extension SessionDelegate: URLSessionDataDelegate { + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + eventMonitor?.urlSession(session, dataTask: dataTask, didReceive: data) - if request.delegate.error != nil { - error = request.delegate.error + guard let request = stateProvider?.request(for: dataTask) as? DataRequest else { + fatalError("dataTask received data for incorrect Request subclass: \(String(describing: stateProvider?.request(for: dataTask)))") } - /// 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) - return - } - - var disposition: URLSession.ResponseDisposition = .allow +extension SessionDelegate: URLSessionDownloadDelegate { + open func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) { + eventMonitor?.urlSession(session, + downloadTask: downloadTask, + didResumeAtOffset: fileOffset, + expectedTotalBytes: expectedTotalBytes) - if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { - disposition = dataTaskDidReceiveResponse(session, dataTask, response) + guard let downloadRequest = stateProvider?.request(for: downloadTask) as? DownloadRequest else { + fatalError("No DownloadRequest found for downloadTask: \(downloadTask)") } - 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) - } - } + 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) - /// 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) - return + guard let downloadRequest = stateProvider?.request(for: downloadTask) as? DownloadRequest else { + fatalError("No DownloadRequest found for downloadTask: \(downloadTask)") } - 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) + guard let request = stateProvider?.request(for: downloadTask) as? DownloadRequest else { + fatalError("Download finished but either no request found or request wasn't DownloadRequest") } - } - /// 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 response = request.response else { + fatalError("URLSessionDownloadTask finished downloading with no response.") } - } - /// 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 - ) - } - } -} + let (destination, options) = (request.destination)(location, response) -// MARK: - URLSessionStreamDelegate + eventMonitor?.request(request, didCreateDestinationURL: destination) -#if !os(watchOS) - -@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/WWCodeDFW/Pods/Alamofire/Source/SessionManager.swift b/WWCodeDFW/Pods/Alamofire/Source/SessionManager.swift deleted file mode 100644 index 9bd8b54..0000000 --- a/WWCodeDFW/Pods/Alamofire/Source/SessionManager.swift +++ /dev/null @@ -1,891 +0,0 @@ -// -// SessionManager.swift -// -// Copyright (c) 2014-2017 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. - open 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. - open 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. - open static let multipartFormDataEncodingMemoryThreshold: UInt64 = 10_000_000 - - /// The underlying session. - open let session: URLSession - - /// The session delegate handling all the task and session delegate callbacks. - open 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`. - 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, - encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) - { - do { - let urlRequest = try URLRequest(url: url, method: method, headers: headers) - - return upload( - multipartFormData: multipartFormData, - usingThreshold: encodingMemoryThreshold, - with: urlRequest, - encodingCompletion: encodingCompletion - ) - } catch { - 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, - 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 - ) - - 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 - } - } - - 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 - } - } - - 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) - - 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/WWCodeDFW/Pods/Alamofire/Source/TaskDelegate.swift b/WWCodeDFW/Pods/Alamofire/Source/TaskDelegate.swift deleted file mode 100644 index 0607758..0000000 --- a/WWCodeDFW/Pods/Alamofire/Source/TaskDelegate.swift +++ /dev/null @@ -1,466 +0,0 @@ -// -// TaskDelegate.swift -// -// Copyright (c) 2014-2017 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. - open 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/WWCodeDFW/Pods/Alamofire/Source/Timeline.swift b/WWCodeDFW/Pods/Alamofire/Source/Timeline.swift deleted file mode 100644 index c5dabd1..0000000 --- a/WWCodeDFW/Pods/Alamofire/Source/Timeline.swift +++ /dev/null @@ -1,136 +0,0 @@ -// -// Timeline.swift -// -// Copyright (c) 2014-2017 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/WWCodeDFW/Pods/Alamofire/Source/URLConvertible+URLRequestConvertible.swift b/WWCodeDFW/Pods/Alamofire/Source/URLConvertible+URLRequestConvertible.swift new file mode 100644 index 0000000..507ea6d --- /dev/null +++ b/WWCodeDFW/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 encoutered. + /// + /// - 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/WWCodeDFW/Pods/Alamofire/Source/URLEncodedFormEncoder.swift b/WWCodeDFW/Pods/Alamofire/Source/URLEncodedFormEncoder.swift new file mode 100644 index 0000000..0bd3cfd --- /dev/null +++ b/WWCodeDFW/Pods/Alamofire/Source/URLEncodedFormEncoder.swift @@ -0,0 +1,949 @@ +// +// 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 sppended 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." + } + } + } + + /// 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: + /// - 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(arrayEncoding: ArrayEncoding = .brackets, + boolEncoding: BoolEncoding = .numeric, + dataEncoding: DataEncoding = .base64, + dateEncoding: DateEncoding = .deferredToDate, + keyEncoding: KeyEncoding = .useDefaultKeys, + spaceEncoding: SpaceEncoding = .percentEscaped, + allowedCharacters: CharacterSet = .afURLQueryAllowed) { + 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(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 + + public 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 { + case string(String) + case array([URLEncodedFormComponent]) + case object([String: URLEncodedFormComponent]) + + /// 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 `[String: URLEncodedFormData]` or returns `nil` if not convertible. + var object: [String: URLEncodedFormComponent]? { + 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?[end.stringValue] ?? .object([:]) + 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 { + object[end.stringValue] = child + context = .object(object) + } else { + context = .object([end.stringValue: 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 arrayEncoding: URLEncodedFormEncoder.ArrayEncoding + private let keyEncoding: URLEncodedFormEncoder.KeyEncoding + private let spaceEncoding: URLEncodedFormEncoder.SpaceEncoding + private let allowedCharacters: CharacterSet + + init(arrayEncoding: URLEncodedFormEncoder.ArrayEncoding, + keyEncoding: URLEncodedFormEncoder.KeyEncoding, + spaceEncoding: URLEncodedFormEncoder.SpaceEncoding, + allowedCharacters: CharacterSet) { + self.arrayEncoding = arrayEncoding + self.keyEncoding = keyEncoding + self.spaceEncoding = spaceEncoding + self.allowedCharacters = allowedCharacters + } + + func serialize(_ object: [String: URLEncodedFormComponent]) -> String { + var output: [String] = [] + for (key, component) in object { + let value = serialize(component, forKey: key) + output.append(value) + } + + 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(dictionary): return serialize(dictionary, forKey: key) + } + } + + func serialize(_ object: [String: URLEncodedFormComponent], forKey key: String) -> String { + let segments: [String] = object.map { subKey, value in + let keyPath = "[\(subKey)]" + return serialize(value, forKey: key + keyPath) + } + + return segments.joinedWithAmpersands() + } + + func serialize(_ array: [URLEncodedFormComponent], forKey key: String) -> String { + let segments: [String] = array.map { component in + let keyPath = arrayEncoding.encode(key) + return serialize(component, forKey: keyPath) + } + + 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: "&") + } +} + +extension CharacterSet { + /// Creates a CharacterSet from RFC 3986 allowed characters. + /// + /// RFC 3986 states that the following characters are "reserved" characters. + /// + /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/" + /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" + /// + /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow + /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" + /// should be percent-escaped in the query string. + public static let afURLQueryAllowed: CharacterSet = { + let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 + let subDelimitersToEncode = "!$&'()*+,;=" + let encodableDelimiters = CharacterSet(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") + + return CharacterSet.urlQueryAllowed.subtracting(encodableDelimiters) + }() +} diff --git a/WWCodeDFW/Pods/Alamofire/Source/URLRequest+Alamofire.swift b/WWCodeDFW/Pods/Alamofire/Source/URLRequest+Alamofire.swift new file mode 100644 index 0000000..b198fe0 --- /dev/null +++ b/WWCodeDFW/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/WWCodeDFW/Pods/Alamofire/Source/URLSessionConfiguration+Alamofire.swift b/WWCodeDFW/Pods/Alamofire/Source/URLSessionConfiguration+Alamofire.swift new file mode 100644 index 0000000..de3e290 --- /dev/null +++ b/WWCodeDFW/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/WWCodeDFW/Pods/Alamofire/Source/Validation.swift b/WWCodeDFW/Pods/Alamofire/Source/Validation.swift index 989ac20..1f702b9 100644 --- a/WWCodeDFW/Pods/Alamofire/Source/Validation.swift +++ b/WWCodeDFW/Pods/Alamofire/Source/Validation.swift @@ -1,7 +1,7 @@ // // Validation.swift // -// Copyright (c) 2014-2017 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.count > 0 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,10 @@ extension DataRequest { /// - returns: The request. @discardableResult public func validate() -> Self { - return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes) + let contentTypes: () -> [String] = { [unowned self] in + self.acceptableContentTypes + } + return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) } } @@ -228,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. @@ -272,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) } } @@ -285,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))) } @@ -310,6 +239,9 @@ extension DownloadRequest { /// - returns: The request. @discardableResult public func validate() -> Self { - return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes) + let contentTypes = { [unowned self] in + self.acceptableContentTypes + } + return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) } } diff --git a/WWCodeDFW/Pods/Manifest.lock b/WWCodeDFW/Pods/Manifest.lock index 40e6f25..d1792db 100644 --- a/WWCodeDFW/Pods/Manifest.lock +++ b/WWCodeDFW/Pods/Manifest.lock @@ -1,21 +1,28 @@ PODS: - - Alamofire (4.5.1) - - SnapKit (3.0.2) - - SwiftLint (0.23.0) - - SwiftyJSON (3.1.4) + - Alamofire (5.0.0-rc.2) + - SnapKit (5.0.1) + - SwiftLint (0.35.0) + - SwiftyJSON (5.0.0) DEPENDENCIES: - - Alamofire (~> 4.5) - - SnapKit (~> 3.0.0) + - Alamofire (~> 5.0.0-rc.2) + - SnapKit (~> 5.0.0) - SwiftLint - SwiftyJSON +SPEC REPOS: + https://github.com/cocoapods/specs.git: + - Alamofire + - SnapKit + - SwiftLint + - SwiftyJSON + SPEC CHECKSUMS: - Alamofire: 2d95912bf4c34f164fdfc335872e8c312acaea4a - SnapKit: 2e456761aa92d4d4067a7a5594c18769d451a8ad - SwiftLint: 6ddf7d305644c2239cb768a11d97cce804816691 - SwiftyJSON: c2842d878f95482ffceec5709abc3d05680c0220 + Alamofire: f9450d3c7f6bea2ad62e7a541c3e9b186c7991d6 + SnapKit: 97b92857e3df3a0c71833cce143274bf6ef8e5eb + SwiftLint: 5553187048b900c91aa03552807681bb6b027846 + SwiftyJSON: 36413e04c44ee145039d332b4f4e2d3e8d6c4db7 -PODFILE CHECKSUM: cf0dec5dff3c2a442745cbd029e92615aff683c5 +PODFILE CHECKSUM: 81ddc0dbf5ed57258b530b6d6fa1e55ccd268d73 -COCOAPODS: 1.3.1 +COCOAPODS: 1.7.5 diff --git a/WWCodeDFW/Pods/Pods.xcodeproj/project.pbxproj b/WWCodeDFW/Pods/Pods.xcodeproj/project.pbxproj index 3a0a547..2fd79a4 100644 --- a/WWCodeDFW/Pods/Pods.xcodeproj/project.pbxproj +++ b/WWCodeDFW/Pods/Pods.xcodeproj/project.pbxproj @@ -6,1090 +6,1287 @@ objectVersion = 46; objects = { +/* Begin PBXAggregateTarget section */ + 52B60EC2A583F24ACBB69C113F5488B9 /* SwiftLint */ = { + isa = PBXAggregateTarget; + buildConfigurationList = AE7B4FB01588B9E6DF09CB79FC7CE7BD /* Build configuration list for PBXAggregateTarget "SwiftLint" */; + buildPhases = ( + ); + dependencies = ( + ); + name = SwiftLint; + }; +/* End PBXAggregateTarget section */ + /* Begin PBXBuildFile section */ - 0950658BCE95CFE494117A110BC654C6 /* ConstraintDSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1390CCA24783C2E95B3264878F43990 /* ConstraintDSL.swift */; }; - 10EB23E9ECC4B33E16933BB1EA560B6A /* Timeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2E2E12CCECCF718F91ACA3B0018A756 /* Timeline.swift */; }; - 1B9EDEDC964E6B08F78920B4F4B9DB84 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 4134F22A9E49EA2F464E71718753DA46 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 1D4389B9F4F9FEB10A21E246D68F17A1 /* ConstraintPriorityTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 12C136C58152FC54E2F406E9B331B244 /* ConstraintPriorityTarget.swift */; }; - 1DE3CC7F8C57C333BE0A309D114E60D1 /* SnapKit-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 5BD89A697635A40B3220858FB4337DCF /* SnapKit-dummy.m */; }; - 1E271897A0FC04A5BE1BA277E62E5E47 /* ConstraintMakerPriortizable.swift in Sources */ = {isa = PBXBuildFile; fileRef = AC0C1A53329F0C3B2C953DD512F1600B /* ConstraintMakerPriortizable.swift */; }; - 1F0DA736A59CE3C69FCFCDAB4A285CD7 /* ConstraintMakerExtendable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5E22A35D4D38B894EF0E688BB6F0DD04 /* ConstraintMakerExtendable.swift */; }; - 25AC37E2CD92BB6D2A70E71682267DF0 /* ConstraintLayoutGuide.swift in Sources */ = {isa = PBXBuildFile; fileRef = A91436829018A3397CC451C4E7C1726C /* ConstraintLayoutGuide.swift */; }; - 32F8484FED98350DAB553971F2DCC3C0 /* ConstraintView+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30D69444A876031C0DD47BFC4F43C6B4 /* ConstraintView+Extensions.swift */; }; - 33B5A5A6726002B88EAE5842CD5FC348 /* ConstraintConfig.swift in Sources */ = {isa = PBXBuildFile; fileRef = 376BEF74A19D59C12528AF337E9B7056 /* ConstraintConfig.swift */; }; - 340C2088655CAE5E0E7D67285D52BAC3 /* ConstraintLayoutSupportDSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 244AAFD6A5CF20E1958B107A68640125 /* ConstraintLayoutSupportDSL.swift */; }; - 3626B94094672CB1C9DEA32B9F9502E1 /* TaskDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = AAB020DE36C50C1E326CBC1E46F38A32 /* TaskDelegate.swift */; }; - 39BD35F68CE705F4A422FDD60304CDFC /* UILayoutGuide+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2FEF61CBBDB8259CD6AD1257BAB8932F /* UILayoutGuide+Extensions.swift */; }; - 3A32EE3F2B5531B15EA3E1AC2BD20139 /* ConstraintViewDSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 92EE5B0ECE9DF92F2087A08233C06D35 /* ConstraintViewDSL.swift */; }; - 4333F3C7ACDB152A0DB989940EC3A2F1 /* ConstraintInsetTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00E4412F67364360F74E8CCF2AA555DD /* ConstraintInsetTarget.swift */; }; - 46C8F0CF77169F83E2B2BCBC1DFB9F41 /* ConstraintMakerRelatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA3D33741DF328C147592105977B9CE9 /* ConstraintMakerRelatable.swift */; }; - 4913E59CC920BB2C409B2B7AB4FE3C68 /* Debugging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75FF1AD01519364BB8C2F851435FD60B /* Debugging.swift */; }; - 50D3BED5CAF1F698C99E2E1E34533241 /* ConstraintAttributes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0ED2A647955895F8E2478887A64478FC /* ConstraintAttributes.swift */; }; - 5387216E723A3C68E851CA15573CDD71 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D7B31B7B1F6740D1AA4CEEF529FD88F /* Request.swift */; }; - 53DEEF2499A9FA94333C7F38D59C9831 /* SnapKit-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 4A20BBBEB5531B60C02D21E98CB45B3A /* SnapKit-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 545A1DF50E2959908CE80483D18B4006 /* ConstraintMakerFinalizable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2B2C3EFE31585F78DE2591E3054690D0 /* ConstraintMakerFinalizable.swift */; }; - 60A5F21DB4AAF6E1998A275CE1CAA8B9 /* ConstraintLayoutGuideDSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 28BF3B0EB3EBD6EEBFBE2A092AC34F81 /* ConstraintLayoutGuideDSL.swift */; }; - 61200D01A1855D7920CEF835C8BE00B0 /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F6BE40E032152F0921979FC371C6BFC /* DispatchQueue+Alamofire.swift */; }; - 62F65AD8DC4F0F9610F4B8B4738EC094 /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4FDA868004B42710EBF6B373767523E3 /* ServerTrustPolicy.swift */; }; - 68C16258E306728749431E133B80BAE2 /* ConstraintView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5E66E8E584A50A01E56998CC586581BD /* ConstraintView.swift */; }; - 6E6A2F4372D72CEDE43C042BAD896C8B /* ConstraintMakerEditable.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4966F0F235C7F44396807DD853056A2 /* ConstraintMakerEditable.swift */; }; - 7042152DEFE0D700F8AE2079B7348372 /* SwiftyJSON-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 7FCD0718E443977536F44F2C41D408E2 /* SwiftyJSON-dummy.m */; }; - 73B9C996AED49ED7CF8EC2A6F1738059 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6604A7D69453B4569E4E4827FB9155A9 /* Foundation.framework */; }; - 7784ACB41695D0BFCF09EDACFC863ED8 /* ConstraintLayoutSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B51A0C17DB6F80A02EC398273876EE8 /* ConstraintLayoutSupport.swift */; }; - 7B5FE28C7EA4122B0598738E54DBEBD8 /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6DD033C1F2C5459D093F98556011ACE /* SessionDelegate.swift */; }; - 7D8CC01E8C9EFFF9F4D65406CDE0AB66 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54A43B2E22A1EC8B0307547BA070ED7B /* Result.swift */; }; - 86CF01DC27A3B9016587EA202BF36F8C /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6604A7D69453B4569E4E4827FB9155A9 /* Foundation.framework */; }; - 8C1F1200F8FC2DE79601824D99B07769 /* SwiftyJSON-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 3165759575400A03BDB5336CD4ABB656 /* SwiftyJSON-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 905ED93A26C017B5F18DB60C768FF3D3 /* ConstraintConstantTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 76BD74AD4191847740695C98F67B7978 /* ConstraintConstantTarget.swift */; }; - 922E76CDC352C626D7A9C530A81E2693 /* Constraint.swift in Sources */ = {isa = PBXBuildFile; fileRef = F3E0E9A410D9D8B6DD2404ECB3329758 /* Constraint.swift */; }; - 9C433F07CFA6F50BD99293D928496E58 /* UILayoutSupport+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6FC7B72688C16A9E4958A6E7F4C79F8C /* UILayoutSupport+Extensions.swift */; }; - 9ED2BB2981896E0A39EFA365503F58CE /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 23DF0BF09622711B35C079E49C8D8701 /* AFError.swift */; }; - A184FD50F870469FA15003696F1B16BA /* LayoutConstraint.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3168036C7D6A18C3EBE01ABDC14D777F /* LayoutConstraint.swift */; }; - A2A6F71B727312BD45CC7A4AAD7B0AB7 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE5EC0FAAC28192E79277BEA6C669B55 /* NetworkReachabilityManager.swift */; }; - A9EEEA7477981DEEBC72432DE9990A4B /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 87A4FD42575EF7D6DDEFAE920F1528DA /* Alamofire-dummy.m */; }; - AA5D1A251FED94EAFC57E1F192A2F959 /* ConstraintDescription.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0D0A1C53BBE67C2A8ED3ECE85014BB9 /* ConstraintDescription.swift */; }; - AE1EF48399533730D0066E04B22CA2D6 /* SessionManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 992A2DBE11BE21161FFA58D73947BB5E /* SessionManager.swift */; }; - B65FCF589DA398C3EFE0128064E510EC /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = C03C272676143735DBAF78D7DF84EAC0 /* MultipartFormData.swift */; }; - BBEFE2F9CEB73DC7BD97FFA66A0D9D4F /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 62FB28794B829890A3BCF9FCEF7F565E /* Validation.swift */; }; - BE5C67A07E289FE1F9BE27335B159997 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 653FBE396161F841A60E129B2CDED598 /* ParameterEncoding.swift */; }; - C0234E523428AA2D53C7E2D952CD5995 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6604A7D69453B4569E4E4827FB9155A9 /* Foundation.framework */; }; - C889ED97467F9763234DCE085D74C9DF /* Pods-WWCodeDFW-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 75A40EDFE893A0C4CEA1EDB17B51161B /* Pods-WWCodeDFW-dummy.m */; }; - C98A797EAD255997ACDD3C8391E52EA7 /* ConstraintOffsetTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4DBD4C8E2336679C83BC14C17459D268 /* ConstraintOffsetTarget.swift */; }; - C9F04B120ADE5D757DE9AA7CED829A7C /* ConstraintItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 163272BF09771EE4D6481761A332AAE4 /* ConstraintItem.swift */; }; - CB6D60925223897FFA2662667DF83E8A /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB8C54435226E98CE66D6D40A76E4112 /* Response.swift */; }; - D431FFB37AEC3F43FF7DC1B0A7D1653F /* ConstraintRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2257B11270A64D3AF5F497010AF0D01B /* ConstraintRelation.swift */; }; - DDB8A5C5BBFEBEB8D564F15172146746 /* ConstraintRelatableTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A4969DA8509FCF2EABA3B5FB095BBBF /* ConstraintRelatableTarget.swift */; }; - E298E9467EC7FB473E3AC6B362C01D17 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6604A7D69453B4569E4E4827FB9155A9 /* Foundation.framework */; }; - E41829C687AFE4242B20317FAC79F0E4 /* ConstraintInsets.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6F7A494B4CD996B3F523C2B28FFEE52 /* ConstraintInsets.swift */; }; - E5CE8462363E29B7B1CC2B970084F1AE /* ConstraintMultiplierTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 01882FD6A64E5846C465601C2F805C0A /* ConstraintMultiplierTarget.swift */; }; - E8E1F6773DD1F8333A281C1AA44E9181 /* Pods-WWCodeDFW-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = A457067AFDFE02D54986C3A675DB0CF3 /* Pods-WWCodeDFW-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - ED56B39274410994E00EF5EB0A798901 /* ConstraintMaker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 67A26D60318A9A85EC52F646C3AB67AA /* ConstraintMaker.swift */; }; - EFD264FC408EBF3BA2528E70B08DDD94 /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4597569C3304C012A453BD0C2CFAA1B6 /* Notifications.swift */; }; - F6509EAF0D2FA37D51423948F6B24D0A /* SwiftyJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2D1A354791813791DECF12B24CCA6CBB /* SwiftyJSON.swift */; }; - F6BECD98B97CBFEBE2C96F0E9E72A6C0 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 521858488A8EBB078CCEDCC388F58137 /* ResponseSerialization.swift */; }; - F8B3D3092ED0417E8CDF32033F6122F5 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95297299E1618043BD1110D4CEC5C2CD /* Alamofire.swift */; }; + 00FA97D56201027AEB1C7692A2C3CF8B /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F0ADDAACB71C0827F5C2692E2192A881 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 01C550A53C9E2047C83F8E85BBB558E6 /* ConstraintLayoutSupportDSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9814C1BF0430FC09DFA1D3A306C00C44 /* ConstraintLayoutSupportDSL.swift */; }; + 039EAFE7935113805F3FC21BF1B7C9D5 /* LayoutConstraint.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E4FCAD90901006470F70E663019746D /* LayoutConstraint.swift */; }; + 0419772A87B16DB7DCF405A9E77D671F /* Protector.swift in Sources */ = {isa = PBXBuildFile; fileRef = BFEBF4AA03E01C4D091EBEB4C8D537D8 /* Protector.swift */; }; + 04543980C4A7CE442330B0F1BC4A9A54 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 222DAEF0D819F359AFCFF3D4F927E8A7 /* Foundation.framework */; }; + 06507A26118BA5ACFBBC8C225776920E /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C553488DEA28084B2F4231B3AB693F3 /* Validation.swift */; }; + 0AE06C3AEA6CA45342BA703230ABD2CB /* CachedResponseHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 23885A65DE219E49A7F9948BC45F4EA0 /* CachedResponseHandler.swift */; }; + 0CC43FF0E31AA320ACFEB0FE6239DF34 /* ServerTrustEvaluation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0AE0F46D2C9DC01A421478544DA764B7 /* ServerTrustEvaluation.swift */; }; + 13457FE4E607509A3B9527B0711033D5 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1AC96EFCCA6682A47864FB240B381D44 /* ResponseSerialization.swift */; }; + 14AB7976E100075ADEA0AB1DB833E72D /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50E3EE3D81F1B9A1610C433B1D95DE46 /* ParameterEncoding.swift */; }; + 17953A9CF2E354B3E69B9ABC2F367AD9 /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = D5255A80CFA98886E4CAAF379205860B /* AFError.swift */; }; + 1942F7D3B7722A5637C3FC0BE44B1E6C /* SwiftyJSON-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 94FDFE7056EC1D9DB4EA8C89A0AB1F7B /* SwiftyJSON-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1956E392D500F3CD899D39A5F805736D /* Typealiases.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6CABAEDBBE4180B8C4FB18EA14FA9E15 /* Typealiases.swift */; }; + 1AFB1E9136716C0B61D6C700FF1E60FD /* ConstraintLayoutGuide+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = EC0F93AB9486D318FF3F34B1B7DE4F7B /* ConstraintLayoutGuide+Extensions.swift */; }; + 21AB1101BBE4D28D74ED4EDF0D59025A /* ConstraintInsets.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE2B8CEF341D5EA7FF0EF91DDA9B4E69 /* ConstraintInsets.swift */; }; + 232B2F922E972D9F43D2EE15ACECE734 /* ConstraintPriority.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F19EE7C03E1B43F1FF41D4A1DE005AA /* ConstraintPriority.swift */; }; + 2A1BBBC87AC2367BD14610A9D10D285E /* ConstraintAttributes.swift in Sources */ = {isa = PBXBuildFile; fileRef = F835E63FFD2E853B5EDA7B06EA17E62C /* ConstraintAttributes.swift */; }; + 2BF6FBC0A64BF107C5D64C61F1397770 /* SwiftyJSON-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 85362A716D7C46C8C1E8F07D6103E36A /* SwiftyJSON-dummy.m */; }; + 2C06F2E972444D359754D21AC46BFFE2 /* ConstraintInsetTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5253A7F4C94E49842026933DAF4A714 /* ConstraintInsetTarget.swift */; }; + 3BDB28864BA09DD602D6A072D308703E /* Pods-WWCodeDFW-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = D45A24230E040C510DFA36CAE246C6BC /* Pods-WWCodeDFW-dummy.m */; }; + 3BFC243AB9BD579969F0D5756560BCAA /* Constraint.swift in Sources */ = {isa = PBXBuildFile; fileRef = 16E549A0951E655F87E750857EEF9326 /* Constraint.swift */; }; + 3E5285F4F36EAD77ECABBFB7F36BB1BB /* ConstraintView+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3B294424D831BD800E40EBD6E1A4FB7A /* ConstraintView+Extensions.swift */; }; + 4082513A35C682F2193D002C80F72B79 /* Result+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5593F02B88EBD5DBE150CF2F5E49F0A2 /* Result+Alamofire.swift */; }; + 42CDB5C986C78BBC8E5C0185F746CABF /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C654B033B1C04E51ED977630E10EF61F /* SessionDelegate.swift */; }; + 44127C4B989C9CC6A90D78B66A929A5E /* AlamofireExtended.swift in Sources */ = {isa = PBXBuildFile; fileRef = 43CE0861FD67C513B840AAC82F8D25F6 /* AlamofireExtended.swift */; }; + 464450D037D17ED5EE2322E180A6A9F5 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 222DAEF0D819F359AFCFF3D4F927E8A7 /* Foundation.framework */; }; + 48D97BE7D5CAED273BD2341C239CC934 /* RequestTaskMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 207FDC0806D5BDCAD5E50A07CE8DAC3C /* RequestTaskMap.swift */; }; + 4C7A676DAE95EEAC3787A75349F0862D /* SnapKit-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = C1EA3AA8BFBE64B16061D4246F2BB8CB /* SnapKit-dummy.m */; }; + 51CD5887014967E77E58F5A163996454 /* ConstraintMaker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F396B2619519A3DE23C24CAA8763851 /* ConstraintMaker.swift */; }; + 56EC8ED1535DAB987F3D2B71D4C05773 /* HTTPHeaders.swift in Sources */ = {isa = PBXBuildFile; fileRef = A210FD675C0C625827FE8C76D6DDCC10 /* HTTPHeaders.swift */; }; + 57B1876F2BE4168E5BFDB63D8CC849A0 /* ConstraintLayoutSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = A80B60D253F6EB6C8848C11B11AE2179 /* ConstraintLayoutSupport.swift */; }; + 5854DF509E8A016B6235793D04083035 /* ConstraintConstantTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = C6C6CED2376FAF35FE0610FD9DCEBAC0 /* ConstraintConstantTarget.swift */; }; + 5C4A0685B5A201436AB52EF25829B333 /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50514B7777AC28C9444C4D90154EA9A2 /* MultipartFormData.swift */; }; + 5D12235D061AEE7459279AAF8C348DFE /* URLEncodedFormEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 48C45D08A0A8C8084260C0281CD2EA6A /* URLEncodedFormEncoder.swift */; }; + 5D61C8ED0DDCC9F8B576B6514B19EE50 /* ParameterEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1AA755DD8BF7D30F2175A0C30067E96 /* ParameterEncoder.swift */; }; + 69ACE4EEE5A8C1C618B22CC1F7B8EF01 /* Session.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA53997A5E2CCFF41BF5738BD0A64F6C /* Session.swift */; }; + 69CCBEEDFCA6D743D80026568D961919 /* ConstraintMakerExtendable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 13C1F87EB6FCA8ABA385BFBD29DE25EE /* ConstraintMakerExtendable.swift */; }; + 69E3A06BBDFDC7D06A9D4BDC4E895E73 /* ConstraintRelatableTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 94060F0D07C2C9B715A3FC5D26B76AB7 /* ConstraintRelatableTarget.swift */; }; + 6A22C46CB1EDE471794D9AB2AC10327F /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18E7F72B7EF4EBD4894D5C53C986D455 /* Request.swift */; }; + 6E0EB9E7FAAEDBB7A73ECF3095F69C4A /* UILayoutSupport+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = DAEFC97DC423B4E3F0A95FDF0B393427 /* UILayoutSupport+Extensions.swift */; }; + 70517C3BAC2D6614347DEAC15299EB84 /* URLConvertible+URLRequestConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = DBA8BE0AFDCCB28E8C4EF3ECE00051C9 /* URLConvertible+URLRequestConvertible.swift */; }; + 71DE9DC2FA583526AB4D1FD7F00C099C /* ConstraintDirectionalInsetTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5CBE3345FE7A6E098E88DC8990F4E94F /* ConstraintDirectionalInsetTarget.swift */; }; + 75E146C12D1287228A0B493E87CDE31F /* ConstraintMakerRelatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6801A7943BF8C6FC06D1CEF2D936DA44 /* ConstraintMakerRelatable.swift */; }; + 77C9889055A3B32EA13A9616824DB0ED /* ConstraintLayoutGuideDSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3A40E6C43AE8DAC3243F6B8D7CA1011A /* ConstraintLayoutGuideDSL.swift */; }; + 7A716FF53BB179A83F30879A054F9517 /* Pods-WWCodeDFW-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = E49FFA5C76E350A578A9976F0A0DB329 /* Pods-WWCodeDFW-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7B4CE5C84161E2BFE477F42DFD634382 /* SwiftyJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA341057A222274517791AE4BECDE83E /* SwiftyJSON.swift */; }; + 7C1702076F3A31D8D2D45A4A9F09B266 /* ConstraintMakerEditable.swift in Sources */ = {isa = PBXBuildFile; fileRef = F73441A77CCB02E381125BE899596B1F /* ConstraintMakerEditable.swift */; }; + 7CF8362BA31492053F5CB165637AE117 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA60FA61B161DA65AB1CC384C4D7A74F /* NetworkReachabilityManager.swift */; }; + 8277256ADEC3C4DCF79957D1CA681A9A /* ConstraintDSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93A3641119044DAAF34D357E1EAE2403 /* ConstraintDSL.swift */; }; + 8705BBF0D428BF0AE1B554A377ECC540 /* ConstraintOffsetTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4377A4C465256EEB8681E90A172DADD /* ConstraintOffsetTarget.swift */; }; + 92811AC5CD9A5004116AE43C4E8FD955 /* OperationQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 81A7CDD945D4005D44D48C2810323C94 /* OperationQueue+Alamofire.swift */; }; + 97A168DFB6DB61770CE2DBF4FD39AA8D /* CFNetwork.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8B079F294DA5D9A879E6D53A91F51A1E /* CFNetwork.framework */; }; + 99B5296A5EDECE0557B9DA53D9E19CA1 /* ConstraintItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B11437C7272707E16C3A0C2667521B6 /* ConstraintItem.swift */; }; + 9B09968922C73D50040C6EEF57890D6E /* ConstraintConfig.swift in Sources */ = {isa = PBXBuildFile; fileRef = 725E4C16A0ACE592FAEFE1415DE54219 /* ConstraintConfig.swift */; }; + A270CD9EC3C541FE86E65AEDCEF500CF /* ConstraintLayoutGuide.swift in Sources */ = {isa = PBXBuildFile; fileRef = FFDB71AA280F49CBB5217FFE1621333D /* ConstraintLayoutGuide.swift */; }; + A66ED57B365A35434C5BAF4B990819B7 /* SnapKit-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = DC21BAAB3FD88C0A9CE3C88A67D780BB /* SnapKit-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A6BB6FAAA15A27EC32508F167E7BB95B /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 222DAEF0D819F359AFCFF3D4F927E8A7 /* Foundation.framework */; }; + AC35C9341C4BB156BB26FDD237EE3721 /* ConstraintDirectionalInsets.swift in Sources */ = {isa = PBXBuildFile; fileRef = 03D69B495F6DCC8BD2D3563ECAF65A56 /* ConstraintDirectionalInsets.swift */; }; + AD9899986955B2EC1EC20818C860C971 /* RequestInterceptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 03E0CE90135820AD6EB98B1708B6686C /* RequestInterceptor.swift */; }; + AF92602937CA016548022C600B8CDC16 /* URLSessionConfiguration+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = F2E50A06339722D33BF003CA1AD08421 /* URLSessionConfiguration+Alamofire.swift */; }; + B1C58F6CED7B3E45170711D9ADF878AF /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A44899DF1DABCA59DD9362A99EEA460 /* Alamofire-dummy.m */; }; + B23E9A5CDA31534491226F4C2EE8F8E6 /* HTTPMethod.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8ED5FE97C61127F2E240B2482D7ACA08 /* HTTPMethod.swift */; }; + B599696DFEF6B2A5ECF528F4E5BB1846 /* ConstraintDescription.swift in Sources */ = {isa = PBXBuildFile; fileRef = 853B4B67909902A8D36D45611D81709A /* ConstraintDescription.swift */; }; + B780B272106411CBE258BB60FFC45410 /* Debugging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9C107F334249B4C7F034D4A75F45DBDC /* Debugging.swift */; }; + B788B3354CCEBE56DFDB963CAFD7F6C2 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0F532BB6F9CDAA87990FEEBEEC0C8B51 /* Alamofire.swift */; }; + BE82AE980F8C7EE28A6448959194F93A /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 222DAEF0D819F359AFCFF3D4F927E8A7 /* Foundation.framework */; }; + BECA67DFB5E0984DFAEFCB775C31972E /* ConstraintView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C31B2EDD8BE2A58CFD16852AB21AD914 /* ConstraintView.swift */; }; + C412F27D75AFC0DF0F0289DBB270931C /* ConstraintMakerFinalizable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6E8BE21373A78F570DA43B1C9B2B965C /* ConstraintMakerFinalizable.swift */; }; + C64AF152F7928CDB59385528DB65FE19 /* RedirectHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF1FB8E30B81304D11B3F8C95426A552 /* RedirectHandler.swift */; }; + C7369563F6946D8984124E1A546B6425 /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE17175641E2D35B161ECEFCC6783A11 /* Notifications.swift */; }; + CACBD166E573774FB5613C34AA6DA7A7 /* EventMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6E83B6C22DAEE09F932BFA6EF6AF9E84 /* EventMonitor.swift */; }; + CE62FEABA57B2B53EABF8C7DCCC6B2C4 /* ConstraintRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 16EB8401383F4A4D8FD5EE35D857CA59 /* ConstraintRelation.swift */; }; + D4697DC40F3B059E4A0867838CA1814E /* ConstraintMultiplierTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3FF5F53F5C512A348BB18B8A3B551F9E /* ConstraintMultiplierTarget.swift */; }; + D6B2983389480F48F27A0704EEB5DC81 /* RetryPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CBF2313A3A2B1A15BAD3AF3070363C1 /* RetryPolicy.swift */; }; + E07BD425C4EA9ADF15DDFCDB10D0B2FB /* MultipartUpload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3F7E292F2BC7EE18246B3E01DC333A74 /* MultipartUpload.swift */; }; + E4E12208D5246E64B7E6CCAE987ADB03 /* URLRequest+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 742F77E864037957DDB07C9941C1F583 /* URLRequest+Alamofire.swift */; }; + E8F2429683B3015CBD39CE883770BCA7 /* ConstraintPriorityTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = B36DD62B3FB61D170312818C61D159F6 /* ConstraintPriorityTarget.swift */; }; + E9A5AC2F471699CCA516952A5FEB990B /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17C65275FA0E11EFAA43B2117A3088CA /* DispatchQueue+Alamofire.swift */; }; + E9A970BC24EA15832F248EA020072746 /* LayoutConstraintItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 665DFD27190A94EB43EB50F42836D682 /* LayoutConstraintItem.swift */; }; + EB1726F5E0D0EEBA20E4528B1E37A8FA /* ConstraintViewDSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = E6F43CF6221ACA96D10DDB06C8D915EA /* ConstraintViewDSL.swift */; }; + EE909C7C786140109051BC9562EEC7C8 /* ConstraintMakerPriortizable.swift in Sources */ = {isa = PBXBuildFile; fileRef = E6A4B412E66BBCEF35ADEC18F6687858 /* ConstraintMakerPriortizable.swift */; }; + F71789DC91A75033EFB79DB828676451 /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = C62FCE30BDD74C6CA538C694AC63A7C0 /* Response.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ - BC7DFE3A281EB7C0F33C91C50A8334E7 /* PBXContainerItemProxy */ = { + 1FBED9898C98868FA66785D019839015 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; proxyType = 1; - remoteGlobalIDString = 6E18B0FFB4F36914492A16C4D9F5E7C8; - remoteInfo = SnapKit; + remoteGlobalIDString = EAAA1AD3A8A1B59AB91319EE40752C6D; + remoteInfo = Alamofire; }; - F6B118EF4291671D7752C41AACAF5394 /* PBXContainerItemProxy */ = { + 44625DBBBF0FFCF1DDCF9EB00788A644 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; proxyType = 1; - remoteGlobalIDString = 88E9EC28B8B46C3631E6B242B50F4442; - remoteInfo = Alamofire; + remoteGlobalIDString = D118A6A04828FD3CDA8640CD2B6796D2; + remoteInfo = SwiftyJSON; }; - FC2DB381F375BF61743F66FA70D03EA0 /* PBXContainerItemProxy */ = { + 5FEE99F93B3F3AE00154BBC1D8868F2A /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; proxyType = 1; - remoteGlobalIDString = CDB25960C355207D9FFA9D17E0F8CD99; - remoteInfo = SwiftyJSON; + remoteGlobalIDString = 52B60EC2A583F24ACBB69C113F5488B9; + remoteInfo = SwiftLint; + }; + C322490DD2D0EC82A3EC5904FF8C92FB /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 19622742EBA51E823D6DAE3F8CDBFAD4; + remoteInfo = SnapKit; }; /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ - 00B2270DBEB57EEA2AFFC9272707BB09 /* SwiftyJSON.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = SwiftyJSON.modulemap; sourceTree = ""; }; - 00CFA1046F9997C3F2279DA92E6C7F9D /* SwiftyJSON-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SwiftyJSON-prefix.pch"; sourceTree = ""; }; - 00E4412F67364360F74E8CCF2AA555DD /* ConstraintInsetTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintInsetTarget.swift; path = Source/ConstraintInsetTarget.swift; sourceTree = ""; }; - 01882FD6A64E5846C465601C2F805C0A /* ConstraintMultiplierTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMultiplierTarget.swift; path = Source/ConstraintMultiplierTarget.swift; sourceTree = ""; }; - 064A7532CBC50377E2722DC5CA09ED89 /* Pods-WWCodeDFW-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-WWCodeDFW-resources.sh"; sourceTree = ""; }; - 0ED2A647955895F8E2478887A64478FC /* ConstraintAttributes.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintAttributes.swift; path = Source/ConstraintAttributes.swift; sourceTree = ""; }; - 1013694FC50E04A5AC0C1E906243B1EA /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 12C136C58152FC54E2F406E9B331B244 /* ConstraintPriorityTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintPriorityTarget.swift; path = Source/ConstraintPriorityTarget.swift; sourceTree = ""; }; - 163272BF09771EE4D6481761A332AAE4 /* ConstraintItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintItem.swift; path = Source/ConstraintItem.swift; sourceTree = ""; }; - 19D12DA9A35038FF4EA790D8ECAC4228 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 1A4969DA8509FCF2EABA3B5FB095BBBF /* ConstraintRelatableTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintRelatableTarget.swift; path = Source/ConstraintRelatableTarget.swift; sourceTree = ""; }; - 2257B11270A64D3AF5F497010AF0D01B /* ConstraintRelation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintRelation.swift; path = Source/ConstraintRelation.swift; sourceTree = ""; }; - 23DF0BF09622711B35C079E49C8D8701 /* AFError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AFError.swift; path = Source/AFError.swift; sourceTree = ""; }; - 244AAFD6A5CF20E1958B107A68640125 /* ConstraintLayoutSupportDSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintLayoutSupportDSL.swift; path = Source/ConstraintLayoutSupportDSL.swift; sourceTree = ""; }; - 28BF3B0EB3EBD6EEBFBE2A092AC34F81 /* ConstraintLayoutGuideDSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintLayoutGuideDSL.swift; path = Source/ConstraintLayoutGuideDSL.swift; sourceTree = ""; }; - 29A64D3DD7AAAE8EFC90C107050EA7DA /* SnapKit.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SnapKit.xcconfig; sourceTree = ""; }; - 2B2C3EFE31585F78DE2591E3054690D0 /* ConstraintMakerFinalizable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerFinalizable.swift; path = Source/ConstraintMakerFinalizable.swift; sourceTree = ""; }; - 2D1A354791813791DECF12B24CCA6CBB /* SwiftyJSON.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SwiftyJSON.swift; path = Source/SwiftyJSON.swift; sourceTree = ""; }; - 2FEF61CBBDB8259CD6AD1257BAB8932F /* UILayoutGuide+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UILayoutGuide+Extensions.swift"; path = "Source/UILayoutGuide+Extensions.swift"; sourceTree = ""; }; - 30D69444A876031C0DD47BFC4F43C6B4 /* ConstraintView+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ConstraintView+Extensions.swift"; path = "Source/ConstraintView+Extensions.swift"; sourceTree = ""; }; - 3165759575400A03BDB5336CD4ABB656 /* SwiftyJSON-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SwiftyJSON-umbrella.h"; sourceTree = ""; }; - 3168036C7D6A18C3EBE01ABDC14D777F /* LayoutConstraint.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LayoutConstraint.swift; path = Source/LayoutConstraint.swift; sourceTree = ""; }; - 31E82A9D837389194284B5BF2B59A6CF /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Alamofire.framework; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 376BEF74A19D59C12528AF337E9B7056 /* ConstraintConfig.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintConfig.swift; path = Source/ConstraintConfig.swift; sourceTree = ""; }; - 3C2E3F461D9829E8EAFC731DB5B6BA35 /* Pods-WWCodeDFW.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = "Pods-WWCodeDFW.modulemap"; sourceTree = ""; }; - 4134F22A9E49EA2F464E71718753DA46 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; - 4597569C3304C012A453BD0C2CFAA1B6 /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; - 4A20BBBEB5531B60C02D21E98CB45B3A /* SnapKit-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SnapKit-umbrella.h"; sourceTree = ""; }; - 4DBD4C8E2336679C83BC14C17459D268 /* ConstraintOffsetTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintOffsetTarget.swift; path = Source/ConstraintOffsetTarget.swift; sourceTree = ""; }; - 4F6BE40E032152F0921979FC371C6BFC /* DispatchQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Alamofire.swift"; path = "Source/DispatchQueue+Alamofire.swift"; sourceTree = ""; }; - 4FDA868004B42710EBF6B373767523E3 /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; - 5066D678D9AF27C7F939DF767A8E9DDF /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 521858488A8EBB078CCEDCC388F58137 /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; - 54A43B2E22A1EC8B0307547BA070ED7B /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; - 5BD89A697635A40B3220858FB4337DCF /* SnapKit-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "SnapKit-dummy.m"; sourceTree = ""; }; - 5E22A35D4D38B894EF0E688BB6F0DD04 /* ConstraintMakerExtendable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerExtendable.swift; path = Source/ConstraintMakerExtendable.swift; sourceTree = ""; }; - 5E66E8E584A50A01E56998CC586581BD /* ConstraintView.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintView.swift; path = Source/ConstraintView.swift; sourceTree = ""; }; - 62FB28794B829890A3BCF9FCEF7F565E /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; - 653FBE396161F841A60E129B2CDED598 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; - 6604A7D69453B4569E4E4827FB9155A9 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.3.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; - 677A15C5C4A29E85F4D45B498214BC3A /* Pods-WWCodeDFW.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-WWCodeDFW.release.xcconfig"; sourceTree = ""; }; - 67A26D60318A9A85EC52F646C3AB67AA /* ConstraintMaker.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMaker.swift; path = Source/ConstraintMaker.swift; sourceTree = ""; }; - 69ED5B0211F6CDE2702F4D92FF06CC89 /* Pods_WWCodeDFW.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_WWCodeDFW.framework; path = "Pods-WWCodeDFW.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; - 6FC7B72688C16A9E4958A6E7F4C79F8C /* UILayoutSupport+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UILayoutSupport+Extensions.swift"; path = "Source/UILayoutSupport+Extensions.swift"; sourceTree = ""; }; - 72EC50C520FDB3DF8E52B09AA5B50854 /* SwiftyJSON.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SwiftyJSON.xcconfig; sourceTree = ""; }; - 754019566FDA07E5500B87178C38BD7B /* SwiftyJSON.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = SwiftyJSON.framework; path = SwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 75A40EDFE893A0C4CEA1EDB17B51161B /* Pods-WWCodeDFW-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-WWCodeDFW-dummy.m"; sourceTree = ""; }; - 75FF1AD01519364BB8C2F851435FD60B /* Debugging.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Debugging.swift; path = Source/Debugging.swift; sourceTree = ""; }; - 76A040BE714228552CF0DE7A04894364 /* Pods-WWCodeDFW.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-WWCodeDFW.debug.xcconfig"; sourceTree = ""; }; - 76BD74AD4191847740695C98F67B7978 /* ConstraintConstantTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintConstantTarget.swift; path = Source/ConstraintConstantTarget.swift; sourceTree = ""; }; - 7B51A0C17DB6F80A02EC398273876EE8 /* ConstraintLayoutSupport.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintLayoutSupport.swift; path = Source/ConstraintLayoutSupport.swift; sourceTree = ""; }; - 7D7B31B7B1F6740D1AA4CEEF529FD88F /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; - 7FCD0718E443977536F44F2C41D408E2 /* SwiftyJSON-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "SwiftyJSON-dummy.m"; sourceTree = ""; }; - 86EA776E2127E554419B449CC53EBB37 /* Pods-WWCodeDFW-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-WWCodeDFW-frameworks.sh"; sourceTree = ""; }; - 87A4FD42575EF7D6DDEFAE920F1528DA /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; - 8A3B15743D850320977FB93C948A3E36 /* Pods-WWCodeDFW-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-WWCodeDFW-acknowledgements.plist"; sourceTree = ""; }; - 8A5D94811A8BB2DE4CAC223B9AC330A6 /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; - 92EE5B0ECE9DF92F2087A08233C06D35 /* ConstraintViewDSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintViewDSL.swift; path = Source/ConstraintViewDSL.swift; sourceTree = ""; }; - 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; - 95297299E1618043BD1110D4CEC5C2CD /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; - 98FBDCF555C053DF3C50AB85167A5153 /* SnapKit.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = SnapKit.modulemap; sourceTree = ""; }; - 992A2DBE11BE21161FFA58D73947BB5E /* SessionManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionManager.swift; path = Source/SessionManager.swift; sourceTree = ""; }; - A0D0A1C53BBE67C2A8ED3ECE85014BB9 /* ConstraintDescription.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintDescription.swift; path = Source/ConstraintDescription.swift; sourceTree = ""; }; - A2E2E12CCECCF718F91ACA3B0018A756 /* Timeline.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeline.swift; path = Source/Timeline.swift; sourceTree = ""; }; - A457067AFDFE02D54986C3A675DB0CF3 /* Pods-WWCodeDFW-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-WWCodeDFW-umbrella.h"; sourceTree = ""; }; - A91436829018A3397CC451C4E7C1726C /* ConstraintLayoutGuide.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintLayoutGuide.swift; path = Source/ConstraintLayoutGuide.swift; sourceTree = ""; }; - AAB020DE36C50C1E326CBC1E46F38A32 /* TaskDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TaskDelegate.swift; path = Source/TaskDelegate.swift; sourceTree = ""; }; - AC0C1A53329F0C3B2C953DD512F1600B /* ConstraintMakerPriortizable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerPriortizable.swift; path = Source/ConstraintMakerPriortizable.swift; sourceTree = ""; }; - BE5EC0FAAC28192E79277BEA6C669B55 /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; - C03C272676143735DBAF78D7DF84EAC0 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; - C7278C33B79918154B6ABFDD22DD1417 /* SnapKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = SnapKit.framework; path = SnapKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - CA2FEBB6E61F686A4D357D56177E47AD /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; - D7C91E6A7F6A9BE9B98B2BD7C70E6BA0 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - E1390CCA24783C2E95B3264878F43990 /* ConstraintDSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintDSL.swift; path = Source/ConstraintDSL.swift; sourceTree = ""; }; - E49D17DE66BA0D742B74E515D9C2DF7F /* SnapKit-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SnapKit-prefix.pch"; sourceTree = ""; }; - E697F9B1B21E934EC9EA4A8BE887AD35 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = Alamofire.modulemap; sourceTree = ""; }; - F36AD9699DA44A5ABBC3BC0C2CF02483 /* Pods-WWCodeDFW-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-WWCodeDFW-acknowledgements.markdown"; sourceTree = ""; }; - F3E0E9A410D9D8B6DD2404ECB3329758 /* Constraint.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Constraint.swift; path = Source/Constraint.swift; sourceTree = ""; }; - F4966F0F235C7F44396807DD853056A2 /* ConstraintMakerEditable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerEditable.swift; path = Source/ConstraintMakerEditable.swift; sourceTree = ""; }; - F6DD033C1F2C5459D093F98556011ACE /* SessionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDelegate.swift; path = Source/SessionDelegate.swift; sourceTree = ""; }; - F6F7A494B4CD996B3F523C2B28FFEE52 /* ConstraintInsets.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintInsets.swift; path = Source/ConstraintInsets.swift; sourceTree = ""; }; - FA3D33741DF328C147592105977B9CE9 /* ConstraintMakerRelatable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerRelatable.swift; path = Source/ConstraintMakerRelatable.swift; sourceTree = ""; }; - FB8C54435226E98CE66D6D40A76E4112 /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; + 015BBD18BF1855CB92828380CF23E4C4 /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; + 03D69B495F6DCC8BD2D3563ECAF65A56 /* ConstraintDirectionalInsets.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintDirectionalInsets.swift; path = Source/ConstraintDirectionalInsets.swift; sourceTree = ""; }; + 03E0CE90135820AD6EB98B1708B6686C /* RequestInterceptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestInterceptor.swift; path = Source/RequestInterceptor.swift; sourceTree = ""; }; + 08FDA4ED3BF404E757C38D951ED51DFC /* SnapKit.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = SnapKit.modulemap; sourceTree = ""; }; + 0AE0F46D2C9DC01A421478544DA764B7 /* ServerTrustEvaluation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustEvaluation.swift; path = Source/ServerTrustEvaluation.swift; sourceTree = ""; }; + 0CBF2313A3A2B1A15BAD3AF3070363C1 /* RetryPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RetryPolicy.swift; path = Source/RetryPolicy.swift; sourceTree = ""; }; + 0F532BB6F9CDAA87990FEEBEEC0C8B51 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; + 13C1F87EB6FCA8ABA385BFBD29DE25EE /* ConstraintMakerExtendable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerExtendable.swift; path = Source/ConstraintMakerExtendable.swift; sourceTree = ""; }; + 15B49BE04AAF5CADC67B31B4F380303C /* SwiftyJSON.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SwiftyJSON.xcconfig; sourceTree = ""; }; + 16E549A0951E655F87E750857EEF9326 /* Constraint.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Constraint.swift; path = Source/Constraint.swift; sourceTree = ""; }; + 16EB8401383F4A4D8FD5EE35D857CA59 /* ConstraintRelation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintRelation.swift; path = Source/ConstraintRelation.swift; sourceTree = ""; }; + 17C65275FA0E11EFAA43B2117A3088CA /* DispatchQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Alamofire.swift"; path = "Source/DispatchQueue+Alamofire.swift"; sourceTree = ""; }; + 185E08DFC78FD74FD5E4DD16703B0D70 /* Pods-WWCodeDFW.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-WWCodeDFW.debug.xcconfig"; sourceTree = ""; }; + 18E7F72B7EF4EBD4894D5C53C986D455 /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; + 1AC96EFCCA6682A47864FB240B381D44 /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; + 207FDC0806D5BDCAD5E50A07CE8DAC3C /* RequestTaskMap.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestTaskMap.swift; path = Source/RequestTaskMap.swift; sourceTree = ""; }; + 222DAEF0D819F359AFCFF3D4F927E8A7 /* 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; }; + 23885A65DE219E49A7F9948BC45F4EA0 /* CachedResponseHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CachedResponseHandler.swift; path = Source/CachedResponseHandler.swift; sourceTree = ""; }; + 2C553488DEA28084B2F4231B3AB693F3 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; + 3A40E6C43AE8DAC3243F6B8D7CA1011A /* ConstraintLayoutGuideDSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintLayoutGuideDSL.swift; path = Source/ConstraintLayoutGuideDSL.swift; sourceTree = ""; }; + 3B294424D831BD800E40EBD6E1A4FB7A /* ConstraintView+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ConstraintView+Extensions.swift"; path = "Source/ConstraintView+Extensions.swift"; sourceTree = ""; }; + 3F7E292F2BC7EE18246B3E01DC333A74 /* MultipartUpload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartUpload.swift; path = Source/MultipartUpload.swift; sourceTree = ""; }; + 3FF5F53F5C512A348BB18B8A3B551F9E /* ConstraintMultiplierTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMultiplierTarget.swift; path = Source/ConstraintMultiplierTarget.swift; sourceTree = ""; }; + 43CE0861FD67C513B840AAC82F8D25F6 /* AlamofireExtended.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AlamofireExtended.swift; path = Source/AlamofireExtended.swift; sourceTree = ""; }; + 48C45D08A0A8C8084260C0281CD2EA6A /* URLEncodedFormEncoder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = URLEncodedFormEncoder.swift; path = Source/URLEncodedFormEncoder.swift; sourceTree = ""; }; + 4C497976C7FAF1DEEA94CBE83D61430F /* Pods-WWCodeDFW-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-WWCodeDFW-Info.plist"; sourceTree = ""; }; + 4F19EE7C03E1B43F1FF41D4A1DE005AA /* ConstraintPriority.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintPriority.swift; path = Source/ConstraintPriority.swift; sourceTree = ""; }; + 4F396B2619519A3DE23C24CAA8763851 /* ConstraintMaker.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMaker.swift; path = Source/ConstraintMaker.swift; sourceTree = ""; }; + 50514B7777AC28C9444C4D90154EA9A2 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; + 50E3EE3D81F1B9A1610C433B1D95DE46 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; + 5593F02B88EBD5DBE150CF2F5E49F0A2 /* Result+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Result+Alamofire.swift"; path = "Source/Result+Alamofire.swift"; sourceTree = ""; }; + 5B11437C7272707E16C3A0C2667521B6 /* ConstraintItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintItem.swift; path = Source/ConstraintItem.swift; sourceTree = ""; }; + 5CBE3345FE7A6E098E88DC8990F4E94F /* ConstraintDirectionalInsetTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintDirectionalInsetTarget.swift; path = Source/ConstraintDirectionalInsetTarget.swift; sourceTree = ""; }; + 5D797E9A5C5782CE845840781FA1CC81 /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Alamofire.framework; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 5F64022683034A8AA85F36A4CB519C2A /* SwiftyJSON-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "SwiftyJSON-Info.plist"; sourceTree = ""; }; + 5FD6FE8733408319093C5B7644E408BC /* SnapKit-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SnapKit-prefix.pch"; sourceTree = ""; }; + 66130A4A3BE6C8519BF4D77A507882CB /* SnapKit-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "SnapKit-Info.plist"; sourceTree = ""; }; + 665DFD27190A94EB43EB50F42836D682 /* LayoutConstraintItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LayoutConstraintItem.swift; path = Source/LayoutConstraintItem.swift; sourceTree = ""; }; + 6801A7943BF8C6FC06D1CEF2D936DA44 /* ConstraintMakerRelatable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerRelatable.swift; path = Source/ConstraintMakerRelatable.swift; sourceTree = ""; }; + 6CABAEDBBE4180B8C4FB18EA14FA9E15 /* Typealiases.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Typealiases.swift; path = Source/Typealiases.swift; sourceTree = ""; }; + 6DF169FFD269C38A9D9A628AC36C42F7 /* SwiftyJSON.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = SwiftyJSON.modulemap; sourceTree = ""; }; + 6E83B6C22DAEE09F932BFA6EF6AF9E84 /* EventMonitor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EventMonitor.swift; path = Source/EventMonitor.swift; sourceTree = ""; }; + 6E8BE21373A78F570DA43B1C9B2B965C /* ConstraintMakerFinalizable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerFinalizable.swift; path = Source/ConstraintMakerFinalizable.swift; sourceTree = ""; }; + 725E4C16A0ACE592FAEFE1415DE54219 /* ConstraintConfig.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintConfig.swift; path = Source/ConstraintConfig.swift; sourceTree = ""; }; + 742F77E864037957DDB07C9941C1F583 /* URLRequest+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLRequest+Alamofire.swift"; path = "Source/URLRequest+Alamofire.swift"; sourceTree = ""; }; + 7EF7CC69E679E85C153F0CA61B29A9D3 /* SnapKit.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SnapKit.xcconfig; sourceTree = ""; }; + 8162923BC3A26324092E2961DBC2746C /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; + 81A7CDD945D4005D44D48C2810323C94 /* OperationQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "OperationQueue+Alamofire.swift"; path = "Source/OperationQueue+Alamofire.swift"; sourceTree = ""; }; + 85362A716D7C46C8C1E8F07D6103E36A /* SwiftyJSON-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "SwiftyJSON-dummy.m"; sourceTree = ""; }; + 853B4B67909902A8D36D45611D81709A /* ConstraintDescription.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintDescription.swift; path = Source/ConstraintDescription.swift; sourceTree = ""; }; + 8A44899DF1DABCA59DD9362A99EEA460 /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; + 8B079F294DA5D9A879E6D53A91F51A1E /* 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; }; + 8E4FCAD90901006470F70E663019746D /* LayoutConstraint.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LayoutConstraint.swift; path = Source/LayoutConstraint.swift; sourceTree = ""; }; + 8ED5FE97C61127F2E240B2482D7ACA08 /* HTTPMethod.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HTTPMethod.swift; path = Source/HTTPMethod.swift; sourceTree = ""; }; + 93A3641119044DAAF34D357E1EAE2403 /* ConstraintDSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintDSL.swift; path = Source/ConstraintDSL.swift; sourceTree = ""; }; + 94060F0D07C2C9B715A3FC5D26B76AB7 /* ConstraintRelatableTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintRelatableTarget.swift; path = Source/ConstraintRelatableTarget.swift; sourceTree = ""; }; + 94FDFE7056EC1D9DB4EA8C89A0AB1F7B /* SwiftyJSON-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SwiftyJSON-umbrella.h"; sourceTree = ""; }; + 979486118B3E90C08386079D57962701 /* SnapKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = SnapKit.framework; path = SnapKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 9814C1BF0430FC09DFA1D3A306C00C44 /* ConstraintLayoutSupportDSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintLayoutSupportDSL.swift; path = Source/ConstraintLayoutSupportDSL.swift; sourceTree = ""; }; + 9C107F334249B4C7F034D4A75F45DBDC /* Debugging.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Debugging.swift; path = Source/Debugging.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; }; + A210FD675C0C625827FE8C76D6DDCC10 /* HTTPHeaders.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HTTPHeaders.swift; path = Source/HTTPHeaders.swift; sourceTree = ""; }; + A74FC8AC9AD8E5265410F78F82AF63BF /* Pods-WWCodeDFW.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-WWCodeDFW.release.xcconfig"; sourceTree = ""; }; + A80B60D253F6EB6C8848C11B11AE2179 /* ConstraintLayoutSupport.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintLayoutSupport.swift; path = Source/ConstraintLayoutSupport.swift; sourceTree = ""; }; + A9490683541D9C86E8BE6AC2450B1FAA /* Pods_WWCodeDFW.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_WWCodeDFW.framework; path = "Pods-WWCodeDFW.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + AFF52223DD0A448825CA36DBA01E0501 /* Alamofire-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Alamofire-Info.plist"; sourceTree = ""; }; + B36DD62B3FB61D170312818C61D159F6 /* ConstraintPriorityTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintPriorityTarget.swift; path = Source/ConstraintPriorityTarget.swift; sourceTree = ""; }; + B4AF76DC816F6C9F7E06936993144605 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Alamofire.modulemap; sourceTree = ""; }; + B81C59E3284628C480B265A0ABBFFB1B /* Pods-WWCodeDFW.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-WWCodeDFW.modulemap"; sourceTree = ""; }; + BE17175641E2D35B161ECEFCC6783A11 /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; + BF1FB8E30B81304D11B3F8C95426A552 /* RedirectHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RedirectHandler.swift; path = Source/RedirectHandler.swift; sourceTree = ""; }; + BFEBF4AA03E01C4D091EBEB4C8D537D8 /* Protector.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Protector.swift; path = Source/Protector.swift; sourceTree = ""; }; + C1EA3AA8BFBE64B16061D4246F2BB8CB /* SnapKit-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "SnapKit-dummy.m"; sourceTree = ""; }; + C31B2EDD8BE2A58CFD16852AB21AD914 /* ConstraintView.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintView.swift; path = Source/ConstraintView.swift; sourceTree = ""; }; + C5253A7F4C94E49842026933DAF4A714 /* ConstraintInsetTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintInsetTarget.swift; path = Source/ConstraintInsetTarget.swift; sourceTree = ""; }; + C62FCE30BDD74C6CA538C694AC63A7C0 /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; + C654B033B1C04E51ED977630E10EF61F /* SessionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDelegate.swift; path = Source/SessionDelegate.swift; sourceTree = ""; }; + C6C6CED2376FAF35FE0610FD9DCEBAC0 /* ConstraintConstantTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintConstantTarget.swift; path = Source/ConstraintConstantTarget.swift; sourceTree = ""; }; + C8E4F9B31C7EB9A06CF46EFCA4BDEE95 /* SwiftLint.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SwiftLint.xcconfig; sourceTree = ""; }; + CA53997A5E2CCFF41BF5738BD0A64F6C /* Session.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Session.swift; path = Source/Session.swift; sourceTree = ""; }; + CA60FA61B161DA65AB1CC384C4D7A74F /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; + CB17097B335E35409CB46110FB5A0616 /* Pods-WWCodeDFW-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-WWCodeDFW-acknowledgements.plist"; sourceTree = ""; }; + CDF96B1EB07CC5CAA3AA5ACBE52B20F5 /* SwiftyJSON-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SwiftyJSON-prefix.pch"; sourceTree = ""; }; + CE2B8CEF341D5EA7FF0EF91DDA9B4E69 /* ConstraintInsets.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintInsets.swift; path = Source/ConstraintInsets.swift; sourceTree = ""; }; + D1AA755DD8BF7D30F2175A0C30067E96 /* ParameterEncoder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoder.swift; path = Source/ParameterEncoder.swift; sourceTree = ""; }; + D4377A4C465256EEB8681E90A172DADD /* ConstraintOffsetTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintOffsetTarget.swift; path = Source/ConstraintOffsetTarget.swift; sourceTree = ""; }; + D45A24230E040C510DFA36CAE246C6BC /* Pods-WWCodeDFW-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-WWCodeDFW-dummy.m"; sourceTree = ""; }; + D5255A80CFA98886E4CAAF379205860B /* AFError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AFError.swift; path = Source/AFError.swift; sourceTree = ""; }; + DAEFC97DC423B4E3F0A95FDF0B393427 /* UILayoutSupport+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UILayoutSupport+Extensions.swift"; path = "Source/UILayoutSupport+Extensions.swift"; sourceTree = ""; }; + DBA8BE0AFDCCB28E8C4EF3ECE00051C9 /* URLConvertible+URLRequestConvertible.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLConvertible+URLRequestConvertible.swift"; path = "Source/URLConvertible+URLRequestConvertible.swift"; sourceTree = ""; }; + DC21BAAB3FD88C0A9CE3C88A67D780BB /* SnapKit-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SnapKit-umbrella.h"; sourceTree = ""; }; + E23C076BA70925415F490FEDB215DA92 /* SwiftyJSON.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = SwiftyJSON.framework; path = SwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + E49FFA5C76E350A578A9976F0A0DB329 /* Pods-WWCodeDFW-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-WWCodeDFW-umbrella.h"; sourceTree = ""; }; + E6A4B412E66BBCEF35ADEC18F6687858 /* ConstraintMakerPriortizable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerPriortizable.swift; path = Source/ConstraintMakerPriortizable.swift; sourceTree = ""; }; + E6F43CF6221ACA96D10DDB06C8D915EA /* ConstraintViewDSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintViewDSL.swift; path = Source/ConstraintViewDSL.swift; sourceTree = ""; }; + E77CC8F2D0CD5C3E53CB528F4FEDA801 /* Pods-WWCodeDFW-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-WWCodeDFW-acknowledgements.markdown"; sourceTree = ""; }; + EA341057A222274517791AE4BECDE83E /* SwiftyJSON.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SwiftyJSON.swift; path = Source/SwiftyJSON/SwiftyJSON.swift; sourceTree = ""; }; + EC0F93AB9486D318FF3F34B1B7DE4F7B /* ConstraintLayoutGuide+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ConstraintLayoutGuide+Extensions.swift"; path = "Source/ConstraintLayoutGuide+Extensions.swift"; sourceTree = ""; }; + F0ADDAACB71C0827F5C2692E2192A881 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; + F2E50A06339722D33BF003CA1AD08421 /* URLSessionConfiguration+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLSessionConfiguration+Alamofire.swift"; path = "Source/URLSessionConfiguration+Alamofire.swift"; sourceTree = ""; }; + F56F4D2FD0FC69F93B69041775FCEB64 /* Pods-WWCodeDFW-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-WWCodeDFW-frameworks.sh"; sourceTree = ""; }; + F73441A77CCB02E381125BE899596B1F /* ConstraintMakerEditable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerEditable.swift; path = Source/ConstraintMakerEditable.swift; sourceTree = ""; }; + F835E63FFD2E853B5EDA7B06EA17E62C /* ConstraintAttributes.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintAttributes.swift; path = Source/ConstraintAttributes.swift; sourceTree = ""; }; + FFDB71AA280F49CBB5217FFE1621333D /* ConstraintLayoutGuide.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintLayoutGuide.swift; path = Source/ConstraintLayoutGuide.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ - 99195E4207764744AEC07ECCBCD550EB /* Frameworks */ = { + 2A7AD185E895038D87AD109FB4FA66B1 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 73B9C996AED49ED7CF8EC2A6F1738059 /* Foundation.framework in Frameworks */, + A6BB6FAAA15A27EC32508F167E7BB95B /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; - BD0D45C7600CD6912D6EF5AF3ACD4B4A /* Frameworks */ = { + 3C8B1704CC97EF12D3409771318C6433 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - E298E9467EC7FB473E3AC6B362C01D17 /* Foundation.framework in Frameworks */, + 04543980C4A7CE442330B0F1BC4A9A54 /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; - C55BD4362198DFA25E1F6D1992807293 /* Frameworks */ = { + 8B0D8633F410345F93419B8C3D7B6916 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 86CF01DC27A3B9016587EA202BF36F8C /* Foundation.framework in Frameworks */, + 97A168DFB6DB61770CE2DBF4FD39AA8D /* CFNetwork.framework in Frameworks */, + BE82AE980F8C7EE28A6448959194F93A /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; - FE359978A45038B288958C8B1A9F6378 /* Frameworks */ = { + AD9C5A8DAF4334B670E91B2EC08DBE2C /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - C0234E523428AA2D53C7E2D952CD5995 /* Foundation.framework in Frameworks */, + 464450D037D17ED5EE2322E180A6A9F5 /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 1A7597C079C30E46B706AA07F719FEA0 /* Support Files */ = { + 1628BF05B4CAFDCC3549A101F5A10A17 /* Frameworks */ = { isa = PBXGroup; children = ( - 1013694FC50E04A5AC0C1E906243B1EA /* Info.plist */, - 00B2270DBEB57EEA2AFFC9272707BB09 /* SwiftyJSON.modulemap */, - 72EC50C520FDB3DF8E52B09AA5B50854 /* SwiftyJSON.xcconfig */, - 7FCD0718E443977536F44F2C41D408E2 /* SwiftyJSON-dummy.m */, - 00CFA1046F9997C3F2279DA92E6C7F9D /* SwiftyJSON-prefix.pch */, - 3165759575400A03BDB5336CD4ABB656 /* SwiftyJSON-umbrella.h */, + E34DCC8E2CF86B8D72232914781A840D /* iOS */, ); - name = "Support Files"; - path = "../Target Support Files/SwiftyJSON"; + name = Frameworks; sourceTree = ""; }; - 1BC4B071A92E6C9C6F1936FCCE0B87B5 /* Support Files */ = { + 26EBC3E8B76CB3E7A202BBB12DBF5990 /* Targets Support Files */ = { isa = PBXGroup; children = ( - E697F9B1B21E934EC9EA4A8BE887AD35 /* Alamofire.modulemap */, - 8A5D94811A8BB2DE4CAC223B9AC330A6 /* Alamofire.xcconfig */, - 87A4FD42575EF7D6DDEFAE920F1528DA /* Alamofire-dummy.m */, - CA2FEBB6E61F686A4D357D56177E47AD /* Alamofire-prefix.pch */, - 4134F22A9E49EA2F464E71718753DA46 /* Alamofire-umbrella.h */, - D7C91E6A7F6A9BE9B98B2BD7C70E6BA0 /* Info.plist */, + 3176EB141049CA5219B869C989C32612 /* Pods-WWCodeDFW */, ); - name = "Support Files"; - path = "../Target Support Files/Alamofire"; + name = "Targets Support Files"; sourceTree = ""; }; - 54FCCF657F4FE3BDB43598BF4E927503 /* Alamofire */ = { + 2A9AA9713656090841F32D0A208C7861 /* SnapKit */ = { isa = PBXGroup; children = ( - 23DF0BF09622711B35C079E49C8D8701 /* AFError.swift */, - 95297299E1618043BD1110D4CEC5C2CD /* Alamofire.swift */, - 4F6BE40E032152F0921979FC371C6BFC /* DispatchQueue+Alamofire.swift */, - C03C272676143735DBAF78D7DF84EAC0 /* MultipartFormData.swift */, - BE5EC0FAAC28192E79277BEA6C669B55 /* NetworkReachabilityManager.swift */, - 4597569C3304C012A453BD0C2CFAA1B6 /* Notifications.swift */, - 653FBE396161F841A60E129B2CDED598 /* ParameterEncoding.swift */, - 7D7B31B7B1F6740D1AA4CEEF529FD88F /* Request.swift */, - FB8C54435226E98CE66D6D40A76E4112 /* Response.swift */, - 521858488A8EBB078CCEDCC388F58137 /* ResponseSerialization.swift */, - 54A43B2E22A1EC8B0307547BA070ED7B /* Result.swift */, - 4FDA868004B42710EBF6B373767523E3 /* ServerTrustPolicy.swift */, - F6DD033C1F2C5459D093F98556011ACE /* SessionDelegate.swift */, - 992A2DBE11BE21161FFA58D73947BB5E /* SessionManager.swift */, - AAB020DE36C50C1E326CBC1E46F38A32 /* TaskDelegate.swift */, - A2E2E12CCECCF718F91ACA3B0018A756 /* Timeline.swift */, - 62FB28794B829890A3BCF9FCEF7F565E /* Validation.swift */, - 1BC4B071A92E6C9C6F1936FCCE0B87B5 /* Support Files */, + 16E549A0951E655F87E750857EEF9326 /* Constraint.swift */, + F835E63FFD2E853B5EDA7B06EA17E62C /* ConstraintAttributes.swift */, + 725E4C16A0ACE592FAEFE1415DE54219 /* ConstraintConfig.swift */, + C6C6CED2376FAF35FE0610FD9DCEBAC0 /* ConstraintConstantTarget.swift */, + 853B4B67909902A8D36D45611D81709A /* ConstraintDescription.swift */, + 03D69B495F6DCC8BD2D3563ECAF65A56 /* ConstraintDirectionalInsets.swift */, + 5CBE3345FE7A6E098E88DC8990F4E94F /* ConstraintDirectionalInsetTarget.swift */, + 93A3641119044DAAF34D357E1EAE2403 /* ConstraintDSL.swift */, + CE2B8CEF341D5EA7FF0EF91DDA9B4E69 /* ConstraintInsets.swift */, + C5253A7F4C94E49842026933DAF4A714 /* ConstraintInsetTarget.swift */, + 5B11437C7272707E16C3A0C2667521B6 /* ConstraintItem.swift */, + FFDB71AA280F49CBB5217FFE1621333D /* ConstraintLayoutGuide.swift */, + EC0F93AB9486D318FF3F34B1B7DE4F7B /* ConstraintLayoutGuide+Extensions.swift */, + 3A40E6C43AE8DAC3243F6B8D7CA1011A /* ConstraintLayoutGuideDSL.swift */, + A80B60D253F6EB6C8848C11B11AE2179 /* ConstraintLayoutSupport.swift */, + 9814C1BF0430FC09DFA1D3A306C00C44 /* ConstraintLayoutSupportDSL.swift */, + 4F396B2619519A3DE23C24CAA8763851 /* ConstraintMaker.swift */, + F73441A77CCB02E381125BE899596B1F /* ConstraintMakerEditable.swift */, + 13C1F87EB6FCA8ABA385BFBD29DE25EE /* ConstraintMakerExtendable.swift */, + 6E8BE21373A78F570DA43B1C9B2B965C /* ConstraintMakerFinalizable.swift */, + E6A4B412E66BBCEF35ADEC18F6687858 /* ConstraintMakerPriortizable.swift */, + 6801A7943BF8C6FC06D1CEF2D936DA44 /* ConstraintMakerRelatable.swift */, + 3FF5F53F5C512A348BB18B8A3B551F9E /* ConstraintMultiplierTarget.swift */, + D4377A4C465256EEB8681E90A172DADD /* ConstraintOffsetTarget.swift */, + 4F19EE7C03E1B43F1FF41D4A1DE005AA /* ConstraintPriority.swift */, + B36DD62B3FB61D170312818C61D159F6 /* ConstraintPriorityTarget.swift */, + 94060F0D07C2C9B715A3FC5D26B76AB7 /* ConstraintRelatableTarget.swift */, + 16EB8401383F4A4D8FD5EE35D857CA59 /* ConstraintRelation.swift */, + C31B2EDD8BE2A58CFD16852AB21AD914 /* ConstraintView.swift */, + 3B294424D831BD800E40EBD6E1A4FB7A /* ConstraintView+Extensions.swift */, + E6F43CF6221ACA96D10DDB06C8D915EA /* ConstraintViewDSL.swift */, + 9C107F334249B4C7F034D4A75F45DBDC /* Debugging.swift */, + 8E4FCAD90901006470F70E663019746D /* LayoutConstraint.swift */, + 665DFD27190A94EB43EB50F42836D682 /* LayoutConstraintItem.swift */, + 6CABAEDBBE4180B8C4FB18EA14FA9E15 /* Typealiases.swift */, + DAEFC97DC423B4E3F0A95FDF0B393427 /* UILayoutSupport+Extensions.swift */, + 3952759BAB777319D4F79D69A0BCABE8 /* Support Files */, ); - name = Alamofire; - path = Alamofire; + name = SnapKit; + path = SnapKit; sourceTree = ""; }; - 60167CD0DCDB064C444589E63C90155C /* SwiftyJSON */ = { + 3176EB141049CA5219B869C989C32612 /* Pods-WWCodeDFW */ = { isa = PBXGroup; children = ( - 2D1A354791813791DECF12B24CCA6CBB /* SwiftyJSON.swift */, - 1A7597C079C30E46B706AA07F719FEA0 /* Support Files */, + B81C59E3284628C480B265A0ABBFFB1B /* Pods-WWCodeDFW.modulemap */, + E77CC8F2D0CD5C3E53CB528F4FEDA801 /* Pods-WWCodeDFW-acknowledgements.markdown */, + CB17097B335E35409CB46110FB5A0616 /* Pods-WWCodeDFW-acknowledgements.plist */, + D45A24230E040C510DFA36CAE246C6BC /* Pods-WWCodeDFW-dummy.m */, + F56F4D2FD0FC69F93B69041775FCEB64 /* Pods-WWCodeDFW-frameworks.sh */, + 4C497976C7FAF1DEEA94CBE83D61430F /* Pods-WWCodeDFW-Info.plist */, + E49FFA5C76E350A578A9976F0A0DB329 /* Pods-WWCodeDFW-umbrella.h */, + 185E08DFC78FD74FD5E4DD16703B0D70 /* Pods-WWCodeDFW.debug.xcconfig */, + A74FC8AC9AD8E5265410F78F82AF63BF /* Pods-WWCodeDFW.release.xcconfig */, ); - name = SwiftyJSON; - path = SwiftyJSON; + name = "Pods-WWCodeDFW"; + path = "Target Support Files/Pods-WWCodeDFW"; sourceTree = ""; }; - 660B48AC182F13E3E4B680122B9DCD48 /* Pods-WWCodeDFW */ = { + 3952759BAB777319D4F79D69A0BCABE8 /* Support Files */ = { isa = PBXGroup; children = ( - 19D12DA9A35038FF4EA790D8ECAC4228 /* Info.plist */, - 3C2E3F461D9829E8EAFC731DB5B6BA35 /* Pods-WWCodeDFW.modulemap */, - F36AD9699DA44A5ABBC3BC0C2CF02483 /* Pods-WWCodeDFW-acknowledgements.markdown */, - 8A3B15743D850320977FB93C948A3E36 /* Pods-WWCodeDFW-acknowledgements.plist */, - 75A40EDFE893A0C4CEA1EDB17B51161B /* Pods-WWCodeDFW-dummy.m */, - 86EA776E2127E554419B449CC53EBB37 /* Pods-WWCodeDFW-frameworks.sh */, - 064A7532CBC50377E2722DC5CA09ED89 /* Pods-WWCodeDFW-resources.sh */, - A457067AFDFE02D54986C3A675DB0CF3 /* Pods-WWCodeDFW-umbrella.h */, - 76A040BE714228552CF0DE7A04894364 /* Pods-WWCodeDFW.debug.xcconfig */, - 677A15C5C4A29E85F4D45B498214BC3A /* Pods-WWCodeDFW.release.xcconfig */, + 08FDA4ED3BF404E757C38D951ED51DFC /* SnapKit.modulemap */, + 7EF7CC69E679E85C153F0CA61B29A9D3 /* SnapKit.xcconfig */, + C1EA3AA8BFBE64B16061D4246F2BB8CB /* SnapKit-dummy.m */, + 66130A4A3BE6C8519BF4D77A507882CB /* SnapKit-Info.plist */, + 5FD6FE8733408319093C5B7644E408BC /* SnapKit-prefix.pch */, + DC21BAAB3FD88C0A9CE3C88A67D780BB /* SnapKit-umbrella.h */, ); - name = "Pods-WWCodeDFW"; - path = "Target Support Files/Pods-WWCodeDFW"; + name = "Support Files"; + path = "../Target Support Files/SnapKit"; sourceTree = ""; }; - 6B51B35B4E4CD2543AC0AF1F9A9D89DB /* Products */ = { + 3C962750AB7D971D4FC1F5716C31EB02 /* Pods */ = { isa = PBXGroup; children = ( - 31E82A9D837389194284B5BF2B59A6CF /* Alamofire.framework */, - 69ED5B0211F6CDE2702F4D92FF06CC89 /* Pods_WWCodeDFW.framework */, - C7278C33B79918154B6ABFDD22DD1417 /* SnapKit.framework */, - 754019566FDA07E5500B87178C38BD7B /* SwiftyJSON.framework */, + BAAD9E2BB284BC15907A8449F7E7FDE0 /* Alamofire */, + 2A9AA9713656090841F32D0A208C7861 /* SnapKit */, + 96AA1095259A081759DCF09E0E6FCE96 /* SwiftLint */, + 8949128CDCF2957D18576353C372F999 /* SwiftyJSON */, ); - name = Products; + name = Pods; sourceTree = ""; }; - 77698DBF2E3EF9389C7861155F8C2B0A /* SnapKit */ = { + 65F5486FC475134E55A84C801CBB9B9F /* Support Files */ = { isa = PBXGroup; children = ( - F3E0E9A410D9D8B6DD2404ECB3329758 /* Constraint.swift */, - 0ED2A647955895F8E2478887A64478FC /* ConstraintAttributes.swift */, - 376BEF74A19D59C12528AF337E9B7056 /* ConstraintConfig.swift */, - 76BD74AD4191847740695C98F67B7978 /* ConstraintConstantTarget.swift */, - A0D0A1C53BBE67C2A8ED3ECE85014BB9 /* ConstraintDescription.swift */, - E1390CCA24783C2E95B3264878F43990 /* ConstraintDSL.swift */, - F6F7A494B4CD996B3F523C2B28FFEE52 /* ConstraintInsets.swift */, - 00E4412F67364360F74E8CCF2AA555DD /* ConstraintInsetTarget.swift */, - 163272BF09771EE4D6481761A332AAE4 /* ConstraintItem.swift */, - A91436829018A3397CC451C4E7C1726C /* ConstraintLayoutGuide.swift */, - 28BF3B0EB3EBD6EEBFBE2A092AC34F81 /* ConstraintLayoutGuideDSL.swift */, - 7B51A0C17DB6F80A02EC398273876EE8 /* ConstraintLayoutSupport.swift */, - 244AAFD6A5CF20E1958B107A68640125 /* ConstraintLayoutSupportDSL.swift */, - 67A26D60318A9A85EC52F646C3AB67AA /* ConstraintMaker.swift */, - F4966F0F235C7F44396807DD853056A2 /* ConstraintMakerEditable.swift */, - 5E22A35D4D38B894EF0E688BB6F0DD04 /* ConstraintMakerExtendable.swift */, - 2B2C3EFE31585F78DE2591E3054690D0 /* ConstraintMakerFinalizable.swift */, - AC0C1A53329F0C3B2C953DD512F1600B /* ConstraintMakerPriortizable.swift */, - FA3D33741DF328C147592105977B9CE9 /* ConstraintMakerRelatable.swift */, - 01882FD6A64E5846C465601C2F805C0A /* ConstraintMultiplierTarget.swift */, - 4DBD4C8E2336679C83BC14C17459D268 /* ConstraintOffsetTarget.swift */, - 12C136C58152FC54E2F406E9B331B244 /* ConstraintPriorityTarget.swift */, - 1A4969DA8509FCF2EABA3B5FB095BBBF /* ConstraintRelatableTarget.swift */, - 2257B11270A64D3AF5F497010AF0D01B /* ConstraintRelation.swift */, - 5E66E8E584A50A01E56998CC586581BD /* ConstraintView.swift */, - 30D69444A876031C0DD47BFC4F43C6B4 /* ConstraintView+Extensions.swift */, - 92EE5B0ECE9DF92F2087A08233C06D35 /* ConstraintViewDSL.swift */, - 75FF1AD01519364BB8C2F851435FD60B /* Debugging.swift */, - 3168036C7D6A18C3EBE01ABDC14D777F /* LayoutConstraint.swift */, - 2FEF61CBBDB8259CD6AD1257BAB8932F /* UILayoutGuide+Extensions.swift */, - 6FC7B72688C16A9E4958A6E7F4C79F8C /* UILayoutSupport+Extensions.swift */, - AF207F92B6A4B7AAE2B3F36A6F548267 /* Support Files */, + C8E4F9B31C7EB9A06CF46EFCA4BDEE95 /* SwiftLint.xcconfig */, ); - name = SnapKit; - path = SnapKit; + name = "Support Files"; + path = "../Target Support Files/SwiftLint"; sourceTree = ""; }; - 7DB346D0F39D3F0E887471402A8071AB = { + 779660EB83C003967CEE19688CAE91D8 /* Support Files */ = { isa = PBXGroup; children = ( - 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, - BC3CA7F9E30CC8F7E2DD044DD34432FC /* Frameworks */, - E06BF47BDAA0B2C658985FE347B2BB37 /* Pods */, - 6B51B35B4E4CD2543AC0AF1F9A9D89DB /* Products */, - EEEE9C7B0DFEFCE39E6C371F75C5A5B9 /* Targets Support Files */, + B4AF76DC816F6C9F7E06936993144605 /* Alamofire.modulemap */, + 015BBD18BF1855CB92828380CF23E4C4 /* Alamofire.xcconfig */, + 8A44899DF1DABCA59DD9362A99EEA460 /* Alamofire-dummy.m */, + AFF52223DD0A448825CA36DBA01E0501 /* Alamofire-Info.plist */, + 8162923BC3A26324092E2961DBC2746C /* Alamofire-prefix.pch */, + F0ADDAACB71C0827F5C2692E2192A881 /* Alamofire-umbrella.h */, ); + name = "Support Files"; + path = "../Target Support Files/Alamofire"; sourceTree = ""; }; - ACB9129598EEC395B9CF034D3861A885 /* SwiftLint */ = { + 8949128CDCF2957D18576353C372F999 /* SwiftyJSON */ = { isa = PBXGroup; children = ( + EA341057A222274517791AE4BECDE83E /* SwiftyJSON.swift */, + F7C63917208D0011BE5734DA5D28E941 /* Support Files */, ); - name = SwiftLint; - path = SwiftLint; + name = SwiftyJSON; + path = SwiftyJSON; sourceTree = ""; }; - AF207F92B6A4B7AAE2B3F36A6F548267 /* Support Files */ = { + 9347B2D723282F2EE38C0BC845A36E69 /* Products */ = { isa = PBXGroup; children = ( - 5066D678D9AF27C7F939DF767A8E9DDF /* Info.plist */, - 98FBDCF555C053DF3C50AB85167A5153 /* SnapKit.modulemap */, - 29A64D3DD7AAAE8EFC90C107050EA7DA /* SnapKit.xcconfig */, - 5BD89A697635A40B3220858FB4337DCF /* SnapKit-dummy.m */, - E49D17DE66BA0D742B74E515D9C2DF7F /* SnapKit-prefix.pch */, - 4A20BBBEB5531B60C02D21E98CB45B3A /* SnapKit-umbrella.h */, + 5D797E9A5C5782CE845840781FA1CC81 /* Alamofire.framework */, + A9490683541D9C86E8BE6AC2450B1FAA /* Pods_WWCodeDFW.framework */, + 979486118B3E90C08386079D57962701 /* SnapKit.framework */, + E23C076BA70925415F490FEDB215DA92 /* SwiftyJSON.framework */, ); - name = "Support Files"; - path = "../Target Support Files/SnapKit"; + name = Products; sourceTree = ""; }; - BC3CA7F9E30CC8F7E2DD044DD34432FC /* Frameworks */ = { + 96AA1095259A081759DCF09E0E6FCE96 /* SwiftLint */ = { isa = PBXGroup; children = ( - D35AF013A5F0BAD4F32504907A52519E /* iOS */, + 65F5486FC475134E55A84C801CBB9B9F /* Support Files */, ); - name = Frameworks; + name = SwiftLint; + path = SwiftLint; sourceTree = ""; }; - D35AF013A5F0BAD4F32504907A52519E /* iOS */ = { + BAAD9E2BB284BC15907A8449F7E7FDE0 /* Alamofire */ = { isa = PBXGroup; children = ( - 6604A7D69453B4569E4E4827FB9155A9 /* Foundation.framework */, + D5255A80CFA98886E4CAAF379205860B /* AFError.swift */, + 0F532BB6F9CDAA87990FEEBEEC0C8B51 /* Alamofire.swift */, + 43CE0861FD67C513B840AAC82F8D25F6 /* AlamofireExtended.swift */, + 23885A65DE219E49A7F9948BC45F4EA0 /* CachedResponseHandler.swift */, + 17C65275FA0E11EFAA43B2117A3088CA /* DispatchQueue+Alamofire.swift */, + 6E83B6C22DAEE09F932BFA6EF6AF9E84 /* EventMonitor.swift */, + A210FD675C0C625827FE8C76D6DDCC10 /* HTTPHeaders.swift */, + 8ED5FE97C61127F2E240B2482D7ACA08 /* HTTPMethod.swift */, + 50514B7777AC28C9444C4D90154EA9A2 /* MultipartFormData.swift */, + 3F7E292F2BC7EE18246B3E01DC333A74 /* MultipartUpload.swift */, + CA60FA61B161DA65AB1CC384C4D7A74F /* NetworkReachabilityManager.swift */, + BE17175641E2D35B161ECEFCC6783A11 /* Notifications.swift */, + 81A7CDD945D4005D44D48C2810323C94 /* OperationQueue+Alamofire.swift */, + D1AA755DD8BF7D30F2175A0C30067E96 /* ParameterEncoder.swift */, + 50E3EE3D81F1B9A1610C433B1D95DE46 /* ParameterEncoding.swift */, + BFEBF4AA03E01C4D091EBEB4C8D537D8 /* Protector.swift */, + BF1FB8E30B81304D11B3F8C95426A552 /* RedirectHandler.swift */, + 18E7F72B7EF4EBD4894D5C53C986D455 /* Request.swift */, + 03E0CE90135820AD6EB98B1708B6686C /* RequestInterceptor.swift */, + 207FDC0806D5BDCAD5E50A07CE8DAC3C /* RequestTaskMap.swift */, + C62FCE30BDD74C6CA538C694AC63A7C0 /* Response.swift */, + 1AC96EFCCA6682A47864FB240B381D44 /* ResponseSerialization.swift */, + 5593F02B88EBD5DBE150CF2F5E49F0A2 /* Result+Alamofire.swift */, + 0CBF2313A3A2B1A15BAD3AF3070363C1 /* RetryPolicy.swift */, + 0AE0F46D2C9DC01A421478544DA764B7 /* ServerTrustEvaluation.swift */, + CA53997A5E2CCFF41BF5738BD0A64F6C /* Session.swift */, + C654B033B1C04E51ED977630E10EF61F /* SessionDelegate.swift */, + DBA8BE0AFDCCB28E8C4EF3ECE00051C9 /* URLConvertible+URLRequestConvertible.swift */, + 48C45D08A0A8C8084260C0281CD2EA6A /* URLEncodedFormEncoder.swift */, + 742F77E864037957DDB07C9941C1F583 /* URLRequest+Alamofire.swift */, + F2E50A06339722D33BF003CA1AD08421 /* URLSessionConfiguration+Alamofire.swift */, + 2C553488DEA28084B2F4231B3AB693F3 /* Validation.swift */, + 779660EB83C003967CEE19688CAE91D8 /* Support Files */, ); - name = iOS; + name = Alamofire; + path = Alamofire; sourceTree = ""; }; - E06BF47BDAA0B2C658985FE347B2BB37 /* Pods */ = { + CF1408CF629C7361332E53B88F7BD30C = { isa = PBXGroup; children = ( - 54FCCF657F4FE3BDB43598BF4E927503 /* Alamofire */, - 77698DBF2E3EF9389C7861155F8C2B0A /* SnapKit */, - ACB9129598EEC395B9CF034D3861A885 /* SwiftLint */, - 60167CD0DCDB064C444589E63C90155C /* SwiftyJSON */, + 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */, + 1628BF05B4CAFDCC3549A101F5A10A17 /* Frameworks */, + 3C962750AB7D971D4FC1F5716C31EB02 /* Pods */, + 9347B2D723282F2EE38C0BC845A36E69 /* Products */, + 26EBC3E8B76CB3E7A202BBB12DBF5990 /* Targets Support Files */, ); - name = Pods; sourceTree = ""; }; - EEEE9C7B0DFEFCE39E6C371F75C5A5B9 /* Targets Support Files */ = { + E34DCC8E2CF86B8D72232914781A840D /* iOS */ = { isa = PBXGroup; children = ( - 660B48AC182F13E3E4B680122B9DCD48 /* Pods-WWCodeDFW */, + 8B079F294DA5D9A879E6D53A91F51A1E /* CFNetwork.framework */, + 222DAEF0D819F359AFCFF3D4F927E8A7 /* Foundation.framework */, ); - name = "Targets Support Files"; + name = iOS; + sourceTree = ""; + }; + F7C63917208D0011BE5734DA5D28E941 /* Support Files */ = { + isa = PBXGroup; + children = ( + 6DF169FFD269C38A9D9A628AC36C42F7 /* SwiftyJSON.modulemap */, + 15B49BE04AAF5CADC67B31B4F380303C /* SwiftyJSON.xcconfig */, + 85362A716D7C46C8C1E8F07D6103E36A /* SwiftyJSON-dummy.m */, + 5F64022683034A8AA85F36A4CB519C2A /* SwiftyJSON-Info.plist */, + CDF96B1EB07CC5CAA3AA5ACBE52B20F5 /* SwiftyJSON-prefix.pch */, + 94FDFE7056EC1D9DB4EA8C89A0AB1F7B /* SwiftyJSON-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/SwiftyJSON"; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXHeadersBuildPhase section */ - 0074C3B08A6E18968274DB2C137BAB80 /* Headers */ = { + 3D7DD627DB5C5AD636646E57B685AFB2 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - 8C1F1200F8FC2DE79601824D99B07769 /* SwiftyJSON-umbrella.h in Headers */, + 1942F7D3B7722A5637C3FC0BE44B1E6C /* SwiftyJSON-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; - 0AD2B81FF0ED2A88D98B26F18C3E437F /* Headers */ = { + 65312B493E0ABCC3A632AE5B1A6284BD /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - 53DEEF2499A9FA94333C7F38D59C9831 /* SnapKit-umbrella.h in Headers */, + 7A716FF53BB179A83F30879A054F9517 /* Pods-WWCodeDFW-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; - B4002B6E97835FDCCAA5963EFE09A3E0 /* Headers */ = { + 7DFCF5F12AEEED0500986DBC9BF76170 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - 1B9EDEDC964E6B08F78920B4F4B9DB84 /* Alamofire-umbrella.h in Headers */, + A66ED57B365A35434C5BAF4B990819B7 /* SnapKit-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; - B69177EADD8F65EC048064FEEB234202 /* Headers */ = { + ADDF288DD930A46B5F0F198C225895C9 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - E8E1F6773DD1F8333A281C1AA44E9181 /* Pods-WWCodeDFW-umbrella.h in Headers */, + 00FA97D56201027AEB1C7692A2C3CF8B /* Alamofire-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXHeadersBuildPhase section */ /* Begin PBXNativeTarget section */ - 34AD074B4FE598FB0F1E7A4850FCBAF5 /* Pods-WWCodeDFW */ = { + 19622742EBA51E823D6DAE3F8CDBFAD4 /* SnapKit */ = { isa = PBXNativeTarget; - buildConfigurationList = 1D593E4399ADA2C2DE56D84F044424C5 /* Build configuration list for PBXNativeTarget "Pods-WWCodeDFW" */; + buildConfigurationList = 7F8CE4DC18DBEA01587212F09727DB3D /* Build configuration list for PBXNativeTarget "SnapKit" */; buildPhases = ( - 328F462B3ED408EEA4B232386F662AD2 /* Sources */, - FE359978A45038B288958C8B1A9F6378 /* Frameworks */, - B69177EADD8F65EC048064FEEB234202 /* Headers */, + 7DFCF5F12AEEED0500986DBC9BF76170 /* Headers */, + 89222AF845A30312C284F407BA48B98F /* Sources */, + 3C8B1704CC97EF12D3409771318C6433 /* Frameworks */, + 9C691CAA90D9565F2EFF5EF823D8A80C /* Resources */, ); buildRules = ( ); dependencies = ( - D0FBF49FB831B2C508A4E49B7B9ECC01 /* PBXTargetDependency */, - D6557299DE9E107D30F5C654423D5EC6 /* PBXTargetDependency */, - 243598EAC4C6B0E5C4AE04517C08A2E0 /* PBXTargetDependency */, ); - name = "Pods-WWCodeDFW"; - productName = "Pods-WWCodeDFW"; - productReference = 69ED5B0211F6CDE2702F4D92FF06CC89 /* Pods_WWCodeDFW.framework */; + name = SnapKit; + productName = SnapKit; + productReference = 979486118B3E90C08386079D57962701 /* SnapKit.framework */; productType = "com.apple.product-type.framework"; }; - 6E18B0FFB4F36914492A16C4D9F5E7C8 /* SnapKit */ = { + 7978B38ADBD0D241978F364A01A9E10D /* Pods-WWCodeDFW */ = { isa = PBXNativeTarget; - buildConfigurationList = 9A5965CFAAC48040F7862B2BB0D91E8F /* Build configuration list for PBXNativeTarget "SnapKit" */; + buildConfigurationList = 0A36563739FDB3506A509EE80326E34E /* Build configuration list for PBXNativeTarget "Pods-WWCodeDFW" */; buildPhases = ( - 40B1A60B3E0CF7A588FD56F36499E2B7 /* Sources */, - C55BD4362198DFA25E1F6D1992807293 /* Frameworks */, - 0AD2B81FF0ED2A88D98B26F18C3E437F /* Headers */, + 65312B493E0ABCC3A632AE5B1A6284BD /* Headers */, + 4D5E374D04AABC3065108A6EB2948106 /* Sources */, + 2A7AD185E895038D87AD109FB4FA66B1 /* Frameworks */, + D229B945F54F5FA7CBBF3D1CC28EB65C /* Resources */, ); buildRules = ( ); dependencies = ( + 0212A150E96A478992ACED15CABEEC0E /* PBXTargetDependency */, + 2AA7D391FDDC258866B6E51DECB0279B /* PBXTargetDependency */, + 456E4B8B7A06091A5A2FCE7D4A7A2AD7 /* PBXTargetDependency */, + 16B3DC1B457ACBBFB48D3E15743031A4 /* PBXTargetDependency */, ); - name = SnapKit; - productName = SnapKit; - productReference = C7278C33B79918154B6ABFDD22DD1417 /* SnapKit.framework */; + name = "Pods-WWCodeDFW"; + productName = "Pods-WWCodeDFW"; + productReference = A9490683541D9C86E8BE6AC2450B1FAA /* Pods_WWCodeDFW.framework */; productType = "com.apple.product-type.framework"; }; - 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */ = { + D118A6A04828FD3CDA8640CD2B6796D2 /* SwiftyJSON */ = { isa = PBXNativeTarget; - buildConfigurationList = 419E5D95491847CD79841B971A8A3277 /* Build configuration list for PBXNativeTarget "Alamofire" */; + buildConfigurationList = 62468BF9C7EDA172E951A24083C3ECA7 /* Build configuration list for PBXNativeTarget "SwiftyJSON" */; buildPhases = ( - 32B9974868188C4803318E36329C87FE /* Sources */, - 99195E4207764744AEC07ECCBCD550EB /* Frameworks */, - B4002B6E97835FDCCAA5963EFE09A3E0 /* Headers */, + 3D7DD627DB5C5AD636646E57B685AFB2 /* Headers */, + 1700C451C98D9DCECBEDFC5E351C5A9E /* Sources */, + AD9C5A8DAF4334B670E91B2EC08DBE2C /* Frameworks */, + D098F7F0080A87A1F472C81FC2F85528 /* Resources */, ); buildRules = ( ); dependencies = ( ); - name = Alamofire; - productName = Alamofire; - productReference = 31E82A9D837389194284B5BF2B59A6CF /* Alamofire.framework */; + name = SwiftyJSON; + productName = SwiftyJSON; + productReference = E23C076BA70925415F490FEDB215DA92 /* SwiftyJSON.framework */; productType = "com.apple.product-type.framework"; }; - CDB25960C355207D9FFA9D17E0F8CD99 /* SwiftyJSON */ = { + EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */ = { isa = PBXNativeTarget; - buildConfigurationList = 27F5C25586C0082954AE719DA5AD3546 /* Build configuration list for PBXNativeTarget "SwiftyJSON" */; + buildConfigurationList = 6B2B8EC7E21CDBFF2BDA26B1B4AC4C0D /* Build configuration list for PBXNativeTarget "Alamofire" */; buildPhases = ( - DEB851C0F93E6A06CA1BCD8A767F96F0 /* Sources */, - BD0D45C7600CD6912D6EF5AF3ACD4B4A /* Frameworks */, - 0074C3B08A6E18968274DB2C137BAB80 /* Headers */, + ADDF288DD930A46B5F0F198C225895C9 /* Headers */, + 7349DB0E9BEBE664696F1DCC25226F26 /* Sources */, + 8B0D8633F410345F93419B8C3D7B6916 /* Frameworks */, + 28FC0024B79C28A420D7C4FEBB9E3AEB /* Resources */, ); buildRules = ( ); dependencies = ( ); - name = SwiftyJSON; - productName = SwiftyJSON; - productReference = 754019566FDA07E5500B87178C38BD7B /* SwiftyJSON.framework */; + name = Alamofire; + productName = Alamofire; + productReference = 5D797E9A5C5782CE845840781FA1CC81 /* Alamofire.framework */; productType = "com.apple.product-type.framework"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ - D41D8CD98F00B204E9800998ECF8427E /* Project object */ = { + BFDFE7DC352907FC980B868725387E98 /* Project object */ = { isa = PBXProject; attributes = { - LastSwiftUpdateCheck = 0830; - LastUpgradeCheck = 0700; + LastSwiftUpdateCheck = 1100; + LastUpgradeCheck = 1100; }; - buildConfigurationList = 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */; + buildConfigurationList = 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */; compatibilityVersion = "Xcode 3.2"; - developmentRegion = English; + developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( en, ); - mainGroup = 7DB346D0F39D3F0E887471402A8071AB; - productRefGroup = 6B51B35B4E4CD2543AC0AF1F9A9D89DB /* Products */; + mainGroup = CF1408CF629C7361332E53B88F7BD30C; + productRefGroup = 9347B2D723282F2EE38C0BC845A36E69 /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( - 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */, - 34AD074B4FE598FB0F1E7A4850FCBAF5 /* Pods-WWCodeDFW */, - 6E18B0FFB4F36914492A16C4D9F5E7C8 /* SnapKit */, - CDB25960C355207D9FFA9D17E0F8CD99 /* SwiftyJSON */, + EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */, + 7978B38ADBD0D241978F364A01A9E10D /* Pods-WWCodeDFW */, + 19622742EBA51E823D6DAE3F8CDBFAD4 /* SnapKit */, + 52B60EC2A583F24ACBB69C113F5488B9 /* SwiftLint */, + D118A6A04828FD3CDA8640CD2B6796D2 /* SwiftyJSON */, ); }; /* End PBXProject section */ +/* Begin PBXResourcesBuildPhase section */ + 28FC0024B79C28A420D7C4FEBB9E3AEB /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9C691CAA90D9565F2EFF5EF823D8A80C /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + D098F7F0080A87A1F472C81FC2F85528 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + D229B945F54F5FA7CBBF3D1CC28EB65C /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + /* Begin PBXSourcesBuildPhase section */ - 328F462B3ED408EEA4B232386F662AD2 /* Sources */ = { + 1700C451C98D9DCECBEDFC5E351C5A9E /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - C889ED97467F9763234DCE085D74C9DF /* Pods-WWCodeDFW-dummy.m in Sources */, + 2BF6FBC0A64BF107C5D64C61F1397770 /* SwiftyJSON-dummy.m in Sources */, + 7B4CE5C84161E2BFE477F42DFD634382 /* SwiftyJSON.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; - 32B9974868188C4803318E36329C87FE /* Sources */ = { + 4D5E374D04AABC3065108A6EB2948106 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 9ED2BB2981896E0A39EFA365503F58CE /* AFError.swift in Sources */, - A9EEEA7477981DEEBC72432DE9990A4B /* Alamofire-dummy.m in Sources */, - F8B3D3092ED0417E8CDF32033F6122F5 /* Alamofire.swift in Sources */, - 61200D01A1855D7920CEF835C8BE00B0 /* DispatchQueue+Alamofire.swift in Sources */, - B65FCF589DA398C3EFE0128064E510EC /* MultipartFormData.swift in Sources */, - A2A6F71B727312BD45CC7A4AAD7B0AB7 /* NetworkReachabilityManager.swift in Sources */, - EFD264FC408EBF3BA2528E70B08DDD94 /* Notifications.swift in Sources */, - BE5C67A07E289FE1F9BE27335B159997 /* ParameterEncoding.swift in Sources */, - 5387216E723A3C68E851CA15573CDD71 /* Request.swift in Sources */, - CB6D60925223897FFA2662667DF83E8A /* Response.swift in Sources */, - F6BECD98B97CBFEBE2C96F0E9E72A6C0 /* ResponseSerialization.swift in Sources */, - 7D8CC01E8C9EFFF9F4D65406CDE0AB66 /* Result.swift in Sources */, - 62F65AD8DC4F0F9610F4B8B4738EC094 /* ServerTrustPolicy.swift in Sources */, - 7B5FE28C7EA4122B0598738E54DBEBD8 /* SessionDelegate.swift in Sources */, - AE1EF48399533730D0066E04B22CA2D6 /* SessionManager.swift in Sources */, - 3626B94094672CB1C9DEA32B9F9502E1 /* TaskDelegate.swift in Sources */, - 10EB23E9ECC4B33E16933BB1EA560B6A /* Timeline.swift in Sources */, - BBEFE2F9CEB73DC7BD97FFA66A0D9D4F /* Validation.swift in Sources */, + 3BDB28864BA09DD602D6A072D308703E /* Pods-WWCodeDFW-dummy.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; - 40B1A60B3E0CF7A588FD56F36499E2B7 /* Sources */ = { + 7349DB0E9BEBE664696F1DCC25226F26 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 922E76CDC352C626D7A9C530A81E2693 /* Constraint.swift in Sources */, - 50D3BED5CAF1F698C99E2E1E34533241 /* ConstraintAttributes.swift in Sources */, - 33B5A5A6726002B88EAE5842CD5FC348 /* ConstraintConfig.swift in Sources */, - 905ED93A26C017B5F18DB60C768FF3D3 /* ConstraintConstantTarget.swift in Sources */, - AA5D1A251FED94EAFC57E1F192A2F959 /* ConstraintDescription.swift in Sources */, - 0950658BCE95CFE494117A110BC654C6 /* ConstraintDSL.swift in Sources */, - E41829C687AFE4242B20317FAC79F0E4 /* ConstraintInsets.swift in Sources */, - 4333F3C7ACDB152A0DB989940EC3A2F1 /* ConstraintInsetTarget.swift in Sources */, - C9F04B120ADE5D757DE9AA7CED829A7C /* ConstraintItem.swift in Sources */, - 25AC37E2CD92BB6D2A70E71682267DF0 /* ConstraintLayoutGuide.swift in Sources */, - 60A5F21DB4AAF6E1998A275CE1CAA8B9 /* ConstraintLayoutGuideDSL.swift in Sources */, - 7784ACB41695D0BFCF09EDACFC863ED8 /* ConstraintLayoutSupport.swift in Sources */, - 340C2088655CAE5E0E7D67285D52BAC3 /* ConstraintLayoutSupportDSL.swift in Sources */, - ED56B39274410994E00EF5EB0A798901 /* ConstraintMaker.swift in Sources */, - 6E6A2F4372D72CEDE43C042BAD896C8B /* ConstraintMakerEditable.swift in Sources */, - 1F0DA736A59CE3C69FCFCDAB4A285CD7 /* ConstraintMakerExtendable.swift in Sources */, - 545A1DF50E2959908CE80483D18B4006 /* ConstraintMakerFinalizable.swift in Sources */, - 1E271897A0FC04A5BE1BA277E62E5E47 /* ConstraintMakerPriortizable.swift in Sources */, - 46C8F0CF77169F83E2B2BCBC1DFB9F41 /* ConstraintMakerRelatable.swift in Sources */, - E5CE8462363E29B7B1CC2B970084F1AE /* ConstraintMultiplierTarget.swift in Sources */, - C98A797EAD255997ACDD3C8391E52EA7 /* ConstraintOffsetTarget.swift in Sources */, - 1D4389B9F4F9FEB10A21E246D68F17A1 /* ConstraintPriorityTarget.swift in Sources */, - DDB8A5C5BBFEBEB8D564F15172146746 /* ConstraintRelatableTarget.swift in Sources */, - D431FFB37AEC3F43FF7DC1B0A7D1653F /* ConstraintRelation.swift in Sources */, - 32F8484FED98350DAB553971F2DCC3C0 /* ConstraintView+Extensions.swift in Sources */, - 68C16258E306728749431E133B80BAE2 /* ConstraintView.swift in Sources */, - 3A32EE3F2B5531B15EA3E1AC2BD20139 /* ConstraintViewDSL.swift in Sources */, - 4913E59CC920BB2C409B2B7AB4FE3C68 /* Debugging.swift in Sources */, - A184FD50F870469FA15003696F1B16BA /* LayoutConstraint.swift in Sources */, - 1DE3CC7F8C57C333BE0A309D114E60D1 /* SnapKit-dummy.m in Sources */, - 39BD35F68CE705F4A422FDD60304CDFC /* UILayoutGuide+Extensions.swift in Sources */, - 9C433F07CFA6F50BD99293D928496E58 /* UILayoutSupport+Extensions.swift 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; }; - DEB851C0F93E6A06CA1BCD8A767F96F0 /* Sources */ = { + 89222AF845A30312C284F407BA48B98F /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 7042152DEFE0D700F8AE2079B7348372 /* SwiftyJSON-dummy.m in Sources */, - F6509EAF0D2FA37D51423948F6B24D0A /* SwiftyJSON.swift in Sources */, + 3BFC243AB9BD579969F0D5756560BCAA /* Constraint.swift in Sources */, + 2A1BBBC87AC2367BD14610A9D10D285E /* ConstraintAttributes.swift in Sources */, + 9B09968922C73D50040C6EEF57890D6E /* ConstraintConfig.swift in Sources */, + 5854DF509E8A016B6235793D04083035 /* ConstraintConstantTarget.swift in Sources */, + B599696DFEF6B2A5ECF528F4E5BB1846 /* ConstraintDescription.swift in Sources */, + AC35C9341C4BB156BB26FDD237EE3721 /* ConstraintDirectionalInsets.swift in Sources */, + 71DE9DC2FA583526AB4D1FD7F00C099C /* ConstraintDirectionalInsetTarget.swift in Sources */, + 8277256ADEC3C4DCF79957D1CA681A9A /* ConstraintDSL.swift in Sources */, + 21AB1101BBE4D28D74ED4EDF0D59025A /* ConstraintInsets.swift in Sources */, + 2C06F2E972444D359754D21AC46BFFE2 /* ConstraintInsetTarget.swift in Sources */, + 99B5296A5EDECE0557B9DA53D9E19CA1 /* ConstraintItem.swift in Sources */, + 1AFB1E9136716C0B61D6C700FF1E60FD /* ConstraintLayoutGuide+Extensions.swift in Sources */, + A270CD9EC3C541FE86E65AEDCEF500CF /* ConstraintLayoutGuide.swift in Sources */, + 77C9889055A3B32EA13A9616824DB0ED /* ConstraintLayoutGuideDSL.swift in Sources */, + 57B1876F2BE4168E5BFDB63D8CC849A0 /* ConstraintLayoutSupport.swift in Sources */, + 01C550A53C9E2047C83F8E85BBB558E6 /* ConstraintLayoutSupportDSL.swift in Sources */, + 51CD5887014967E77E58F5A163996454 /* ConstraintMaker.swift in Sources */, + 7C1702076F3A31D8D2D45A4A9F09B266 /* ConstraintMakerEditable.swift in Sources */, + 69CCBEEDFCA6D743D80026568D961919 /* ConstraintMakerExtendable.swift in Sources */, + C412F27D75AFC0DF0F0289DBB270931C /* ConstraintMakerFinalizable.swift in Sources */, + EE909C7C786140109051BC9562EEC7C8 /* ConstraintMakerPriortizable.swift in Sources */, + 75E146C12D1287228A0B493E87CDE31F /* ConstraintMakerRelatable.swift in Sources */, + D4697DC40F3B059E4A0867838CA1814E /* ConstraintMultiplierTarget.swift in Sources */, + 8705BBF0D428BF0AE1B554A377ECC540 /* ConstraintOffsetTarget.swift in Sources */, + 232B2F922E972D9F43D2EE15ACECE734 /* ConstraintPriority.swift in Sources */, + E8F2429683B3015CBD39CE883770BCA7 /* ConstraintPriorityTarget.swift in Sources */, + 69E3A06BBDFDC7D06A9D4BDC4E895E73 /* ConstraintRelatableTarget.swift in Sources */, + CE62FEABA57B2B53EABF8C7DCCC6B2C4 /* ConstraintRelation.swift in Sources */, + 3E5285F4F36EAD77ECABBFB7F36BB1BB /* ConstraintView+Extensions.swift in Sources */, + BECA67DFB5E0984DFAEFCB775C31972E /* ConstraintView.swift in Sources */, + EB1726F5E0D0EEBA20E4528B1E37A8FA /* ConstraintViewDSL.swift in Sources */, + B780B272106411CBE258BB60FFC45410 /* Debugging.swift in Sources */, + 039EAFE7935113805F3FC21BF1B7C9D5 /* LayoutConstraint.swift in Sources */, + E9A970BC24EA15832F248EA020072746 /* LayoutConstraintItem.swift in Sources */, + 4C7A676DAE95EEAC3787A75349F0862D /* SnapKit-dummy.m in Sources */, + 1956E392D500F3CD899D39A5F805736D /* Typealiases.swift in Sources */, + 6E0EB9E7FAAEDBB7A73ECF3095F69C4A /* UILayoutSupport+Extensions.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ - 243598EAC4C6B0E5C4AE04517C08A2E0 /* PBXTargetDependency */ = { + 0212A150E96A478992ACED15CABEEC0E /* PBXTargetDependency */ = { isa = PBXTargetDependency; - name = SwiftyJSON; - target = CDB25960C355207D9FFA9D17E0F8CD99 /* SwiftyJSON */; - targetProxy = FC2DB381F375BF61743F66FA70D03EA0 /* PBXContainerItemProxy */; + name = Alamofire; + target = EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */; + targetProxy = 1FBED9898C98868FA66785D019839015 /* PBXContainerItemProxy */; }; - D0FBF49FB831B2C508A4E49B7B9ECC01 /* PBXTargetDependency */ = { + 16B3DC1B457ACBBFB48D3E15743031A4 /* PBXTargetDependency */ = { isa = PBXTargetDependency; - name = Alamofire; - target = 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */; - targetProxy = F6B118EF4291671D7752C41AACAF5394 /* PBXContainerItemProxy */; + name = SwiftyJSON; + target = D118A6A04828FD3CDA8640CD2B6796D2 /* SwiftyJSON */; + targetProxy = 44625DBBBF0FFCF1DDCF9EB00788A644 /* PBXContainerItemProxy */; }; - D6557299DE9E107D30F5C654423D5EC6 /* PBXTargetDependency */ = { + 2AA7D391FDDC258866B6E51DECB0279B /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = SnapKit; - target = 6E18B0FFB4F36914492A16C4D9F5E7C8 /* SnapKit */; - targetProxy = BC7DFE3A281EB7C0F33C91C50A8334E7 /* PBXContainerItemProxy */; + target = 19622742EBA51E823D6DAE3F8CDBFAD4 /* SnapKit */; + targetProxy = C322490DD2D0EC82A3EC5904FF8C92FB /* PBXContainerItemProxy */; + }; + 456E4B8B7A06091A5A2FCE7D4A7A2AD7 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = SwiftLint; + target = 52B60EC2A583F24ACBB69C113F5488B9 /* SwiftLint */; + targetProxy = 5FEE99F93B3F3AE00154BBC1D8868F2A /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ /* Begin XCBuildConfiguration section */ - 03A89CC700388BFF7A86FA01F0E56188 /* Release */ = { + 00319A2330DC739FCBFBB6CFB0C5F58D /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 29A64D3DD7AAAE8EFC90C107050EA7DA /* SnapKit.xcconfig */; + baseConfigurationReference = 015BBD18BF1855CB92828380CF23E4C4 /* 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; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; - GCC_PREFIX_HEADER = "Target Support Files/SnapKit/SnapKit-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/SnapKit/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/SnapKit/SnapKit.modulemap"; - MTL_ENABLE_DEBUG_INFO = NO; - PRODUCT_NAME = SnapKit; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; - SWIFT_VERSION = 3.0; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; - 077C4BB7DBEAA715DED46C057DC8051C /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 8A5D94811A8BB2DE4CAC223B9AC330A6 /* Alamofire.xcconfig */; - buildSettings = { - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + 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"; - MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_MODULE_NAME = Alamofire; PRODUCT_NAME = Alamofire; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; - SWIFT_VERSION = 3.0; + SWIFT_VERSION = 5.1; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; - name = Release; + name = Debug; }; - 69C9BF6FCDBD52FCBBF55D055E93D4EE /* Debug */ = { + 020BEC27E3AD6D7C84D288C148A58E74 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 72EC50C520FDB3DF8E52B09AA5B50854 /* SwiftyJSON.xcconfig */; + baseConfigurationReference = 7EF7CC69E679E85C153F0CA61B29A9D3 /* SnapKit.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; - DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; - GCC_PREFIX_HEADER = "Target Support Files/SwiftyJSON/SwiftyJSON-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/SwiftyJSON/Info.plist"; + GCC_PREFIX_HEADER = "Target Support Files/SnapKit/SnapKit-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/SnapKit/SnapKit-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/SwiftyJSON/SwiftyJSON.modulemap"; - MTL_ENABLE_DEBUG_INFO = YES; - PRODUCT_NAME = SwiftyJSON; + MODULEMAP_FILE = "Target Support Files/SnapKit/SnapKit.modulemap"; + PRODUCT_MODULE_NAME = SnapKit; + PRODUCT_NAME = SnapKit; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 3.0; + SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; - name = Debug; + name = Release; }; - 9BFC9E4A7AAD7A607ACE06D95A401A5A /* Debug */ = { + 196DFA3E4A09A28224918543529A1885 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + 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_DIRECT_OBJC_ISA_USAGE = 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_OBJC_ROOT_CLASS = 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; - CODE_SIGNING_REQUIRED = NO; COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_C_LANGUAGE_STANDARD = gnu11; GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "POD_CONFIGURATION_DEBUG=1", "DEBUG=1", "$(inherited)", ); - GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = 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 = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; ONLY_ACTIVE_ARCH = YES; - PROVISIONING_PROFILE_SPECIFIER = NO_SIGNING/; + PRODUCT_NAME = "$(TARGET_NAME)"; STRIP_INSTALLED_PRODUCT = NO; SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; SYMROOT = "${SRCROOT}/../build"; }; name = Debug; }; - B48DB407C7D8E2DFDD01A589B0F367D9 /* Release */ = { + 2E3C8A300772E0028147E4BAF0D5078A /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 72EC50C520FDB3DF8E52B09AA5B50854 /* SwiftyJSON.xcconfig */; + baseConfigurationReference = 7EF7CC69E679E85C153F0CA61B29A9D3 /* SnapKit.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/SnapKit/SnapKit-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/SnapKit/SnapKit-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/SnapKit/SnapKit.modulemap"; + PRODUCT_MODULE_NAME = SnapKit; + PRODUCT_NAME = SnapKit; + 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; + }; + 4F2A52AC0A717F24B191CDEB2CE9B483 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 185E08DFC78FD74FD5E4DD16703B0D70 /* Pods-WWCodeDFW.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-WWCodeDFW/Pods-WWCodeDFW-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-WWCodeDFW/Pods-WWCodeDFW.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; + }; + 6E2226BAF771B9AEEA8FE646C18E7879 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 15B49BE04AAF5CADC67B31B4F380303C /* SwiftyJSON.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; GCC_PREFIX_HEADER = "Target Support Files/SwiftyJSON/SwiftyJSON-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/SwiftyJSON/Info.plist"; + INFOPLIST_FILE = "Target Support Files/SwiftyJSON/SwiftyJSON-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/SwiftyJSON/SwiftyJSON.modulemap"; - MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_MODULE_NAME = SwiftyJSON; PRODUCT_NAME = SwiftyJSON; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; - SWIFT_VERSION = 3.0; + SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Release; }; - C03B8870130C98D1B02B59D003687524 /* Release */ = { + 84D7C4574E8F0F3095623F0E06F5B402 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = C8E4F9B31C7EB9A06CF46EFCA4BDEE95 /* SwiftLint.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_IDENTITY = "iPhone Developer"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + B01D14FDC83DCF9D4BE53066BEA96D05 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + 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_DIRECT_OBJC_ISA_USAGE = 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_OBJC_ROOT_CLASS = 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; - CODE_SIGNING_REQUIRED = NO; - COPY_PHASE_STRIP = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; - GCC_C_LANGUAGE_STANDARD = gnu99; + 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; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 10.0; - PROVISIONING_PROFILE_SPECIFIER = NO_SIGNING/; + 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"; - VALIDATE_PRODUCT = YES; }; name = Release; }; - CD3E88913517A21FE2E363EAE35034AF /* Release */ = { + DEED47E09AF743F48544C1C4FEADEF47 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 677A15C5C4A29E85F4D45B498214BC3A /* Pods-WWCodeDFW.release.xcconfig */; + baseConfigurationReference = C8E4F9B31C7EB9A06CF46EFCA4BDEE95 /* SwiftLint.xcconfig */; buildSettings = { - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; - INFOPLIST_FILE = "Target Support Files/Pods-WWCodeDFW/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-WWCodeDFW/Pods-WWCodeDFW.modulemap"; - MTL_ENABLE_DEBUG_INFO = NO; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = Pods_WWCodeDFW; + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_IDENTITY = "iPhone Developer"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; - SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; }; - name = Release; + name = Debug; }; - D29A217B6D96E6B5ECA382A0082807CB /* Debug */ = { + E8F35927ECB754A46E0AC8C2BACAF32D /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 29A64D3DD7AAAE8EFC90C107050EA7DA /* SnapKit.xcconfig */; + baseConfigurationReference = 15B49BE04AAF5CADC67B31B4F380303C /* SwiftyJSON.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; - GCC_PREFIX_HEADER = "Target Support Files/SnapKit/SnapKit-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/SnapKit/Info.plist"; + GCC_PREFIX_HEADER = "Target Support Files/SwiftyJSON/SwiftyJSON-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/SwiftyJSON/SwiftyJSON-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/SnapKit/SnapKit.modulemap"; - MTL_ENABLE_DEBUG_INFO = YES; - PRODUCT_NAME = SnapKit; + MODULEMAP_FILE = "Target Support Files/SwiftyJSON/SwiftyJSON.modulemap"; + PRODUCT_MODULE_NAME = SwiftyJSON; + PRODUCT_NAME = SwiftyJSON; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 3.0; + SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Debug; }; - D60F8C4DE6B0D221A33959774DA3DAFF /* Debug */ = { + F659822BFF3B3C20B29B76B89800A5E9 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 8A5D94811A8BB2DE4CAC223B9AC330A6 /* Alamofire.xcconfig */; + baseConfigurationReference = 015BBD18BF1855CB92828380CF23E4C4 /* 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; - DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + 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"; - MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_MODULE_NAME = Alamofire; PRODUCT_NAME = Alamofire; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 3.0; + SWIFT_VERSION = 5.1; TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; - name = Debug; + name = Release; }; - E99906A92A7FFC9B98AA7A30DD09ED3A /* Debug */ = { + FB6055AAD98D517B69C83255AD482FB0 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 76A040BE714228552CF0DE7A04894364 /* Pods-WWCodeDFW.debug.xcconfig */; + baseConfigurationReference = A74FC8AC9AD8E5265410F78F82AF63BF /* Pods-WWCodeDFW.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*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; - INFOPLIST_FILE = "Target Support Files/Pods-WWCodeDFW/Info.plist"; + INFOPLIST_FILE = "Target Support Files/Pods-WWCodeDFW/Pods-WWCodeDFW-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-WWCodeDFW/Pods-WWCodeDFW.modulemap"; - MTL_ENABLE_DEBUG_INFO = YES; OTHER_LDFLAGS = ""; OTHER_LIBTOOLFLAGS = ""; PODS_ROOT = "$(SRCROOT)"; PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = Pods_WWCodeDFW; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; SDKROOT = iphoneos; SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; - name = Debug; + name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ - 1D593E4399ADA2C2DE56D84F044424C5 /* Build configuration list for PBXNativeTarget "Pods-WWCodeDFW" */ = { + 0A36563739FDB3506A509EE80326E34E /* Build configuration list for PBXNativeTarget "Pods-WWCodeDFW" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 4F2A52AC0A717F24B191CDEB2CE9B483 /* Debug */, + FB6055AAD98D517B69C83255AD482FB0 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */ = { isa = XCConfigurationList; buildConfigurations = ( - E99906A92A7FFC9B98AA7A30DD09ED3A /* Debug */, - CD3E88913517A21FE2E363EAE35034AF /* Release */, + 196DFA3E4A09A28224918543529A1885 /* Debug */, + B01D14FDC83DCF9D4BE53066BEA96D05 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 27F5C25586C0082954AE719DA5AD3546 /* Build configuration list for PBXNativeTarget "SwiftyJSON" */ = { + 62468BF9C7EDA172E951A24083C3ECA7 /* Build configuration list for PBXNativeTarget "SwiftyJSON" */ = { isa = XCConfigurationList; buildConfigurations = ( - 69C9BF6FCDBD52FCBBF55D055E93D4EE /* Debug */, - B48DB407C7D8E2DFDD01A589B0F367D9 /* Release */, + E8F35927ECB754A46E0AC8C2BACAF32D /* Debug */, + 6E2226BAF771B9AEEA8FE646C18E7879 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */ = { + 6B2B8EC7E21CDBFF2BDA26B1B4AC4C0D /* Build configuration list for PBXNativeTarget "Alamofire" */ = { isa = XCConfigurationList; buildConfigurations = ( - 9BFC9E4A7AAD7A607ACE06D95A401A5A /* Debug */, - C03B8870130C98D1B02B59D003687524 /* Release */, + 00319A2330DC739FCBFBB6CFB0C5F58D /* Debug */, + F659822BFF3B3C20B29B76B89800A5E9 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 419E5D95491847CD79841B971A8A3277 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { + 7F8CE4DC18DBEA01587212F09727DB3D /* Build configuration list for PBXNativeTarget "SnapKit" */ = { isa = XCConfigurationList; buildConfigurations = ( - D60F8C4DE6B0D221A33959774DA3DAFF /* Debug */, - 077C4BB7DBEAA715DED46C057DC8051C /* Release */, + 2E3C8A300772E0028147E4BAF0D5078A /* Debug */, + 020BEC27E3AD6D7C84D288C148A58E74 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 9A5965CFAAC48040F7862B2BB0D91E8F /* Build configuration list for PBXNativeTarget "SnapKit" */ = { + AE7B4FB01588B9E6DF09CB79FC7CE7BD /* Build configuration list for PBXAggregateTarget "SwiftLint" */ = { isa = XCConfigurationList; buildConfigurations = ( - D29A217B6D96E6B5ECA382A0082807CB /* Debug */, - 03A89CC700388BFF7A86FA01F0E56188 /* Release */, + DEED47E09AF743F48544C1C4FEADEF47 /* Debug */, + 84D7C4574E8F0F3095623F0E06F5B402 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; - rootObject = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + rootObject = BFDFE7DC352907FC980B868725387E98 /* Project object */; } diff --git a/WWCodeDFW/Pods/SnapKit/README.md b/WWCodeDFW/Pods/SnapKit/README.md index 8b14ba8..0945ce6 100644 --- a/WWCodeDFW/Pods/SnapKit/README.md +++ b/WWCodeDFW/Pods/SnapKit/README.md @@ -7,8 +7,8 @@ SnapKit is a DSL to make Auto Layout easy on both iOS and OS X. [![Cocoapods Compatible](https://img.shields.io/cocoapods/v/SnapKit.svg)](https://cocoapods.org/pods/SnapKit) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) -#### ⚠️ **To use with Swift 2.x please ensure you are using == 0.22.0** ⚠️ -#### ⚠️ **To use with Swift 3.x please ensure you are using >= 3.0.0** ⚠️ +#### ⚠️ **To use with Swift 4.x please ensure you are using >= 4.0.0** ⚠️ +#### ⚠️ **To use with Swift 5.x please ensure you are using >= 5.0.0** ⚠️ ## Contents @@ -22,13 +22,9 @@ SnapKit is a DSL to make Auto Layout easy on both iOS and OS X. ## Requirements -- iOS 8.0+ / Mac OS X 10.11+ / tvOS 9.0+ -- Xcode 8.0+ -- Swift 3.0+ - -## Migration Guides - -- [SnapKit 3.0 Migration Guide](https://github.com/SnapKit/SnapKit/blob/master/Documentation/SnapKit%203.0%20Migration%20Guide.md) +- iOS 10.0+ / Mac OS X 10.12+ / tvOS 10.0+ +- Xcode 10.0+ +- Swift 4.0+ ## Communication @@ -49,7 +45,7 @@ SnapKit is a DSL to make Auto Layout easy on both iOS and OS X. $ gem install cocoapods ``` -> CocoaPods 1.1.0+ is required to build SnapKit 3.0.0+. +> CocoaPods 1.1.0+ is required to build SnapKit 4.0.0+. To integrate SnapKit into your Xcode project using CocoaPods, specify it in your `Podfile`: @@ -59,7 +55,7 @@ platform :ios, '10.0' use_frameworks! target '' do - pod 'SnapKit', '~> 3.0.2' + pod 'SnapKit', '~> 5.0.0' end ``` @@ -83,7 +79,7 @@ $ brew install carthage To integrate SnapKit into your Xcode project using Carthage, specify it in your `Cartfile`: ```ogdl -github "SnapKit/SnapKit" ~> 3.0.2 +github "SnapKit/SnapKit" ~> 5.0.0 ``` Run `carthage update` to build the framework and drag the built `SnapKit.framework` into your Xcode project. @@ -118,6 +114,13 @@ class MyViewController: UIViewController { } ``` +### Playground +You can try SnapKit in Playground. + +**Note:** + +> To try SnapKit in playground, open `SnapKit.xcworkspace` and build SnapKit.framework for any simulator first. + ### Resources - [Documentation](http://snapkit.io/docs/) diff --git a/WWCodeDFW/Pods/SnapKit/Source/Constraint.swift b/WWCodeDFW/Pods/SnapKit/Source/Constraint.swift index e5086c1..390629e 100644 --- a/WWCodeDFW/Pods/SnapKit/Source/Constraint.swift +++ b/WWCodeDFW/Pods/SnapKit/Source/Constraint.swift @@ -27,11 +27,11 @@ import AppKit #endif -public class Constraint { - +public final class Constraint { + internal let sourceLocation: (String, UInt) internal let label: String? - + private let from: ConstraintItem private let to: ConstraintItem private let relation: ConstraintRelation @@ -46,10 +46,30 @@ public class Constraint { self.updateConstantAndPriorityIfNeeded() } } - private var layoutConstraints: [LayoutConstraint] + public var layoutConstraints: [LayoutConstraint] - // MARK: Initialization + public var isActive: Bool { + set { + if newValue { + activate() + } + else { + deactivate() + } + } + + get { + for layoutConstraint in self.layoutConstraints { + if layoutConstraint.isActive { + return true + } + } + return false + } + } + // MARK: Initialization + internal init(from: ConstraintItem, to: ConstraintItem, relation: ConstraintRelation, @@ -67,20 +87,20 @@ public class Constraint { self.constant = constant self.priority = priority self.layoutConstraints = [] - + // get attributes let layoutFromAttributes = self.from.attributes.layoutAttributes let layoutToAttributes = self.to.attributes.layoutAttributes - + // get layout from - let layoutFrom: ConstraintView = self.from.view! - + let layoutFrom = self.from.layoutConstraintItem! + // get relation let layoutRelation = self.relation.layoutRelation - + for layoutFromAttribute in layoutFromAttributes { // get layout to attribute - let layoutToAttribute: NSLayoutAttribute + let layoutToAttribute: LayoutAttribute #if os(iOS) || os(tvOS) if layoutToAttributes.count > 0 { if self.from.attributes == .edges && self.to.attributes == .margins { @@ -109,6 +129,32 @@ public class Constraint { default: fatalError() } + } else if self.from.attributes == .directionalEdges && self.to.attributes == .directionalMargins { + switch layoutFromAttribute { + case .leading: + layoutToAttribute = .leadingMargin + case .trailing: + layoutToAttribute = .trailingMargin + case .top: + layoutToAttribute = .topMargin + case .bottom: + layoutToAttribute = .bottomMargin + default: + fatalError() + } + } else if self.from.attributes == .directionalMargins && self.to.attributes == .directionalEdges { + switch layoutFromAttribute { + case .leadingMargin: + layoutToAttribute = .leading + case .trailingMargin: + layoutToAttribute = .trailing + case .topMargin: + layoutToAttribute = .top + case .bottomMargin: + layoutToAttribute = .bottom + default: + fatalError() + } } else if self.from.attributes == self.to.attributes { layoutToAttribute = layoutFromAttribute } else { @@ -130,18 +176,18 @@ public class Constraint { layoutToAttribute = layoutFromAttribute } #endif - + // get layout constant let layoutConstant: CGFloat = self.constant.constraintConstantTargetValueFor(layoutAttribute: layoutToAttribute) - + // get layout to var layoutTo: AnyObject? = self.to.target - + // use superview if possible if layoutTo == nil && layoutToAttribute != .width && layoutToAttribute != .height { layoutTo = layoutFrom.superview } - + // create layout constraint let layoutConstraint = LayoutConstraint( item: layoutFrom, @@ -152,131 +198,144 @@ public class Constraint { multiplier: self.multiplier.constraintMultiplierTargetValue, constant: layoutConstant ) - + // set label layoutConstraint.label = self.label - + // set priority - layoutConstraint.priority = self.priority.constraintPriorityTargetValue - + layoutConstraint.priority = LayoutPriority(rawValue: self.priority.constraintPriorityTargetValue) + // set constraint layoutConstraint.constraint = self - + // append self.layoutConstraints.append(layoutConstraint) } } - + // MARK: Public - - @available(*, deprecated:3.0, message:"Use activate().") + + @available(*, deprecated, message:"Use activate().") public func install() { self.activate() } - - @available(*, deprecated:3.0, message:"Use deactivate().") + + @available(*, deprecated, message:"Use deactivate().") public func uninstall() { self.deactivate() } - + public func activate() { self.activateIfNeeded() } - + public func deactivate() { self.deactivateIfNeeded() } - + @discardableResult public func update(offset: ConstraintOffsetTarget) -> Constraint { self.constant = offset.constraintOffsetTargetValue return self } - + @discardableResult public func update(inset: ConstraintInsetTarget) -> Constraint { self.constant = inset.constraintInsetTargetValue return self } - + + #if os(iOS) || os(tvOS) + @discardableResult + @available(iOS 11.0, tvOS 11.0, *) + public func update(inset: ConstraintDirectionalInsetTarget) -> Constraint { + self.constant = inset.constraintDirectionalInsetTargetValue + return self + } + #endif + @discardableResult public func update(priority: ConstraintPriorityTarget) -> Constraint { self.priority = priority.constraintPriorityTargetValue return self } - - @available(*, deprecated:3.0, message:"Use update(offset: ConstraintOffsetTarget) instead.") + + @discardableResult + public func update(priority: ConstraintPriority) -> Constraint { + self.priority = priority.value + return self + } + + @available(*, deprecated, message:"Use update(offset: ConstraintOffsetTarget) instead.") public func updateOffset(amount: ConstraintOffsetTarget) -> Void { self.update(offset: amount) } - - @available(*, deprecated:3.0, message:"Use update(inset: ConstraintInsetTarget) instead.") + + @available(*, deprecated, message:"Use update(inset: ConstraintInsetTarget) instead.") public func updateInsets(amount: ConstraintInsetTarget) -> Void { self.update(inset: amount) } - - @available(*, deprecated:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.") + + @available(*, deprecated, message:"Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriority(amount: ConstraintPriorityTarget) -> Void { self.update(priority: amount) } - - @available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.") + + @available(*, deprecated, message:"Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriorityRequired() -> Void {} - - @available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.") + + @available(*, deprecated, message:"Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriorityHigh() -> Void { fatalError("Must be implemented by Concrete subclass.") } - - @available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.") + + @available(*, deprecated, message:"Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriorityMedium() -> Void { fatalError("Must be implemented by Concrete subclass.") } - - @available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.") + + @available(*, deprecated, message:"Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriorityLow() -> Void { fatalError("Must be implemented by Concrete subclass.") } - + // MARK: Internal - + internal func updateConstantAndPriorityIfNeeded() { for layoutConstraint in self.layoutConstraints { let attribute = (layoutConstraint.secondAttribute == .notAnAttribute) ? layoutConstraint.firstAttribute : layoutConstraint.secondAttribute layoutConstraint.constant = self.constant.constraintConstantTargetValueFor(layoutAttribute: attribute) - - #if os(iOS) || os(tvOS) - let requiredPriority: UILayoutPriority = UILayoutPriorityRequired - #else - let requiredPriority: Float = 1000.0 - #endif - - - if (layoutConstraint.priority < requiredPriority), (self.priority.constraintPriorityTargetValue != requiredPriority) { - layoutConstraint.priority = self.priority.constraintPriorityTargetValue + + let requiredPriority = ConstraintPriority.required.value + if (layoutConstraint.priority.rawValue < requiredPriority), (self.priority.constraintPriorityTargetValue != requiredPriority) { + layoutConstraint.priority = LayoutPriority(rawValue: self.priority.constraintPriorityTargetValue) } } } - + internal func activateIfNeeded(updatingExisting: Bool = false) { - guard let view = self.from.view else { - print("WARNING: SnapKit failed to get from view from constraint. Activate will be a no-op.") + guard let item = self.from.layoutConstraintItem else { + print("WARNING: SnapKit failed to get from item from constraint. Activate will be a no-op.") return } let layoutConstraints = self.layoutConstraints - let existingLayoutConstraints = view.snp.constraints.map({ $0.layoutConstraints }).reduce([]) { $0 + $1 } - + if updatingExisting { + var existingLayoutConstraints: [LayoutConstraint] = [] + for constraint in item.constraints { + existingLayoutConstraints += constraint.layoutConstraints + } + for layoutConstraint in layoutConstraints { let existingLayoutConstraint = existingLayoutConstraints.first { $0 == layoutConstraint } guard let updateLayoutConstraint = existingLayoutConstraint else { fatalError("Updated constraint could not find existing matching constraint to update: \(layoutConstraint)") } - + let updateLayoutAttribute = (updateLayoutConstraint.secondAttribute == .notAnAttribute) ? updateLayoutConstraint.firstAttribute : updateLayoutConstraint.secondAttribute updateLayoutConstraint.constant = self.constant.constraintConstantTargetValueFor(layoutAttribute: updateLayoutAttribute) } } else { NSLayoutConstraint.activate(layoutConstraints) - view.snp.add(constraints: [self]) + item.add(constraints: [self]) } } - + internal func deactivateIfNeeded() { - guard let view = self.from.view else { - print("WARNING: SnapKit failed to get from view from constraint. Deactivate will be a no-op.") + guard let item = self.from.layoutConstraintItem else { + print("WARNING: SnapKit failed to get from item from constraint. Deactivate will be a no-op.") return } let layoutConstraints = self.layoutConstraints NSLayoutConstraint.deactivate(layoutConstraints) - view.snp.remove(constraints: [self]) + item.remove(constraints: [self]) } } diff --git a/WWCodeDFW/Pods/SnapKit/Source/ConstraintAttributes.swift b/WWCodeDFW/Pods/SnapKit/Source/ConstraintAttributes.swift index 7236d24..2f0fbe9 100644 --- a/WWCodeDFW/Pods/SnapKit/Source/ConstraintAttributes.swift +++ b/WWCodeDFW/Pods/SnapKit/Source/ConstraintAttributes.swift @@ -28,7 +28,9 @@ #endif -internal struct ConstraintAttributes: OptionSet { +internal struct ConstraintAttributes : OptionSet, ExpressibleByIntegerLiteral { + + typealias IntegerLiteralType = UInt internal init(rawValue: UInt) { self.rawValue = rawValue @@ -39,10 +41,13 @@ internal struct ConstraintAttributes: OptionSet { internal init(nilLiteral: ()) { self.rawValue = 0 } + internal init(integerLiteral rawValue: IntegerLiteralType) { + self.init(rawValue: rawValue) + } internal private(set) var rawValue: UInt - internal static var allZeros: ConstraintAttributes { return self.init(0) } - internal static func convertFromNilLiteral() -> ConstraintAttributes { return self.init(0) } + internal static var allZeros: ConstraintAttributes { return 0 } + internal static func convertFromNilLiteral() -> ConstraintAttributes { return 0 } internal var boolValue: Bool { return self.rawValue != 0 } internal func toRaw() -> UInt { return self.rawValue } @@ -51,60 +56,64 @@ internal struct ConstraintAttributes: OptionSet { // normal - internal static var none: ConstraintAttributes { return self.init(0) } - internal static var left: ConstraintAttributes { return self.init(1) } - internal static var top: ConstraintAttributes { return self.init(2) } - internal static var right: ConstraintAttributes { return self.init(4) } - internal static var bottom: ConstraintAttributes { return self.init(8) } - internal static var leading: ConstraintAttributes { return self.init(16) } - internal static var trailing: ConstraintAttributes { return self.init(32) } - internal static var width: ConstraintAttributes { return self.init(64) } - internal static var height: ConstraintAttributes { return self.init(128) } - internal static var centerX: ConstraintAttributes { return self.init(256) } - internal static var centerY: ConstraintAttributes { return self.init(512) } - internal static var lastBaseline: ConstraintAttributes { return self.init(1024) } + internal static var none: ConstraintAttributes { return 0 } + internal static var left: ConstraintAttributes { return 1 } + internal static var top: ConstraintAttributes { return 2 } + internal static var right: ConstraintAttributes { return 4 } + internal static var bottom: ConstraintAttributes { return 8 } + internal static var leading: ConstraintAttributes { return 16 } + internal static var trailing: ConstraintAttributes { return 32 } + internal static var width: ConstraintAttributes { return 64 } + internal static var height: ConstraintAttributes { return 128 } + internal static var centerX: ConstraintAttributes { return 256 } + internal static var centerY: ConstraintAttributes { return 512 } + internal static var lastBaseline: ConstraintAttributes { return 1024 } @available(iOS 8.0, OSX 10.11, *) - internal static var firstBaseline: ConstraintAttributes { return self.init(2048) } + internal static var firstBaseline: ConstraintAttributes { return 2048 } @available(iOS 8.0, *) - internal static var leftMargin: ConstraintAttributes { return self.init(4096) } + internal static var leftMargin: ConstraintAttributes { return 4096 } @available(iOS 8.0, *) - internal static var rightMargin: ConstraintAttributes { return self.init(8192) } + internal static var rightMargin: ConstraintAttributes { return 8192 } @available(iOS 8.0, *) - internal static var topMargin: ConstraintAttributes { return self.init(16384) } + internal static var topMargin: ConstraintAttributes { return 16384 } @available(iOS 8.0, *) - internal static var bottomMargin: ConstraintAttributes { return self.init(32768) } + internal static var bottomMargin: ConstraintAttributes { return 32768 } @available(iOS 8.0, *) - internal static var leadingMargin: ConstraintAttributes { return self.init(65536) } + internal static var leadingMargin: ConstraintAttributes { return 65536 } @available(iOS 8.0, *) - internal static var trailingMargin: ConstraintAttributes { return self.init(131072) } + internal static var trailingMargin: ConstraintAttributes { return 131072 } @available(iOS 8.0, *) - internal static var centerXWithinMargins: ConstraintAttributes { return self.init(262144) } + internal static var centerXWithinMargins: ConstraintAttributes { return 262144 } @available(iOS 8.0, *) - internal static var centerYWithinMargins: ConstraintAttributes { return self.init(524288) } + internal static var centerYWithinMargins: ConstraintAttributes { return 524288 } // aggregates - internal static var edges: ConstraintAttributes { return self.init(15) } - internal static var size: ConstraintAttributes { return self.init(192) } - internal static var center: ConstraintAttributes { return self.init(768) } + internal static var edges: ConstraintAttributes { return 15 } + internal static var directionalEdges: ConstraintAttributes { return 58 } + internal static var size: ConstraintAttributes { return 192 } + internal static var center: ConstraintAttributes { return 768 } @available(iOS 8.0, *) - internal static var margins: ConstraintAttributes { return self.init(61440) } + internal static var margins: ConstraintAttributes { return 61440 } @available(iOS 8.0, *) - internal static var centerWithinMargins: ConstraintAttributes { return self.init(786432) } + internal static var directionalMargins: ConstraintAttributes { return 245760 } + + @available(iOS 8.0, *) + internal static var centerWithinMargins: ConstraintAttributes { return 786432 } - internal var layoutAttributes:[NSLayoutAttribute] { - var attrs = [NSLayoutAttribute]() + internal var layoutAttributes:[LayoutAttribute] { + var attrs = [LayoutAttribute]() if (self.contains(ConstraintAttributes.left)) { attrs.append(.left) } diff --git a/WWCodeDFW/Pods/SnapKit/Source/ConstraintConstantTarget.swift b/WWCodeDFW/Pods/SnapKit/Source/ConstraintConstantTarget.swift index 801bb79..7f54907 100644 --- a/WWCodeDFW/Pods/SnapKit/Source/ConstraintConstantTarget.swift +++ b/WWCodeDFW/Pods/SnapKit/Source/ConstraintConstantTarget.swift @@ -40,9 +40,15 @@ extension CGSize: ConstraintConstantTarget { extension ConstraintInsets: ConstraintConstantTarget { } +#if os(iOS) || os(tvOS) +@available(iOS 11.0, tvOS 11.0, *) +extension ConstraintDirectionalInsets: ConstraintConstantTarget { +} +#endif + extension ConstraintConstantTarget { - internal func constraintConstantTargetValueFor(layoutAttribute: NSLayoutAttribute) -> CGFloat { + internal func constraintConstantTargetValueFor(layoutAttribute: LayoutAttribute) -> CGFloat { if let value = self as? CGFloat { return value } @@ -82,7 +88,11 @@ extension ConstraintConstantTarget { return value.y case .width, .height, .notAnAttribute: return 0.0 - } + #if swift(>=5.0) + @unknown default: + return 0.0 + #endif + } #else switch layoutAttribute { case .left, .right, .leading, .trailing, .centerX: @@ -91,56 +101,112 @@ extension ConstraintConstantTarget { return value.y case .width, .height, .notAnAttribute: return 0.0 - } + #if swift(>=5.0) + @unknown default: + return 0.0 + #endif + } #endif } if let value = self as? ConstraintInsets { #if os(iOS) || os(tvOS) switch layoutAttribute { - case .left, .leftMargin, .centerX, .centerXWithinMargins: + case .left, .leftMargin: return value.left - case .top, .topMargin, .centerY, .centerYWithinMargins, .lastBaseline, .firstBaseline: + case .top, .topMargin, .firstBaseline: return value.top case .right, .rightMargin: return -value.right - case .bottom, .bottomMargin: + case .bottom, .bottomMargin, .lastBaseline: return -value.bottom case .leading, .leadingMargin: return (ConstraintConfig.interfaceLayoutDirection == .leftToRight) ? value.left : value.right case .trailing, .trailingMargin: return (ConstraintConfig.interfaceLayoutDirection == .leftToRight) ? -value.right : -value.left + case .centerX, .centerXWithinMargins: + return (value.left - value.right) / 2 + case .centerY, .centerYWithinMargins: + return (value.top - value.bottom) / 2 case .width: return -(value.left + value.right) case .height: return -(value.top + value.bottom) case .notAnAttribute: return 0.0 - } + #if swift(>=5.0) + @unknown default: + return 0.0 + #endif + } #else switch layoutAttribute { - case .left, .centerX: + case .left: return value.left - case .top, .centerY, .lastBaseline, .firstBaseline: + case .top, .firstBaseline: return value.top case .right: return -value.right - case .bottom: + case .bottom, .lastBaseline: return -value.bottom case .leading: return (ConstraintConfig.interfaceLayoutDirection == .leftToRight) ? value.left : value.right case .trailing: return (ConstraintConfig.interfaceLayoutDirection == .leftToRight) ? -value.right : -value.left + case .centerX: + return (value.left - value.right) / 2 + case .centerY: + return (value.top - value.bottom) / 2 case .width: return -(value.left + value.right) case .height: return -(value.top + value.bottom) case .notAnAttribute: return 0.0 - } + #if swift(>=5.0) + @unknown default: + return 0.0 + #endif + } #endif } + #if os(iOS) || os(tvOS) + if #available(iOS 11.0, tvOS 11.0, *), let value = self as? ConstraintDirectionalInsets { + switch layoutAttribute { + case .left, .leftMargin: + return (ConstraintConfig.interfaceLayoutDirection == .leftToRight) ? value.leading : value.trailing + case .top, .topMargin, .firstBaseline: + return value.top + case .right, .rightMargin: + return (ConstraintConfig.interfaceLayoutDirection == .leftToRight) ? -value.trailing : -value.leading + case .bottom, .bottomMargin, .lastBaseline: + return -value.bottom + case .leading, .leadingMargin: + return value.leading + case .trailing, .trailingMargin: + return -value.trailing + case .centerX, .centerXWithinMargins: + return (value.leading - value.trailing) / 2 + case .centerY, .centerYWithinMargins: + return (value.top - value.bottom) / 2 + case .width: + return -(value.leading + value.trailing) + case .height: + return -(value.top + value.bottom) + case .notAnAttribute: + return 0.0 + #if swift(>=5.0) + @unknown default: + return 0.0 + #else + default: + return 0.0 + #endif + } + } + #endif + return 0.0 } diff --git a/WWCodeDFW/Pods/SnapKit/Source/ConstraintDSL.swift b/WWCodeDFW/Pods/SnapKit/Source/ConstraintDSL.swift index cda83a0..ecc5173 100644 --- a/WWCodeDFW/Pods/SnapKit/Source/ConstraintDSL.swift +++ b/WWCodeDFW/Pods/SnapKit/Source/ConstraintDSL.swift @@ -39,22 +39,22 @@ public protocol ConstraintDSL { extension ConstraintDSL { public func setLabel(_ value: String?) { - objc_setAssociatedObject(self.target, &labelKey, value, .OBJC_ASSOCIATION_COPY_NONATOMIC) + objc_setAssociatedObject(self.target as Any, &labelKey, value, .OBJC_ASSOCIATION_COPY_NONATOMIC) } public func label() -> String? { - return objc_getAssociatedObject(self.target, &labelKey) as? String + return objc_getAssociatedObject(self.target as Any, &labelKey) as? String } } private var labelKey: UInt8 = 0 -public protocol ConstraintAttributesDSL: ConstraintDSL { +public protocol ConstraintBasicAttributesDSL : ConstraintDSL { } -extension ConstraintAttributesDSL { +extension ConstraintBasicAttributesDSL { // MARK: Basics - + public var left: ConstraintItem { return ConstraintItem(target: self.target, attributes: ConstraintAttributes.left) } @@ -99,6 +99,10 @@ extension ConstraintAttributesDSL { return ConstraintItem(target: self.target, attributes: ConstraintAttributes.edges) } + public var directionalEdges: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.directionalEdges) + } + public var size: ConstraintItem { return ConstraintItem(target: self.target, attributes: ConstraintAttributes.size) } @@ -107,9 +111,15 @@ extension ConstraintAttributesDSL { return ConstraintItem(target: self.target, attributes: ConstraintAttributes.center) } +} + +public protocol ConstraintAttributesDSL : ConstraintBasicAttributesDSL { +} +extension ConstraintAttributesDSL { + // MARK: Baselines - @available(*, deprecated:3.0, message:"Use .lastBaseline instead") + @available(*, deprecated, message:"Use .lastBaseline instead") public var baseline: ConstraintItem { return ConstraintItem(target: self.target, attributes: ConstraintAttributes.lastBaseline) } @@ -171,6 +181,11 @@ extension ConstraintAttributesDSL { return ConstraintItem(target: self.target, attributes: ConstraintAttributes.margins) } + @available(iOS 8.0, *) + public var directionalMargins: ConstraintItem { + return ConstraintItem(target: self.target, attributes: ConstraintAttributes.directionalMargins) + } + @available(iOS 8.0, *) public var centerWithinMargins: ConstraintItem { return ConstraintItem(target: self.target, attributes: ConstraintAttributes.centerWithinMargins) diff --git a/WWCodeDFW/Pods/SnapKit/Source/ConstraintDescription.swift b/WWCodeDFW/Pods/SnapKit/Source/ConstraintDescription.swift index d961fb5..3521f9f 100644 --- a/WWCodeDFW/Pods/SnapKit/Source/ConstraintDescription.swift +++ b/WWCodeDFW/Pods/SnapKit/Source/ConstraintDescription.swift @@ -30,7 +30,7 @@ public class ConstraintDescription { - internal let view: ConstraintView + internal let item: LayoutConstraintItem internal var attributes: ConstraintAttributes internal var relation: ConstraintRelation? = nil internal var sourceLocation: (String, UInt)? = nil @@ -45,7 +45,7 @@ public class ConstraintDescription { let sourceLocation = self.sourceLocation else { return nil } - let from = ConstraintItem(target: self.view, attributes: self.attributes) + let from = ConstraintItem(target: self.item, attributes: self.attributes) return Constraint( from: from, @@ -61,8 +61,8 @@ public class ConstraintDescription { // MARK: Initialization - internal init(view: ConstraintView, attributes: ConstraintAttributes) { - self.view = view + internal init(item: LayoutConstraintItem, attributes: ConstraintAttributes) { + self.item = item self.attributes = attributes } diff --git a/WWCodeDFW/Pods/SnapKit/Source/ConstraintDirectionalInsetTarget.swift b/WWCodeDFW/Pods/SnapKit/Source/ConstraintDirectionalInsetTarget.swift new file mode 100644 index 0000000..955aec3 --- /dev/null +++ b/WWCodeDFW/Pods/SnapKit/Source/ConstraintDirectionalInsetTarget.swift @@ -0,0 +1,49 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) +import UIKit +#else +import AppKit +#endif + +#if os(iOS) || os(tvOS) +public protocol ConstraintDirectionalInsetTarget: ConstraintConstantTarget { +} + +@available(iOS 11.0, tvOS 11.0, *) +extension ConstraintDirectionalInsets: ConstraintDirectionalInsetTarget { +} + +extension ConstraintDirectionalInsetTarget { + + @available(iOS 11.0, tvOS 11.0, *) + internal var constraintDirectionalInsetTargetValue: ConstraintDirectionalInsets { + if let amount = self as? ConstraintDirectionalInsets { + return amount + } else { + return ConstraintDirectionalInsets(top: 0, leading: 0, bottom: 0, trailing: 0) + } + } +} +#endif diff --git a/WWCodeDFW/Pods/SnapKit/Source/ConstraintDirectionalInsets.swift b/WWCodeDFW/Pods/SnapKit/Source/ConstraintDirectionalInsets.swift new file mode 100644 index 0000000..ada8ed5 --- /dev/null +++ b/WWCodeDFW/Pods/SnapKit/Source/ConstraintDirectionalInsets.swift @@ -0,0 +1,34 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + + +#if os(iOS) || os(tvOS) + @available(iOS 11.0, tvOS 11.0, *) + public typealias ConstraintDirectionalInsets = NSDirectionalEdgeInsets +#endif diff --git a/WWCodeDFW/Pods/SnapKit/Source/ConstraintInsets.swift b/WWCodeDFW/Pods/SnapKit/Source/ConstraintInsets.swift index 6ecac6b..738ca05 100644 --- a/WWCodeDFW/Pods/SnapKit/Source/ConstraintInsets.swift +++ b/WWCodeDFW/Pods/SnapKit/Source/ConstraintInsets.swift @@ -31,5 +31,5 @@ #if os(iOS) || os(tvOS) public typealias ConstraintInsets = UIEdgeInsets #else - public typealias ConstraintInsets = EdgeInsets + public typealias ConstraintInsets = NSEdgeInsets #endif diff --git a/WWCodeDFW/Pods/SnapKit/Source/ConstraintItem.swift b/WWCodeDFW/Pods/SnapKit/Source/ConstraintItem.swift index a9477da..a342c1d 100644 --- a/WWCodeDFW/Pods/SnapKit/Source/ConstraintItem.swift +++ b/WWCodeDFW/Pods/SnapKit/Source/ConstraintItem.swift @@ -28,7 +28,7 @@ #endif -public class ConstraintItem: Equatable { +public final class ConstraintItem { internal weak var target: AnyObject? internal let attributes: ConstraintAttributes @@ -38,8 +38,8 @@ public class ConstraintItem: Equatable { self.attributes = attributes } - internal var view: ConstraintView? { - return self.target as? ConstraintView + internal var layoutConstraintItem: LayoutConstraintItem? { + return self.target as? LayoutConstraintItem } } diff --git a/WWCodeDFW/Pods/SnapKit/Source/UILayoutGuide+Extensions.swift b/WWCodeDFW/Pods/SnapKit/Source/ConstraintLayoutGuide+Extensions.swift similarity index 94% rename from WWCodeDFW/Pods/SnapKit/Source/UILayoutGuide+Extensions.swift rename to WWCodeDFW/Pods/SnapKit/Source/ConstraintLayoutGuide+Extensions.swift index cd89d8a..d429e0c 100644 --- a/WWCodeDFW/Pods/SnapKit/Source/UILayoutGuide+Extensions.swift +++ b/WWCodeDFW/Pods/SnapKit/Source/ConstraintLayoutGuide+Extensions.swift @@ -26,10 +26,10 @@ #endif -@available(iOS 9.0, *) +@available(iOS 9.0, OSX 10.11, *) public extension ConstraintLayoutGuide { - public var snp: ConstraintLayoutGuideDSL { + var snp: ConstraintLayoutGuideDSL { return ConstraintLayoutGuideDSL(guide: self) } diff --git a/WWCodeDFW/Pods/SnapKit/Source/ConstraintLayoutGuide.swift b/WWCodeDFW/Pods/SnapKit/Source/ConstraintLayoutGuide.swift index f6eba82..e3e50c8 100644 --- a/WWCodeDFW/Pods/SnapKit/Source/ConstraintLayoutGuide.swift +++ b/WWCodeDFW/Pods/SnapKit/Source/ConstraintLayoutGuide.swift @@ -32,5 +32,6 @@ @available(iOS 9.0, *) public typealias ConstraintLayoutGuide = UILayoutGuide #else - public class ConstraintLayoutGuide {} + @available(OSX 10.11, *) + public typealias ConstraintLayoutGuide = NSLayoutGuide #endif diff --git a/WWCodeDFW/Pods/SnapKit/Source/ConstraintLayoutGuideDSL.swift b/WWCodeDFW/Pods/SnapKit/Source/ConstraintLayoutGuideDSL.swift index 62bd9b4..0007819 100644 --- a/WWCodeDFW/Pods/SnapKit/Source/ConstraintLayoutGuideDSL.swift +++ b/WWCodeDFW/Pods/SnapKit/Source/ConstraintLayoutGuideDSL.swift @@ -28,9 +28,30 @@ #endif -@available(iOS 9.0, *) +@available(iOS 9.0, OSX 10.11, *) public struct ConstraintLayoutGuideDSL: ConstraintAttributesDSL { + @discardableResult + public func prepareConstraints(_ closure: (_ make: ConstraintMaker) -> Void) -> [Constraint] { + return ConstraintMaker.prepareConstraints(item: self.guide, closure: closure) + } + + public func makeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { + ConstraintMaker.makeConstraints(item: self.guide, closure: closure) + } + + public func remakeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { + ConstraintMaker.remakeConstraints(item: self.guide, closure: closure) + } + + public func updateConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { + ConstraintMaker.updateConstraints(item: self.guide, closure: closure) + } + + public func removeConstraints() { + ConstraintMaker.removeConstraints(item: self.guide) + } + public var target: AnyObject? { return self.guide } diff --git a/WWCodeDFW/Pods/SnapKit/Source/ConstraintMaker.swift b/WWCodeDFW/Pods/SnapKit/Source/ConstraintMaker.swift index 63c1be4..38f4d31 100644 --- a/WWCodeDFW/Pods/SnapKit/Source/ConstraintMaker.swift +++ b/WWCodeDFW/Pods/SnapKit/Source/ConstraintMaker.swift @@ -69,7 +69,7 @@ public class ConstraintMaker { return self.makeExtendableWithAttributes(.centerY) } - @available(*, deprecated:3.0, message:"Use lastBaseline instead") + @available(*, deprecated, message:"Use lastBaseline instead") public var baseline: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.lastBaseline) } @@ -126,6 +126,9 @@ public class ConstraintMaker { public var edges: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.edges) } + public var directionalEdges: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.directionalEdges) + } public var size: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.size) } @@ -138,71 +141,69 @@ public class ConstraintMaker { return self.makeExtendableWithAttributes(.margins) } + @available(iOS 8.0, *) + public var directionalMargins: ConstraintMakerExtendable { + return self.makeExtendableWithAttributes(.directionalMargins) + } + @available(iOS 8.0, *) public var centerWithinMargins: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.centerWithinMargins) } - private let view: ConstraintView + private let item: LayoutConstraintItem private var descriptions = [ConstraintDescription]() - internal init(view: ConstraintView) { - self.view = view - self.view.translatesAutoresizingMaskIntoConstraints = false + internal init(item: LayoutConstraintItem) { + self.item = item + self.item.prepare() } internal func makeExtendableWithAttributes(_ attributes: ConstraintAttributes) -> ConstraintMakerExtendable { - let description = ConstraintDescription(view: self.view, attributes: attributes) + let description = ConstraintDescription(item: self.item, attributes: attributes) self.descriptions.append(description) return ConstraintMakerExtendable(description) } - internal static func prepareConstraints(view: ConstraintView, closure: (_ make: ConstraintMaker) -> Void) -> [Constraint] { - let maker = ConstraintMaker(view: view) + internal static func prepareConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void) -> [Constraint] { + let maker = ConstraintMaker(item: item) closure(maker) - let constraints = maker.descriptions - .map { $0.constraint } - .filter { $0 != nil } - .map { $0! } + var constraints: [Constraint] = [] + for description in maker.descriptions { + guard let constraint = description.constraint else { + continue + } + constraints.append(constraint) + } return constraints } - internal static func makeConstraints(view: ConstraintView, closure: (_ make: ConstraintMaker) -> Void) { - let maker = ConstraintMaker(view: view) - closure(maker) - let constraints = maker.descriptions - .map { $0.constraint } - .filter { $0 != nil } - .map { $0! } + internal static func makeConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void) { + let constraints = prepareConstraints(item: item, closure: closure) for constraint in constraints { constraint.activateIfNeeded(updatingExisting: false) } } - internal static func remakeConstraints(view: ConstraintView, closure: (_ make: ConstraintMaker) -> Void) { - self.removeConstraints(view: view) - self.makeConstraints(view: view, closure: closure) + internal static func remakeConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void) { + self.removeConstraints(item: item) + self.makeConstraints(item: item, closure: closure) } - internal static func updateConstraints(view: ConstraintView, closure: (_ make: ConstraintMaker) -> Void) { - guard view.snp.constraints.count > 0 else { - self.makeConstraints(view: view, closure: closure) + internal static func updateConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void) { + guard item.constraints.count > 0 else { + self.makeConstraints(item: item, closure: closure) return } - let maker = ConstraintMaker(view: view) - closure(maker) - let constraints = maker.descriptions - .map { $0.constraint } - .filter { $0 != nil } - .map { $0! } + let constraints = prepareConstraints(item: item, closure: closure) for constraint in constraints { constraint.activateIfNeeded(updatingExisting: true) } } - internal static func removeConstraints(view: ConstraintView) { - let constraints = view.snp.constraints + internal static func removeConstraints(item: LayoutConstraintItem) { + let constraints = item.constraints for constraint in constraints { constraint.deactivateIfNeeded() } diff --git a/WWCodeDFW/Pods/SnapKit/Source/ConstraintMakerEditable.swift b/WWCodeDFW/Pods/SnapKit/Source/ConstraintMakerEditable.swift index fb88c41..f768a17 100644 --- a/WWCodeDFW/Pods/SnapKit/Source/ConstraintMakerEditable.swift +++ b/WWCodeDFW/Pods/SnapKit/Source/ConstraintMakerEditable.swift @@ -53,4 +53,12 @@ public class ConstraintMakerEditable: ConstraintMakerPriortizable { return self } + #if os(iOS) || os(tvOS) + @discardableResult + @available(iOS 11.0, tvOS 11.0, *) + public func inset(_ amount: ConstraintDirectionalInsetTarget) -> ConstraintMakerEditable { + self.description.constant = amount.constraintDirectionalInsetTargetValue + return self + } + #endif } diff --git a/WWCodeDFW/Pods/SnapKit/Source/ConstraintMakerExtendable.swift b/WWCodeDFW/Pods/SnapKit/Source/ConstraintMakerExtendable.swift index 658c833..ce47169 100644 --- a/WWCodeDFW/Pods/SnapKit/Source/ConstraintMakerExtendable.swift +++ b/WWCodeDFW/Pods/SnapKit/Source/ConstraintMakerExtendable.swift @@ -80,7 +80,7 @@ public class ConstraintMakerExtendable: ConstraintMakerRelatable { return self } - @available(*, deprecated:3.0, message:"Use lastBaseline instead") + @available(*, deprecated, message:"Use lastBaseline instead") public var baseline: ConstraintMakerExtendable { self.description.attributes += .lastBaseline return self @@ -109,6 +109,12 @@ public class ConstraintMakerExtendable: ConstraintMakerRelatable { return self } + @available(iOS 8.0, *) + public var topMargin: ConstraintMakerExtendable { + self.description.attributes += .topMargin + return self + } + @available(iOS 8.0, *) public var bottomMargin: ConstraintMakerExtendable { self.description.attributes += .bottomMargin @@ -143,6 +149,10 @@ public class ConstraintMakerExtendable: ConstraintMakerRelatable { self.description.attributes += .edges return self } + public var directionalEdges: ConstraintMakerExtendable { + self.description.attributes += .directionalEdges + return self + } public var size: ConstraintMakerExtendable { self.description.attributes += .size return self @@ -154,6 +164,12 @@ public class ConstraintMakerExtendable: ConstraintMakerRelatable { return self } + @available(iOS 8.0, *) + public var directionalMargins: ConstraintMakerExtendable { + self.description.attributes += .directionalMargins + return self + } + @available(iOS 8.0, *) public var centerWithinMargins: ConstraintMakerExtendable { self.description.attributes += .centerWithinMargins diff --git a/WWCodeDFW/Pods/SnapKit/Source/ConstraintMakerPriortizable.swift b/WWCodeDFW/Pods/SnapKit/Source/ConstraintMakerPriortizable.swift index 82a6de6..e0d452d 100644 --- a/WWCodeDFW/Pods/SnapKit/Source/ConstraintMakerPriortizable.swift +++ b/WWCodeDFW/Pods/SnapKit/Source/ConstraintMakerPriortizable.swift @@ -30,38 +30,39 @@ public class ConstraintMakerPriortizable: ConstraintMakerFinalizable { + @discardableResult + public func priority(_ amount: ConstraintPriority) -> ConstraintMakerFinalizable { + self.description.priority = amount.value + return self + } + @discardableResult public func priority(_ amount: ConstraintPriorityTarget) -> ConstraintMakerFinalizable { self.description.priority = amount return self } - @available(*, deprecated:3.0, message:"Use priority(_ amount: ConstraintPriorityTarget) instead.") + @available(*, deprecated, message:"Use priority(.required) instead.") @discardableResult public func priorityRequired() -> ConstraintMakerFinalizable { - return self.priority(1000) + return self.priority(.required) } - @available(*, deprecated:3.0, message:"Use priority(_ amount: ConstraintPriorityTarget) instead.") + @available(*, deprecated, message:"Use priority(.high) instead.") @discardableResult public func priorityHigh() -> ConstraintMakerFinalizable { - return self.priority(750) + return self.priority(.high) } - @available(*, deprecated:3.0, message:"Use priority(_ amount: ConstraintPriorityTarget) instead.") + @available(*, deprecated, message:"Use priority(.medium) instead.") @discardableResult public func priorityMedium() -> ConstraintMakerFinalizable { - #if os(iOS) || os(tvOS) - return self.priority(500) - #else - return self.priority(501) - #endif + return self.priority(.medium) } - @available(*, deprecated:3.0, message:"Use priority(_ amount: ConstraintPriorityTarget) instead.") + @available(*, deprecated, message:"Use priority(.low) instead.") @discardableResult public func priorityLow() -> ConstraintMakerFinalizable { - return self.priority(250) + return self.priority(.low) } - } diff --git a/WWCodeDFW/Pods/SnapKit/Source/ConstraintMakerRelatable.swift b/WWCodeDFW/Pods/SnapKit/Source/ConstraintMakerRelatable.swift index d50b423..7889532 100644 --- a/WWCodeDFW/Pods/SnapKit/Source/ConstraintMakerRelatable.swift +++ b/WWCodeDFW/Pods/SnapKit/Source/ConstraintMakerRelatable.swift @@ -45,7 +45,9 @@ public class ConstraintMakerRelatable { other.attributes.layoutAttributes.count <= 1 || other.attributes.layoutAttributes == self.description.attributes.layoutAttributes || other.attributes == .edges && self.description.attributes == .margins || - other.attributes == .margins && self.description.attributes == .edges else { + other.attributes == .margins && self.description.attributes == .edges || + other.attributes == .directionalEdges && self.description.attributes == .directionalMargins || + other.attributes == .directionalMargins && self.description.attributes == .directionalEdges else { fatalError("Cannot constraint to multiple non identical attributes. (\(file), \(line))"); } @@ -57,6 +59,9 @@ public class ConstraintMakerRelatable { } else if let other = other as? ConstraintConstantTarget { related = ConstraintItem(target: nil, attributes: ConstraintAttributes.none) constant = other + } else if #available(iOS 9.0, OSX 10.11, *), let other = other as? ConstraintLayoutGuide { + related = ConstraintItem(target: other, attributes: ConstraintAttributes.none) + constant = 0.0 } else { fatalError("Invalid constraint. (\(file), \(line))") } @@ -76,7 +81,7 @@ public class ConstraintMakerRelatable { @discardableResult public func equalToSuperview(_ file: String = #file, _ line: UInt = #line) -> ConstraintMakerEditable { - guard let other = self.description.view.superview else { + guard let other = self.description.item.superview else { fatalError("Expected superview but found nil when attempting make constraint `equalToSuperview`.") } return self.relatedTo(other, relation: .equal, file: file, line: line) @@ -89,7 +94,7 @@ public class ConstraintMakerRelatable { @discardableResult public func lessThanOrEqualToSuperview(_ file: String = #file, _ line: UInt = #line) -> ConstraintMakerEditable { - guard let other = self.description.view.superview else { + guard let other = self.description.item.superview else { fatalError("Expected superview but found nil when attempting make constraint `lessThanOrEqualToSuperview`.") } return self.relatedTo(other, relation: .lessThanOrEqual, file: file, line: line) @@ -102,7 +107,7 @@ public class ConstraintMakerRelatable { @discardableResult public func greaterThanOrEqualToSuperview(_ file: String = #file, line: UInt = #line) -> ConstraintMakerEditable { - guard let other = self.description.view.superview else { + guard let other = self.description.item.superview else { fatalError("Expected superview but found nil when attempting make constraint `greaterThanOrEqualToSuperview`.") } return self.relatedTo(other, relation: .greaterThanOrEqual, file: file, line: line) diff --git a/WWCodeDFW/Pods/SnapKit/Source/ConstraintPriority.swift b/WWCodeDFW/Pods/SnapKit/Source/ConstraintPriority.swift new file mode 100644 index 0000000..f9dab16 --- /dev/null +++ b/WWCodeDFW/Pods/SnapKit/Source/ConstraintPriority.swift @@ -0,0 +1,77 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + +public struct ConstraintPriority : ExpressibleByFloatLiteral, Equatable, Strideable { + public typealias FloatLiteralType = Float + + public let value: Float + + public init(floatLiteral value: Float) { + self.value = value + } + + public init(_ value: Float) { + self.value = value + } + + public static var required: ConstraintPriority { + return 1000.0 + } + + public static var high: ConstraintPriority { + return 750.0 + } + + public static var medium: ConstraintPriority { + #if os(OSX) + return 501.0 + #else + return 500.0 + #endif + + } + + public static var low: ConstraintPriority { + return 250.0 + } + + public static func ==(lhs: ConstraintPriority, rhs: ConstraintPriority) -> Bool { + return lhs.value == rhs.value + } + + // MARK: Strideable + + public func advanced(by n: FloatLiteralType) -> ConstraintPriority { + return ConstraintPriority(floatLiteral: value + n) + } + + public func distance(to other: ConstraintPriority) -> FloatLiteralType { + return other.value - value + } +} diff --git a/WWCodeDFW/Pods/SnapKit/Source/ConstraintPriorityTarget.swift b/WWCodeDFW/Pods/SnapKit/Source/ConstraintPriorityTarget.swift index eb32f79..064f750 100644 --- a/WWCodeDFW/Pods/SnapKit/Source/ConstraintPriorityTarget.swift +++ b/WWCodeDFW/Pods/SnapKit/Source/ConstraintPriorityTarget.swift @@ -73,3 +73,13 @@ extension CGFloat: ConstraintPriorityTarget { } } + +#if os(iOS) || os(tvOS) +extension UILayoutPriority: ConstraintPriorityTarget { + + public var constraintPriorityTargetValue: Float { + return self.rawValue + } + +} +#endif diff --git a/WWCodeDFW/Pods/SnapKit/Source/ConstraintRelatableTarget.swift b/WWCodeDFW/Pods/SnapKit/Source/ConstraintRelatableTarget.swift index 4d1e37d..d517a61 100644 --- a/WWCodeDFW/Pods/SnapKit/Source/ConstraintRelatableTarget.swift +++ b/WWCodeDFW/Pods/SnapKit/Source/ConstraintRelatableTarget.swift @@ -55,8 +55,18 @@ extension CGPoint: ConstraintRelatableTarget { extension ConstraintInsets: ConstraintRelatableTarget { } +#if os(iOS) || os(tvOS) +@available(iOS 11.0, tvOS 11.0, *) +extension ConstraintDirectionalInsets: ConstraintRelatableTarget { +} +#endif + extension ConstraintItem: ConstraintRelatableTarget { } extension ConstraintView: ConstraintRelatableTarget { } + +@available(iOS 9.0, OSX 10.11, *) +extension ConstraintLayoutGuide: ConstraintRelatableTarget { +} diff --git a/WWCodeDFW/Pods/SnapKit/Source/ConstraintRelation.swift b/WWCodeDFW/Pods/SnapKit/Source/ConstraintRelation.swift index 48afbfc..446aaf7 100644 --- a/WWCodeDFW/Pods/SnapKit/Source/ConstraintRelation.swift +++ b/WWCodeDFW/Pods/SnapKit/Source/ConstraintRelation.swift @@ -28,12 +28,12 @@ #endif -internal enum ConstraintRelation: Int { +internal enum ConstraintRelation : Int { case equal = 1 case lessThanOrEqual case greaterThanOrEqual - internal var layoutRelation: NSLayoutRelation { + internal var layoutRelation: LayoutRelation { get { switch(self) { case .equal: diff --git a/WWCodeDFW/Pods/SnapKit/Source/ConstraintView+Extensions.swift b/WWCodeDFW/Pods/SnapKit/Source/ConstraintView+Extensions.swift index 77afad9..a4898dc 100644 --- a/WWCodeDFW/Pods/SnapKit/Source/ConstraintView+Extensions.swift +++ b/WWCodeDFW/Pods/SnapKit/Source/ConstraintView+Extensions.swift @@ -30,122 +30,122 @@ public extension ConstraintView { - @available(*, deprecated:3.0, message:"Use newer snp.* syntax.") - public var snp_left: ConstraintItem { return self.snp.left } + @available(*, deprecated, message:"Use newer snp.* syntax.") + var snp_left: ConstraintItem { return self.snp.left } - @available(*, deprecated:3.0, message:"Use newer snp.* syntax.") - public var snp_top: ConstraintItem { return self.snp.top } + @available(*, deprecated, message:"Use newer snp.* syntax.") + var snp_top: ConstraintItem { return self.snp.top } - @available(*, deprecated:3.0, message:"Use newer snp.* syntax.") - public var snp_right: ConstraintItem { return self.snp.right } + @available(*, deprecated, message:"Use newer snp.* syntax.") + var snp_right: ConstraintItem { return self.snp.right } - @available(*, deprecated:3.0, message:"Use newer snp.* syntax.") - public var snp_bottom: ConstraintItem { return self.snp.bottom } + @available(*, deprecated, message:"Use newer snp.* syntax.") + var snp_bottom: ConstraintItem { return self.snp.bottom } - @available(*, deprecated:3.0, message:"Use newer snp.* syntax.") - public var snp_leading: ConstraintItem { return self.snp.leading } + @available(*, deprecated, message:"Use newer snp.* syntax.") + var snp_leading: ConstraintItem { return self.snp.leading } - @available(*, deprecated:3.0, message:"Use newer snp.* syntax.") - public var snp_trailing: ConstraintItem { return self.snp.trailing } + @available(*, deprecated, message:"Use newer snp.* syntax.") + var snp_trailing: ConstraintItem { return self.snp.trailing } - @available(*, deprecated:3.0, message:"Use newer snp.* syntax.") - public var snp_width: ConstraintItem { return self.snp.width } + @available(*, deprecated, message:"Use newer snp.* syntax.") + var snp_width: ConstraintItem { return self.snp.width } - @available(*, deprecated:3.0, message:"Use newer snp.* syntax.") - public var snp_height: ConstraintItem { return self.snp.height } + @available(*, deprecated, message:"Use newer snp.* syntax.") + var snp_height: ConstraintItem { return self.snp.height } - @available(*, deprecated:3.0, message:"Use newer snp.* syntax.") - public var snp_centerX: ConstraintItem { return self.snp.centerX } + @available(*, deprecated, message:"Use newer snp.* syntax.") + var snp_centerX: ConstraintItem { return self.snp.centerX } - @available(*, deprecated:3.0, message:"Use newer snp.* syntax.") - public var snp_centerY: ConstraintItem { return self.snp.centerY } + @available(*, deprecated, message:"Use newer snp.* syntax.") + var snp_centerY: ConstraintItem { return self.snp.centerY } - @available(*, deprecated:3.0, message:"Use newer snp.* syntax.") - public var snp_baseline: ConstraintItem { return self.snp.baseline } + @available(*, deprecated, message:"Use newer snp.* syntax.") + var snp_baseline: ConstraintItem { return self.snp.baseline } - @available(*, deprecated:3.0, message:"Use newer snp.* syntax.") + @available(*, deprecated, message:"Use newer snp.* syntax.") @available(iOS 8.0, OSX 10.11, *) - public var snp_lastBaseline: ConstraintItem { return self.snp.lastBaseline } + var snp_lastBaseline: ConstraintItem { return self.snp.lastBaseline } - @available(iOS, deprecated:3.0, message:"Use newer snp.* syntax.") + @available(iOS, deprecated, message:"Use newer snp.* syntax.") @available(iOS 8.0, OSX 10.11, *) - public var snp_firstBaseline: ConstraintItem { return self.snp.firstBaseline } + var snp_firstBaseline: ConstraintItem { return self.snp.firstBaseline } - @available(iOS, deprecated:3.0, message:"Use newer snp.* syntax.") + @available(iOS, deprecated, message:"Use newer snp.* syntax.") @available(iOS 8.0, *) - public var snp_leftMargin: ConstraintItem { return self.snp.leftMargin } + var snp_leftMargin: ConstraintItem { return self.snp.leftMargin } - @available(iOS, deprecated:3.0, message:"Use newer snp.* syntax.") + @available(iOS, deprecated, message:"Use newer snp.* syntax.") @available(iOS 8.0, *) - public var snp_topMargin: ConstraintItem { return self.snp.topMargin } + var snp_topMargin: ConstraintItem { return self.snp.topMargin } - @available(iOS, deprecated:3.0, message:"Use newer snp.* syntax.") + @available(iOS, deprecated, message:"Use newer snp.* syntax.") @available(iOS 8.0, *) - public var snp_rightMargin: ConstraintItem { return self.snp.rightMargin } + var snp_rightMargin: ConstraintItem { return self.snp.rightMargin } - @available(iOS, deprecated:3.0, message:"Use newer snp.* syntax.") + @available(iOS, deprecated, message:"Use newer snp.* syntax.") @available(iOS 8.0, *) - public var snp_bottomMargin: ConstraintItem { return self.snp.bottomMargin } + var snp_bottomMargin: ConstraintItem { return self.snp.bottomMargin } - @available(iOS, deprecated:3.0, message:"Use newer snp.* syntax.") + @available(iOS, deprecated, message:"Use newer snp.* syntax.") @available(iOS 8.0, *) - public var snp_leadingMargin: ConstraintItem { return self.snp.leadingMargin } + var snp_leadingMargin: ConstraintItem { return self.snp.leadingMargin } - @available(iOS, deprecated:3.0, message:"Use newer snp.* syntax.") + @available(iOS, deprecated, message:"Use newer snp.* syntax.") @available(iOS 8.0, *) - public var snp_trailingMargin: ConstraintItem { return self.snp.trailingMargin } + var snp_trailingMargin: ConstraintItem { return self.snp.trailingMargin } - @available(iOS, deprecated:3.0, message:"Use newer snp.* syntax.") + @available(iOS, deprecated, message:"Use newer snp.* syntax.") @available(iOS 8.0, *) - public var snp_centerXWithinMargins: ConstraintItem { return self.snp.centerXWithinMargins } + var snp_centerXWithinMargins: ConstraintItem { return self.snp.centerXWithinMargins } - @available(iOS, deprecated:3.0, message:"Use newer snp.* syntax.") + @available(iOS, deprecated, message:"Use newer snp.* syntax.") @available(iOS 8.0, *) - public var snp_centerYWithinMargins: ConstraintItem { return self.snp.centerYWithinMargins } + var snp_centerYWithinMargins: ConstraintItem { return self.snp.centerYWithinMargins } - @available(*, deprecated:3.0, message:"Use newer snp.* syntax.") - public var snp_edges: ConstraintItem { return self.snp.edges } + @available(*, deprecated, message:"Use newer snp.* syntax.") + var snp_edges: ConstraintItem { return self.snp.edges } - @available(*, deprecated:3.0, message:"Use newer snp.* syntax.") - public var snp_size: ConstraintItem { return self.snp.size } + @available(*, deprecated, message:"Use newer snp.* syntax.") + var snp_size: ConstraintItem { return self.snp.size } - @available(*, deprecated:3.0, message:"Use newer snp.* syntax.") - public var snp_center: ConstraintItem { return self.snp.center } + @available(*, deprecated, message:"Use newer snp.* syntax.") + var snp_center: ConstraintItem { return self.snp.center } - @available(iOS, deprecated:3.0, message:"Use newer snp.* syntax.") + @available(iOS, deprecated, message:"Use newer snp.* syntax.") @available(iOS 8.0, *) - public var snp_margins: ConstraintItem { return self.snp.margins } + var snp_margins: ConstraintItem { return self.snp.margins } - @available(iOS, deprecated:3.0, message:"Use newer snp.* syntax.") + @available(iOS, deprecated, message:"Use newer snp.* syntax.") @available(iOS 8.0, *) - public var snp_centerWithinMargins: ConstraintItem { return self.snp.centerWithinMargins } + var snp_centerWithinMargins: ConstraintItem { return self.snp.centerWithinMargins } - @available(*, deprecated:3.0, message:"Use newer snp.* syntax.") - public func snp_prepareConstraints(_ closure: (_ make: ConstraintMaker) -> Void) -> [Constraint] { + @available(*, deprecated, message:"Use newer snp.* syntax.") + func snp_prepareConstraints(_ closure: (_ make: ConstraintMaker) -> Void) -> [Constraint] { return self.snp.prepareConstraints(closure) } - @available(*, deprecated:3.0, message:"Use newer snp.* syntax.") - public func snp_makeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { + @available(*, deprecated, message:"Use newer snp.* syntax.") + func snp_makeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { self.snp.makeConstraints(closure) } - @available(*, deprecated:3.0, message:"Use newer snp.* syntax.") - public func snp_remakeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { + @available(*, deprecated, message:"Use newer snp.* syntax.") + func snp_remakeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { self.snp.remakeConstraints(closure) } - @available(*, deprecated:3.0, message:"Use newer snp.* syntax.") - public func snp_updateConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { + @available(*, deprecated, message:"Use newer snp.* syntax.") + func snp_updateConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { self.snp.updateConstraints(closure) } - @available(*, deprecated:3.0, message:"Use newer snp.* syntax.") - public func snp_removeConstraints() { + @available(*, deprecated, message:"Use newer snp.* syntax.") + func snp_removeConstraints() { self.snp.removeConstraints() } - public var snp: ConstraintViewDSL { + var snp: ConstraintViewDSL { return ConstraintViewDSL(view: self) } diff --git a/WWCodeDFW/Pods/SnapKit/Source/ConstraintViewDSL.swift b/WWCodeDFW/Pods/SnapKit/Source/ConstraintViewDSL.swift index 541d18b..a0187f9 100644 --- a/WWCodeDFW/Pods/SnapKit/Source/ConstraintViewDSL.swift +++ b/WWCodeDFW/Pods/SnapKit/Source/ConstraintViewDSL.swift @@ -32,60 +32,58 @@ public struct ConstraintViewDSL: ConstraintAttributesDSL { @discardableResult public func prepareConstraints(_ closure: (_ make: ConstraintMaker) -> Void) -> [Constraint] { - return ConstraintMaker.prepareConstraints(view: self.view, closure: closure) + return ConstraintMaker.prepareConstraints(item: self.view, closure: closure) } public func makeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { - ConstraintMaker.makeConstraints(view: self.view, closure: closure) + ConstraintMaker.makeConstraints(item: self.view, closure: closure) } public func remakeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { - ConstraintMaker.remakeConstraints(view: self.view, closure: closure) + ConstraintMaker.remakeConstraints(item: self.view, closure: closure) } public func updateConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { - ConstraintMaker.updateConstraints(view: self.view, closure: closure) + ConstraintMaker.updateConstraints(item: self.view, closure: closure) } public func removeConstraints() { - ConstraintMaker.removeConstraints(view: self.view) + ConstraintMaker.removeConstraints(item: self.view) } - - public var contentHuggingHorizontalPriority: Float { get { - return self.view.contentHuggingPriority(for: .horizontal) + return self.view.contentHuggingPriority(for: .horizontal).rawValue } - set { - self.view.setContentHuggingPriority(newValue, for: .horizontal) + nonmutating set { + self.view.setContentHuggingPriority(LayoutPriority(rawValue: newValue), for: .horizontal) } } public var contentHuggingVerticalPriority: Float { get { - return self.view.contentHuggingPriority(for: .vertical) + return self.view.contentHuggingPriority(for: .vertical).rawValue } - set { - self.view.setContentHuggingPriority(newValue, for: .vertical) + nonmutating set { + self.view.setContentHuggingPriority(LayoutPriority(rawValue: newValue), for: .vertical) } } public var contentCompressionResistanceHorizontalPriority: Float { get { - return self.view.contentCompressionResistancePriority(for: .horizontal) + return self.view.contentCompressionResistancePriority(for: .horizontal).rawValue } - set { - self.view.setContentHuggingPriority(newValue, for: .horizontal) + nonmutating set { + self.view.setContentCompressionResistancePriority(LayoutPriority(rawValue: newValue), for: .horizontal) } } public var contentCompressionResistanceVerticalPriority: Float { get { - return self.view.contentCompressionResistancePriority(for: .vertical) + return self.view.contentCompressionResistancePriority(for: .vertical).rawValue } - set { - self.view.setContentCompressionResistancePriority(newValue, for: .vertical) + nonmutating set { + self.view.setContentCompressionResistancePriority(LayoutPriority(rawValue: newValue), for: .vertical) } } @@ -100,36 +98,4 @@ public struct ConstraintViewDSL: ConstraintAttributesDSL { } - internal var constraints: [Constraint] { - return self.constraintsHashTable.allObjects - } - - internal func add(constraints: [Constraint]) { - let hashTable = self.constraintsHashTable - for constraint in constraints { - hashTable.add(constraint) - } - } - - internal func remove(constraints: [Constraint]) { - let hashTable = self.constraintsHashTable - for constraint in constraints { - hashTable.remove(constraint) - } - } - - private var constraintsHashTable: NSHashTable { - let constraints: NSHashTable - - if let existing = objc_getAssociatedObject(self.view, &constraintsKey) as? NSHashTable { - constraints = existing - } else { - constraints = NSHashTable() - objc_setAssociatedObject(self.view, &constraintsKey, constraints, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) - } - return constraints - - } - } -private var constraintsKey: UInt8 = 0 diff --git a/WWCodeDFW/Pods/SnapKit/Source/Debugging.swift b/WWCodeDFW/Pods/SnapKit/Source/Debugging.swift index fdc505d..a78579a 100644 --- a/WWCodeDFW/Pods/SnapKit/Source/Debugging.swift +++ b/WWCodeDFW/Pods/SnapKit/Source/Debugging.swift @@ -29,7 +29,7 @@ public extension LayoutConstraint { - override public var description: String { + override var description: String { var description = "<" description += descriptionForObject(self) @@ -66,7 +66,7 @@ public extension LayoutConstraint { } } - if self.priority != 1000.0 { + if self.priority.rawValue != 1000.0 { description += " ^\(self.priority)" } @@ -77,15 +77,18 @@ public extension LayoutConstraint { } -private func descriptionForRelation(_ relation: NSLayoutRelation) -> String { +private func descriptionForRelation(_ relation: LayoutRelation) -> String { switch relation { case .equal: return "==" case .greaterThanOrEqual: return ">=" case .lessThanOrEqual: return "<=" + #if swift(>=5.0) + @unknown default: return "unknown" + #endif } } -private func descriptionForAttribute(_ attribute: NSLayoutAttribute) -> String { +private func descriptionForAttribute(_ attribute: LayoutAttribute) -> String { #if os(iOS) || os(tvOS) switch attribute { case .notAnAttribute: return "notAnAttribute" @@ -109,7 +112,10 @@ private func descriptionForAttribute(_ attribute: NSLayoutAttribute) -> String { case .trailingMargin: return "trailingMargin" case .centerXWithinMargins: return "centerXWithinMargins" case .centerYWithinMargins: return "centerYWithinMargins" - } + #if swift(>=5.0) + @unknown default: return "unknown" + #endif + } #else switch attribute { case .notAnAttribute: return "notAnAttribute" @@ -125,7 +131,10 @@ private func descriptionForAttribute(_ attribute: NSLayoutAttribute) -> String { case .centerY: return "centerY" case .lastBaseline: return "lastBaseline" case .firstBaseline: return "firstBaseline" - } + #if swift(>=5.0) + @unknown default: return "unknown" + #endif + } #endif } diff --git a/WWCodeDFW/Pods/SnapKit/Source/LayoutConstraint.swift b/WWCodeDFW/Pods/SnapKit/Source/LayoutConstraint.swift index 27c4105..5425ea8 100644 --- a/WWCodeDFW/Pods/SnapKit/Source/LayoutConstraint.swift +++ b/WWCodeDFW/Pods/SnapKit/Source/LayoutConstraint.swift @@ -28,7 +28,7 @@ #endif -public class LayoutConstraint: NSLayoutConstraint { +public class LayoutConstraint : NSLayoutConstraint { public var label: String? { get { @@ -44,13 +44,17 @@ public class LayoutConstraint: NSLayoutConstraint { } internal func ==(lhs: LayoutConstraint, rhs: LayoutConstraint) -> Bool { - guard lhs.firstItem === rhs.firstItem && - lhs.secondItem === rhs.secondItem && - lhs.firstAttribute == rhs.firstAttribute && + // If firstItem or secondItem on either constraint has a dangling pointer + // this comparison can cause a crash. The solution for this is to ensure + // your layout code hold strong references to things like Views, LayoutGuides + // and LayoutAnchors as SnapKit will not keep strong references to any of these. + guard lhs.firstAttribute == rhs.firstAttribute && lhs.secondAttribute == rhs.secondAttribute && lhs.relation == rhs.relation && lhs.priority == rhs.priority && - lhs.multiplier == rhs.multiplier else { + lhs.multiplier == rhs.multiplier && + lhs.secondItem === rhs.secondItem && + lhs.firstItem === rhs.firstItem else { return false } return true diff --git a/WWCodeDFW/Pods/SnapKit/Source/LayoutConstraintItem.swift b/WWCodeDFW/Pods/SnapKit/Source/LayoutConstraintItem.swift new file mode 100644 index 0000000..a59de6b --- /dev/null +++ b/WWCodeDFW/Pods/SnapKit/Source/LayoutConstraintItem.swift @@ -0,0 +1,93 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) + import UIKit +#else + import AppKit +#endif + + +public protocol LayoutConstraintItem: class { +} + +@available(iOS 9.0, OSX 10.11, *) +extension ConstraintLayoutGuide : LayoutConstraintItem { +} + +extension ConstraintView : LayoutConstraintItem { +} + + +extension LayoutConstraintItem { + + internal func prepare() { + if let view = self as? ConstraintView { + view.translatesAutoresizingMaskIntoConstraints = false + } + } + + internal var superview: ConstraintView? { + if let view = self as? ConstraintView { + return view.superview + } + + if #available(iOS 9.0, OSX 10.11, *), let guide = self as? ConstraintLayoutGuide { + return guide.owningView + } + + return nil + } + internal var constraints: [Constraint] { + return self.constraintsSet.allObjects as! [Constraint] + } + + internal func add(constraints: [Constraint]) { + let constraintsSet = self.constraintsSet + for constraint in constraints { + constraintsSet.add(constraint) + } + } + + internal func remove(constraints: [Constraint]) { + let constraintsSet = self.constraintsSet + for constraint in constraints { + constraintsSet.remove(constraint) + } + } + + private var constraintsSet: NSMutableSet { + let constraintsSet: NSMutableSet + + if let existing = objc_getAssociatedObject(self, &constraintsKey) as? NSMutableSet { + constraintsSet = existing + } else { + constraintsSet = NSMutableSet() + objc_setAssociatedObject(self, &constraintsKey, constraintsSet, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + return constraintsSet + + } + +} +private var constraintsKey: UInt8 = 0 diff --git a/WWCodeDFW/Pods/SnapKit/Source/Typealiases.swift b/WWCodeDFW/Pods/SnapKit/Source/Typealiases.swift new file mode 100644 index 0000000..ded96cc --- /dev/null +++ b/WWCodeDFW/Pods/SnapKit/Source/Typealiases.swift @@ -0,0 +1,42 @@ +// +// SnapKit +// +// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +#if os(iOS) || os(tvOS) + import UIKit +#if swift(>=4.2) + typealias LayoutRelation = NSLayoutConstraint.Relation + typealias LayoutAttribute = NSLayoutConstraint.Attribute +#else + typealias LayoutRelation = NSLayoutRelation + typealias LayoutAttribute = NSLayoutAttribute +#endif + typealias LayoutPriority = UILayoutPriority +#else + import AppKit + typealias LayoutRelation = NSLayoutConstraint.Relation + typealias LayoutAttribute = NSLayoutConstraint.Attribute + typealias LayoutPriority = NSLayoutConstraint.Priority +#endif + diff --git a/WWCodeDFW/Pods/SnapKit/Source/UILayoutSupport+Extensions.swift b/WWCodeDFW/Pods/SnapKit/Source/UILayoutSupport+Extensions.swift index cfbce2e..8e7644c 100644 --- a/WWCodeDFW/Pods/SnapKit/Source/UILayoutSupport+Extensions.swift +++ b/WWCodeDFW/Pods/SnapKit/Source/UILayoutSupport+Extensions.swift @@ -29,7 +29,7 @@ @available(iOS 8.0, *) public extension ConstraintLayoutSupport { - public var snp: ConstraintLayoutSupportDSL { + var snp: ConstraintLayoutSupportDSL { return ConstraintLayoutSupportDSL(support: self) } diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Resources b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Resources deleted file mode 120000 index 953ee36..0000000 --- a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Resources +++ /dev/null @@ -1 +0,0 @@ -Versions/Current/Resources \ No newline at end of file diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/SwiftLintFramework b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/SwiftLintFramework deleted file mode 120000 index a6d8984..0000000 --- a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/SwiftLintFramework +++ /dev/null @@ -1 +0,0 @@ -Versions/Current/SwiftLintFramework \ No newline at end of file diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Commandant.framework/Commandant b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Commandant.framework/Commandant deleted file mode 120000 index 9c4b622..0000000 --- a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Commandant.framework/Commandant +++ /dev/null @@ -1 +0,0 @@ -Versions/Current/Commandant \ No newline at end of file diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Commandant.framework/Resources b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Commandant.framework/Resources deleted file mode 120000 index 953ee36..0000000 --- a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Commandant.framework/Resources +++ /dev/null @@ -1 +0,0 @@ -Versions/Current/Resources \ No newline at end of file diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Commandant.framework/Versions/A/Commandant b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Commandant.framework/Versions/A/Commandant deleted file mode 100755 index 08e3990..0000000 Binary files a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Commandant.framework/Versions/A/Commandant and /dev/null differ diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Commandant.framework/Versions/A/Resources/Info.plist b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Commandant.framework/Versions/A/Resources/Info.plist deleted file mode 100644 index 4299c3c..0000000 --- a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Commandant.framework/Versions/A/Resources/Info.plist +++ /dev/null @@ -1,46 +0,0 @@ - - - - - BuildMachineOSBuild - 17A365 - CFBundleDevelopmentRegion - en - CFBundleExecutable - Commandant - CFBundleIdentifier - org.carthage.Commandant - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - Commandant - CFBundlePackageType - FMWK - CFBundleShortVersionString - 0.12.0 - CFBundleSignature - ???? - CFBundleSupportedPlatforms - - MacOSX - - CFBundleVersion - 1 - DTCompiler - com.apple.compilers.llvm.clang.1_0 - DTPlatformBuild - 9A235 - DTPlatformVersion - GM - DTSDKBuild - 17A360 - DTSDKName - macosx10.13 - DTXcode - 0900 - DTXcodeBuild - 9A235 - NSHumanReadableCopyright - Copyright © 2014 Carthage. All rights reserved. - - diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Commandant.framework/Versions/Current b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Commandant.framework/Versions/Current deleted file mode 120000 index 8c7e5a6..0000000 --- a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Commandant.framework/Versions/Current +++ /dev/null @@ -1 +0,0 @@ -A \ No newline at end of file diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Result.framework/Resources b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Result.framework/Resources deleted file mode 120000 index 953ee36..0000000 --- a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Result.framework/Resources +++ /dev/null @@ -1 +0,0 @@ -Versions/Current/Resources \ No newline at end of file diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Result.framework/Result b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Result.framework/Result deleted file mode 120000 index d95252c..0000000 --- a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Result.framework/Result +++ /dev/null @@ -1 +0,0 @@ -Versions/Current/Result \ No newline at end of file diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Result.framework/Versions/A/Resources/Info.plist b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Result.framework/Versions/A/Resources/Info.plist deleted file mode 100644 index b8c29ec..0000000 --- a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Result.framework/Versions/A/Resources/Info.plist +++ /dev/null @@ -1,46 +0,0 @@ - - - - - BuildMachineOSBuild - 17A365 - CFBundleDevelopmentRegion - en - CFBundleExecutable - Result - CFBundleIdentifier - com.antitypical.Result - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - Result - CFBundlePackageType - FMWK - CFBundleShortVersionString - 3.2.3 - CFBundleSignature - ???? - CFBundleSupportedPlatforms - - MacOSX - - CFBundleVersion - 1 - DTCompiler - com.apple.compilers.llvm.clang.1_0 - DTPlatformBuild - 9A235 - DTPlatformVersion - GM - DTSDKBuild - 17A360 - DTSDKName - macosx10.13 - DTXcode - 0900 - DTXcodeBuild - 9A235 - NSHumanReadableCopyright - Copyright © 2015 Rob Rix. All rights reserved. - - diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Result.framework/Versions/A/Result b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Result.framework/Versions/A/Result deleted file mode 100755 index 687f127..0000000 Binary files a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Result.framework/Versions/A/Result and /dev/null differ diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Result.framework/Versions/Current b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Result.framework/Versions/Current deleted file mode 120000 index 8c7e5a6..0000000 --- a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Result.framework/Versions/Current +++ /dev/null @@ -1 +0,0 @@ -A \ No newline at end of file diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SWXMLHash.framework/Resources b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SWXMLHash.framework/Resources deleted file mode 120000 index 953ee36..0000000 --- a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SWXMLHash.framework/Resources +++ /dev/null @@ -1 +0,0 @@ -Versions/Current/Resources \ No newline at end of file diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SWXMLHash.framework/SWXMLHash b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SWXMLHash.framework/SWXMLHash deleted file mode 120000 index fb92f1c..0000000 --- a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SWXMLHash.framework/SWXMLHash +++ /dev/null @@ -1 +0,0 @@ -Versions/Current/SWXMLHash \ No newline at end of file diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SWXMLHash.framework/Versions/A/Resources/Info.plist b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SWXMLHash.framework/Versions/A/Resources/Info.plist deleted file mode 100644 index f363371..0000000 --- a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SWXMLHash.framework/Versions/A/Resources/Info.plist +++ /dev/null @@ -1,49 +0,0 @@ - - - - - BuildMachineOSBuild - 17A365 - CFBundleDevelopmentRegion - en - CFBundleExecutable - SWXMLHash - CFBundleIdentifier - drmohundro.SWXMLHash - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - SWXMLHash - CFBundlePackageType - FMWK - CFBundleShortVersionString - 2.0 - CFBundleSignature - ???? - CFBundleSupportedPlatforms - - MacOSX - - CFBundleVersion - 1 - DTCompiler - com.apple.compilers.llvm.clang.1_0 - DTPlatformBuild - 9A235 - DTPlatformVersion - GM - DTSDKBuild - 17A360 - DTSDKName - macosx10.13 - DTXcode - 0900 - DTXcodeBuild - 9A235 - UIDeviceFamily - - 1 - 2 - - - diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SWXMLHash.framework/Versions/A/SWXMLHash b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SWXMLHash.framework/Versions/A/SWXMLHash deleted file mode 100755 index 9f25511..0000000 Binary files a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SWXMLHash.framework/Versions/A/SWXMLHash and /dev/null differ diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SWXMLHash.framework/Versions/Current b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SWXMLHash.framework/Versions/Current deleted file mode 120000 index 8c7e5a6..0000000 --- a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SWXMLHash.framework/Versions/Current +++ /dev/null @@ -1 +0,0 @@ -A \ No newline at end of file diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SourceKittenFramework.framework/Resources b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SourceKittenFramework.framework/Resources deleted file mode 120000 index 953ee36..0000000 --- a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SourceKittenFramework.framework/Resources +++ /dev/null @@ -1 +0,0 @@ -Versions/Current/Resources \ No newline at end of file diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SourceKittenFramework.framework/SourceKittenFramework b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SourceKittenFramework.framework/SourceKittenFramework deleted file mode 120000 index e339a39..0000000 --- a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SourceKittenFramework.framework/SourceKittenFramework +++ /dev/null @@ -1 +0,0 @@ -Versions/Current/SourceKittenFramework \ No newline at end of file diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SourceKittenFramework.framework/Versions/A/Resources/Info.plist b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SourceKittenFramework.framework/Versions/A/Resources/Info.plist deleted file mode 100644 index 469439a..0000000 --- a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SourceKittenFramework.framework/Versions/A/Resources/Info.plist +++ /dev/null @@ -1,46 +0,0 @@ - - - - - BuildMachineOSBuild - 17A365 - CFBundleDevelopmentRegion - en - CFBundleExecutable - SourceKittenFramework - CFBundleIdentifier - com.sourcekitten.SourceKittenFramework - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - SourceKittenFramework - CFBundlePackageType - FMWK - CFBundleShortVersionString - 0.18.1 - CFBundleSignature - ???? - CFBundleSupportedPlatforms - - MacOSX - - CFBundleVersion - 1 - DTCompiler - com.apple.compilers.llvm.clang.1_0 - DTPlatformBuild - 9A235 - DTPlatformVersion - GM - DTSDKBuild - 17A360 - DTSDKName - macosx10.13 - DTXcode - 0900 - DTXcodeBuild - 9A235 - NSHumanReadableCopyright - Copyright © 2015 SourceKitten. All rights reserved. - - diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SourceKittenFramework.framework/Versions/A/SourceKittenFramework b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SourceKittenFramework.framework/Versions/A/SourceKittenFramework deleted file mode 100755 index 91061f2..0000000 Binary files a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SourceKittenFramework.framework/Versions/A/SourceKittenFramework and /dev/null differ diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SourceKittenFramework.framework/Versions/Current b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SourceKittenFramework.framework/Versions/Current deleted file mode 120000 index 8c7e5a6..0000000 --- a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SourceKittenFramework.framework/Versions/Current +++ /dev/null @@ -1 +0,0 @@ -A \ No newline at end of file diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SwiftyTextTable.framework/Resources b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SwiftyTextTable.framework/Resources deleted file mode 120000 index 953ee36..0000000 --- a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SwiftyTextTable.framework/Resources +++ /dev/null @@ -1 +0,0 @@ -Versions/Current/Resources \ No newline at end of file diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SwiftyTextTable.framework/SwiftyTextTable b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SwiftyTextTable.framework/SwiftyTextTable deleted file mode 120000 index ebb760f..0000000 --- a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SwiftyTextTable.framework/SwiftyTextTable +++ /dev/null @@ -1 +0,0 @@ -Versions/Current/SwiftyTextTable \ No newline at end of file diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SwiftyTextTable.framework/Versions/A/Resources/Info.plist b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SwiftyTextTable.framework/Versions/A/Resources/Info.plist deleted file mode 100644 index 3afc6e1..0000000 --- a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SwiftyTextTable.framework/Versions/A/Resources/Info.plist +++ /dev/null @@ -1,46 +0,0 @@ - - - - - BuildMachineOSBuild - 17A365 - CFBundleDevelopmentRegion - en - CFBundleExecutable - SwiftyTextTable - CFBundleIdentifier - com.scotthoyt.SwiftyTextTable - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - SwiftyTextTable - CFBundlePackageType - FMWK - CFBundleShortVersionString - 0.1.0 - CFBundleSignature - ???? - CFBundleSupportedPlatforms - - MacOSX - - CFBundleVersion - 1 - DTCompiler - com.apple.compilers.llvm.clang.1_0 - DTPlatformBuild - 9A235 - DTPlatformVersion - GM - DTSDKBuild - 17A360 - DTSDKName - macosx10.13 - DTXcode - 0900 - DTXcodeBuild - 9A235 - NSHumanReadableCopyright - Copyright © 2016 Scott Hoyt. All rights reserved. - - diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SwiftyTextTable.framework/Versions/A/SwiftyTextTable b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SwiftyTextTable.framework/Versions/A/SwiftyTextTable deleted file mode 100755 index f2fc7cb..0000000 Binary files a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SwiftyTextTable.framework/Versions/A/SwiftyTextTable and /dev/null differ diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SwiftyTextTable.framework/Versions/Current b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SwiftyTextTable.framework/Versions/Current deleted file mode 120000 index 8c7e5a6..0000000 --- a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/SwiftyTextTable.framework/Versions/Current +++ /dev/null @@ -1 +0,0 @@ -A \ No newline at end of file diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Yams.framework/Resources b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Yams.framework/Resources deleted file mode 120000 index 953ee36..0000000 --- a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Yams.framework/Resources +++ /dev/null @@ -1 +0,0 @@ -Versions/Current/Resources \ No newline at end of file diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Yams.framework/Versions/A/Resources/Info.plist b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Yams.framework/Versions/A/Resources/Info.plist deleted file mode 100644 index 038a60e..0000000 --- a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Yams.framework/Versions/A/Resources/Info.plist +++ /dev/null @@ -1,44 +0,0 @@ - - - - - BuildMachineOSBuild - 17A365 - CFBundleDevelopmentRegion - en - CFBundleExecutable - Yams - CFBundleIdentifier - Yams - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - Yams - CFBundlePackageType - FMWK - CFBundleShortVersionString - 0.3.6 - CFBundleSignature - ???? - CFBundleSupportedPlatforms - - MacOSX - - CFBundleVersion - 1 - DTCompiler - com.apple.compilers.llvm.clang.1_0 - DTPlatformBuild - 9A235 - DTPlatformVersion - GM - DTSDKBuild - 17A360 - DTSDKName - macosx10.13 - DTXcode - 0900 - DTXcodeBuild - 9A235 - - diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Yams.framework/Versions/A/Yams b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Yams.framework/Versions/A/Yams deleted file mode 100755 index 1dd2dce..0000000 Binary files a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Yams.framework/Versions/A/Yams and /dev/null differ diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Yams.framework/Versions/Current b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Yams.framework/Versions/Current deleted file mode 120000 index 8c7e5a6..0000000 --- a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Yams.framework/Versions/Current +++ /dev/null @@ -1 +0,0 @@ -A \ No newline at end of file diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Yams.framework/Yams b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Yams.framework/Yams deleted file mode 120000 index 151b404..0000000 --- a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/Yams.framework/Yams +++ /dev/null @@ -1 +0,0 @@ -Versions/Current/Yams \ No newline at end of file diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/libswiftCore.dylib b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/libswiftCore.dylib deleted file mode 100755 index f1bdc00..0000000 Binary files a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/libswiftCore.dylib and /dev/null differ diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/libswiftCoreFoundation.dylib b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/libswiftCoreFoundation.dylib deleted file mode 100755 index 3909481..0000000 Binary files a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/libswiftCoreFoundation.dylib and /dev/null differ diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/libswiftCoreGraphics.dylib b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/libswiftCoreGraphics.dylib deleted file mode 100755 index 22a6470..0000000 Binary files a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/libswiftCoreGraphics.dylib and /dev/null differ diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/libswiftDarwin.dylib b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/libswiftDarwin.dylib deleted file mode 100755 index e41640b..0000000 Binary files a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/libswiftDarwin.dylib and /dev/null differ diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/libswiftDispatch.dylib b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/libswiftDispatch.dylib deleted file mode 100755 index 25ff02e..0000000 Binary files a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/libswiftDispatch.dylib and /dev/null differ diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/libswiftFoundation.dylib b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/libswiftFoundation.dylib deleted file mode 100755 index cbff82a..0000000 Binary files a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/libswiftFoundation.dylib and /dev/null differ diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/libswiftIOKit.dylib b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/libswiftIOKit.dylib deleted file mode 100755 index b83b306..0000000 Binary files a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/libswiftIOKit.dylib and /dev/null differ diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/libswiftObjectiveC.dylib b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/libswiftObjectiveC.dylib deleted file mode 100755 index 8a66973..0000000 Binary files a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Frameworks/libswiftObjectiveC.dylib and /dev/null differ diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Resources/Info.plist b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Resources/Info.plist deleted file mode 100644 index 4b0acc5..0000000 --- a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/Resources/Info.plist +++ /dev/null @@ -1,46 +0,0 @@ - - - - - BuildMachineOSBuild - 17A365 - CFBundleDevelopmentRegion - en - CFBundleExecutable - SwiftLintFramework - CFBundleIdentifier - io.realm.SwiftLintFramework - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - SwiftLintFramework - CFBundlePackageType - FMWK - CFBundleShortVersionString - 0.23.0 - CFBundleSignature - ???? - CFBundleSupportedPlatforms - - MacOSX - - CFBundleVersion - 1 - DTCompiler - com.apple.compilers.llvm.clang.1_0 - DTPlatformBuild - 9A235 - DTPlatformVersion - GM - DTSDKBuild - 17A360 - DTSDKName - macosx10.13 - DTXcode - 0900 - DTXcodeBuild - 9A235 - NSHumanReadableCopyright - Copyright © 2015 Realm. All rights reserved. - - diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/SwiftLintFramework b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/SwiftLintFramework deleted file mode 100755 index 28a3e13..0000000 Binary files a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/A/SwiftLintFramework and /dev/null differ diff --git a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/Current b/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/Current deleted file mode 120000 index 8c7e5a6..0000000 --- a/WWCodeDFW/Pods/SwiftLint/SwiftLintFramework.framework/Versions/Current +++ /dev/null @@ -1 +0,0 @@ -A \ No newline at end of file diff --git a/WWCodeDFW/Pods/SwiftLint/swiftlint b/WWCodeDFW/Pods/SwiftLint/swiftlint index f21d684..eb4e5e9 100755 Binary files a/WWCodeDFW/Pods/SwiftLint/swiftlint and b/WWCodeDFW/Pods/SwiftLint/swiftlint differ diff --git a/WWCodeDFW/Pods/SwiftyJSON/LICENSE b/WWCodeDFW/Pods/SwiftyJSON/LICENSE index 916a0ac..68e3fd7 100644 --- a/WWCodeDFW/Pods/SwiftyJSON/LICENSE +++ b/WWCodeDFW/Pods/SwiftyJSON/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2016 Ruoyu Fu +Copyright (c) 2017 Ruoyu Fu 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/WWCodeDFW/Pods/SwiftyJSON/README.md b/WWCodeDFW/Pods/SwiftyJSON/README.md index 6256c84..7a10e29 100644 --- a/WWCodeDFW/Pods/SwiftyJSON/README.md +++ b/WWCodeDFW/Pods/SwiftyJSON/README.md @@ -1,9 +1,15 @@ # SwiftyJSON -[![Travis CI](https://travis-ci.org/SwiftyJSON/SwiftyJSON.svg?branch=master)](https://travis-ci.org/SwiftyJSON/SwiftyJSON) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) ![CocoaPods](https://img.shields.io/cocoapods/v/SwiftyJSON.svg) ![Platform](https://img.shields.io/badge/platforms-iOS%208.0+%20%7C%20macOS%2010.10+%20%7C%20tvOS%209.0+%20%7C%20watchOS%202.0+-333333.svg) +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) ![CocoaPods](https://img.shields.io/cocoapods/v/SwiftyJSON.svg) ![Platform](https://img.shields.io/badge/platforms-iOS%208.0%20%7C%20macOS%2010.10%20%7C%20tvOS%209.0%20%7C%20watchOS%203.0-F28D00.svg) [![Reviewed by Hound](https://img.shields.io/badge/Reviewed_by-Hound-8E64B0.svg)](https://houndci.com) SwiftyJSON makes it easy to deal with JSON data in Swift. +Platform | Build Status +---------| --------------| +*OS | [![Travis CI](https://travis-ci.org/SwiftyJSON/SwiftyJSON.svg?branch=master)](https://travis-ci.org/SwiftyJSON/SwiftyJSON) | +[Linux](https://github.com/IBM-Swift/SwiftyJSON) | [![Build Status](https://travis-ci.org/IBM-Swift/SwiftyJSON.svg?branch=master)](https://travis-ci.org/IBM-Swift/SwiftyJSON) | + + 1. [Why is the typical JSON handling in Swift NOT good](#why-is-the-typical-json-handling-in-swift-not-good) 2. [Requirements](#requirements) 3. [Integration](#integration) @@ -19,8 +25,8 @@ SwiftyJSON makes it easy to deal with JSON data in Swift. - [Literal convertibles](#literal-convertibles) - [Merging](#merging) 5. [Work with Alamofire](#work-with-alamofire) - -> For Legacy Swift support, take a look at the [swift2 branch](https://github.com/SwiftyJSON/SwiftyJSON/tree/swift2) +6. [Work with Moya](#work-with-moya) +7. [SwiftyJSON Model Generator](#swiftyjson-model-generator) > [中文介绍](http://tangplin.github.io/swiftyjson/) @@ -29,7 +35,7 @@ SwiftyJSON makes it easy to deal with JSON data in Swift. Swift is very strict about types. But although explicit typing is good for saving us from mistakes, it becomes painful when dealing with JSON and other areas that are, by nature, implicit about types. -Take the Twitter API for example. Say we want to retrieve a user's "name" value of some tweet in Swift (according to Twitter's API https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline). +Take the Twitter API for example. Say we want to retrieve a user's "name" value of some tweet in Swift (according to [Twitter's API](https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline)). The code would look like this: @@ -67,11 +73,12 @@ And don't worry about the Optional Wrapping thing. It's done for you automatical ```swift let json = JSON(data: dataFromNetworking) -if let userName = json[999999]["wrong_key"]["wrong_name"].string { +let result = json[999999]["wrong_key"]["wrong_name"] +if let userName = result.string { //Calm down, take it easy, the ".string" property still produces the correct Optional String type with safety } else { //Print the error - print(json[999999]["wrong_key"]["wrong_name"]) + print(result.error) } ``` @@ -84,45 +91,43 @@ if let userName = json[999999]["wrong_key"]["wrong_name"].string { #### CocoaPods (iOS 8+, OS X 10.9+) -You can use [CocoaPods](http://cocoapods.org/) to install `SwiftyJSON`by adding it to your `Podfile`: +You can use [CocoaPods](http://cocoapods.org/) to install `SwiftyJSON` by adding it to your `Podfile`: ```ruby platform :ios, '8.0' use_frameworks! target 'MyApp' do - pod 'SwiftyJSON' + pod 'SwiftyJSON', '~> 4.0' end ``` -Note that this requires CocoaPods version 36, and your iOS deployment target to be at least 8.0: - - #### Carthage (iOS 8+, OS X 10.9+) You can use [Carthage](https://github.com/Carthage/Carthage) to install `SwiftyJSON` by adding it to your `Cartfile`: ``` -github "SwiftyJSON/SwiftyJSON" +github "SwiftyJSON/SwiftyJSON" ~> 4.0 ``` +If you use Carthage to build your dependencies, make sure you have added `SwiftyJSON.framework` to the "Linked Frameworks and Libraries" section of your target, and have included them in your Carthage framework copying build phase. + #### Swift Package Manager You can use [The Swift Package Manager](https://swift.org/package-manager) to install `SwiftyJSON` by adding the proper description to your `Package.swift` file: ```swift +// swift-tools-version:4.0 import PackageDescription let package = Package( name: "YOUR_PROJECT_NAME", - targets: [], dependencies: [ - .Package(url: "https://github.com/SwiftyJSON/SwiftyJSON.git", versions: Version(1,0,0).. = json["list"].arrayValue ``` ```swift -//If not a Dictionary or nil, return [:] +// If not a Dictionary or nil, return [:] let user: Dictionary = json["user"].dictionaryValue ``` @@ -341,31 +355,36 @@ json.dictionaryObject = ["name":"Jack", "age":25] #### Raw object ```swift -let jsonObject: Any = json.object +let rawObject: Any = json.object ``` ```swift -if let jsonObject: Any = json.rawValue +let rawValue: Any = json.rawValue ``` ```swift //convert the JSON to raw NSData -if let data = json.rawData() { - //Do something you want +do { + let rawData = try json.rawData() + //Do something you want +} catch { + print("Error \(error)") } ``` ```swift //convert the JSON to a raw String -if let string = json.rawString() { - //Do something you want +if let rawString = json.rawString() { + //Do something you want +} else { + print("json.rawString is nil") } ``` #### Existence ```swift -//shows you whether value specified in JSON or not +// shows you whether value specified in JSON or not if json["name"].exists() ``` @@ -374,59 +393,54 @@ if json["name"].exists() For more info about literal convertibles: [Swift Literal Convertibles](http://nshipster.com/swift-literal-convertible/) ```swift -//StringLiteralConvertible +// StringLiteralConvertible let json: JSON = "I'm a json" ``` ```swift -//IntegerLiteralConvertible +/ /IntegerLiteralConvertible let json: JSON = 12345 ``` ```swift -//BooleanLiteralConvertible +// BooleanLiteralConvertible let json: JSON = true ``` ```swift -//FloatLiteralConvertible +// FloatLiteralConvertible let json: JSON = 2.8765 ``` ```swift -//DictionaryLiteralConvertible +// DictionaryLiteralConvertible let json: JSON = ["I":"am", "a":"json"] ``` ```swift -//ArrayLiteralConvertible +// ArrayLiteralConvertible let json: JSON = ["I", "am", "a", "json"] ``` ```swift -//NilLiteralConvertible -let json: JSON = nil -``` - -```swift -//With subscript in array +// With subscript in array var json: JSON = [1,2,3] json[0] = 100 json[1] = 200 json[2] = 300 -json[999] = 300 //Don't worry, nothing will happen +json[999] = 300 // Don't worry, nothing will happen ``` ```swift -//With subscript in dictionary +// With subscript in dictionary var json: JSON = ["name": "Jack", "age": 25] json["name"] = "Mike" -json["age"] = "25" //It's OK to set String +json["age"] = "25" // It's OK to set String json["address"] = "L.A." // Add the "address": "L.A." in json ``` ```swift -//Array & Dictionary +// Array & Dictionary var json: JSON = ["name": "Jack", "age": 25, "list": ["a", "b", "c", ["what": "this"]]] json["list"][3]["what"] = "that" json["list",3,"what"] = "that" @@ -435,10 +449,10 @@ json[path] = "that" ``` ```swift -//With other JSON objects +// With other JSON objects let user: JSON = ["username" : "Steve", "password": "supersecurepassword"] let auth: JSON = [ - "user": user.object //use user.object instead of just user + "user": user.object, // use user.object instead of just user "apikey": "supersecretapitoken" ] ``` @@ -449,7 +463,7 @@ It is possible to merge one JSON into another JSON. Merging a JSON into another If both JSONs contain a value for the same key, _mostly_ this value gets overwritten in the original JSON, but there are two cases where it provides some special treatment: -- In case of both values being a `JSON.Type.array` the values form the array found in the `other` JSON getting appended to the original JSON's array value. +- In case of both values being a `JSON.Type.array` the values form the array found in the `other` JSON getting appended to the original JSON's array value. - In case of both values being a `JSON.Type.dictionary` both JSON-values are getting merged the same way the encapsulating JSON is merged. In case, where two fields in a JSON have a different types, the value will get always overwritten. @@ -502,7 +516,7 @@ let representation = json.rawString(options: [.castNilToNSNull: true]) // representation is "{\"1\":2,\"2\":\"two\",\"3\":null}", which represents {"1":2,"2":"two","3":null} ``` -## Work with Alamofire +## Work with [Alamofire](https://github.com/Alamofire/Alamofire) SwiftyJSON nicely wraps the result of the Alamofire JSON response handler: @@ -517,3 +531,32 @@ Alamofire.request(url, method: .get).validate().responseJSON { response in } } ``` + +We also provide an extension of Alamofire for serializing NSData to SwiftyJSON's JSON. + +See: [Alamofire-SwiftyJSON](https://github.com/SwiftyJSON/Alamofire-SwiftyJSON) + + +## Work with [Moya](https://github.com/Moya/Moya) + +SwiftyJSON parse data to JSON: + +```swift +let provider = MoyaProvider() +provider.request(.showProducts) { result in + switch result { + case let .success(moyaResponse): + let data = moyaResponse.data + let json = JSON(data: data) // convert network data to json + print(json) + case let .failure(error): + print("error: \(error)") + } +} + +``` + +## SwiftyJSON Model Generator +Tools to generate SwiftyJSON Models +* [JSON Cafe](http://www.jsoncafe.com/) +* [JSON Export](https://github.com/Ahmed-Ali/JSONExport) diff --git a/WWCodeDFW/Pods/SwiftyJSON/Source/SwiftyJSON.swift b/WWCodeDFW/Pods/SwiftyJSON/Source/SwiftyJSON.swift deleted file mode 100644 index e79c10d..0000000 --- a/WWCodeDFW/Pods/SwiftyJSON/Source/SwiftyJSON.swift +++ /dev/null @@ -1,1485 +0,0 @@ -// SwiftyJSON.swift -// -// Copyright (c) 2014 - 2017 Ruoyu Fu, Pinglin Tang -// -// 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: - Error - -///Error domain -public let ErrorDomain: String = "SwiftyJSONErrorDomain" - -///Error code -public let ErrorUnsupportedType: Int = 999 -public let ErrorIndexOutOfBounds: Int = 900 -public let ErrorWrongType: Int = 901 -public let ErrorNotExist: Int = 500 -public let ErrorInvalidJSON: Int = 490 - -// MARK: - JSON Type - -/** - JSON's type definitions. - - See http://www.json.org - */ -public enum Type :Int{ - - case number - case string - case bool - case array - case dictionary - case null - case unknown -} - -// MARK: - JSON Base -public struct JSON { - - /** - Creates a JSON using the data. - - - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary - - parameter opt: The JSON serialization reading options. `.AllowFragments` by default. - - parameter error: The NSErrorPointer used to return the error. `nil` by default. - - - returns: The created JSON - */ - public init(data: Data, options opt: JSONSerialization.ReadingOptions = .allowFragments, error: NSErrorPointer = nil) { - do { - let object: Any = try JSONSerialization.jsonObject(with: data, options: opt) - self.init(jsonObject: object) - } catch let aError as NSError { - if error != nil { - error?.pointee = aError - } - self.init(jsonObject: NSNull()) - } - } - - /** - Creates a JSON object - - parameter object: the object - - note: this does not parse a `String` into JSON, instead use `init(parseJSON: String)` - - returns: the created JSON object - */ - public init(_ object: Any) { - switch object { - case let object as [JSON] where object.count > 0: - self.init(array: object) - case let object as [String: JSON] where object.count > 0: - self.init(dictionary: object) - case let object as Data: - self.init(data: object) - default: - self.init(jsonObject: object) - } - } - - /** - Parses the JSON string into a JSON object - - parameter json: the JSON string - - returns: the created JSON object - */ - public init(parseJSON jsonString: String) { - if let data = jsonString.data(using: .utf8) { - self.init(data) - } else { - self.init(NSNull()) - } - } - - /** - Creates a JSON from JSON string - - parameter string: Normal json string like '{"a":"b"}' - - - returns: The created JSON - */ - @available(*, deprecated: 3.2, message: "Use instead `init(parseJSON: )`") - public static func parse(_ json: String) -> JSON { - return json.data(using: String.Encoding.utf8) - .flatMap{ JSON(data: $0) } ?? JSON(NSNull()) - } - - /** - Creates a JSON using the object. - - - parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity. - - - returns: The created JSON - */ - fileprivate init(jsonObject: Any) { - self.object = jsonObject - } - - /** - Creates a JSON from a [JSON] - - - parameter jsonArray: A Swift array of JSON objects - - - returns: The created JSON - */ - fileprivate init(array: [JSON]) { - self.init(array.map { $0.object }) - } - - /** - Creates a JSON from a [String: JSON] - - - parameter jsonDictionary: A Swift dictionary of JSON objects - - - returns: The created JSON - */ - fileprivate init(dictionary: [String: JSON]) { - var newDictionary = [String: Any](minimumCapacity: dictionary.count) - for (key, json) in dictionary { - newDictionary[key] = json.object - } - - self.init(newDictionary) - } - - /** - Merges another JSON into this JSON, whereas primitive values which are not present in this JSON are getting added, - present values getting overwritten, array values getting appended and nested JSONs getting merged the same way. - - - parameter other: The JSON which gets merged into this JSON - - throws `ErrorWrongType` if the other JSONs differs in type on the top level. - */ - public mutating func merge(with other: JSON) throws { - try self.merge(with: other, typecheck: true) - } - - /** - Merges another JSON into this JSON and returns a new JSON, whereas primitive values which are not present in this JSON are getting added, - present values getting overwritten, array values getting appended and nested JSONS getting merged the same way. - - - parameter other: The JSON which gets merged into this JSON - - returns: New merged JSON - - throws `ErrorWrongType` if the other JSONs differs in type on the top level. - */ - public func merged(with other: JSON) throws -> JSON { - var merged = self - try merged.merge(with: other, typecheck: true) - return merged - } - - // Private woker function which does the actual merging - // Typecheck is set to true for the first recursion level to prevent total override of the source JSON - fileprivate mutating func merge(with other: JSON, typecheck: Bool) throws { - if self.type == other.type { - switch self.type { - case .dictionary: - for (key, _) in other { - try self[key].merge(with: other[key], typecheck: false) - } - case .array: - self = JSON(self.arrayValue + other.arrayValue) - default: - self = other - } - } else { - if typecheck { - throw NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Couldn't merge, because the JSONs differ in type on top level."]) - } else { - self = other - } - } - } - - /// Private object - fileprivate var rawArray: [Any] = [] - fileprivate var rawDictionary: [String : Any] = [:] - fileprivate var rawString: String = "" - fileprivate var rawNumber: NSNumber = 0 - fileprivate var rawNull: NSNull = NSNull() - fileprivate var rawBool: Bool = false - /// Private type - fileprivate var _type: Type = .null - /// prviate error - fileprivate var _error: NSError? = nil - - /// Object in JSON - public var object: Any { - get { - switch self.type { - case .array: - return self.rawArray - case .dictionary: - return self.rawDictionary - case .string: - return self.rawString - case .number: - return self.rawNumber - case .bool: - return self.rawBool - default: - return self.rawNull - } - } - set { - _error = nil - switch newValue { - case let number as NSNumber: - if number.isBool { - _type = .bool - self.rawBool = number.boolValue - } else { - _type = .number - self.rawNumber = number - } - case let string as String: - _type = .string - self.rawString = string - case _ as NSNull: - _type = .null - case _ as [JSON]: - _type = .array - case nil: - _type = .null - case let array as [Any]: - _type = .array - self.rawArray = array - case let dictionary as [String : Any]: - _type = .dictionary - self.rawDictionary = dictionary - default: - _type = .unknown - _error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"]) - } - } - } - - /// JSON type - public var type: Type { get { return _type } } - - /// Error in JSON - public var error: NSError? { get { return self._error } } - - /// The static null JSON - @available(*, unavailable, renamed:"null") - public static var nullJSON: JSON { get { return null } } - public static var null: JSON { get { return JSON(NSNull()) } } -} - -public enum Index: Comparable -{ - case array(Int) - case dictionary(DictionaryIndex) - case null - - static public func ==(lhs: Index, rhs: Index) -> Bool { - switch (lhs, rhs) { - case (.array(let left), .array(let right)): - return left == right - case (.dictionary(let left), .dictionary(let right)): - return left == right - case (.null, .null): return true - default: - return false - } - } - - static public func <(lhs: Index, rhs: Index) -> Bool { - switch (lhs, rhs) { - case (.array(let left), .array(let right)): - return left < right - case (.dictionary(let left), .dictionary(let right)): - return left < right - default: - return false - } - } -} - -public typealias JSONIndex = Index -public typealias JSONRawIndex = Index - - -extension JSON: Collection -{ - - public typealias Index = JSONRawIndex - - public var startIndex: Index - { - switch type - { - case .array: - return .array(rawArray.startIndex) - case .dictionary: - return .dictionary(rawDictionary.startIndex) - default: - return .null - } - } - - public var endIndex: Index - { - switch type - { - case .array: - return .array(rawArray.endIndex) - case .dictionary: - return .dictionary(rawDictionary.endIndex) - default: - return .null - } - } - - public func index(after i: Index) -> Index - { - switch i - { - case .array(let idx): - return .array(rawArray.index(after: idx)) - case .dictionary(let idx): - return .dictionary(rawDictionary.index(after: idx)) - default: - return .null - } - - } - - public subscript (position: Index) -> (String, JSON) - { - switch position - { - case .array(let idx): - return (String(idx), JSON(self.rawArray[idx])) - case .dictionary(let idx): - let (key, value) = self.rawDictionary[idx] - return (key, JSON(value)) - default: - return ("", JSON.null) - } - } - - -} - -// MARK: - Subscript - -/** - * To mark both String and Int can be used in subscript. - */ -public enum JSONKey -{ - case index(Int) - case key(String) -} - -public protocol JSONSubscriptType { - var jsonKey:JSONKey { get } -} - -extension Int: JSONSubscriptType { - public var jsonKey:JSONKey { - return JSONKey.index(self) - } -} - -extension String: JSONSubscriptType { - public var jsonKey:JSONKey { - return JSONKey.key(self) - } -} - -extension JSON { - - /// If `type` is `.Array`, return json whose object is `array[index]`, otherwise return null json with error. - fileprivate subscript(index index: Int) -> JSON { - get { - if self.type != .array { - var r = JSON.null - r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"]) - return r - } else if index >= 0 && index < self.rawArray.count { - return JSON(self.rawArray[index]) - } else { - var r = JSON.null - r._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"]) - return r - } - } - set { - if self.type == .array { - if self.rawArray.count > index && newValue.error == nil { - self.rawArray[index] = newValue.object - } - } - } - } - - /// If `type` is `.Dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error. - fileprivate subscript(key key: String) -> JSON { - get { - var r = JSON.null - if self.type == .dictionary { - if let o = self.rawDictionary[key] { - r = JSON(o) - } else { - r._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"]) - } - } else { - r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"]) - } - return r - } - set { - if self.type == .dictionary && newValue.error == nil { - self.rawDictionary[key] = newValue.object - } - } - } - - /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. - fileprivate subscript(sub sub: JSONSubscriptType) -> JSON { - get { - switch sub.jsonKey { - case .index(let index): return self[index: index] - case .key(let key): return self[key: key] - } - } - set { - switch sub.jsonKey { - case .index(let index): self[index: index] = newValue - case .key(let key): self[key: key] = newValue - } - } - } - - /** - Find a json in the complex data structures by using array of Int and/or String as path. - - - parameter path: The target json's path. Example: - - let json = JSON[data] - let path = [9,"list","person","name"] - let name = json[path] - - The same as: let name = json[9]["list"]["person"]["name"] - - - returns: Return a json found by the path or a null json with error - */ - public subscript(path: [JSONSubscriptType]) -> JSON { - get { - return path.reduce(self) { $0[sub: $1] } - } - set { - switch path.count { - case 0: - return - case 1: - self[sub:path[0]].object = newValue.object - default: - var aPath = path; aPath.remove(at: 0) - var nextJSON = self[sub: path[0]] - nextJSON[aPath] = newValue - self[sub: path[0]] = nextJSON - } - } - } - - /** - Find a json in the complex data structures by using array of Int and/or String as path. - - - parameter path: The target json's path. Example: - - let name = json[9,"list","person","name"] - - The same as: let name = json[9]["list"]["person"]["name"] - - - returns: Return a json found by the path or a null json with error - */ - public subscript(path: JSONSubscriptType...) -> JSON { - get { - return self[path] - } - set { - self[path] = newValue - } - } -} - -// MARK: - LiteralConvertible - -extension JSON: Swift.ExpressibleByStringLiteral { - - public init(stringLiteral value: StringLiteralType) { - self.init(value as Any) - } - - public init(extendedGraphemeClusterLiteral value: StringLiteralType) { - self.init(value as Any) - } - - public init(unicodeScalarLiteral value: StringLiteralType) { - self.init(value as Any) - } -} - -extension JSON: Swift.ExpressibleByIntegerLiteral { - - public init(integerLiteral value: IntegerLiteralType) { - self.init(value as Any) - } -} - -extension JSON: Swift.ExpressibleByBooleanLiteral { - - public init(booleanLiteral value: BooleanLiteralType) { - self.init(value as Any) - } -} - -extension JSON: Swift.ExpressibleByFloatLiteral { - - public init(floatLiteral value: FloatLiteralType) { - self.init(value as Any) - } -} - -extension JSON: Swift.ExpressibleByDictionaryLiteral { - public init(dictionaryLiteral elements: (String, Any)...) { - let array = elements - self.init(dictionaryLiteral: array) - } - - public init(dictionaryLiteral elements: [(String, Any)]) { - let jsonFromDictionaryLiteral: ([String : Any]) -> JSON = { dictionary in - let initializeElement = Array(dictionary.keys).flatMap { key -> (String, Any)? in - if let value = dictionary[key] { - return (key, value) - } - return nil - } - return JSON(dictionaryLiteral: initializeElement) - } - - var dict = [String : Any](minimumCapacity: elements.count) - - for element in elements { - let elementToSet: Any - if let json = element.1 as? JSON { - elementToSet = json.object - } else if let jsonArray = element.1 as? [JSON] { - elementToSet = JSON(jsonArray).object - } else if let dictionary = element.1 as? [String : Any] { - elementToSet = jsonFromDictionaryLiteral(dictionary).object - } else if let dictArray = element.1 as? [[String : Any]] { - let jsonArray = dictArray.map { jsonFromDictionaryLiteral($0) } - elementToSet = JSON(jsonArray).object - } else { - elementToSet = element.1 - } - dict[element.0] = elementToSet - } - - self.init(dict) - } -} - -extension JSON: Swift.ExpressibleByArrayLiteral { - - public init(arrayLiteral elements: Any...) { - self.init(elements as Any) - } -} - -extension JSON: Swift.ExpressibleByNilLiteral { - - @available(*, deprecated, message: "use JSON.null instead. Will be removed in future versions") - public init(nilLiteral: ()) { - self.init(NSNull() as Any) - } -} - -// MARK: - Raw - -extension JSON: Swift.RawRepresentable { - - public init?(rawValue: Any) { - if JSON(rawValue).type == .unknown { - return nil - } else { - self.init(rawValue) - } - } - - public var rawValue: Any { - return self.object - } - - public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data { - guard JSONSerialization.isValidJSONObject(self.object) else { - throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "JSON is invalid"]) - } - - return try JSONSerialization.data(withJSONObject: self.object, options: opt) - } - - public func rawString(_ encoding: String.Encoding = .utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? { - do { - return try _rawString(encoding, options: [.jsonSerialization: opt]) - } catch { - print("Could not serialize object to JSON because:", error.localizedDescription) - return nil - } - } - - public func rawString(_ options: [writtingOptionsKeys: Any]) -> String? { - let encoding = options[.encoding] as? String.Encoding ?? String.Encoding.utf8 - let maxObjectDepth = options[.maxObjextDepth] as? Int ?? 10 - do { - return try _rawString(encoding, options: options, maxObjectDepth: maxObjectDepth) - } catch { - print("Could not serialize object to JSON because:", error.localizedDescription) - return nil - } - } - - fileprivate func _rawString( - _ encoding: String.Encoding = .utf8, - options: [writtingOptionsKeys: Any], - maxObjectDepth: Int = 10 - ) throws -> String? { - if (maxObjectDepth < 0) { - throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Element too deep. Increase maxObjectDepth and make sure there is no reference loop"]) - } - switch self.type { - case .dictionary: - do { - if !(options[.castNilToNSNull] as? Bool ?? false) { - let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted - let data = try self.rawData(options: jsonOption) - return String(data: data, encoding: encoding) - } - - guard let dict = self.object as? [String: Any?] else { - return nil - } - let body = try dict.keys.map { key throws -> String in - guard let value = dict[key] else { - return "\"\(key)\": null" - } - guard let unwrappedValue = value else { - return "\"\(key)\": null" - } - - let nestedValue = JSON(unwrappedValue) - guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { - throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Could not serialize nested JSON"]) - } - if nestedValue.type == .string { - return "\"\(key)\": \"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" - } else { - return "\"\(key)\": \(nestedString)" - } - } - - return "{\(body.joined(separator: ","))}" - } catch _ { - return nil - } - case .array: - do { - if !(options[.castNilToNSNull] as? Bool ?? false) { - let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted - let data = try self.rawData(options: jsonOption) - return String(data: data, encoding: encoding) - } - - guard let array = self.object as? [Any?] else { - return nil - } - let body = try array.map { value throws -> String in - guard let unwrappedValue = value else { - return "null" - } - - let nestedValue = JSON(unwrappedValue) - guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { - throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Could not serialize nested JSON"]) - } - if nestedValue.type == .string { - return "\"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" - } else { - return nestedString - } - } - - return "[\(body.joined(separator: ","))]" - } catch _ { - return nil - } - case .string: - return self.rawString - case .number: - return self.rawNumber.stringValue - case .bool: - return self.rawBool.description - case .null: - return "null" - default: - return nil - } - } -} - -// MARK: - Printable, DebugPrintable - -extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertible { - - public var description: String { - if let string = self.rawString(options:.prettyPrinted) { - return string - } else { - return "unknown" - } - } - - public var debugDescription: String { - return description - } -} - -// MARK: - Array - -extension JSON { - - //Optional [JSON] - public var array: [JSON]? { - get { - if self.type == .array { - return self.rawArray.map{ JSON($0) } - } else { - return nil - } - } - } - - //Non-optional [JSON] - public var arrayValue: [JSON] { - get { - return self.array ?? [] - } - } - - //Optional [Any] - public var arrayObject: [Any]? { - get { - switch self.type { - case .array: - return self.rawArray - default: - return nil - } - } - set { - if let array = newValue { - self.object = array as Any - } else { - self.object = NSNull() - } - } - } -} - -// MARK: - Dictionary - -extension JSON { - - //Optional [String : JSON] - public var dictionary: [String : JSON]? { - if self.type == .dictionary { - var d = [String : JSON](minimumCapacity: rawDictionary.count) - for (key, value) in rawDictionary { - d[key] = JSON(value) - } - return d - } else { - return nil - } - } - - //Non-optional [String : JSON] - public var dictionaryValue: [String : JSON] { - return self.dictionary ?? [:] - } - - //Optional [String : Any] - - public var dictionaryObject: [String : Any]? { - get { - switch self.type { - case .dictionary: - return self.rawDictionary - default: - return nil - } - } - set { - if let v = newValue { - self.object = v as Any - } else { - self.object = NSNull() - } - } - } -} - -// MARK: - Bool - -extension JSON { // : Swift.Bool - - //Optional bool - public var bool: Bool? { - get { - switch self.type { - case .bool: - return self.rawBool - default: - return nil - } - } - set { - if let newValue = newValue { - self.object = newValue as Bool - } else { - self.object = NSNull() - } - } - } - - //Non-optional bool - public var boolValue: Bool { - get { - switch self.type { - case .bool: - return self.rawBool - case .number: - return self.rawNumber.boolValue - case .string: - return ["true", "y", "t"].contains() { (truthyString) in - return self.rawString.caseInsensitiveCompare(truthyString) == .orderedSame - } - default: - return false - } - } - set { - self.object = newValue - } - } -} - -// MARK: - String - -extension JSON { - - //Optional string - public var string: String? { - get { - switch self.type { - case .string: - return self.object as? String - default: - return nil - } - } - set { - if let newValue = newValue { - self.object = NSString(string:newValue) - } else { - self.object = NSNull() - } - } - } - - //Non-optional string - public var stringValue: String { - get { - switch self.type { - case .string: - return self.object as? String ?? "" - case .number: - return self.rawNumber.stringValue - case .bool: - return (self.object as? Bool).map { String($0) } ?? "" - default: - return "" - } - } - set { - self.object = NSString(string:newValue) - } - } -} - -// MARK: - Number -extension JSON { - - //Optional number - public var number: NSNumber? { - get { - switch self.type { - case .number: - return self.rawNumber - case .bool: - return NSNumber(value: self.rawBool ? 1 : 0) - default: - return nil - } - } - set { - self.object = newValue ?? NSNull() - } - } - - //Non-optional number - public var numberValue: NSNumber { - get { - switch self.type { - case .string: - let decimal = NSDecimalNumber(string: self.object as? String) - if decimal == NSDecimalNumber.notANumber { // indicates parse error - return NSDecimalNumber.zero - } - return decimal - case .number: - return self.object as? NSNumber ?? NSNumber(value: 0) - case .bool: - return NSNumber(value: self.rawBool ? 1 : 0) - default: - return NSNumber(value: 0.0) - } - } - set { - self.object = newValue - } - } -} - -//MARK: - Null -extension JSON { - - public var null: NSNull? { - get { - switch self.type { - case .null: - return self.rawNull - default: - return nil - } - } - set { - self.object = NSNull() - } - } - public func exists() -> Bool{ - if let errorValue = error, errorValue.code == ErrorNotExist || - errorValue.code == ErrorIndexOutOfBounds || - errorValue.code == ErrorWrongType { - return false - } - return true - } -} - -//MARK: - URL -extension JSON { - - //Optional URL - public var url: URL? { - get { - switch self.type { - case .string: - // Check for existing percent escapes first to prevent double-escaping of % character - if let _ = self.rawString.range(of: "%[0-9A-Fa-f]{2}", options: .regularExpression, range: nil, locale: nil) { - return Foundation.URL(string: self.rawString) - } else if let encodedString_ = self.rawString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) { - // We have to use `Foundation.URL` otherwise it conflicts with the variable name. - return Foundation.URL(string: encodedString_) - } else { - return nil - } - default: - return nil - } - } - set { - self.object = newValue?.absoluteString ?? NSNull() - } - } -} - -// MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 - -extension JSON { - - public var double: Double? { - get { - return self.number?.doubleValue - } - set { - if let newValue = newValue { - self.object = NSNumber(value: newValue) - } else { - self.object = NSNull() - } - } - } - - public var doubleValue: Double { - get { - return self.numberValue.doubleValue - } - set { - self.object = NSNumber(value: newValue) - } - } - - public var float: Float? { - get { - return self.number?.floatValue - } - set { - if let newValue = newValue { - self.object = NSNumber(value: newValue) - } else { - self.object = NSNull() - } - } - } - - public var floatValue: Float { - get { - return self.numberValue.floatValue - } - set { - self.object = NSNumber(value: newValue) - } - } - - public var int: Int? - { - get - { - return self.number?.intValue - } - set - { - if let newValue = newValue - { - self.object = NSNumber(value: newValue) - } else - { - self.object = NSNull() - } - } - } - - public var intValue: Int { - get { - return self.numberValue.intValue - } - set { - self.object = NSNumber(value: newValue) - } - } - - public var uInt: UInt? { - get { - return self.number?.uintValue - } - set { - if let newValue = newValue { - self.object = NSNumber(value: newValue) - } else { - self.object = NSNull() - } - } - } - - public var uIntValue: UInt { - get { - return self.numberValue.uintValue - } - set { - self.object = NSNumber(value: newValue) - } - } - - public var int8: Int8? { - get { - return self.number?.int8Value - } - set { - if let newValue = newValue { - self.object = NSNumber(value: Int(newValue)) - } else { - self.object = NSNull() - } - } - } - - public var int8Value: Int8 { - get { - return self.numberValue.int8Value - } - set { - self.object = NSNumber(value: Int(newValue)) - } - } - - public var uInt8: UInt8? { - get { - return self.number?.uint8Value - } - set { - if let newValue = newValue { - self.object = NSNumber(value: newValue) - } else { - self.object = NSNull() - } - } - } - - public var uInt8Value: UInt8 { - get { - return self.numberValue.uint8Value - } - set { - self.object = NSNumber(value: newValue) - } - } - - public var int16: Int16? { - get { - return self.number?.int16Value - } - set { - if let newValue = newValue { - self.object = NSNumber(value: newValue) - } else { - self.object = NSNull() - } - } - } - - public var int16Value: Int16 { - get { - return self.numberValue.int16Value - } - set { - self.object = NSNumber(value: newValue) - } - } - - public var uInt16: UInt16? { - get { - return self.number?.uint16Value - } - set { - if let newValue = newValue { - self.object = NSNumber(value: newValue) - } else { - self.object = NSNull() - } - } - } - - public var uInt16Value: UInt16 { - get { - return self.numberValue.uint16Value - } - set { - self.object = NSNumber(value: newValue) - } - } - - public var int32: Int32? { - get { - return self.number?.int32Value - } - set { - if let newValue = newValue { - self.object = NSNumber(value: newValue) - } else { - self.object = NSNull() - } - } - } - - public var int32Value: Int32 { - get { - return self.numberValue.int32Value - } - set { - self.object = NSNumber(value: newValue) - } - } - - public var uInt32: UInt32? { - get { - return self.number?.uint32Value - } - set { - if let newValue = newValue { - self.object = NSNumber(value: newValue) - } else { - self.object = NSNull() - } - } - } - - public var uInt32Value: UInt32 { - get { - return self.numberValue.uint32Value - } - set { - self.object = NSNumber(value: newValue) - } - } - - public var int64: Int64? { - get { - return self.number?.int64Value - } - set { - if let newValue = newValue { - self.object = NSNumber(value: newValue) - } else { - self.object = NSNull() - } - } - } - - public var int64Value: Int64 { - get { - return self.numberValue.int64Value - } - set { - self.object = NSNumber(value: newValue) - } - } - - public var uInt64: UInt64? { - get { - return self.number?.uint64Value - } - set { - if let newValue = newValue { - self.object = NSNumber(value: newValue) - } else { - self.object = NSNull() - } - } - } - - public var uInt64Value: UInt64 { - get { - return self.numberValue.uint64Value - } - set { - self.object = NSNumber(value: newValue) - } - } -} - -//MARK: - Comparable -extension JSON : Swift.Comparable {} - -public func ==(lhs: JSON, rhs: JSON) -> Bool { - - switch (lhs.type, rhs.type) { - case (.number, .number): - return lhs.rawNumber == rhs.rawNumber - case (.string, .string): - return lhs.rawString == rhs.rawString - case (.bool, .bool): - return lhs.rawBool == rhs.rawBool - case (.array, .array): - return lhs.rawArray as NSArray == rhs.rawArray as NSArray - case (.dictionary, .dictionary): - return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary - case (.null, .null): - return true - default: - return false - } -} - -public func <=(lhs: JSON, rhs: JSON) -> Bool { - - switch (lhs.type, rhs.type) { - case (.number, .number): - return lhs.rawNumber <= rhs.rawNumber - case (.string, .string): - return lhs.rawString <= rhs.rawString - case (.bool, .bool): - return lhs.rawBool == rhs.rawBool - case (.array, .array): - return lhs.rawArray as NSArray == rhs.rawArray as NSArray - case (.dictionary, .dictionary): - return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary - case (.null, .null): - return true - default: - return false - } -} - -public func >=(lhs: JSON, rhs: JSON) -> Bool { - - switch (lhs.type, rhs.type) { - case (.number, .number): - return lhs.rawNumber >= rhs.rawNumber - case (.string, .string): - return lhs.rawString >= rhs.rawString - case (.bool, .bool): - return lhs.rawBool == rhs.rawBool - case (.array, .array): - return lhs.rawArray as NSArray == rhs.rawArray as NSArray - case (.dictionary, .dictionary): - return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary - case (.null, .null): - return true - default: - return false - } -} - -public func >(lhs: JSON, rhs: JSON) -> Bool { - - switch (lhs.type, rhs.type) { - case (.number, .number): - return lhs.rawNumber > rhs.rawNumber - case (.string, .string): - return lhs.rawString > rhs.rawString - default: - return false - } -} - -public func <(lhs: JSON, rhs: JSON) -> Bool { - - switch (lhs.type, rhs.type) { - case (.number, .number): - return lhs.rawNumber < rhs.rawNumber - case (.string, .string): - return lhs.rawString < rhs.rawString - default: - return false - } -} - -private let trueNumber = NSNumber(value: true) -private let falseNumber = NSNumber(value: false) -private let trueObjCType = String(cString: trueNumber.objCType) -private let falseObjCType = String(cString: falseNumber.objCType) - -// MARK: - NSNumber: Comparable - -extension NSNumber { - var isBool:Bool { - get { - let objCType = String(cString: self.objCType) - if (self.compare(trueNumber) == .orderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == .orderedSame && objCType == falseObjCType){ - return true - } else { - return false - } - } - } -} - -func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { - switch (lhs.isBool, rhs.isBool) { - case (false, true): - return false - case (true, false): - return false - default: - return lhs.compare(rhs) == .orderedSame - } -} - -func !=(lhs: NSNumber, rhs: NSNumber) -> Bool { - return !(lhs == rhs) -} - -func <(lhs: NSNumber, rhs: NSNumber) -> Bool { - - switch (lhs.isBool, rhs.isBool) { - case (false, true): - return false - case (true, false): - return false - default: - return lhs.compare(rhs) == .orderedAscending - } -} - -func >(lhs: NSNumber, rhs: NSNumber) -> Bool { - - switch (lhs.isBool, rhs.isBool) { - case (false, true): - return false - case (true, false): - return false - default: - return lhs.compare(rhs) == ComparisonResult.orderedDescending - } -} - -func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { - - switch (lhs.isBool, rhs.isBool) { - case (false, true): - return false - case (true, false): - return false - default: - return lhs.compare(rhs) != .orderedDescending - } -} - -func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { - - switch (lhs.isBool, rhs.isBool) { - case (false, true): - return false - case (true, false): - return false - default: - return lhs.compare(rhs) != .orderedAscending - } -} - -public enum writtingOptionsKeys { - case jsonSerialization - case castNilToNSNull - case maxObjextDepth - case encoding -} diff --git a/WWCodeDFW/Pods/SwiftyJSON/Source/SwiftyJSON/SwiftyJSON.swift b/WWCodeDFW/Pods/SwiftyJSON/Source/SwiftyJSON/SwiftyJSON.swift new file mode 100644 index 0000000..f7a3f08 --- /dev/null +++ b/WWCodeDFW/Pods/SwiftyJSON/Source/SwiftyJSON/SwiftyJSON.swift @@ -0,0 +1,1401 @@ +// SwiftyJSON.swift +// +// Copyright (c) 2014 - 2017 Ruoyu Fu, Pinglin Tang +// +// 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: - Error +// swiftlint:disable line_length +public enum SwiftyJSONError: Int, Swift.Error { + case unsupportedType = 999 + case indexOutOfBounds = 900 + case elementTooDeep = 902 + case wrongType = 901 + case notExist = 500 + case invalidJSON = 490 +} + +extension SwiftyJSONError: CustomNSError { + + /// return the error domain of SwiftyJSONError + public static var errorDomain: String { return "com.swiftyjson.SwiftyJSON" } + + /// return the error code of SwiftyJSONError + public var errorCode: Int { return self.rawValue } + + /// return the userInfo of SwiftyJSONError + public var errorUserInfo: [String: Any] { + switch self { + case .unsupportedType: + return [NSLocalizedDescriptionKey: "It is an unsupported type."] + case .indexOutOfBounds: + return [NSLocalizedDescriptionKey: "Array Index is out of bounds."] + case .wrongType: + return [NSLocalizedDescriptionKey: "Couldn't merge, because the JSONs differ in type on top level."] + case .notExist: + return [NSLocalizedDescriptionKey: "Dictionary key does not exist."] + case .invalidJSON: + return [NSLocalizedDescriptionKey: "JSON is invalid."] + case .elementTooDeep: + return [NSLocalizedDescriptionKey: "Element too deep. Increase maxObjectDepth and make sure there is no reference loop."] + } + } +} + +// MARK: - JSON Type + +/** +JSON's type definitions. + +See http://www.json.org +*/ +public enum Type: Int { + case number + case string + case bool + case array + case dictionary + case null + case unknown +} + +// MARK: - JSON Base + +public struct JSON { + + /** + Creates a JSON using the data. + + - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary + - parameter opt: The JSON serialization reading options. `[]` by default. + + - returns: The created JSON + */ + public init(data: Data, options opt: JSONSerialization.ReadingOptions = []) throws { + let object: Any = try JSONSerialization.jsonObject(with: data, options: opt) + self.init(jsonObject: object) + } + + /** + Creates a JSON object + - note: this does not parse a `String` into JSON, instead use `init(parseJSON: String)` + + - parameter object: the object + + - returns: the created JSON object + */ + public init(_ object: Any) { + switch object { + case let object as Data: + do { + try self.init(data: object) + } catch { + self.init(jsonObject: NSNull()) + } + default: + self.init(jsonObject: object) + } + } + + /** + Parses the JSON string into a JSON object + + - parameter json: the JSON string + + - returns: the created JSON object + */ + public init(parseJSON jsonString: String) { + if let data = jsonString.data(using: .utf8) { + self.init(data) + } else { + self.init(NSNull()) + } + } + + /** + Creates a JSON using the object. + + - parameter jsonObject: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity. + + - returns: The created JSON + */ + fileprivate init(jsonObject: Any) { + object = jsonObject + } + + /** + Merges another JSON into this JSON, whereas primitive values which are not present in this JSON are getting added, + present values getting overwritten, array values getting appended and nested JSONs getting merged the same way. + + - parameter other: The JSON which gets merged into this JSON + + - throws `ErrorWrongType` if the other JSONs differs in type on the top level. + */ + public mutating func merge(with other: JSON) throws { + try self.merge(with: other, typecheck: true) + } + + /** + Merges another JSON into this JSON and returns a new JSON, whereas primitive values which are not present in this JSON are getting added, + present values getting overwritten, array values getting appended and nested JSONS getting merged the same way. + + - parameter other: The JSON which gets merged into this JSON + + - throws `ErrorWrongType` if the other JSONs differs in type on the top level. + + - returns: New merged JSON + */ + public func merged(with other: JSON) throws -> JSON { + var merged = self + try merged.merge(with: other, typecheck: true) + return merged + } + + /** + Private woker function which does the actual merging + Typecheck is set to true for the first recursion level to prevent total override of the source JSON + */ + fileprivate mutating func merge(with other: JSON, typecheck: Bool) throws { + if type == other.type { + switch type { + case .dictionary: + for (key, _) in other { + try self[key].merge(with: other[key], typecheck: false) + } + case .array: + self = JSON(arrayValue + other.arrayValue) + default: + self = other + } + } else { + if typecheck { + throw SwiftyJSONError.wrongType + } else { + self = other + } + } + } + + /// Private object + fileprivate var rawArray: [Any] = [] + fileprivate var rawDictionary: [String: Any] = [:] + fileprivate var rawString: String = "" + fileprivate var rawNumber: NSNumber = 0 + fileprivate var rawNull: NSNull = NSNull() + fileprivate var rawBool: Bool = false + + /// JSON type, fileprivate setter + public fileprivate(set) var type: Type = .null + + /// Error in JSON, fileprivate setter + public fileprivate(set) var error: SwiftyJSONError? + + /// Object in JSON + public var object: Any { + get { + switch type { + case .array: return rawArray + case .dictionary: return rawDictionary + case .string: return rawString + case .number: return rawNumber + case .bool: return rawBool + default: return rawNull + } + } + set { + error = nil + switch unwrap(newValue) { + case let number as NSNumber: + if number.isBool { + type = .bool + rawBool = number.boolValue + } else { + type = .number + rawNumber = number + } + case let string as String: + type = .string + rawString = string + case _ as NSNull: + type = .null + case nil: + type = .null + case let array as [Any]: + type = .array + rawArray = array + case let dictionary as [String: Any]: + type = .dictionary + rawDictionary = dictionary + default: + type = .unknown + error = SwiftyJSONError.unsupportedType + } + } + } + + /// The static null JSON + @available(*, unavailable, renamed:"null") + public static var nullJSON: JSON { return null } + public static var null: JSON { return JSON(NSNull()) } +} + +/// Private method to unwarp an object recursively +private func unwrap(_ object: Any) -> Any { + switch object { + case let json as JSON: + return unwrap(json.object) + case let array as [Any]: + return array.map(unwrap) + case let dictionary as [String: Any]: + var d = dictionary + dictionary.forEach { pair in + d[pair.key] = unwrap(pair.value) + } + return d + default: + return object + } +} + +public enum Index: Comparable { + case array(Int) + case dictionary(DictionaryIndex) + case null + + static public func == (lhs: Index, rhs: Index) -> Bool { + switch (lhs, rhs) { + case (.array(let left), .array(let right)): return left == right + case (.dictionary(let left), .dictionary(let right)): return left == right + case (.null, .null): return true + default: return false + } + } + + static public func < (lhs: Index, rhs: Index) -> Bool { + switch (lhs, rhs) { + case (.array(let left), .array(let right)): return left < right + case (.dictionary(let left), .dictionary(let right)): return left < right + default: return false + } + } +} + +public typealias JSONIndex = Index +public typealias JSONRawIndex = Index + +extension JSON: Swift.Collection { + + public typealias Index = JSONRawIndex + + public var startIndex: Index { + switch type { + case .array: return .array(rawArray.startIndex) + case .dictionary: return .dictionary(rawDictionary.startIndex) + default: return .null + } + } + + public var endIndex: Index { + switch type { + case .array: return .array(rawArray.endIndex) + case .dictionary: return .dictionary(rawDictionary.endIndex) + default: return .null + } + } + + public func index(after i: Index) -> Index { + switch i { + case .array(let idx): return .array(rawArray.index(after: idx)) + case .dictionary(let idx): return .dictionary(rawDictionary.index(after: idx)) + default: return .null + } + } + + public subscript (position: Index) -> (String, JSON) { + switch position { + case .array(let idx): return (String(idx), JSON(rawArray[idx])) + case .dictionary(let idx): return (rawDictionary[idx].key, JSON(rawDictionary[idx].value)) + default: return ("", JSON.null) + } + } +} + +// MARK: - Subscript + +/** + * To mark both String and Int can be used in subscript. + */ +public enum JSONKey { + case index(Int) + case key(String) +} + +public protocol JSONSubscriptType { + var jsonKey: JSONKey { get } +} + +extension Int: JSONSubscriptType { + public var jsonKey: JSONKey { + return JSONKey.index(self) + } +} + +extension String: JSONSubscriptType { + public var jsonKey: JSONKey { + return JSONKey.key(self) + } +} + +extension JSON { + + /// If `type` is `.array`, return json whose object is `array[index]`, otherwise return null json with error. + fileprivate subscript(index index: Int) -> JSON { + get { + if type != .array { + var r = JSON.null + r.error = self.error ?? SwiftyJSONError.wrongType + return r + } else if rawArray.indices.contains(index) { + return JSON(rawArray[index]) + } else { + var r = JSON.null + r.error = SwiftyJSONError.indexOutOfBounds + return r + } + } + set { + if type == .array && + rawArray.indices.contains(index) && + newValue.error == nil { + rawArray[index] = newValue.object + } + } + } + + /// If `type` is `.dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error. + fileprivate subscript(key key: String) -> JSON { + get { + var r = JSON.null + if type == .dictionary { + if let o = rawDictionary[key] { + r = JSON(o) + } else { + r.error = SwiftyJSONError.notExist + } + } else { + r.error = self.error ?? SwiftyJSONError.wrongType + } + return r + } + set { + if type == .dictionary && newValue.error == nil { + rawDictionary[key] = newValue.object + } + } + } + + /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. + fileprivate subscript(sub sub: JSONSubscriptType) -> JSON { + get { + switch sub.jsonKey { + case .index(let index): return self[index: index] + case .key(let key): return self[key: key] + } + } + set { + switch sub.jsonKey { + case .index(let index): self[index: index] = newValue + case .key(let key): self[key: key] = newValue + } + } + } + + /** + Find a json in the complex data structures by using array of Int and/or String as path. + + Example: + + ``` + let json = JSON[data] + let path = [9,"list","person","name"] + let name = json[path] + ``` + + The same as: let name = json[9]["list"]["person"]["name"] + + - parameter path: The target json's path. + + - returns: Return a json found by the path or a null json with error + */ + public subscript(path: [JSONSubscriptType]) -> JSON { + get { + return path.reduce(self) { $0[sub: $1] } + } + set { + switch path.count { + case 0: return + case 1: self[sub:path[0]].object = newValue.object + default: + var aPath = path + aPath.remove(at: 0) + var nextJSON = self[sub: path[0]] + nextJSON[aPath] = newValue + self[sub: path[0]] = nextJSON + } + } + } + + /** + Find a json in the complex data structures by using array of Int and/or String as path. + + - parameter path: The target json's path. Example: + + let name = json[9,"list","person","name"] + + The same as: let name = json[9]["list"]["person"]["name"] + + - returns: Return a json found by the path or a null json with error + */ + public subscript(path: JSONSubscriptType...) -> JSON { + get { + return self[path] + } + set { + self[path] = newValue + } + } +} + +// MARK: - LiteralConvertible + +extension JSON: Swift.ExpressibleByStringLiteral { + + public init(stringLiteral value: StringLiteralType) { + self.init(value) + } + + public init(extendedGraphemeClusterLiteral value: StringLiteralType) { + self.init(value) + } + + public init(unicodeScalarLiteral value: StringLiteralType) { + self.init(value) + } +} + +extension JSON: Swift.ExpressibleByIntegerLiteral { + + public init(integerLiteral value: IntegerLiteralType) { + self.init(value) + } +} + +extension JSON: Swift.ExpressibleByBooleanLiteral { + + public init(booleanLiteral value: BooleanLiteralType) { + self.init(value) + } +} + +extension JSON: Swift.ExpressibleByFloatLiteral { + + public init(floatLiteral value: FloatLiteralType) { + self.init(value) + } +} + +extension JSON: Swift.ExpressibleByDictionaryLiteral { + public init(dictionaryLiteral elements: (String, Any)...) { + let dictionary = elements.reduce(into: [String: Any](), { $0[$1.0] = $1.1}) + self.init(dictionary) + } +} + +extension JSON: Swift.ExpressibleByArrayLiteral { + + public init(arrayLiteral elements: Any...) { + self.init(elements) + } +} + +// MARK: - Raw + +extension JSON: Swift.RawRepresentable { + + public init?(rawValue: Any) { + if JSON(rawValue).type == .unknown { + return nil + } else { + self.init(rawValue) + } + } + + public var rawValue: Any { + return object + } + + public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data { + guard JSONSerialization.isValidJSONObject(object) else { + throw SwiftyJSONError.invalidJSON + } + + return try JSONSerialization.data(withJSONObject: object, options: opt) + } + + public func rawString(_ encoding: String.Encoding = .utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? { + do { + return try _rawString(encoding, options: [.jsonSerialization: opt]) + } catch { + print("Could not serialize object to JSON because:", error.localizedDescription) + return nil + } + } + + public func rawString(_ options: [writingOptionsKeys: Any]) -> String? { + let encoding = options[.encoding] as? String.Encoding ?? String.Encoding.utf8 + let maxObjectDepth = options[.maxObjextDepth] as? Int ?? 10 + do { + return try _rawString(encoding, options: options, maxObjectDepth: maxObjectDepth) + } catch { + print("Could not serialize object to JSON because:", error.localizedDescription) + return nil + } + } + + fileprivate func _rawString(_ encoding: String.Encoding = .utf8, options: [writingOptionsKeys: Any], maxObjectDepth: Int = 10) throws -> String? { + guard maxObjectDepth > 0 else { throw SwiftyJSONError.invalidJSON } + switch type { + case .dictionary: + do { + if !(options[.castNilToNSNull] as? Bool ?? false) { + let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted + let data = try rawData(options: jsonOption) + return String(data: data, encoding: encoding) + } + + guard let dict = object as? [String: Any?] else { + return nil + } + let body = try dict.keys.map { key throws -> String in + guard let value = dict[key] else { + return "\"\(key)\": null" + } + guard let unwrappedValue = value else { + return "\"\(key)\": null" + } + + let nestedValue = JSON(unwrappedValue) + guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { + throw SwiftyJSONError.elementTooDeep + } + if nestedValue.type == .string { + return "\"\(key)\": \"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" + } else { + return "\"\(key)\": \(nestedString)" + } + } + + return "{\(body.joined(separator: ","))}" + } catch _ { + return nil + } + case .array: + do { + if !(options[.castNilToNSNull] as? Bool ?? false) { + let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted + let data = try rawData(options: jsonOption) + return String(data: data, encoding: encoding) + } + + guard let array = object as? [Any?] else { + return nil + } + let body = try array.map { value throws -> String in + guard let unwrappedValue = value else { + return "null" + } + + let nestedValue = JSON(unwrappedValue) + guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { + throw SwiftyJSONError.invalidJSON + } + if nestedValue.type == .string { + return "\"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" + } else { + return nestedString + } + } + + return "[\(body.joined(separator: ","))]" + } catch _ { + return nil + } + case .string: return rawString + case .number: return rawNumber.stringValue + case .bool: return rawBool.description + case .null: return "null" + default: return nil + } + } +} + +// MARK: - Printable, DebugPrintable + +extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertible { + + public var description: String { + return rawString(options: .prettyPrinted) ?? "unknown" + } + + public var debugDescription: String { + return description + } +} + +// MARK: - Array + +extension JSON { + + //Optional [JSON] + public var array: [JSON]? { + return type == .array ? rawArray.map { JSON($0) } : nil + } + + //Non-optional [JSON] + public var arrayValue: [JSON] { + return self.array ?? [] + } + + //Optional [Any] + public var arrayObject: [Any]? { + get { + switch type { + case .array: return rawArray + default: return nil + } + } + set { + self.object = newValue ?? NSNull() + } + } +} + +// MARK: - Dictionary + +extension JSON { + + //Optional [String : JSON] + public var dictionary: [String: JSON]? { + if type == .dictionary { + var d = [String: JSON](minimumCapacity: rawDictionary.count) + rawDictionary.forEach { pair in + d[pair.key] = JSON(pair.value) + } + return d + } else { + return nil + } + } + + //Non-optional [String : JSON] + public var dictionaryValue: [String: JSON] { + return dictionary ?? [:] + } + + //Optional [String : Any] + + public var dictionaryObject: [String: Any]? { + get { + switch type { + case .dictionary: return rawDictionary + default: return nil + } + } + set { + object = newValue ?? NSNull() + } + } +} + +// MARK: - Bool + +extension JSON { // : Swift.Bool + + //Optional bool + public var bool: Bool? { + get { + switch type { + case .bool: return rawBool + default: return nil + } + } + set { + object = newValue ?? NSNull() + } + } + + //Non-optional bool + public var boolValue: Bool { + get { + switch type { + case .bool: return rawBool + case .number: return rawNumber.boolValue + case .string: return ["true", "y", "t", "yes", "1"].contains { rawString.caseInsensitiveCompare($0) == .orderedSame } + default: return false + } + } + set { + object = newValue + } + } +} + +// MARK: - String + +extension JSON { + + //Optional string + public var string: String? { + get { + switch type { + case .string: return object as? String + default: return nil + } + } + set { + object = newValue ?? NSNull() + } + } + + //Non-optional string + public var stringValue: String { + get { + switch type { + case .string: return object as? String ?? "" + case .number: return rawNumber.stringValue + case .bool: return (object as? Bool).map { String($0) } ?? "" + default: return "" + } + } + set { + object = newValue + } + } +} + +// MARK: - Number + +extension JSON { + + //Optional number + public var number: NSNumber? { + get { + switch type { + case .number: return rawNumber + case .bool: return NSNumber(value: rawBool ? 1 : 0) + default: return nil + } + } + set { + object = newValue ?? NSNull() + } + } + + //Non-optional number + public var numberValue: NSNumber { + get { + switch type { + case .string: + let decimal = NSDecimalNumber(string: object as? String) + return decimal == .notANumber ? .zero : decimal + case .number: return object as? NSNumber ?? NSNumber(value: 0) + case .bool: return NSNumber(value: rawBool ? 1 : 0) + default: return NSNumber(value: 0.0) + } + } + set { + object = newValue + } + } +} + +// MARK: - Null + +extension JSON { + + public var null: NSNull? { + set { + object = NSNull() + } + get { + switch type { + case .null: return rawNull + default: return nil + } + } + } + public func exists() -> Bool { + if let errorValue = error, (400...1000).contains(errorValue.errorCode) { + return false + } + return true + } +} + +// MARK: - URL + +extension JSON { + + //Optional URL + public var url: URL? { + get { + switch type { + case .string: + // Check for existing percent escapes first to prevent double-escaping of % character + if rawString.range(of: "%[0-9A-Fa-f]{2}", options: .regularExpression, range: nil, locale: nil) != nil { + return Foundation.URL(string: rawString) + } else if let encodedString_ = rawString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) { + // We have to use `Foundation.URL` otherwise it conflicts with the variable name. + return Foundation.URL(string: encodedString_) + } else { + return nil + } + default: + return nil + } + } + set { + object = newValue?.absoluteString ?? NSNull() + } + } +} + +// MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 + +extension JSON { + + public var double: Double? { + get { + return number?.doubleValue + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var doubleValue: Double { + get { + return numberValue.doubleValue + } + set { + object = NSNumber(value: newValue) + } + } + + public var float: Float? { + get { + return number?.floatValue + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var floatValue: Float { + get { + return numberValue.floatValue + } + set { + object = NSNumber(value: newValue) + } + } + + public var int: Int? { + get { + return number?.intValue + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var intValue: Int { + get { + return numberValue.intValue + } + set { + object = NSNumber(value: newValue) + } + } + + public var uInt: UInt? { + get { + return number?.uintValue + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var uIntValue: UInt { + get { + return numberValue.uintValue + } + set { + object = NSNumber(value: newValue) + } + } + + public var int8: Int8? { + get { + return number?.int8Value + } + set { + if let newValue = newValue { + object = NSNumber(value: Int(newValue)) + } else { + object = NSNull() + } + } + } + + public var int8Value: Int8 { + get { + return numberValue.int8Value + } + set { + object = NSNumber(value: Int(newValue)) + } + } + + public var uInt8: UInt8? { + get { + return number?.uint8Value + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var uInt8Value: UInt8 { + get { + return numberValue.uint8Value + } + set { + object = NSNumber(value: newValue) + } + } + + public var int16: Int16? { + get { + return number?.int16Value + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var int16Value: Int16 { + get { + return numberValue.int16Value + } + set { + object = NSNumber(value: newValue) + } + } + + public var uInt16: UInt16? { + get { + return number?.uint16Value + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var uInt16Value: UInt16 { + get { + return numberValue.uint16Value + } + set { + object = NSNumber(value: newValue) + } + } + + public var int32: Int32? { + get { + return number?.int32Value + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var int32Value: Int32 { + get { + return numberValue.int32Value + } + set { + object = NSNumber(value: newValue) + } + } + + public var uInt32: UInt32? { + get { + return number?.uint32Value + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var uInt32Value: UInt32 { + get { + return numberValue.uint32Value + } + set { + object = NSNumber(value: newValue) + } + } + + public var int64: Int64? { + get { + return number?.int64Value + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var int64Value: Int64 { + get { + return numberValue.int64Value + } + set { + object = NSNumber(value: newValue) + } + } + + public var uInt64: UInt64? { + get { + return number?.uint64Value + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var uInt64Value: UInt64 { + get { + return numberValue.uint64Value + } + set { + object = NSNumber(value: newValue) + } + } +} + +// MARK: - Comparable + +extension JSON: Swift.Comparable {} + +public func == (lhs: JSON, rhs: JSON) -> Bool { + + switch (lhs.type, rhs.type) { + case (.number, .number): return lhs.rawNumber == rhs.rawNumber + case (.string, .string): return lhs.rawString == rhs.rawString + case (.bool, .bool): return lhs.rawBool == rhs.rawBool + case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray + case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary + case (.null, .null): return true + default: return false + } +} + +public func <= (lhs: JSON, rhs: JSON) -> Bool { + + switch (lhs.type, rhs.type) { + case (.number, .number): return lhs.rawNumber <= rhs.rawNumber + case (.string, .string): return lhs.rawString <= rhs.rawString + case (.bool, .bool): return lhs.rawBool == rhs.rawBool + case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray + case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary + case (.null, .null): return true + default: return false + } +} + +public func >= (lhs: JSON, rhs: JSON) -> Bool { + + switch (lhs.type, rhs.type) { + case (.number, .number): return lhs.rawNumber >= rhs.rawNumber + case (.string, .string): return lhs.rawString >= rhs.rawString + case (.bool, .bool): return lhs.rawBool == rhs.rawBool + case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray + case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary + case (.null, .null): return true + default: return false + } +} + +public func > (lhs: JSON, rhs: JSON) -> Bool { + + switch (lhs.type, rhs.type) { + case (.number, .number): return lhs.rawNumber > rhs.rawNumber + case (.string, .string): return lhs.rawString > rhs.rawString + default: return false + } +} + +public func < (lhs: JSON, rhs: JSON) -> Bool { + + switch (lhs.type, rhs.type) { + case (.number, .number): return lhs.rawNumber < rhs.rawNumber + case (.string, .string): return lhs.rawString < rhs.rawString + default: return false + } +} + +private let trueNumber = NSNumber(value: true) +private let falseNumber = NSNumber(value: false) +private let trueObjCType = String(cString: trueNumber.objCType) +private let falseObjCType = String(cString: falseNumber.objCType) + +// MARK: - NSNumber: Comparable + +extension NSNumber { + fileprivate var isBool: Bool { + let objCType = String(cString: self.objCType) + if (self.compare(trueNumber) == .orderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == .orderedSame && objCType == falseObjCType) { + return true + } else { + return false + } + } +} + +func == (lhs: NSNumber, rhs: NSNumber) -> Bool { + switch (lhs.isBool, rhs.isBool) { + case (false, true): return false + case (true, false): return false + default: return lhs.compare(rhs) == .orderedSame + } +} + +func != (lhs: NSNumber, rhs: NSNumber) -> Bool { + return !(lhs == rhs) +} + +func < (lhs: NSNumber, rhs: NSNumber) -> Bool { + + switch (lhs.isBool, rhs.isBool) { + case (false, true): return false + case (true, false): return false + default: return lhs.compare(rhs) == .orderedAscending + } +} + +func > (lhs: NSNumber, rhs: NSNumber) -> Bool { + + switch (lhs.isBool, rhs.isBool) { + case (false, true): return false + case (true, false): return false + default: return lhs.compare(rhs) == ComparisonResult.orderedDescending + } +} + +func <= (lhs: NSNumber, rhs: NSNumber) -> Bool { + + switch (lhs.isBool, rhs.isBool) { + case (false, true): return false + case (true, false): return false + default: return lhs.compare(rhs) != .orderedDescending + } +} + +func >= (lhs: NSNumber, rhs: NSNumber) -> Bool { + + switch (lhs.isBool, rhs.isBool) { + case (false, true): return false + case (true, false): return false + default: return lhs.compare(rhs) != .orderedAscending + } +} + +public enum writingOptionsKeys { + case jsonSerialization + case castNilToNSNull + case maxObjextDepth + case encoding +} + +// MARK: - JSON: Codable +extension JSON: Codable { + private static var codableTypes: [Codable.Type] { + return [ + Bool.self, + Int.self, + Int8.self, + Int16.self, + Int32.self, + Int64.self, + UInt.self, + UInt8.self, + UInt16.self, + UInt32.self, + UInt64.self, + Double.self, + String.self, + [JSON].self, + [String: JSON].self + ] + } + public init(from decoder: Decoder) throws { + var object: Any? + + if let container = try? decoder.singleValueContainer(), !container.decodeNil() { + for type in JSON.codableTypes { + if object != nil { + break + } + // try to decode value + switch type { + case let boolType as Bool.Type: + object = try? container.decode(boolType) + case let intType as Int.Type: + object = try? container.decode(intType) + case let int8Type as Int8.Type: + object = try? container.decode(int8Type) + case let int32Type as Int32.Type: + object = try? container.decode(int32Type) + case let int64Type as Int64.Type: + object = try? container.decode(int64Type) + case let uintType as UInt.Type: + object = try? container.decode(uintType) + case let uint8Type as UInt8.Type: + object = try? container.decode(uint8Type) + case let uint16Type as UInt16.Type: + object = try? container.decode(uint16Type) + case let uint32Type as UInt32.Type: + object = try? container.decode(uint32Type) + case let uint64Type as UInt64.Type: + object = try? container.decode(uint64Type) + case let doubleType as Double.Type: + object = try? container.decode(doubleType) + case let stringType as String.Type: + object = try? container.decode(stringType) + case let jsonValueArrayType as [JSON].Type: + object = try? container.decode(jsonValueArrayType) + case let jsonValueDictType as [String: JSON].Type: + object = try? container.decode(jsonValueDictType) + default: + break + } + } + } + self.init(object ?? NSNull()) + } + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + if object is NSNull { + try container.encodeNil() + return + } + switch object { + case let intValue as Int: + try container.encode(intValue) + case let int8Value as Int8: + try container.encode(int8Value) + case let int32Value as Int32: + try container.encode(int32Value) + case let int64Value as Int64: + try container.encode(int64Value) + case let uintValue as UInt: + try container.encode(uintValue) + case let uint8Value as UInt8: + try container.encode(uint8Value) + case let uint16Value as UInt16: + try container.encode(uint16Value) + case let uint32Value as UInt32: + try container.encode(uint32Value) + case let uint64Value as UInt64: + try container.encode(uint64Value) + case let doubleValue as Double: + try container.encode(doubleValue) + case let boolValue as Bool: + try container.encode(boolValue) + case let stringValue as String: + try container.encode(stringValue) + case is [Any]: + let jsonValueArray = array ?? [] + try container.encode(jsonValueArray) + case is [String: Any]: + let jsonValueDictValue = dictionary ?? [:] + try container.encode(jsonValueDictValue) + default: + break + } + } +} diff --git a/WWCodeDFW/Pods/Target Support Files/Alamofire/Alamofire-Info.plist b/WWCodeDFW/Pods/Target Support Files/Alamofire/Alamofire-Info.plist new file mode 100644 index 0000000..e2771ff --- /dev/null +++ b/WWCodeDFW/Pods/Target Support Files/Alamofire/Alamofire-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 5.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/WWCodeDFW/Pods/Target Support Files/Alamofire/Alamofire.xcconfig b/WWCodeDFW/Pods/Target Support Files/Alamofire/Alamofire.xcconfig index 27b9863..d95b883 100644 --- a/WWCodeDFW/Pods/Target Support Files/Alamofire/Alamofire.xcconfig +++ b/WWCodeDFW/Pods/Target Support Files/Alamofire/Alamofire.xcconfig @@ -1,9 +1,9 @@ -CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/Alamofire +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Alamofire GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/SwiftLint" -OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" -PODS_BUILD_DIR = $BUILD_DIR -PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +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) PODS_ROOT = ${SRCROOT} PODS_TARGET_SRCROOT = ${PODS_ROOT}/Alamofire PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} diff --git a/WWCodeDFW/Pods/Target Support Files/Pods-WWCodeDFW/Pods-WWCodeDFW-Info.plist b/WWCodeDFW/Pods/Target Support Files/Pods-WWCodeDFW/Pods-WWCodeDFW-Info.plist new file mode 100644 index 0000000..2243fe6 --- /dev/null +++ b/WWCodeDFW/Pods/Target Support Files/Pods-WWCodeDFW/Pods-WWCodeDFW-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/WWCodeDFW/Pods/Target Support Files/Pods-WWCodeDFW/Pods-WWCodeDFW-acknowledgements.markdown b/WWCodeDFW/Pods/Target Support Files/Pods-WWCodeDFW/Pods-WWCodeDFW-acknowledgements.markdown index 91ac19a..316e80e 100644 --- a/WWCodeDFW/Pods/Target Support Files/Pods-WWCodeDFW/Pods-WWCodeDFW-acknowledgements.markdown +++ b/WWCodeDFW/Pods/Target Support Files/Pods-WWCodeDFW/Pods-WWCodeDFW-acknowledgements.markdown @@ -3,7 +3,7 @@ This application makes use of the following third party libraries: ## Alamofire -Copyright (c) 2014-2017 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 @@ -76,7 +76,7 @@ SOFTWARE. The MIT License (MIT) -Copyright (c) 2016 Ruoyu Fu +Copyright (c) 2017 Ruoyu Fu 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/WWCodeDFW/Pods/Target Support Files/Pods-WWCodeDFW/Pods-WWCodeDFW-acknowledgements.plist b/WWCodeDFW/Pods/Target Support Files/Pods-WWCodeDFW/Pods-WWCodeDFW-acknowledgements.plist index 0de2ee4..1c5fbab 100644 --- a/WWCodeDFW/Pods/Target Support Files/Pods-WWCodeDFW/Pods-WWCodeDFW-acknowledgements.plist +++ b/WWCodeDFW/Pods/Target Support Files/Pods-WWCodeDFW/Pods-WWCodeDFW-acknowledgements.plist @@ -14,7 +14,7 @@ FooterText - Copyright (c) 2014-2017 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 @@ -105,7 +105,7 @@ SOFTWARE. FooterText The MIT License (MIT) -Copyright (c) 2016 Ruoyu Fu +Copyright (c) 2017 Ruoyu Fu 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/WWCodeDFW/Pods/Target Support Files/Pods-WWCodeDFW/Pods-WWCodeDFW-frameworks.sh b/WWCodeDFW/Pods/Target Support Files/Pods-WWCodeDFW/Pods-WWCodeDFW-frameworks.sh index 8613e35..b28f7d0 100755 --- a/WWCodeDFW/Pods/Target Support Files/Pods-WWCodeDFW/Pods-WWCodeDFW-frameworks.sh +++ b/WWCodeDFW/Pods/Target Support Files/Pods-WWCodeDFW/Pods-WWCodeDFW-frameworks.sh @@ -1,15 +1,33 @@ #!/bin/sh set -e +set -u +set -o pipefail + +function on_error { + echo "$(realpath -mq "${0}"):$1: error: Unexpected failure" +} +trap 'on_error $LINENO' ERR + +if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then + # If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy + # frameworks to, so exit 0 (signalling the script phase was successful). + exit 0 +fi echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" +COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" +# Used as a return value for each invocation of `strip_invalid_archs` function. +STRIP_BINARY_RETVAL=0 + # This protects against multiple targets copying the same framework dependency at the same time. The solution # was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") +# Copies and strips a vendored framework install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then @@ -23,8 +41,8 @@ install_framework() local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" if [ -L "${source}" ]; then - echo "Symlinked..." - source="$(readlink "${source}")" + echo "Symlinked..." + source="$(readlink "${source}")" fi # Use filter instead of exclude so missing patterns don't throw errors. @@ -34,8 +52,13 @@ install_framework() local basename basename="$(basename -s .framework "$1")" binary="${destination}/${basename}.framework/${basename}" + if ! [ -r "$binary" ]; then binary="${destination}/${basename}" + elif [ -L "${binary}" ]; then + echo "Destination binary is symlinked..." + dirname="$(dirname "${binary}")" + binary="${dirname}/$(readlink "${binary}")" fi # Strip invalid architectures so "fat" simulator / device frameworks work on device @@ -49,7 +72,7 @@ install_framework() # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then local swift_runtime_libs - swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) + swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u) for lib in $swift_runtime_libs; do echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" @@ -58,21 +81,48 @@ install_framework() fi } -# Copies the dSYM of a vendored framework +# Copies and strips a vendored dSYM install_dsym() { local source="$1" if [ -r "$source" ]; then - echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DWARF_DSYM_FOLDER_PATH}\"" - rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DWARF_DSYM_FOLDER_PATH}" + # Copy the dSYM into a the targets temp dir. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" + + local basename + basename="$(basename -s .framework.dSYM "$source")" + binary="${DERIVED_FILES_DIR}/${basename}.framework.dSYM/Contents/Resources/DWARF/${basename}" + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"Mach-O "*"dSYM companion"* ]]; then + strip_invalid_archs "$binary" + fi + + if [[ $STRIP_BINARY_RETVAL == 1 ]]; then + # Move the stripped file into its final destination. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.framework.dSYM" "${DWARF_DSYM_FOLDER_PATH}" + else + # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. + touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.framework.dSYM" + fi fi } +# Copies the bcsymbolmap files of a vendored framework +install_bcsymbolmap() { + local bcsymbolmap_path="$1" + local destination="${BUILT_PRODUCTS_DIR}" + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}" +} + # Signs a framework with the provided identity code_sign_if_enabled() { - if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then - # Use the current code_sign_identitiy + if [ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then + # Use the current code_sign_identity echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" - local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements '$1'" + local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'" if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then code_sign_cmd="$code_sign_cmd &" @@ -85,19 +135,28 @@ code_sign_if_enabled() { # Strip invalid architectures strip_invalid_archs() { binary="$1" - # Get architectures for current file - archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)" + # Get architectures for current target binary + binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" + # Intersect them with the architectures we are building for + intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" + # If there are no archs supported by this binary then warn the user + if [[ -z "$intersected_archs" ]]; then + echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." + STRIP_BINARY_RETVAL=0 + return + fi stripped="" - for arch in $archs; do + for arch in $binary_archs; do if ! [[ "${ARCHS}" == *"$arch"* ]]; then # Strip non-valid architectures in-place - lipo -remove "$arch" -output "$binary" "$binary" || exit 1 + lipo -remove "$arch" -output "$binary" "$binary" stripped="$stripped $arch" fi done if [[ "$stripped" ]]; then echo "Stripped $binary of architectures:$stripped" fi + STRIP_BINARY_RETVAL=1 } diff --git a/WWCodeDFW/Pods/Target Support Files/Pods-WWCodeDFW/Pods-WWCodeDFW.debug.xcconfig b/WWCodeDFW/Pods/Target Support Files/Pods-WWCodeDFW/Pods-WWCodeDFW.debug.xcconfig index f6d4fcb..84a2647 100644 --- a/WWCodeDFW/Pods/Target Support Files/Pods-WWCodeDFW/Pods-WWCodeDFW.debug.xcconfig +++ b/WWCodeDFW/Pods/Target Support Files/Pods-WWCodeDFW/Pods-WWCodeDFW.debug.xcconfig @@ -1,12 +1,11 @@ ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES -FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/SnapKit" "$PODS_CONFIGURATION_BUILD_DIR/SwiftyJSON" +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/SnapKit" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftyJSON" GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/SwiftLint" +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SnapKit/SnapKit.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftyJSON/SwiftyJSON.framework/Headers" LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' -OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/SnapKit/SnapKit.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/SwiftyJSON/SwiftyJSON.framework/Headers" -isystem "${PODS_ROOT}/Headers/Public" -isystem "${PODS_ROOT}/Headers/Public/SwiftLint" -OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "SnapKit" -framework "SwiftyJSON" -OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" -PODS_BUILD_DIR = $BUILD_DIR -PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "SnapKit" -framework "SwiftyJSON" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_PODFILE_DIR_PATH = ${SRCROOT}/. PODS_ROOT = ${SRCROOT}/Pods diff --git a/WWCodeDFW/Pods/Target Support Files/Pods-WWCodeDFW/Pods-WWCodeDFW.release.xcconfig b/WWCodeDFW/Pods/Target Support Files/Pods-WWCodeDFW/Pods-WWCodeDFW.release.xcconfig index f6d4fcb..84a2647 100644 --- a/WWCodeDFW/Pods/Target Support Files/Pods-WWCodeDFW/Pods-WWCodeDFW.release.xcconfig +++ b/WWCodeDFW/Pods/Target Support Files/Pods-WWCodeDFW/Pods-WWCodeDFW.release.xcconfig @@ -1,12 +1,11 @@ ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES -FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/SnapKit" "$PODS_CONFIGURATION_BUILD_DIR/SwiftyJSON" +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/SnapKit" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftyJSON" GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/SwiftLint" +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SnapKit/SnapKit.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftyJSON/SwiftyJSON.framework/Headers" LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' -OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/SnapKit/SnapKit.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/SwiftyJSON/SwiftyJSON.framework/Headers" -isystem "${PODS_ROOT}/Headers/Public" -isystem "${PODS_ROOT}/Headers/Public/SwiftLint" -OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "SnapKit" -framework "SwiftyJSON" -OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" -PODS_BUILD_DIR = $BUILD_DIR -PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "SnapKit" -framework "SwiftyJSON" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_PODFILE_DIR_PATH = ${SRCROOT}/. PODS_ROOT = ${SRCROOT}/Pods diff --git a/WWCodeDFW/Pods/Target Support Files/SnapKit/SnapKit-Info.plist b/WWCodeDFW/Pods/Target Support Files/SnapKit/SnapKit-Info.plist new file mode 100644 index 0000000..8d87a1a --- /dev/null +++ b/WWCodeDFW/Pods/Target Support Files/SnapKit/SnapKit-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 5.0.1 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/WWCodeDFW/Pods/Target Support Files/SnapKit/SnapKit.xcconfig b/WWCodeDFW/Pods/Target Support Files/SnapKit/SnapKit.xcconfig index 2502a0a..5ba2657 100644 --- a/WWCodeDFW/Pods/Target Support Files/SnapKit/SnapKit.xcconfig +++ b/WWCodeDFW/Pods/Target Support Files/SnapKit/SnapKit.xcconfig @@ -1,9 +1,8 @@ -CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/SnapKit +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/SnapKit GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/SwiftLint" -OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" -PODS_BUILD_DIR = $BUILD_DIR -PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_ROOT = ${SRCROOT} PODS_TARGET_SRCROOT = ${PODS_ROOT}/SnapKit PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} diff --git a/WWCodeDFW/Pods/Target Support Files/SwiftLint/SwiftLint.xcconfig b/WWCodeDFW/Pods/Target Support Files/SwiftLint/SwiftLint.xcconfig new file mode 100644 index 0000000..00f22eb --- /dev/null +++ b/WWCodeDFW/Pods/Target Support Files/SwiftLint/SwiftLint.xcconfig @@ -0,0 +1,8 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/SwiftLint +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/SwiftLint +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/WWCodeDFW/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-Info.plist b/WWCodeDFW/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-Info.plist new file mode 100644 index 0000000..e2771ff --- /dev/null +++ b/WWCodeDFW/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 5.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/WWCodeDFW/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.xcconfig b/WWCodeDFW/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.xcconfig index de7d977..9abafa2 100644 --- a/WWCodeDFW/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.xcconfig +++ b/WWCodeDFW/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.xcconfig @@ -1,11 +1,9 @@ -CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/SwiftyJSON +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/SwiftyJSON GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/SwiftLint" -OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" -PODS_BUILD_DIR = $BUILD_DIR -PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_ROOT = ${SRCROOT} PODS_TARGET_SRCROOT = ${PODS_ROOT}/SwiftyJSON PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} SKIP_INSTALL = YES -SWIFT_VERSION = 3.0 diff --git a/WWCodeDFW/WWCodeDFW.xcodeproj/project.pbxproj b/WWCodeDFW/WWCodeDFW.xcodeproj/project.pbxproj index 3b69bd4..1864968 100644 --- a/WWCodeDFW/WWCodeDFW.xcodeproj/project.pbxproj +++ b/WWCodeDFW/WWCodeDFW.xcodeproj/project.pbxproj @@ -258,7 +258,6 @@ 6E7B99E11F8BA636006A5343 /* Frameworks */, 6E7B99E21F8BA636006A5343 /* Resources */, 11A4C475C8D8673C3D9C531C /* [CP] Embed Pods Frameworks */, - 28C5FE35F8C996A2B15DD9CE /* [CP] Copy Pods Resources */, 6E7B9A151F8BAFF0006A5343 /* ShellScript */, ); buildRules = ( @@ -337,6 +336,7 @@ developmentRegion = English; hasScannedForEncodings = 0; knownRegions = ( + English, en, Base, ); @@ -390,7 +390,7 @@ files = ( ); inputPaths = ( - "${SRCROOT}/Pods/Target Support Files/Pods-WWCodeDFW/Pods-WWCodeDFW-frameworks.sh", + "${PODS_ROOT}/Target Support Files/Pods-WWCodeDFW/Pods-WWCodeDFW-frameworks.sh", "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework", "${BUILT_PRODUCTS_DIR}/SnapKit/SnapKit.framework", "${BUILT_PRODUCTS_DIR}/SwiftyJSON/SwiftyJSON.framework", @@ -403,22 +403,7 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-WWCodeDFW/Pods-WWCodeDFW-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; - 28C5FE35F8C996A2B15DD9CE /* [CP] Copy Pods Resources */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - ); - name = "[CP] Copy Pods Resources"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-WWCodeDFW/Pods-WWCodeDFW-resources.sh\"\n"; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-WWCodeDFW/Pods-WWCodeDFW-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; 6E7B9A151F8BAFF0006A5343 /* ShellScript */ = { @@ -635,7 +620,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = WWC.WWCodeDFW; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 3.0; + SWIFT_VERSION = 5.0; }; name = Debug; }; @@ -649,7 +634,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = WWC.WWCodeDFW; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 3.0; + SWIFT_VERSION = 5.0; }; name = Release; }; diff --git a/WWCodeDFW/WWCodeDFW.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/WWCodeDFW/WWCodeDFW.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/WWCodeDFW/WWCodeDFW.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/WWCodeDFW/WWCodeDFW/ApiService.swift b/WWCodeDFW/WWCodeDFW/ApiService.swift index 19efcec..0d445e6 100644 --- a/WWCodeDFW/WWCodeDFW/ApiService.swift +++ b/WWCodeDFW/WWCodeDFW/ApiService.swift @@ -12,30 +12,10 @@ import Alamofire enum ApiServiceError: Error { case modelParsingError case invalidResourceError + case failureRequestError } -enum ApiResult { - case success(T) - case failure(Error) - - var value: T? { - switch self { - case .success(let value): - return value - case .failure: - return nil - } - } - - var error: Error? { - switch self { - case .success: - return nil - case .failure(let error): - return error - } - } -} +typealias ApiResult = Result protocol Resource { /// HTTP Method the API request will use @@ -61,13 +41,14 @@ class ApiService: ApiServicing { switch response.result { case .success(let data): if let model = resource.parse(responseData: data) { - responseHandler(ApiResult.success(model)) + responseHandler(.success(model)) } else { print("[ApiService] Resource failed to parse model: \(resource)") - responseHandler(ApiResult.failure(ApiServiceError.modelParsingError)) + responseHandler(.failure(ApiServiceError.modelParsingError)) } case .failure(let error): - responseHandler(ApiResult.failure(error)) + print("[ApiService] Request has been failed due to: ", error.localizedDescription) + responseHandler(.failure(ApiServiceError.failureRequestError)) } } } @@ -75,7 +56,7 @@ class ApiService: ApiServicing { // MARK: Helpers private func request(for resource: Resource) -> DataRequest { - return Alamofire.request(resource.url, + return AF.request(resource.url, method: resource.method, parameters: nil, encoding: parameterEncoding(for: resource), diff --git a/WWCodeDFW/WWCodeDFW/AppDelegate.swift b/WWCodeDFW/WWCodeDFW/AppDelegate.swift index 87a609b..47a2a23 100644 --- a/WWCodeDFW/WWCodeDFW/AppDelegate.swift +++ b/WWCodeDFW/WWCodeDFW/AppDelegate.swift @@ -13,7 +13,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? - func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. //set global tab bar tint color diff --git a/WWCodeDFW/WWCodeDFW/MediumPost.swift b/WWCodeDFW/WWCodeDFW/MediumPost.swift index 28fe309..f434d86 100644 --- a/WWCodeDFW/WWCodeDFW/MediumPost.swift +++ b/WWCodeDFW/WWCodeDFW/MediumPost.swift @@ -30,7 +30,7 @@ class MediumPost: Model { self.createdAt = Date(timeIntervalSince1970: createdAt) self.author = author self.paragraphs = (json["value"]["content"]["bodyModel"]["paragraphs"].array ?? []) - .flatMap { MediumPostParagraph(json: $0) } + .compactMap { MediumPostParagraph(json: $0) } } } diff --git a/WWCodeDFW/WWCodeDFW/MediumPostCollection.swift b/WWCodeDFW/WWCodeDFW/MediumPostCollection.swift index 6c4a98d..0473938 100644 --- a/WWCodeDFW/WWCodeDFW/MediumPostCollection.swift +++ b/WWCodeDFW/WWCodeDFW/MediumPostCollection.swift @@ -15,8 +15,8 @@ class MediumPostCollection: Model { required init?(json: JSON) { guard let parser = MediumPostCollectionParser(json: json) else { return nil } - - self.postPreviews = parser.postPreviewsJson.flatMap { MediumPostPreview(json: $0) } + + self.postPreviews = parser.postPreviewsJson.compactMap { MediumPostPreview(json: $0) } self.pagingInformation = parser.pagingJson } } diff --git a/WWCodeDFW/WWCodeDFW/MediumPostCollectionParser.swift b/WWCodeDFW/WWCodeDFW/MediumPostCollectionParser.swift index b926369..3b4e11d 100644 --- a/WWCodeDFW/WWCodeDFW/MediumPostCollectionParser.swift +++ b/WWCodeDFW/WWCodeDFW/MediumPostCollectionParser.swift @@ -19,7 +19,7 @@ class MediumPostCollectionParser { let postsArray = postsJson let pagingJson = json["paging"] - let postPreviewsJson = postsArray.flatMap { (postJson) -> JSON? in + let postPreviewsJson = postsArray.compactMap { (postJson) -> JSON? in guard let authorId = postJson["creatorId"].string else { return nil } var json = postJson diff --git a/WWCodeDFW/WWCodeDFW/MediumService.swift b/WWCodeDFW/WWCodeDFW/MediumService.swift index 3735934..94cd1bb 100644 --- a/WWCodeDFW/WWCodeDFW/MediumService.swift +++ b/WWCodeDFW/WWCodeDFW/MediumService.swift @@ -60,7 +60,7 @@ enum MediumResource: Resource { // strip security json prefix from Medium's json response let strippedString = string.replacingOccurrences(of: "])}while(1);", with: "") if let strippedData = strippedString.data(using: .utf8) { - return JSON(data: strippedData) + return try? JSON(data: strippedData) } return nil @@ -74,17 +74,18 @@ class MediumService { * json fixtures stored on disk instead of actually make a request to Medium's API * (ex: let service = MediumService(apiService: MediumService.OfflineTestingApiService())) */ - class OfflineTestingApiService: ApiServicing { + class OfflineTestingApiService: ApiServicing { + func load(resource: Resource, responseHandler: @escaping (ApiResult) -> Void) { guard let mediumResource = resource as? MediumResource else { assertionFailure("[OfflineTestingApiService] Requires parameterized resource to be of type MediumResource") - responseHandler(ApiResult.failure(ApiServiceError.invalidResourceError)) + responseHandler(.failure(ApiServiceError.invalidResourceError)) return } if let model = mockModel(for: mediumResource) { - responseHandler(ApiResult.success(model)) + responseHandler(.success(model)) } else { - responseHandler(ApiResult.failure(ApiServiceError.modelParsingError)) + responseHandler(.failure(ApiServiceError.modelParsingError)) } } diff --git a/WWCodeDFW/WWCodeDFW/UIViewControllerExtensions.swift b/WWCodeDFW/WWCodeDFW/UIViewControllerExtensions.swift index 0210722..c9bd6e3 100644 --- a/WWCodeDFW/WWCodeDFW/UIViewControllerExtensions.swift +++ b/WWCodeDFW/WWCodeDFW/UIViewControllerExtensions.swift @@ -20,7 +20,7 @@ extension UIViewController { self.navigationItem.rightBarButtonItem = rightButton } - func donate() { + @objc func donate() { let donateVC = DonationsViewController() donateVC.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(donateVC, animated: true)