From 7a7249b80f3a90b8dd3a706d3cdc9251e73f18fb Mon Sep 17 00:00:00 2001 From: Charlie Qiu Date: Sun, 2 Oct 2016 01:17:07 +0800 Subject: [PATCH] Update for swift 3. - Convert code to swift 3 - Update alamofire to 4.0.1 for swift 3. --- Podfile | 2 +- Podfile.lock | 8 +- Pods/Alamofire/README.md | 2022 ++++++++++------- Pods/Alamofire/Source/AFError.swift | 450 ++++ Pods/Alamofire/Source/Alamofire.swift | 676 +++--- .../Source/DispatchQueue+Alamofire.swift | 43 + Pods/Alamofire/Source/Download.swift | 248 -- Pods/Alamofire/Source/Error.swift | 88 - Pods/Alamofire/Source/Manager.swift | 755 ------ Pods/Alamofire/Source/MultipartFormData.swift | 632 +++--- .../Source/NetworkReachabilityManager.swift | 171 +- Pods/Alamofire/Source/Notifications.swift | 35 +- Pods/Alamofire/Source/ParameterEncoding.swift | 512 +++-- Pods/Alamofire/Source/Request.swift | 870 +++---- Pods/Alamofire/Source/Response.swift | 259 ++- .../Source/ResponseSerialization.swift | 772 +++++-- Pods/Alamofire/Source/Result.swift | 43 +- Pods/Alamofire/Source/ServerTrustPolicy.swift | 241 +- Pods/Alamofire/Source/SessionDelegate.swift | 681 ++++++ Pods/Alamofire/Source/SessionManager.swift | 776 +++++++ Pods/Alamofire/Source/Stream.swift | 182 -- Pods/Alamofire/Source/TaskDelegate.swift | 449 ++++ Pods/Alamofire/Source/Timeline.swift | 75 +- Pods/Alamofire/Source/Upload.swift | 376 --- Pods/Alamofire/Source/Validation.swift | 383 ++-- Pods/Manifest.lock | 8 +- Pods/Pods.xcodeproj/project.pbxproj | 490 ++-- .../Target Support Files/Alamofire/Info.plist | 40 +- .../GCDWebServer/Info.plist | 40 +- ShadowsocksX-NG.xcodeproj/project.pbxproj | 10 +- .../AdvPreferencesWindowController.swift | 6 +- ShadowsocksX-NG/AppDelegate.swift | 170 +- ShadowsocksX-NG/LaunchAgentUtils.swift | 58 +- ShadowsocksX-NG/PACUtils.swift | 92 +- .../PreferencesWindowController.swift | 114 +- .../ProxyPreferencesController.swift | 46 +- ShadowsocksX-NG/ServerProfile.swift | 54 +- ShadowsocksX-NG/ServerProfileManager.swift | 24 +- ShadowsocksX-NG/UserRulesController.swift | 24 +- ShadowsocksX-NG/Utils.swift | 12 +- .../ShadowsocksX_NGTests.swift | 2 +- 41 files changed, 6976 insertions(+), 4963 deletions(-) create mode 100644 Pods/Alamofire/Source/AFError.swift create mode 100644 Pods/Alamofire/Source/DispatchQueue+Alamofire.swift delete mode 100644 Pods/Alamofire/Source/Download.swift delete mode 100644 Pods/Alamofire/Source/Error.swift delete mode 100644 Pods/Alamofire/Source/Manager.swift create mode 100644 Pods/Alamofire/Source/SessionDelegate.swift create mode 100644 Pods/Alamofire/Source/SessionManager.swift delete mode 100644 Pods/Alamofire/Source/Stream.swift create mode 100644 Pods/Alamofire/Source/TaskDelegate.swift delete mode 100644 Pods/Alamofire/Source/Upload.swift diff --git a/Podfile b/Podfile index 187975a..58e3edb 100644 --- a/Podfile +++ b/Podfile @@ -6,7 +6,7 @@ target 'ShadowsocksX-NG' do use_frameworks! # Pods for ShadowsocksX-NG - pod 'Alamofire', '~> 3.4' + pod 'Alamofire', '~> 4.0.1' pod "GCDWebServer", "~> 3.0" target 'ShadowsocksX-NGTests' do diff --git a/Podfile.lock b/Podfile.lock index 96580b2..d1abbe2 100644 --- a/Podfile.lock +++ b/Podfile.lock @@ -1,20 +1,20 @@ PODS: - - Alamofire (3.4.0) + - Alamofire (4.0.1) - BRLOptionParser (0.3.1) - GCDWebServer (3.3.3): - GCDWebServer/Core (= 3.3.3) - GCDWebServer/Core (3.3.3) DEPENDENCIES: - - Alamofire (~> 3.4) + - Alamofire (~> 4.0.1) - BRLOptionParser (~> 0.3.1) - GCDWebServer (~> 3.0) SPEC CHECKSUMS: - Alamofire: c19a627cefd6a95f840401c49ab1f124e07f54ee + Alamofire: 7682d43245de14874acd142ec137b144aa1dd335 BRLOptionParser: a03256a8ff003ca1f5376c55f55f210e085a3958 GCDWebServer: 1c39a1f0763e4eb492bee021e4270fce097d3555 -PODFILE CHECKSUM: 038d7dc431157cfa86a2856ee236c4ed1ddfd26b +PODFILE CHECKSUM: e675030dbd86de38216dc6c44e64ca1458be94bc COCOAPODS: 1.0.1 diff --git a/Pods/Alamofire/README.md b/Pods/Alamofire/README.md index 68e54e9..bfaed03 100644 --- a/Pods/Alamofire/README.md +++ b/Pods/Alamofire/README.md @@ -1,6 +1,6 @@ ![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/assets/alamofire.png) -[![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg)](https://travis-ci.org/Alamofire/Alamofire) +[![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg?branch=master)](https://travis-ci.org/Alamofire/Alamofire) [![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)](http://cocoadocs.org/docsets/Alamofire) @@ -8,34 +8,60 @@ Alamofire is an HTTP networking library written in Swift. +- [Features](#features) +- [Component Libraries](#component-libraries) +- [Requirements](#requirements) +- [Migration Guides](#migration-guides) +- [Communication](#communication) +- [Installation](#installation) +- [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) +- [Open Radars](#open-radars) +- [FAQ](#faq) +- [Credits](#credits) +- [Donations](#donations) +- [License](#license) + ## Features -- [x] Chainable Request / Response methods +- [x] Chainable Request / Response Methods - [x] URL / JSON / plist Parameter Encoding - [x] Upload File / Data / Stream / MultipartFormData -- [x] Download using Request or Resume data -- [x] Authentication with NSURLCredential +- [x] Download File using Request or Resume Data +- [x] Authentication with URLCredential - [x] HTTP Response Validation +- [x] Upload and Download Progress Closures with Progress +- [x] cURL Command Output +- [x] Dynamically Adapt and Retry Requests - [x] TLS Certificate and Public Key Pinning -- [x] Progress Closure & NSProgress -- [x] cURL Debug Output -- [x] Comprehensive Unit Test Coverage +- [x] Network Reachability +- [x] Comprehensive Unit and Integration Test Coverage - [x] [Complete Documentation](http://cocoadocs.org/docsets/Alamofire) ## Component Libraries In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem. -* [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system. -* [AlamofireNetworkActivityIndicator](https://github.com/Alamofire/AlamofireNetworkActivityIndicator) - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support `NSURLSession` instances not managed by Alamofire. +- [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system. +- [AlamofireNetworkActivityIndicator](https://github.com/Alamofire/AlamofireNetworkActivityIndicator) - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support `URLSession` instances not managed by Alamofire. ## Requirements -- iOS 8.0+ / Mac OS X 10.9+ / tvOS 9.0+ / watchOS 2.0+ -- Xcode 7.3+ +- iOS 9.0+ / macOS 10.11+ / tvOS 9.0+ / watchOS 2.0+ +- Xcode 8.0+ +- Swift 3.0+ ## Migration Guides +- [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) @@ -49,10 +75,6 @@ In order to keep Alamofire focused specifically on core networking implementatio ## Installation -> **Embedded frameworks require a minimum deployment target of iOS 8 or OS X Mavericks (10.9).** -> -> Alamofire is no longer supported on iOS 7 due to the lack of support for frameworks. Without frameworks, running Travis-CI against iOS 7 would require a second duplicated test target. The separate test suite would need to import all the Swift files and the tests would need to be duplicated and re-written. This split would be too difficult to maintain to ensure the highest possible quality of the Alamofire ecosystem. - ### CocoaPods [CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command: @@ -61,16 +83,18 @@ In order to keep Alamofire focused specifically on core networking implementatio $ gem install cocoapods ``` -> CocoaPods 0.39.0+ is required to build Alamofire 3.0.0+. +> CocoaPods 1.1.0+ is required to build Alamofire 4.0.0+. To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`: ```ruby source 'https://github.com/CocoaPods/Specs.git' -platform :ios, '9.0' +platform :ios, '10.0' use_frameworks! -pod 'Alamofire', '~> 3.4' +target '' do + pod 'Alamofire', '~> 4.0' +end ``` Then, run the following command: @@ -93,7 +117,7 @@ $ brew install carthage To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: ```ogdl -github "Alamofire/Alamofire" ~> 3.4 +github "Alamofire/Alamofire" ~> 4.0 ``` Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project. @@ -126,11 +150,11 @@ $ git submodule add https://github.com/Alamofire/Alamofire.git - Click on the `+` button under the "Embedded Binaries" section. - You will see two different `Alamofire.xcodeproj` folders each with two different versions of the `Alamofire.framework` nested inside a `Products` folder. - > It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`. - + > 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. - > 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` or `Alamofire OSX`. + > 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`. - And that's it! @@ -145,42 +169,176 @@ $ git submodule add https://github.com/Alamofire/Alamofire.git ```swift import Alamofire -Alamofire.request(.GET, "https://httpbin.org/get") +Alamofire.request("https://httpbin.org/get") ``` ### Response Handling -```swift -Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) - .responseJSON { response in - print(response.request) // original URL request - print(response.response) // URL response - print(response.data) // server data - print(response.result) // result of response serialization +Handling the `Response` of a `Request` made in Alamofire involves chaining a response handler onto the `Request`. - if let JSON = response.result.value { - print("JSON: \(JSON)") - } - } +```swift +Alamofire.request("https://httpbin.org/get").responseJSON { response in + print(response.request) // original URL request + print(response.response) // HTTP URL response + print(response.data) // server data + print(response.result) // result of response serialization + + if let JSON = response.result.value { + print("JSON: \(JSON)") + } +} ``` +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. -> Rather than blocking execution to wait for a response from the server, a [callback](http://en.wikipedia.org/wiki/Callback_%28computer_programming%29) is specified to handle the response once it's received. The result of a request is only available inside the scope of a response handler. Any execution contingent on the response or data received from the server must be done within a handler. +Alamofire contains five different response handlers by default including: -### Validation +```swift +// Response Handler - Unserialized Response +func response( + queue: DispatchQueue?, + completionHandler: @escaping (DefaultDownloadResponse) -> 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..<499` and `500..<599` 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.data)") + + 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(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) - .validate(statusCode: 200..<300) - .validate(contentType: ["application/json"]) - .response { response in - print(response) - } +Alamofire.request("https://httpbin.org/get") + .validate(statusCode: 200..<300) + .validate(contentType: ["application/json"]) + .response { response in + switch response.result { + case .success: + print("Validation Successful") + case .failure(let error): + print(error) + } + } ``` #### Automatic Validation @@ -188,124 +346,83 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) Automatically validates status code within `200...299` range, and that the `Content-Type` header of the response matches the `Accept` header of the request, if one is provided. ```swift -Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) - .validate() - .responseJSON { response in - switch response.result { - case .Success: - print("Validation Successful") - case .Failure(let error): - print(error) - } - } -``` - -### Response Serialization - -**Built-in Response Methods** - -- `response()` -- `responseData()` -- `responseString(encoding: NSStringEncoding)` -- `responseJSON(options: NSJSONReadingOptions)` -- `responsePropertyList(options: NSPropertyListReadOptions)` - -#### Response Handler - -```swift -Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) - .validate() - .response { request, response, data, error in - print(request) - print(response) - print(data) - print(error) - } -``` - -> The `response` serializer does NOT evaluate any of the response data. It merely forwards on all the information directly from the URL session delegate. We strongly encourage you to leverage the other response serializers taking advantage of `Response` and `Result` types. - -#### Response Data Handler - -```swift -Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) - .validate() - .responseData { response in - print(response.request) - print(response.response) - print(response.result) - } -``` - -#### Response String Handler - -```swift -Alamofire.request(.GET, "https://httpbin.org/get") - .validate() - .responseString { response in - print("Success: \(response.result.isSuccess)") - print("Response String: \(response.result.value)") - } -``` - -#### Response JSON Handler - -```swift -Alamofire.request(.GET, "https://httpbin.org/get") - .validate() - .responseJSON { response in - debugPrint(response) - } -``` - -#### Chained Response Handlers - -Response handlers can even be chained: - -```swift -Alamofire.request(.GET, "https://httpbin.org/get") - .validate() - .responseString { response in - print("Response String: \(response.result.value)") - } - .responseJSON { response in - print("Response JSON: \(response.result.value)") - } -``` - -### HTTP Methods - -`Alamofire.Method` lists the HTTP methods defined in [RFC 7231 §4.3](http://tools.ietf.org/html/rfc7231#section-4.3): - -```swift -public enum Method: String { - case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT +Alamofire.request("https://httpbin.org/get").validate().responseJSON { response in + switch response.result { + case .success: + print("Validation Successful") + case .failure(let error): + print(error) + } } ``` -These values can be passed as the first argument of the `Alamofire.request` method: +### 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-configurations) 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 -Alamofire.request(.POST, "https://httpbin.org/post") - -Alamofire.request(.PUT, "https://httpbin.org/put") - -Alamofire.request(.DELETE, "https://httpbin.org/delete") +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" +} ``` -### Parameters - -#### GET Request With URL-Encoded Parameters +These values can be passed as the `method` argument to the `Alamofire.request` API: ```swift -Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) +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 +##### POST Request With URL-Encoded Parameters ```swift -let parameters = [ +let parameters: Parameters = [ "foo": "bar", "baz": ["a", 1], "qux": [ @@ -315,221 +432,107 @@ let parameters = [ ] ] -Alamofire.request(.POST, "https://httpbin.org/post", parameters: parameters) +// All three of these calls are equivalent +Alamofire.request("https://httpbin.org/post", parameters: parameters) +Alamofire.request("https://httpbin.org/post", parameters: parameters, encoding: URLEncoding.default) +Alamofire.request("https://httpbin.org/post", parameters: parameters, encoding: URLEncoding.httpBody) + // HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3 ``` -### Parameter Encoding +#### JSON Encoding -Parameters can also be encoded as JSON, Property List, or any custom format, using the `ParameterEncoding` enum: +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 -enum ParameterEncoding { - case URL - case URLEncodedInURL - case JSON - case PropertyList(format: NSPropertyListFormat, options: NSPropertyListWriteOptions) - case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?)) - - func encode(request: NSURLRequest, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) - { ... } -} -``` - -- `URL`: A query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded`. _Since there is no published specification for how to encode collection types, Alamofire follows 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`)._ -- `URLEncodedInURL`: Creates query string to be set as or appended to any existing URL query. Uses the same implementation as the `.URL` case, but always applies the encoded result to the URL. -- `JSON`: Uses `NSJSONSerialization` 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`. -- `PropertyList`: Uses `NSPropertyListSerialization` 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`: Uses the associated closure value to construct a new request given an existing request and parameters. - -#### Manual Parameter Encoding of an NSURLRequest - -```swift -let URL = NSURL(string: "https://httpbin.org/get")! -var request = NSMutableURLRequest(URL: URL) - -let parameters = ["foo": "bar"] -let encoding = Alamofire.ParameterEncoding.URL -(request, _) = encoding.encode(request, parameters: parameters) -``` - -#### POST Request with JSON-encoded Parameters - -```swift -let parameters = [ +let parameters: Parameters = [ "foo": [1,2,3], "bar": [ "baz": "qux" ] ] -Alamofire.request(.POST, "https://httpbin.org/post", parameters: parameters, encoding: .JSON) +// 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 = urlRequest.urlRequest + + 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. -> For HTTP headers that do not change, it is recommended to set them on the `NSURLSessionConfiguration` so they are automatically applied to any `NSURLSessionTask` created by the underlying `NSURLSession`. - ```swift -let headers = [ +let headers: HTTPHeaders = [ "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", "Accept": "application/json" ] -Alamofire.request(.GET, "https://httpbin.org/get", headers: headers) - .responseJSON { response in - debugPrint(response) - } -``` - -### Caching - -Caching is handled on the system framework level by [`NSURLCache`](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLCache_Class/Reference/Reference.html#//apple_ref/occ/cl/NSURLCache). - -### Uploading - -**Supported Upload Types** - -- File -- Data -- Stream -- MultipartFormData - -#### Uploading a File - -```swift -let fileURL = NSBundle.mainBundle().URLForResource("Default", withExtension: "png") -Alamofire.upload(.POST, "https://httpbin.org/post", file: fileURL) -``` - -#### Uploading with Progress - -```swift -Alamofire.upload(.POST, "https://httpbin.org/post", file: fileURL) - .progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in - print(totalBytesWritten) - - // This closure is NOT called on the main queue for performance - // reasons. To update your ui, dispatch to the main queue. - dispatch_async(dispatch_get_main_queue()) { - print("Total bytes written on main queue: \(totalBytesWritten)") - } - } - .validate() - .responseJSON { response in - debugPrint(response) - } -``` - -#### Uploading MultipartFormData - -```swift -Alamofire.upload( - .POST, - "https://httpbin.org/post", - multipartFormData: { multipartFormData in - multipartFormData.appendBodyPart(fileURL: unicornImageURL, name: "unicorn") - multipartFormData.appendBodyPart(fileURL: rainbowImageURL, name: "rainbow") - }, - encodingCompletion: { encodingResult in - switch encodingResult { - case .Success(let upload, _, _): - upload.responseJSON { response in - debugPrint(response) - } - case .Failure(let encodingError): - print(encodingError) - } - } -) -``` - -### Downloading - -**Supported Download Types** - -- Request -- Resume Data - -#### Downloading a File - -```swift -Alamofire.download(.GET, "https://httpbin.org/stream/100") { temporaryURL, response in - let fileManager = NSFileManager.defaultManager() - let directoryURL = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] - let pathComponent = response.suggestedFilename - - return directoryURL.URLByAppendingPathComponent(pathComponent!) +Alamofire.request("https://httpbin.org/headers", headers: headers).responseJSON { response in + debugPrint(response) } ``` -#### Using the Default Download Destination +> 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-configurations) section. -```swift -let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask) -Alamofire.download(.GET, "https://httpbin.org/stream/100", destination: destination) -``` +The default Alamofire `SessionManager` provides a default set of headers for every `Request`. These include: -#### Downloading a File w/Progress +- `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). -```swift -Alamofire.download(.GET, "https://httpbin.org/stream/100", destination: destination) - .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in - print(totalBytesRead) - - // This closure is NOT called on the main queue for performance - // reasons. To update your ui, dispatch to the main queue. - dispatch_async(dispatch_get_main_queue()) { - print("Total bytes read on main queue: \(totalBytesRead)") - } - } - .response { _, _, _, error in - if let error = error { - print("Failed with error: \(error)") - } else { - print("Downloaded file successfully") - } - } -``` - -#### Accessing Resume Data for Failed Downloads - -```swift -Alamofire.download(.GET, "https://httpbin.org/stream/100", destination: destination) - .response { _, _, data, _ in - if let - data = data, - resumeDataString = NSString(data: data, encoding: NSUTF8StringEncoding) - { - print("Resume Data: \(resumeDataString)") - } else { - print("Resume Data was empty") - } - } -``` - -> The `data` parameter is automatically populated with the `resumeData` if available. - -```swift -let download = Alamofire.download(.GET, "https://httpbin.org/stream/100", destination: destination) -download.response { _, _, _, _ in - if let - resumeData = download.resumeData, - resumeDataString = NSString(data: resumeData, encoding: NSUTF8StringEncoding) - { - print("Resume Data: \(resumeDataString)") - } else { - print("Resume Data was empty") - } -} -``` +If you need to customize these headers, a custom `URLSessionManagerConfiguration` 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 [`NSURLCredential` and `NSURLAuthenticationChallenge`](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLAuthenticationChallenge_Class/Reference/Reference.html). +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** @@ -540,17 +543,17 @@ Authentication is handled on the system framework level by [`NSURLCredential` an #### HTTP Basic Authentication -The `authenticate` method on a `Request` will automatically provide an `NSURLCredential` to an `NSURLAuthenticationChallenge` when appropriate: +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(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)") - .authenticate(user: user, password: password) - .responseJSON { response in - debugPrint(response) - } +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: @@ -559,42 +562,228 @@ Depending upon your server implementation, an `Authorization` header may also be let user = "user" let password = "password" -let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)! -let base64Credentials = credentialData.base64EncodedStringWithOptions([]) +var headers: HTTPHeaders = [:] -let headers = ["Authorization": "Basic \(base64Credentials)"] +if let authorizationHeader = Request.authorizationHeader(user: user, password: password) { + headers[authorizationHeader.key] = authorizationHeader.value +} -Alamofire.request(.GET, "https://httpbin.org/basic-auth/user/password", headers: headers) - .responseJSON { response in - debugPrint(response) - } +Alamofire.request("https://httpbin.org/basic-auth/user/password", headers: headers) + .responseJSON { response in + debugPrint(response) + } ``` -#### Authentication with NSURLCredential +#### Authentication with URLCredential ```swift let user = "user" let password = "password" -let credential = NSURLCredential(user: user, password: password, persistence: .ForSession) +let credential = URLCredential(user: user, password: password, persistence: .forSession) -Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)") - .authenticate(usingCredential: credential) - .responseJSON { response in - debugPrint(response) - } +Alamofire.request("https://httpbin.org/basic-auth/\(user)/\(password)") + .authenticate(usingCredential: credential) + .responseJSON { response in + debugPrint(response) + } ``` -### Timeline +> 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`. -Alamofire collects timings throughout the lifecycle of a `Request` and creates a `Timeline` object exposed as a property on a `Response`. +### 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. ```swift -Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) - .validate() - .responseJSON { response in - print(response.timeline) - } +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-configurations) 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.appendPathComponent("pig.png") + + return (fileURL, [.removePreviousFile, .createIntermediateDirectories]) +} + +Alamofire.download(urlString, to: destination).response { response in + print(response) + + if response.result.isSuccess, let imagePath = response.destinationURL?.path { + let image = UIImage(contentsOfFile: imagePath) + } +} +``` + +You can also use the suggested download destination API. + +```swift +let destination = DownloadRequest.suggestedDownloadDestination(directory: .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. + +```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.appendPathComponent("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-configurations) section. + +#### Uploading Data + +```swift +let imageData = UIPNGRepresentation(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 + +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. + +```swift +let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov") + +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) + } +``` + +### Statistical Metrics + +#### Timeline + +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: @@ -604,29 +793,52 @@ The above reports the following `Timeline` info: - `Serialization Duration`: 0.001 seconds - `Total Duration`: 0.429 seconds -### Printable +#### 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 -let request = Alamofire.request(.GET, "https://httpbin.org/ip") +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) ``` -### DebugPrintable +#### CustomDebugStringConvertible ```swift -let request = Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) - +let request = Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"]) debugPrint(request) ``` -#### Output (cURL) +Outputs: ```bash $ curl -i \ - -H "User-Agent: Alamofire" \ - -H "Accept-Encoding: Accept-Encoding: gzip;q=1.0,compress;q=0.5" \ + -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" ``` @@ -635,435 +847,107 @@ $ curl -i \ ## Advanced Usage -> Alamofire is built on `NSURLSession` 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. +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) -- [NSURLSession Class Reference](https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLSession_class/Introduction/Introduction.html#//apple_ref/occ/cl/NSURLSession) -- [NSURLCache Class Reference](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLCache_Class/Reference/Reference.html#//apple_ref/occ/cl/NSURLCache) -- [NSURLAuthenticationChallenge Class Reference](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLAuthenticationChallenge_Class/Reference/Reference.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) -### Manager +### Session Manager -Top-level convenience methods like `Alamofire.request` use a shared instance of `Alamofire.Manager`, which is configured with the default `NSURLSessionConfiguration`. +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(.GET, "https://httpbin.org/get") +Alamofire.request("https://httpbin.org/get") ``` ```swift -let manager = Alamofire.Manager.sharedInstance -manager.request(NSURLRequest(URL: NSURL(string: "https://httpbin.org/get")!)) +let sessionManager = Alamofire.SessionManager.default +sessionManager.request("https://httpbin.org/get") ``` -Applications can create 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`). +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 Manager with Default Configuration +#### Creating a Session Manager with Default Configuration ```swift -let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() -let manager = Alamofire.Manager(configuration: configuration) +let configuration = URLSessionConfiguration.default +let sessionManager = Alamofire.SessionManager(configuration: configuration) ``` -#### Creating a Manager with Background Configuration +#### Creating a Session Manager with Background Configuration ```swift -let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("com.example.app.background") -let manager = Alamofire.Manager(configuration: configuration) +let configuration = URLSessionConfiguration.background(withIdentifier: "com.example.app.background") +let sessionManager = Alamofire.SessionManager(configuration: configuration) ``` -#### Creating a Manager with Ephemeral Configuration +#### Creating a Session Manager with Ephemeral Configuration ```swift -let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration() -let manager = Alamofire.Manager(configuration: configuration) +let configuration = URLSessionConfiguration.ephemeral +let sessionManager = Alamofire.SessionManager(configuration: configuration) ``` -#### Modifying Session Configuration +#### Modifying the Session Configuration ```swift -var defaultHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:] +var defaultHeaders = Alamofire.SessionManager.default.defaultHTTPHeaders defaultHeaders["DNT"] = "1 (Do Not Track Enabled)" -let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() -configuration.HTTPAdditionalHeaders = defaultHeaders +let configuration = URLSessionConfiguration.default +configuration.httpAdditionalHeaders = defaultHeaders -let manager = Alamofire.Manager(configuration: configuration) +let sessionManager = Alamofire.SessionManager(configuration: configuration) ``` -> This is **not** recommended for `Authorization` or `Content-Type` headers. Instead, use `URLRequestConvertible` and `ParameterEncoding`, respectively. +> 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. -### Request +### Session Delegate -The result of a `request`, `upload`, or `download` method is an instance of `Alamofire.Request`. A request is always created using a constructor method from an owning manager, and never initialized directly. - -Methods like `authenticate`, `validate` and `responseData` return the caller in order to facilitate 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. - -### Response Serialization - -#### 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.Request`. - -For example, here's how a response handler using [Ono](https://github.com/mattt/Ono) might be implemented: - -```swift -extension Request { - public static func XMLResponseSerializer() -> ResponseSerializer { - return ResponseSerializer { request, response, data, error in - guard error == nil else { return .Failure(error!) } - - guard let validData = data else { - let failureReason = "Data could not be serialized. Input data was nil." - let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason) - return .Failure(error) - } - - do { - let XML = try ONOXMLDocument(data: validData) - return .Success(XML) - } catch { - return .Failure(error as NSError) - } - } - } - - public func responseXMLDocument(completionHandler: Response -> Void) -> Self { - return response(responseSerializer: Request.XMLResponseSerializer(), completionHandler: completionHandler) - } -} -``` - -#### Generic Response Object Serialization - -Generics can be used to provide automatic, type-safe response object serialization. - -```swift -public protocol ResponseObjectSerializable { - init?(response: NSHTTPURLResponse, representation: AnyObject) -} - -extension Request { - public func responseObject(completionHandler: Response -> Void) -> Self { - let responseSerializer = ResponseSerializer { request, response, data, error in - guard error == nil else { return .Failure(error!) } - - let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments) - let result = JSONResponseSerializer.serializeResponse(request, response, data, error) - - switch result { - case .Success(let value): - if let - response = response, - responseObject = T(response: response, representation: value) - { - return .Success(responseObject) - } else { - let failureReason = "JSON could not be serialized into response object: \(value)" - let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason) - return .Failure(error) - } - case .Failure(let error): - return .Failure(error) - } - } - - return response(responseSerializer: responseSerializer, completionHandler: completionHandler) - } -} -``` - -```swift -final class User: ResponseObjectSerializable { - let username: String - let name: String - - init?(response: NSHTTPURLResponse, representation: AnyObject) { - self.username = response.URL!.lastPathComponent! - self.name = representation.valueForKeyPath("name") as! String - } -} -``` - -```swift -Alamofire.request(.GET, "https://example.com/users/mattt") - .responseObject { (response: Response) in - debugPrint(response) - } -``` - -The same approach can also be used to handle endpoints that return a representation of a collection of objects: - -```swift -public protocol ResponseCollectionSerializable { - static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Self] -} - -extension Alamofire.Request { - public func responseCollection(completionHandler: Response<[T], NSError> -> Void) -> Self { - let responseSerializer = ResponseSerializer<[T], NSError> { request, response, data, error in - guard error == nil else { return .Failure(error!) } - - let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments) - let result = JSONSerializer.serializeResponse(request, response, data, error) - - switch result { - case .Success(let value): - if let response = response { - return .Success(T.collection(response: response, representation: value)) - } else { - let failureReason = "Response collection could not be serialized due to nil response" - let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason) - return .Failure(error) - } - case .Failure(let error): - return .Failure(error) - } - } - - return response(responseSerializer: responseSerializer, completionHandler: completionHandler) - } -} -``` - -```swift -final class User: ResponseObjectSerializable, ResponseCollectionSerializable { - let username: String - let name: String - - init?(response: NSHTTPURLResponse, representation: AnyObject) { - self.username = response.URL!.lastPathComponent! - self.name = representation.valueForKeyPath("name") as! String - } - - static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [User] { - var users: [User] = [] - - if let representation = representation as? [[String: AnyObject]] { - for userRepresentation in representation { - if let user = User(response: response, representation: userRepresentation) { - users.append(user) - } - } - } - - return users - } -} -``` - -```swift -Alamofire.request(.GET, "http://example.com/users") - .responseCollection { (response: Response<[User], NSError>) in - debugPrint(response) - } -``` - -### URLStringConvertible - -Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to construct URL requests. `NSString`, `NSURL`, `NSURLComponents`, and `NSURLRequest` conform to `URLStringConvertible` by default, allowing any of them to be passed as `URLString` parameters to the `request`, `upload`, and `download` methods: - -```swift -let string = NSString(string: "https://httpbin.org/post") -Alamofire.request(.POST, string) - -let URL = NSURL(string: string)! -Alamofire.request(.POST, URL) - -let URLRequest = NSURLRequest(URL: URL) -Alamofire.request(.POST, URLRequest) // overrides `HTTPMethod` of `URLRequest` - -let URLComponents = NSURLComponents(URL: URL, resolvingAgainstBaseURL: true) -Alamofire.request(.POST, URLComponents) -``` - -Applications interacting with web applications in a significant manner are encouraged to have custom types conform to `URLStringConvertible` as a convenient way to map domain-specific models to server resources. - -#### Type-Safe Routing - -```swift -extension User: URLStringConvertible { - static let baseURLString = "http://example.com" - - var URLString: String { - return User.baseURLString + "/users/\(username)/" - } -} -``` - -```swift -let user = User(username: "mattt") -Alamofire.request(.GET, user) // http://example.com/users/mattt -``` - -### URLRequestConvertible - -Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. `NSURLRequest` 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 = NSURL(string: "https://httpbin.org/post")! -let mutableURLRequest = NSMutableURLRequest(URL: URL) -mutableURLRequest.HTTPMethod = "POST" - -let parameters = ["foo": "bar"] - -do { - mutableURLRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions()) -} catch { - // No-op -} - -mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") - -Alamofire.request(mutableURLRequest) -``` - -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 { - static let baseURLString = "http://example.com" - static let perPage = 50 - - case Search(query: String, page: Int) - - // MARK: URLRequestConvertible - - var URLRequest: NSMutableURLRequest { - let result: (path: String, parameters: [String: AnyObject]) = { - switch self { - case .Search(let query, let page) where page > 1: - return ("/search", ["q": query, "offset": Router.perPage * page]) - case .Search(let query, _): - return ("/search", ["q": query]) - } - }() - - let URL = NSURL(string: Router.baseURLString)! - let URLRequest = NSURLRequest(URL: URL.URLByAppendingPathComponent(result.path)) - let encoding = Alamofire.ParameterEncoding.URL - - return encoding.encode(URLRequest, parameters: result.parameters).0 - } -} -``` - -```swift -Alamofire.request(Router.Search(query: "foo bar", page: 1)) // ?q=foo%20bar&offset=50 -``` - -#### CRUD & Authorization - -```swift -enum Router: URLRequestConvertible { - static let baseURLString = "http://example.com" - static var OAuthToken: String? - - case CreateUser([String: AnyObject]) - case ReadUser(String) - case UpdateUser(String, [String: AnyObject]) - case DestroyUser(String) - - var method: Alamofire.Method { - 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 - - var URLRequest: NSMutableURLRequest { - let URL = NSURL(string: Router.baseURLString)! - let mutableURLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path)) - mutableURLRequest.HTTPMethod = method.rawValue - - if let token = Router.OAuthToken { - mutableURLRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") - } - - switch self { - case .CreateUser(let parameters): - return Alamofire.ParameterEncoding.JSON.encode(mutableURLRequest, parameters: parameters).0 - case .UpdateUser(_, let parameters): - return Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: parameters).0 - default: - return mutableURLRequest - } - } -} -``` - -```swift -Alamofire.request(Router.ReadUser("mattt")) // GET /users/mattt -``` - -### SessionDelegate - -By default, an Alamofire `Manager` instance creates an internal `SessionDelegate` object to handle all the various types of delegate callbacks that are generated by the underlying `NSURLSession`. 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. +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 NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`. -public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? +/// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`. +open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? -/// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`. -public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)? +/// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`. +open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)? -/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`. -public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? +/// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`. +open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? -/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`. -public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)? +/// 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 delegate: Alamofire.Manager.SessionDelegate = manager.delegate +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 where originalRequest.URLString.containsString("apple.com") { - finalRequest = originalRequest - } + if + let originalRequest = task.originalRequest, + let urlString = originalRequest.url?.urlString, + urlString.contains("apple.com") + { + finalRequest = originalRequest + } - return finalRequest + return finalRequest } ``` @@ -1072,17 +956,17 @@ delegate.taskWillPerformHTTPRedirection = { session, task, response, request in 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: Manager.SessionDelegate { - override func URLSession( - session: NSURLSession, - task: NSURLSessionTask, - willPerformHTTPRedirection response: NSHTTPURLResponse, - newRequest request: NSURLRequest, - completionHandler: NSURLRequest? -> Void) +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( + super.urlSession( session, task: task, willPerformHTTPRedirection: response, @@ -1093,20 +977,587 @@ class LoggingSessionDelegate: Manager.SessionDelegate { } ``` -Generally, either the default implementation or the override closures should provide the necessary functionality required. Subclassing should only be used as a last resort. +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(.post, URLComponents) +``` + +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)) // ?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 /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 urlRequest.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 url = urlRequest.url, url.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: String] { + completion(true, json["access_token"], json["refresh_token"]) + } 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 + +#### 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 `NSURLAuthenticationChallenge` when connecting to a server over a secure HTTPS connection. +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( +let serverTrustPolicy = ServerTrustPolicy.pinCertificates( certificates: ServerTrustPolicy.certificatesInBundle(), validateCertificateChain: true, validateHost: true @@ -1115,41 +1566,41 @@ let serverTrustPolicy = ServerTrustPolicy.PinCertificates( 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. +* `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. +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( + "test.example.com": .pinCertificates( certificates: ServerTrustPolicy.certificatesInBundle(), validateCertificateChain: true, validateHost: true ), - "insecure.expired-apis.com": .DisableEvaluation + "insecure.expired-apis.com": .disableEvaluation ] -let manager = Manager( +let sessionManager = SessionManager( serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies) ) ``` -> Make sure to keep a reference to the new `Manager` instance, otherwise your requests will all get cancelled when your `manager` is deallocated. +> 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. +- `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 @@ -1157,7 +1608,7 @@ If you find yourself needing more flexible server trust policy matching behavior ```swift class CustomServerTrustPolicyManager: ServerTrustPolicyManager { - override func serverTrustPolicyForHost(host: String) -> ServerTrustPolicy? { + override func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? { var policy: ServerTrustPolicy? // Implement your custom domain matching behavior... @@ -1169,7 +1620,7 @@ class CustomServerTrustPolicyManager: ServerTrustPolicyManager { #### 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. +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. @@ -1232,22 +1683,25 @@ manager?.startListening() 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." +- **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 Rdars +## Open Radars -The following rdars have some affect on the current implementation of Alamofire. +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://21349340`](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case +- [`rdar://26761490`](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage +- `rdar://26870455` - Background URL Session Configurations do not work in the simulator +- `rdar://26849668` - Some URLProtocol APIs do not properly handle `URLRequest` ## FAQ @@ -1255,6 +1709,12 @@ The following rdars have some affect on the current implementation of 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 @@ -1265,6 +1725,20 @@ Alamofire is owned and maintained by the [Alamofire Software Foundation](http:// If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. +## 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: + +- 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. + +Click here to lend your support to: Alamofire Software Foundation and make a donation at pledgie.com ! + ## License Alamofire is released under the MIT license. See LICENSE for details. diff --git a/Pods/Alamofire/Source/AFError.swift b/Pods/Alamofire/Source/AFError.swift new file mode 100644 index 0000000..82e8a25 --- /dev/null +++ b/Pods/Alamofire/Source/AFError.swift @@ -0,0 +1,450 @@ +// +// AFError.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 + +/// `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. + public enum MultipartEncodingFailureReason { + case bodyPartURLInvalid(url: URL) + case bodyPartFilenameInvalid(in: URL) + case bodyPartFileNotReachable(at: URL) + case bodyPartFileNotReachableWithError(atURL: URL, error: Error) + case bodyPartFileIsDirectory(at: URL) + case bodyPartFileSizeNotAvailable(at: URL) + case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error) + case bodyPartInputStreamCreationFailed(for: URL) + + case outputStreamCreationFailed(for: URL) + case outputStreamFileAlreadyExists(at: URL) + case outputStreamURLInvalid(url: URL) + case outputStreamWriteFailed(error: 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. + public enum ResponseValidationFailureReason { + case dataFileNil + case dataFileReadFailed(at: URL) + case missingContentType(acceptableContentTypes: [String]) + case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String) + case unacceptableStatusCode(code: Int) + } + + /// 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 + case inputDataNilOrZeroLength + case inputFileNil + case inputFileReadFailed(at: URL) + case stringSerializationFailed(encoding: String.Encoding) + case jsonSerializationFailed(error: Error) + case propertyListSerializationFailed(error: Error) + } + + case invalidURL(url: URLConvertible) + case parameterEncodingFailed(reason: ParameterEncodingFailureReason) + case multipartEncodingFailed(reason: MultipartEncodingFailureReason) + case responseValidationFailed(reason: ResponseValidationFailureReason) + case responseSerializationFailed(reason: ResponseSerializationFailureReason) +} + +// MARK: - Error Booleans + +extension AFError { + /// Returns whether the AFError is an invalid URL error. + 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 + /// 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. + 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. + 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 + /// `underlyingError` properties will contain the associated values. + public var isResponseSerializationError: Bool { + if case .responseSerializationFailed = self { return true } + return false + } +} + +// MARK: - Convenience Properties + +extension AFError { + /// The `URLConvertible` associated with the error. + public var urlConvertible: URLConvertible? { + switch self { + case .invalidURL(let url): + return url + default: + return nil + } + } + + /// The `URL` associated with the error. + public var url: URL? { + switch self { + case .multipartEncodingFailed(let reason): + return reason.url + default: + return nil + } + } + + /// The `Error` returned by a system framework associated with a `.parameterEncodingFailed`, + /// `.multipartEncodingFailed` or `.responseSerializationFailed` error. + public var underlyingError: Error? { + switch self { + case .parameterEncodingFailed(let reason): + return reason.underlyingError + case .multipartEncodingFailed(let reason): + return reason.underlyingError + case .responseSerializationFailed(let reason): + return reason.underlyingError + default: + 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 + } + } + + /// The response `Content-Type` of a `.responseValidationFailed` error. + public var responseContentType: String? { + switch self { + case .responseValidationFailed(let reason): + return reason.responseContentType + default: + return nil + } + } + + /// The response code of a `.responseValidationFailed` error. + public var responseCode: Int? { + switch self { + case .responseValidationFailed(let reason): + return reason.responseCode + default: + return nil + } + } + + /// The `String.Encoding` associated with a failed `.stringResponse()` call. + public var failedStringEncoding: String.Encoding? { + switch self { + case .responseSerializationFailed(let reason): + return reason.failedStringEncoding + default: + return nil + } + } +} + +extension AFError.ParameterEncodingFailureReason { + var underlyingError: Error? { + switch self { + case .jsonEncodingFailed(let error), .propertyListEncodingFailed(let error): + return error + default: + return nil + } + } +} + +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, _): + return url + default: + return nil + } + } + + var underlyingError: Error? { + switch self { + case .bodyPartFileNotReachableWithError(_, let error), .bodyPartFileSizeQueryFailedWithError(_, let error), + .outputStreamWriteFailed(let error), .inputStreamReadFailed(let error): + return error + default: + return nil + } + } +} + +extension AFError.ResponseValidationFailureReason { + var acceptableContentTypes: [String]? { + switch self { + case .missingContentType(let types), .unacceptableContentType(let types, _): + return types + default: + return nil + } + } + + var responseContentType: String? { + switch self { + case .unacceptableContentType(_, let responseType): + return responseType + default: + return nil + } + } + + var responseCode: Int? { + switch self { + case .unacceptableStatusCode(let code): + return code + default: + return nil + } + } +} + +extension AFError.ResponseSerializationFailureReason { + var failedStringEncoding: String.Encoding? { + switch self { + case .stringSerializationFailed(let encoding): + return encoding + default: + return nil + } + } + + var underlyingError: Error? { + switch self { + case .jsonSerializationFailed(let error), .propertyListSerializationFailed(let error): + return error + default: + return nil + } + } +} + +// MARK: - Error Descriptions + +extension AFError: LocalizedError { + public var errorDescription: String? { + switch self { + case .invalidURL(let url): + return "URL is not valid: \(url)" + case .parameterEncodingFailed(let reason): + return reason.localizedDescription + case .multipartEncodingFailed(let reason): + return reason.localizedDescription + case .responseValidationFailed(let reason): + return reason.localizedDescription + case .responseSerializationFailed(let reason): + return reason.localizedDescription + } + } +} + +extension AFError.ParameterEncodingFailureReason { + var localizedDescription: String { + switch self { + case .missingURL: + return "URL request to encode was missing a URL" + case .jsonEncodingFailed(let 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)" + } + } +} + +extension AFError.MultipartEncodingFailureReason { + var localizedDescription: String { + switch self { + case .bodyPartURLInvalid(let url): + return "The URL provided is not a file URL: \(url)" + case .bodyPartFilenameInvalid(let url): + return "The URL provided does not have a valid filename: \(url)" + case .bodyPartFileNotReachable(let 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): + return "The URL provided is a directory: \(url)" + case .bodyPartFileSizeNotAvailable(let 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): + return "Failed to create an InputStream for the provided URL: \(url)" + case .outputStreamCreationFailed(let url): + return "Failed to create an OutputStream for URL: \(url)" + case .outputStreamFileAlreadyExists(let url): + return "A file already exists at the provided URL: \(url)" + case .outputStreamURLInvalid(let url): + return "The provided OutputStream URL is invalid: \(url)" + case .outputStreamWriteFailed(let error): + return "OutputStream write failed with error: \(error)" + case .inputStreamReadFailed(let error): + return "InputStream read failed with error: \(error)" + } + } +} + +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): + return "Response could not be serialized, input file could not be read: \(url)." + case .stringSerializationFailed(let encoding): + return "String could not be serialized with encoding: \(encoding)." + case .jsonSerializationFailed(let 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)" + } + } +} + +extension AFError.ResponseValidationFailureReason { + var localizedDescription: String { + switch self { + case .dataFileNil: + return "Response could not be validated, data file was nil." + case .dataFileReadFailed(let 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): + return "Response status code was unacceptable: \(code)." + } + } +} diff --git a/Pods/Alamofire/Source/Alamofire.swift b/Pods/Alamofire/Source/Alamofire.swift index cb4b36a..7566587 100644 --- a/Pods/Alamofire/Source/Alamofire.swift +++ b/Pods/Alamofire/Source/Alamofire.swift @@ -24,347 +24,433 @@ import Foundation -// MARK: - URLStringConvertible - -/** - Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to - construct URL requests. -*/ -public protocol URLStringConvertible { - /** - A URL that conforms to RFC 2396. - - Methods accepting a `URLStringConvertible` type parameter parse it according to RFCs 1738 and 1808. - - See https://tools.ietf.org/html/rfc2396 - See https://tools.ietf.org/html/rfc1738 - See https://tools.ietf.org/html/rfc1808 - */ - var URLString: String { get } +/// Types adopting the `URLConvertible` protocol can be used to construct URLs, which are then used to construct +/// URL requests. +public protocol URLConvertible { + /// Returns a URL that conforms to RFC 2396 or throws an `Error`. + /// + /// - throws: An `Error` if the type cannot be converted to a `URL`. + /// + /// - returns: A URL or throws an `Error`. + func asURL() throws -> URL } -extension String: URLStringConvertible { - public var URLString: String { - return self +extension String: URLConvertible { + /// Returns a URL if `self` represents a valid URL string that conforms to RFC 2396 or throws an `AFError`. + /// + /// - throws: An `AFError.invalidURL` if `self` is not a valid URL string. + /// + /// - returns: A URL or throws an `AFError`. + public func asURL() throws -> URL { + guard let url = URL(string: self) else { throw AFError.invalidURL(url: self) } + return url } } -extension NSURL: URLStringConvertible { - public var URLString: String { - return absoluteString +extension URL: URLConvertible { + /// Returns self. + public func asURL() throws -> URL { return self } +} + +extension URLComponents: URLConvertible { + /// Returns a URL if `url` is not nil, otherise throws an `Error`. + /// + /// - throws: An `AFError.invalidURL` if `url` is `nil`. + /// + /// - returns: A URL or throws an `AFError`. + public func asURL() throws -> URL { + guard let url = url else { throw AFError.invalidURL(url: self) } + return url } } -extension NSURLComponents: URLStringConvertible { - public var URLString: String { - return URL!.URLString - } -} +// MARK: - -extension NSURLRequest: URLStringConvertible { - public var URLString: String { - return URL!.URLString - } -} - -// MARK: - URLRequestConvertible - -/** - Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. -*/ +/// Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. public protocol URLRequestConvertible { + /// Returns a URL request or throws if an `Error` was encountered. + /// + /// - throws: An `Error` if the underlying `URLRequest` is `nil`. + /// + /// - returns: A URL request. + func asURLRequest() throws -> URLRequest +} + +extension URLRequestConvertible { /// The URL request. - var URLRequest: NSMutableURLRequest { get } + public var urlRequest: URLRequest? { return try? asURLRequest() } } -extension NSURLRequest: URLRequestConvertible { - public var URLRequest: NSMutableURLRequest { - return self.mutableCopy() as! NSMutableURLRequest - } +extension URLRequest: URLRequestConvertible { + /// Returns a URL request or throws if an `Error` was encountered. + public func asURLRequest() throws -> URLRequest { return self } } -// MARK: - Convenience +// MARK: - -func URLRequest( - method: Method, - _ URLString: URLStringConvertible, - headers: [String: String]? = nil) - -> NSMutableURLRequest -{ - let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString)!) - mutableURLRequest.HTTPMethod = method.rawValue +extension URLRequest { + /// Creates an instance with the specified `method`, `urlString` and `headers`. + /// + /// - parameter url: The URL. + /// - parameter method: The HTTP method. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The new `URLRequest` instance. + public init(url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws { + let url = try url.asURL() - if let headers = headers { - for (headerField, headerValue) in headers { - mutableURLRequest.setValue(headerValue, forHTTPHeaderField: headerField) + self.init(url: url) + + httpMethod = method.rawValue + + if let headers = headers { + for (headerField, headerValue) in headers { + setValue(headerValue, forHTTPHeaderField: headerField) + } } } - return mutableURLRequest + func adapt(using adapter: RequestAdapter?) throws -> URLRequest { + guard let adapter = adapter else { return self } + return try adapter.adapt(self) + } } -// MARK: - Request Methods +// MARK: - Data Request -/** - Creates a request using the shared manager instance for the specified method, URL string, parameters, and - parameter encoding. - - - parameter method: The HTTP method. - - parameter URLString: The URL string. - - parameter parameters: The parameters. `nil` by default. - - parameter encoding: The parameter encoding. `.URL` by default. - - parameter headers: The HTTP headers. `nil` by default. - - - returns: The created request. -*/ +/// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, +/// `method`, `parameters`, `encoding` and `headers`. +/// +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.get` by default. +/// - parameter parameters: The parameters. `nil` by default. +/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `DataRequest`. +@discardableResult public func request( - method: Method, - _ URLString: URLStringConvertible, - parameters: [String: AnyObject]? = nil, - encoding: ParameterEncoding = .URL, - headers: [String: String]? = nil) - -> Request + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil) + -> DataRequest { - return Manager.sharedInstance.request( - method, - URLString, + return SessionManager.default.request( + url, + method: method, parameters: parameters, encoding: encoding, headers: headers ) } -/** - Creates a request using the shared manager instance for the specified URL request. - - If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - - - parameter URLRequest: The URL request - - - returns: The created request. -*/ -public func request(URLRequest: URLRequestConvertible) -> Request { - return Manager.sharedInstance.request(URLRequest.URLRequest) +/// 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: - Upload Methods - -// MARK: File - -/** - Creates an upload request using the shared manager instance for the specified method, URL string, and file. - - - parameter method: The HTTP method. - - parameter URLString: The URL string. - - parameter headers: The HTTP headers. `nil` by default. - - parameter file: The file to upload. - - - returns: The created upload request. -*/ -public func upload( - method: Method, - _ URLString: URLStringConvertible, - headers: [String: String]? = nil, - file: NSURL) - -> Request -{ - return Manager.sharedInstance.upload(method, URLString, headers: headers, file: file) -} - -/** - Creates an upload request using the shared manager instance for the specified URL request and file. - - - parameter URLRequest: The URL request. - - parameter file: The file to upload. - - - returns: The created upload request. -*/ -public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request { - return Manager.sharedInstance.upload(URLRequest, file: file) -} - -// MARK: Data - -/** - Creates an upload request using the shared manager instance for the specified method, URL string, and data. - - - parameter method: The HTTP method. - - parameter URLString: The URL string. - - parameter headers: The HTTP headers. `nil` by default. - - parameter data: The data to upload. - - - returns: The created upload request. -*/ -public func upload( - method: Method, - _ URLString: URLStringConvertible, - headers: [String: String]? = nil, - data: NSData) - -> Request -{ - return Manager.sharedInstance.upload(method, URLString, headers: headers, data: data) -} - -/** - Creates an upload request using the shared manager instance for the specified URL request and data. - - - parameter URLRequest: The URL request. - - parameter data: The data to upload. - - - returns: The created upload request. -*/ -public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request { - return Manager.sharedInstance.upload(URLRequest, data: data) -} - -// MARK: Stream - -/** - Creates an upload request using the shared manager instance for the specified method, URL string, and stream. - - - parameter method: The HTTP method. - - parameter URLString: The URL string. - - parameter headers: The HTTP headers. `nil` by default. - - parameter stream: The stream to upload. - - - returns: The created upload request. -*/ -public func upload( - method: Method, - _ URLString: URLStringConvertible, - headers: [String: String]? = nil, - stream: NSInputStream) - -> Request -{ - return Manager.sharedInstance.upload(method, URLString, headers: headers, stream: stream) -} - -/** - Creates an upload request using the shared manager instance for the specified URL request and stream. - - - parameter URLRequest: The URL request. - - parameter stream: The stream to upload. - - - returns: The created upload request. -*/ -public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request { - return Manager.sharedInstance.upload(URLRequest, stream: stream) -} - -// MARK: MultipartFormData - -/** - Creates an upload request using the shared manager instance for the specified method and URL string. - - - parameter method: The HTTP method. - - parameter URLString: The URL string. - - parameter headers: The HTTP headers. `nil` by default. - - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. - `MultipartFormDataEncodingMemoryThreshold` by default. - - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. -*/ -public func upload( - method: Method, - _ URLString: URLStringConvertible, - headers: [String: String]? = nil, - multipartFormData: MultipartFormData -> Void, - encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, - encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?) -{ - return Manager.sharedInstance.upload( - method, - URLString, - headers: headers, - multipartFormData: multipartFormData, - encodingMemoryThreshold: encodingMemoryThreshold, - encodingCompletion: encodingCompletion - ) -} - -/** - Creates an upload request using the shared manager instance for the specified method and URL string. - - - parameter URLRequest: The URL request. - - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. - `MultipartFormDataEncodingMemoryThreshold` by default. - - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. -*/ -public func upload( - URLRequest: URLRequestConvertible, - multipartFormData: MultipartFormData -> Void, - encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, - encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?) -{ - return Manager.sharedInstance.upload( - URLRequest, - multipartFormData: multipartFormData, - encodingMemoryThreshold: encodingMemoryThreshold, - encodingCompletion: encodingCompletion - ) -} - -// MARK: - Download Methods +// MARK: - Download Request // MARK: URL Request -/** - Creates a download request using the shared manager instance for the specified method and URL string. - - - parameter method: The HTTP method. - - parameter URLString: The URL string. - - parameter parameters: The parameters. `nil` by default. - - parameter encoding: The parameter encoding. `.URL` by default. - - parameter headers: The HTTP headers. `nil` by default. - - parameter destination: The closure used to determine the destination of the downloaded file. - - - returns: The created download 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( - method: Method, - _ URLString: URLStringConvertible, - parameters: [String: AnyObject]? = nil, - encoding: ParameterEncoding = .URL, - headers: [String: String]? = nil, - destination: Request.DownloadFileDestination) - -> Request + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest { - return Manager.sharedInstance.download( - method, - URLString, + return SessionManager.default.download( + url, + method: method, parameters: parameters, encoding: encoding, headers: headers, - destination: destination + to: destination ) } -/** - Creates a download request using the shared manager instance for the specified URL request. - - - parameter URLRequest: The URL request. - - parameter destination: The closure used to determine the destination of the downloaded file. - - - returns: The created download request. -*/ -public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request { - return Manager.sharedInstance.download(URLRequest, destination: 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 request using the shared manager instance for downloading from the resume data produced from a - previous request cancellation. - - - parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` - when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional - information. - - parameter destination: The closure used to determine the destination of the downloaded file. - - - returns: The created download request. -*/ -public func download(resumeData data: NSData, destination: Request.DownloadFileDestination) -> Request { - return Manager.sharedInstance.download(data, destination: destination) +/// 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. +/// +/// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` +/// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for additional +/// information. +/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. +/// +/// - returns: The created `DownloadRequest`. +@discardableResult +public func download( + resumingWith resumeData: Data, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest +{ + return SessionManager.default.download(resumingWith: resumeData, to: destination) } + +// MARK: - Upload Request + +// MARK: File + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` +/// for uploading the `file`. +/// +/// - parameter file: The file to upload. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload( + _ fileURL: URL, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest +{ + return SessionManager.default.upload(fileURL, to: url, method: method, headers: headers) +} + +/// Creates a `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for +/// uploading the `file`. +/// +/// - parameter file: The file to upload. +/// - parameter urlRequest: The URL request. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { + return SessionManager.default.upload(fileURL, with: urlRequest) +} + +// MARK: Data + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` +/// for uploading the `data`. +/// +/// - parameter data: The data to upload. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload( + _ data: Data, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest +{ + return SessionManager.default.upload(data, to: url, method: method, headers: headers) +} + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for +/// uploading the `data`. +/// +/// - parameter data: The data to upload. +/// - parameter urlRequest: The URL request. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { + return SessionManager.default.upload(data, with: urlRequest) +} + +// MARK: InputStream + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` +/// for uploading the `stream`. +/// +/// - parameter stream: The stream to upload. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload( + _ stream: InputStream, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest +{ + return SessionManager.default.upload(stream, to: url, method: method, headers: headers) +} + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for +/// uploading the `stream`. +/// +/// - parameter urlRequest: The URL request. +/// - parameter stream: The stream to upload. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { + return SessionManager.default.upload(stream, with: urlRequest) +} + +// MARK: MultipartFormData + +/// Encodes `multipartFormData` using `encodingMemoryThreshold` with the default `SessionManager` and calls +/// `encodingCompletion` with new `UploadRequest` using the `url`, `method` and `headers`. +/// +/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative +/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most +/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to +/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory +/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be +/// used for larger payloads such as video content. +/// +/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory +/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, +/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk +/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding +/// technique was used. +/// +/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. +/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. +/// `multipartFormDataEncodingMemoryThreshold` by default. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. +public func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) +{ + return SessionManager.default.upload( + multipartFormData: multipartFormData, + usingThreshold: encodingMemoryThreshold, + to: url, + method: method, + headers: headers, + encodingCompletion: encodingCompletion + ) +} + +/// Encodes `multipartFormData` using `encodingMemoryThreshold` and the default `SessionManager` and +/// calls `encodingCompletion` with new `UploadRequest` using the `urlRequest`. +/// +/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative +/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most +/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to +/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory +/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be +/// used for larger payloads such as video content. +/// +/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory +/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, +/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk +/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding +/// technique was used. +/// +/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. +/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. +/// `multipartFormDataEncodingMemoryThreshold` by default. +/// - parameter urlRequest: The URL request. +/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. +public func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + with urlRequest: URLRequestConvertible, + encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) +{ + return SessionManager.default.upload( + multipartFormData: multipartFormData, + usingThreshold: encodingMemoryThreshold, + with: urlRequest, + encodingCompletion: encodingCompletion + ) +} + +#if !os(watchOS) + +// MARK: - Stream Request + +// MARK: Hostname and Port + +/// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `hostname` +/// and `port`. +/// +/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. +/// +/// - parameter hostName: The hostname of the server to connect to. +/// - parameter port: The port of the server to connect to. +/// +/// - returns: The created `StreamRequest`. +@discardableResult +public func stream(withHostName hostName: String, port: Int) -> StreamRequest { + return SessionManager.default.stream(withHostName: hostName, port: port) +} + +// MARK: NetService + +/// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `netService`. +/// +/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. +/// +/// - parameter netService: The net service used to identify the endpoint. +/// +/// - returns: The created `StreamRequest`. +@discardableResult +public func stream(with netService: NetService) -> StreamRequest { + return SessionManager.default.stream(with: netService) +} + +#endif diff --git a/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift b/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift new file mode 100644 index 0000000..5019d0d --- /dev/null +++ b/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift @@ -0,0 +1,43 @@ +// +// DispatchQueue+Alamofire.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 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) } + + func after(_ delay: TimeInterval, execute closure: @escaping () -> Void) { + asyncAfter(deadline: .now() + delay, execute: closure) + } + + func syncResult(_ closure: () -> T) -> T { + var result: T! + sync { result = closure() } + return result + } +} diff --git a/Pods/Alamofire/Source/Download.swift b/Pods/Alamofire/Source/Download.swift deleted file mode 100644 index 97b146f..0000000 --- a/Pods/Alamofire/Source/Download.swift +++ /dev/null @@ -1,248 +0,0 @@ -// -// Download.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 - -extension Manager { - private enum Downloadable { - case Request(NSURLRequest) - case ResumeData(NSData) - } - - private func download(downloadable: Downloadable, destination: Request.DownloadFileDestination) -> Request { - var downloadTask: NSURLSessionDownloadTask! - - switch downloadable { - case .Request(let request): - dispatch_sync(queue) { - downloadTask = self.session.downloadTaskWithRequest(request) - } - case .ResumeData(let resumeData): - dispatch_sync(queue) { - downloadTask = self.session.downloadTaskWithResumeData(resumeData) - } - } - - let request = Request(session: session, task: downloadTask) - - if let downloadDelegate = request.delegate as? Request.DownloadTaskDelegate { - downloadDelegate.downloadTaskDidFinishDownloadingToURL = { session, downloadTask, URL in - return destination(URL, downloadTask.response as! NSHTTPURLResponse) - } - } - - delegate[request.delegate.task] = request.delegate - - if startRequestsImmediately { - request.resume() - } - - return request - } - - // MARK: Request - - /** - Creates a download request for the specified method, URL string, parameters, parameter encoding, headers - and destination. - - If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - - - parameter method: The HTTP method. - - parameter URLString: The URL string. - - parameter parameters: The parameters. `nil` by default. - - parameter encoding: The parameter encoding. `.URL` by default. - - parameter headers: The HTTP headers. `nil` by default. - - parameter destination: The closure used to determine the destination of the downloaded file. - - - returns: The created download request. - */ - public func download( - method: Method, - _ URLString: URLStringConvertible, - parameters: [String: AnyObject]? = nil, - encoding: ParameterEncoding = .URL, - headers: [String: String]? = nil, - destination: Request.DownloadFileDestination) - -> Request - { - let mutableURLRequest = URLRequest(method, URLString, headers: headers) - let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0 - - return download(encodedURLRequest, destination: destination) - } - - /** - Creates a request for downloading from the specified URL request. - - 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. - - - returns: The created download request. - */ - public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request { - return download(.Request(URLRequest.URLRequest), destination: destination) - } - - // MARK: Resume Data - - /** - Creates a request for downloading from the resume data produced from a previous request cancellation. - - If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - - - parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` - when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for - additional information. - - parameter destination: The closure used to determine the destination of the downloaded file. - - - returns: The created download request. - */ - public func download(resumeData: NSData, destination: Request.DownloadFileDestination) -> Request { - return download(.ResumeData(resumeData), destination: destination) - } -} - -// MARK: - - -extension Request { - /** - A closure executed once a 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 single argument: the file URL where the temporary file should be moved. - */ - public typealias DownloadFileDestination = (NSURL, NSHTTPURLResponse) -> NSURL - - /** - 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. - - - parameter directory: The search path directory. `.DocumentDirectory` by default. - - parameter domain: The search path domain mask. `.UserDomainMask` by default. - - - returns: A download file destination closure. - */ - public class func suggestedDownloadDestination( - directory directory: NSSearchPathDirectory = .DocumentDirectory, - domain: NSSearchPathDomainMask = .UserDomainMask) - -> DownloadFileDestination - { - return { temporaryURL, response -> NSURL in - let directoryURLs = NSFileManager.defaultManager().URLsForDirectory(directory, inDomains: domain) - - if !directoryURLs.isEmpty { - return directoryURLs[0].URLByAppendingPathComponent(response.suggestedFilename!) - } - - return temporaryURL - } - } - - /// The resume data of the underlying download task if available after a failure. - public var resumeData: NSData? { - var data: NSData? - - if let delegate = delegate as? DownloadTaskDelegate { - data = delegate.resumeData - } - - return data - } - - // MARK: - DownloadTaskDelegate - - class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate { - var downloadTask: NSURLSessionDownloadTask? { return task as? NSURLSessionDownloadTask } - var downloadProgress: ((Int64, Int64, Int64) -> Void)? - - var resumeData: NSData? - override var data: NSData? { return resumeData } - - // MARK: - NSURLSessionDownloadDelegate - - // MARK: Override Closures - - var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> NSURL)? - var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)? - var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)? - - // MARK: Delegate Methods - - func URLSession( - session: NSURLSession, - downloadTask: NSURLSessionDownloadTask, - didFinishDownloadingToURL location: NSURL) - { - if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { - do { - let destination = downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) - try NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination) - } catch { - self.error = error as NSError - } - } - } - - func URLSession( - session: NSURLSession, - downloadTask: NSURLSessionDownloadTask, - 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 - - downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) - } - } - - func URLSession( - session: NSURLSession, - downloadTask: NSURLSessionDownloadTask, - didResumeAtOffset fileOffset: Int64, - expectedTotalBytes: Int64) - { - if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { - downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) - } else { - progress.totalUnitCount = expectedTotalBytes - progress.completedUnitCount = fileOffset - } - } - } -} diff --git a/Pods/Alamofire/Source/Error.swift b/Pods/Alamofire/Source/Error.swift deleted file mode 100644 index 467d99c..0000000 --- a/Pods/Alamofire/Source/Error.swift +++ /dev/null @@ -1,88 +0,0 @@ -// -// Error.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 - -/// The `Error` struct provides a convenience for creating custom Alamofire NSErrors. -public struct Error { - /// The domain used for creating all Alamofire errors. - public static let Domain = "com.alamofire.error" - - /// The custom error codes generated by Alamofire. - public enum Code: Int { - case InputStreamReadFailed = -6000 - case OutputStreamWriteFailed = -6001 - case ContentTypeValidationFailed = -6002 - case StatusCodeValidationFailed = -6003 - case DataSerializationFailed = -6004 - case StringSerializationFailed = -6005 - case JSONSerializationFailed = -6006 - case PropertyListSerializationFailed = -6007 - } - - /// Custom keys contained within certain NSError `userInfo` dictionaries generated by Alamofire. - public struct UserInfoKeys { - /// The content type user info key for a `.ContentTypeValidationFailed` error stored as a `String` value. - public static let ContentType = "ContentType" - - /// The status code user info key for a `.StatusCodeValidationFailed` error stored as an `Int` value. - public static let StatusCode = "StatusCode" - } - - /** - Creates an `NSError` with the given error code and failure reason. - - - parameter code: The error code. - - parameter failureReason: The failure reason. - - - returns: An `NSError` with the given error code and failure reason. - */ - @available(*, deprecated=3.4.0) - public static func errorWithCode(code: Code, failureReason: String) -> NSError { - return errorWithCode(code.rawValue, failureReason: failureReason) - } - - /** - Creates an `NSError` with the given error code and failure reason. - - - parameter code: The error code. - - parameter failureReason: The failure reason. - - - returns: An `NSError` with the given error code and failure reason. - */ - @available(*, deprecated=3.4.0) - public static func errorWithCode(code: Int, failureReason: String) -> NSError { - let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] - return NSError(domain: Domain, code: code, userInfo: userInfo) - } - - static func error(domain domain: String = Error.Domain, code: Code, failureReason: String) -> NSError { - return error(domain: domain, code: code.rawValue, failureReason: failureReason) - } - - static func error(domain domain: String = Error.Domain, code: Int, failureReason: String) -> NSError { - let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] - return NSError(domain: domain, code: code, userInfo: userInfo) - } -} diff --git a/Pods/Alamofire/Source/Manager.swift b/Pods/Alamofire/Source/Manager.swift deleted file mode 100644 index 7b5f888..0000000 --- a/Pods/Alamofire/Source/Manager.swift +++ /dev/null @@ -1,755 +0,0 @@ -// -// Manager.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 creating and managing `Request` objects, as well as their underlying `NSURLSession`. -*/ -public class Manager { - - // MARK: - Properties - - /** - A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly - for any ad hoc requests. - */ - public static let sharedInstance: Manager = { - let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() - configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders - - return Manager(configuration: configuration) - }() - - /** - Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. - */ - public static let defaultHTTPHeaders: [String: String] = { - // 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 = NSLocale.preferredLanguages().prefix(6).enumerate().map { index, languageCode in - let quality = 1.0 - (Double(index) * 0.1) - return "\(languageCode);q=\(quality)" - }.joinWithSeparator(", ") - - // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 - let userAgent: String = { - if let info = NSBundle.mainBundle().infoDictionary { - let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" - let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" - let version = info[kCFBundleVersionKey as String] as? String ?? "Unknown" - let os = NSProcessInfo.processInfo().operatingSystemVersionString - - var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString - let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString - - if CFStringTransform(mutableUserAgent, UnsafeMutablePointer(nil), transform, false) { - return mutableUserAgent as String - } - } - - return "Alamofire" - }() - - return [ - "Accept-Encoding": acceptEncoding, - "Accept-Language": acceptLanguage, - "User-Agent": userAgent - ] - }() - - let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL) - - /// The underlying session. - public let session: NSURLSession - - /// The session delegate handling all the task and session delegate callbacks. - public let delegate: SessionDelegate - - /// Whether to start requests immediately after being constructed. `true` by default. - public var startRequestsImmediately: Bool = true - - /** - 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. - */ - public var backgroundCompletionHandler: (() -> Void)? - - // MARK: - Lifecycle - - /** - Initializes the `Manager` instance with the specified configuration, delegate and server trust policy. - - - parameter configuration: The configuration used to construct the managed session. - `NSURLSessionConfiguration.defaultSessionConfiguration()` 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 `Manager` instance. - */ - public init( - configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration(), - delegate: SessionDelegate = SessionDelegate(), - serverTrustPolicyManager: ServerTrustPolicyManager? = nil) - { - self.delegate = delegate - self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) - - commonInit(serverTrustPolicyManager: serverTrustPolicyManager) - } - - /** - Initializes the `Manager` instance with the specified session, delegate and server trust policy. - - - 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 `Manager` instance if the URL session's delegate matches the delegate parameter. - */ - public init?( - session: NSURLSession, - 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: ServerTrustPolicyManager?) { - session.serverTrustPolicyManager = serverTrustPolicyManager - - delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in - guard let strongSelf = self else { return } - dispatch_async(dispatch_get_main_queue()) { strongSelf.backgroundCompletionHandler?() } - } - } - - deinit { - session.invalidateAndCancel() - } - - // MARK: - Request - - /** - Creates a request for the specified method, URL string, parameters, parameter encoding and headers. - - - parameter method: The HTTP method. - - parameter URLString: The URL string. - - parameter parameters: The parameters. `nil` by default. - - parameter encoding: The parameter encoding. `.URL` by default. - - parameter headers: The HTTP headers. `nil` by default. - - - returns: The created request. - */ - public func request( - method: Method, - _ URLString: URLStringConvertible, - parameters: [String: AnyObject]? = nil, - encoding: ParameterEncoding = .URL, - headers: [String: String]? = nil) - -> Request - { - let mutableURLRequest = URLRequest(method, URLString, headers: headers) - let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0 - return request(encodedURLRequest) - } - - /** - Creates a request for the specified URL request. - - If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - - - parameter URLRequest: The URL request - - - returns: The created request. - */ - public func request(URLRequest: URLRequestConvertible) -> Request { - var dataTask: NSURLSessionDataTask! - dispatch_sync(queue) { dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest) } - - let request = Request(session: session, task: dataTask) - delegate[request.delegate.task] = request.delegate - - if startRequestsImmediately { - request.resume() - } - - return request - } - - // MARK: - SessionDelegate - - /** - Responsible for handling all delegate callbacks for the underlying session. - */ - public class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate { - private var subdelegates: [Int: Request.TaskDelegate] = [:] - private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) - - /// Access the task delegate for the specified task in a thread-safe manner. - public subscript(task: NSURLSessionTask) -> Request.TaskDelegate? { - get { - var subdelegate: Request.TaskDelegate? - dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] } - - return subdelegate - } - set { - dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue } - } - } - - /** - Initializes the `SessionDelegate` instance. - - - returns: The new `SessionDelegate` instance. - */ - public override init() { - super.init() - } - - // MARK: - NSURLSessionDelegate - - // MARK: Override Closures - - /// Overrides default behavior for NSURLSessionDelegate method `URLSession:didBecomeInvalidWithError:`. - public var sessionDidBecomeInvalidWithError: ((NSURLSession, NSError?) -> Void)? - - /// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`. - public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? - - /// Overrides all behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:` and requires the caller to call the `completionHandler`. - public var sessionDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)? - - /// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`. - public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)? - - // MARK: Delegate Methods - - /** - 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. - */ - public func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) { - sessionDidBecomeInvalidWithError?(session, error) - } - - /** - Requests credentials from the delegate in response to a session-level authentication request from the remote server. - - - 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. - */ - public func URLSession( - session: NSURLSession, - didReceiveChallenge challenge: NSURLAuthenticationChallenge, - completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) - { - guard sessionDidReceiveChallengeWithCompletion == nil else { - sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler) - return - } - - var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling - var credential: NSURLCredential? - - 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?.serverTrustPolicyForHost(host), - serverTrust = challenge.protectionSpace.serverTrust - { - if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) { - disposition = .UseCredential - credential = NSURLCredential(forTrust: serverTrust) - } else { - disposition = .CancelAuthenticationChallenge - } - } - } - - completionHandler(disposition, credential) - } - - /** - Tells the delegate that all messages enqueued for a session have been delivered. - - - parameter session: The session that no longer has any outstanding requests. - */ - public func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) { - sessionDidFinishEventsForBackgroundURLSession?(session) - } - - // MARK: - NSURLSessionTaskDelegate - - // MARK: Override Closures - - /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`. - public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? - - /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:` and - /// requires the caller to call the `completionHandler`. - public var taskWillPerformHTTPRedirectionWithCompletion: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest, NSURLRequest? -> Void) -> Void)? - - /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`. - public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? - - /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:` and - /// requires the caller to call the `completionHandler`. - public var taskDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)? - - /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`. - public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)? - - /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:` and - /// requires the caller to call the `completionHandler`. - public var taskNeedNewBodyStreamWithCompletion: ((NSURLSession, NSURLSessionTask, NSInputStream? -> Void) -> Void)? - - /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. - public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)? - - /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didCompleteWithError:`. - public var taskDidComplete: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)? - - // MARK: Delegate Methods - - /** - 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. - */ - public func URLSession( - session: NSURLSession, - task: NSURLSessionTask, - willPerformHTTPRedirection response: NSHTTPURLResponse, - newRequest request: NSURLRequest, - completionHandler: NSURLRequest? -> Void) - { - guard taskWillPerformHTTPRedirectionWithCompletion == nil else { - taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler) - return - } - - var redirectRequest: NSURLRequest? = request - - if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { - redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) - } - - completionHandler(redirectRequest) - } - - /** - 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. - */ - public func URLSession( - session: NSURLSession, - task: NSURLSessionTask, - didReceiveChallenge challenge: NSURLAuthenticationChallenge, - completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) - { - guard taskDidReceiveChallengeWithCompletion == nil else { - taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler) - return - } - - if let taskDidReceiveChallenge = taskDidReceiveChallenge { - let result = taskDidReceiveChallenge(session, task, challenge) - completionHandler(result.0, result.1) - } else if let delegate = self[task] { - delegate.URLSession( - session, - task: task, - didReceiveChallenge: challenge, - completionHandler: completionHandler - ) - } else { - URLSession(session, didReceiveChallenge: 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. - */ - public func URLSession( - session: NSURLSession, - task: NSURLSessionTask, - needNewBodyStream completionHandler: NSInputStream? -> 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.URLSession(session, task: task, needNewBodyStream: completionHandler) - } - } - - /** - 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. - */ - public func URLSession( - session: NSURLSession, - task: NSURLSessionTask, - didSendBodyData bytesSent: Int64, - totalBytesSent: Int64, - totalBytesExpectedToSend: Int64) - { - if let taskDidSendBodyData = taskDidSendBodyData { - taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) - } else if let delegate = self[task] as? Request.UploadTaskDelegate { - delegate.URLSession( - session, - task: task, - didSendBodyData: bytesSent, - totalBytesSent: totalBytesSent, - totalBytesExpectedToSend: totalBytesExpectedToSend - ) - } - } - - /** - 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. - */ - public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { - if let taskDidComplete = taskDidComplete { - taskDidComplete(session, task, error) - } else if let delegate = self[task] { - delegate.URLSession(session, task: task, didCompleteWithError: error) - } - - NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidComplete, object: task) - - self[task] = nil - } - - // MARK: - NSURLSessionDataDelegate - - // MARK: Override Closures - - /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`. - public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)? - - /// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:` and - /// requires caller to call the `completionHandler`. - public var dataTaskDidReceiveResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSURLResponse, NSURLSessionResponseDisposition -> Void) -> Void)? - - /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`. - public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)? - - /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveData:`. - public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)? - - /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`. - public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)? - - /// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:` and - /// requires caller to call the `completionHandler`. - public var dataTaskWillCacheResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse, NSCachedURLResponse? -> Void) -> Void)? - - // MARK: Delegate Methods - - /** - 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. - */ - public func URLSession( - session: NSURLSession, - dataTask: NSURLSessionDataTask, - didReceiveResponse response: NSURLResponse, - completionHandler: NSURLSessionResponseDisposition -> Void) - { - guard dataTaskDidReceiveResponseWithCompletion == nil else { - dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler) - return - } - - var disposition: NSURLSessionResponseDisposition = .Allow - - if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { - disposition = dataTaskDidReceiveResponse(session, dataTask, response) - } - - completionHandler(disposition) - } - - /** - 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. - */ - public func URLSession( - session: NSURLSession, - dataTask: NSURLSessionDataTask, - didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) - { - if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask { - dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask) - } else { - let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask) - self[downloadTask] = downloadDelegate - } - } - - /** - 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. - */ - public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { - if let dataTaskDidReceiveData = dataTaskDidReceiveData { - dataTaskDidReceiveData(session, dataTask, data) - } else if let delegate = self[dataTask] as? Request.DataTaskDelegate { - delegate.URLSession(session, dataTask: dataTask, didReceiveData: data) - } - } - - /** - Asks the delegate whether the data (or upload) task should store the response in the cache. - - - parameter session: The session containing the data (or upload) task. - - parameter dataTask: The data (or upload) task. - - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current - caching policy and the values of certain received headers, such as the Pragma - and Cache-Control headers. - - parameter completionHandler: A block that your handler must call, providing either the original proposed - response, a modified version of that response, or NULL to prevent caching the - response. If your delegate implements this method, it must call this completion - handler; otherwise, your app leaks memory. - */ - public func URLSession( - session: NSURLSession, - dataTask: NSURLSessionDataTask, - willCacheResponse proposedResponse: NSCachedURLResponse, - completionHandler: NSCachedURLResponse? -> Void) - { - guard dataTaskWillCacheResponseWithCompletion == nil else { - dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler) - return - } - - if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { - completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) - } else if let delegate = self[dataTask] as? Request.DataTaskDelegate { - delegate.URLSession( - session, - dataTask: dataTask, - willCacheResponse: proposedResponse, - completionHandler: completionHandler - ) - } else { - completionHandler(proposedResponse) - } - } - - // MARK: - NSURLSessionDownloadDelegate - - // MARK: Override Closures - - /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didFinishDownloadingToURL:`. - public var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> Void)? - - /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`. - public var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)? - - /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`. - public var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)? - - // MARK: Delegate Methods - - /** - 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. - */ - public func URLSession( - session: NSURLSession, - downloadTask: NSURLSessionDownloadTask, - didFinishDownloadingToURL location: NSURL) - { - if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { - downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) - } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { - delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location) - } - } - - /** - Periodically informs the delegate about the download’s progress. - - - parameter session: The session containing the download task. - - parameter downloadTask: The download task. - - parameter bytesWritten: The number of bytes transferred since the last time this delegate - method was called. - - parameter totalBytesWritten: The total number of bytes transferred so far. - - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length - header. If this header was not provided, the value is - `NSURLSessionTransferSizeUnknown`. - */ - public func URLSession( - session: NSURLSession, - downloadTask: NSURLSessionDownloadTask, - didWriteData bytesWritten: Int64, - totalBytesWritten: Int64, - totalBytesExpectedToWrite: Int64) - { - if let downloadTaskDidWriteData = downloadTaskDidWriteData { - downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) - } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { - delegate.URLSession( - session, - downloadTask: downloadTask, - didWriteData: bytesWritten, - totalBytesWritten: totalBytesWritten, - totalBytesExpectedToWrite: totalBytesExpectedToWrite - ) - } - } - - /** - 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. - */ - public func URLSession( - session: NSURLSession, - downloadTask: NSURLSessionDownloadTask, - didResumeAtOffset fileOffset: Int64, - expectedTotalBytes: Int64) - { - if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { - downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) - } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { - delegate.URLSession( - session, - downloadTask: downloadTask, - didResumeAtOffset: fileOffset, - expectedTotalBytes: expectedTotalBytes - ) - } - } - - // MARK: - NSURLSessionStreamDelegate - - var _streamTaskReadClosed: Any? - var _streamTaskWriteClosed: Any? - var _streamTaskBetterRouteDiscovered: Any? - var _streamTaskDidBecomeInputStream: Any? - - // MARK: - NSObject - - public override func respondsToSelector(selector: Selector) -> Bool { - #if !os(OSX) - if selector == #selector(NSURLSessionDelegate.URLSessionDidFinishEventsForBackgroundURLSession(_:)) { - return sessionDidFinishEventsForBackgroundURLSession != nil - } - #endif - - switch selector { - case #selector(NSURLSessionDelegate.URLSession(_:didBecomeInvalidWithError:)): - return sessionDidBecomeInvalidWithError != nil - case #selector(NSURLSessionDelegate.URLSession(_:didReceiveChallenge:completionHandler:)): - return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil) - case #selector(NSURLSessionTaskDelegate.URLSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)): - return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil) - case #selector(NSURLSessionDataDelegate.URLSession(_:dataTask:didReceiveResponse:completionHandler:)): - return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil) - default: - return self.dynamicType.instancesRespondToSelector(selector) - } - } - } -} diff --git a/Pods/Alamofire/Source/MultipartFormData.swift b/Pods/Alamofire/Source/MultipartFormData.swift index b4087ec..1ce4d19 100644 --- a/Pods/Alamofire/Source/MultipartFormData.swift +++ b/Pods/Alamofire/Source/MultipartFormData.swift @@ -26,65 +26,63 @@ import Foundation #if os(iOS) || os(watchOS) || os(tvOS) import MobileCoreServices -#elseif os(OSX) +#elseif os(macOS) import CoreServices #endif -/** - Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode - multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead - to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the - data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for - larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset. - - For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well - and the w3 form documentation. - - - https://www.ietf.org/rfc/rfc2388.txt - - https://www.ietf.org/rfc/rfc2045.txt - - https://www.w3.org/TR/html401/interact/forms.html#h-17.13 -*/ -public class MultipartFormData { +/// Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode +/// multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead +/// to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the +/// data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for +/// larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset. +/// +/// For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well +/// and the w3 form documentation. +/// +/// - https://www.ietf.org/rfc/rfc2388.txt +/// - https://www.ietf.org/rfc/rfc2045.txt +/// - https://www.w3.org/TR/html401/interact/forms.html#h-17.13 +open class MultipartFormData { // MARK: - Helper Types struct EncodingCharacters { - static let CRLF = "\r\n" + static let crlf = "\r\n" } struct BoundaryGenerator { enum BoundaryType { - case Initial, Encapsulated, Final + case initial, encapsulated, final } static func randomBoundary() -> String { return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random()) } - static func boundaryData(boundaryType boundaryType: BoundaryType, boundary: String) -> NSData { + static func boundaryData(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data { let boundaryText: String switch boundaryType { - case .Initial: - boundaryText = "--\(boundary)\(EncodingCharacters.CRLF)" - case .Encapsulated: - boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)\(EncodingCharacters.CRLF)" - case .Final: - boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)--\(EncodingCharacters.CRLF)" + case .initial: + boundaryText = "--\(boundary)\(EncodingCharacters.crlf)" + case .encapsulated: + boundaryText = "\(EncodingCharacters.crlf)--\(boundary)\(EncodingCharacters.crlf)" + case .final: + boundaryText = "\(EncodingCharacters.crlf)--\(boundary)--\(EncodingCharacters.crlf)" } - return boundaryText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! + return boundaryText.data(using: String.Encoding.utf8, allowLossyConversion: false)! } } class BodyPart { - let headers: [String: String] - let bodyStream: NSInputStream + let headers: HTTPHeaders + let bodyStream: InputStream let bodyContentLength: UInt64 var hasInitialBoundary = false var hasFinalBoundary = false - init(headers: [String: String], bodyStream: NSInputStream, bodyContentLength: UInt64) { + init(headers: HTTPHeaders, bodyStream: InputStream, bodyContentLength: UInt64) { self.headers = headers self.bodyStream = bodyStream self.bodyContentLength = bodyContentLength @@ -94,7 +92,7 @@ public class MultipartFormData { // MARK: - Properties /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`. - public var contentType: String { return "multipart/form-data; boundary=\(boundary)" } + open var contentType: String { return "multipart/form-data; boundary=\(boundary)" } /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries. public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } } @@ -103,151 +101,137 @@ public class MultipartFormData { public let boundary: String private var bodyParts: [BodyPart] - private var bodyPartError: NSError? + private var bodyPartError: AFError? private let streamBufferSize: Int // MARK: - Lifecycle - /** - Creates a multipart form data object. - - - returns: The multipart form data object. - */ + /// Creates a multipart form data object. + /// + /// - 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 - */ + /// + /// 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 } // MARK: - Body Parts - /** - 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 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) - 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 appendBodyPart(data data: NSData, name: String) { - let headers = contentHeaders(name: name) - let stream = NSInputStream(data: data) - let length = UInt64(data.length) - - appendBodyPart(stream: stream, length: length, headers: headers) + 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 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) - 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 appendBodyPart(data data: NSData, name: String, mimeType: String) { - let headers = contentHeaders(name: name, mimeType: mimeType) - let stream = NSInputStream(data: data) - let length = UInt64(data.length) - - appendBodyPart(stream: stream, length: length, headers: headers) + 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 multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) + /// - `Content-Type: #{mimeType}` (HTTP Header) + /// - Encoded file data + /// - Multipart form boundary + /// + /// - 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) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + let stream = InputStream(data: data) + let length = UInt64(data.count) - The body part data will be encoded using the following format: - - - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) - - `Content-Type: #{mimeType}` (HTTP Header) - - Encoded file data - - Multipart form boundary - - - 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 appendBodyPart(data data: NSData, name: String, fileName: String, mimeType: String) { - let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType) - let stream = NSInputStream(data: data) - let length = UInt64(data.length) - - appendBodyPart(stream: stream, length: length, headers: headers) + 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 multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header) + /// - `Content-Type: #{generated mimeType}` (HTTP Header) + /// - Encoded file data + /// - Multipart form boundary + /// + /// The filename in the `Content-Disposition` HTTP header is generated from the last path component of the + /// `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the + /// system associated MIME type. + /// + /// - 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. + public func append(_ fileURL: URL, withName name: String) { + let fileName = fileURL.lastPathComponent + let pathExtension = fileURL.pathExtension - The body part data will be encoded using the following format: - - - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header) - - `Content-Type: #{generated mimeType}` (HTTP Header) - - Encoded file data - - Multipart form boundary - - The filename in the `Content-Disposition` HTTP header is generated from the last path component of the - `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the - system associated MIME type. - - - 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. - */ - public func appendBodyPart(fileURL fileURL: NSURL, name: String) { - if let - fileName = fileURL.lastPathComponent, - pathExtension = fileURL.pathExtension - { - let mimeType = mimeTypeForPathExtension(pathExtension) - appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType) + if !fileName.isEmpty && !pathExtension.isEmpty { + let mime = mimeType(forPathExtension: pathExtension) + append(fileURL, withName: name, fileName: fileName, mimeType: mime) } else { - let failureReason = "Failed to extract the fileName of the provided URL: \(fileURL)" - setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) + setBodyPartError(withReason: .bodyPartFilenameInvalid(in: fileURL)) } } - /** - Creates a body part from the file 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}; filename=#{filename} (HTTP Header) - - Content-Type: #{mimeType} (HTTP Header) - - 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. - */ - public func appendBodyPart(fileURL fileURL: NSURL, name: String, fileName: String, mimeType: String) { - let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType) + /// Creates a body part from the file 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}; filename=#{filename} (HTTP Header) + /// - Content-Type: #{mimeType} (HTTP Header) + /// - 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. + public func append(_ fileURL: URL, withName name: String, fileName: String, mimeType: String) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) //============================================================ // Check 1 - is file URL? //============================================================ - guard fileURL.fileURL else { - let failureReason = "The file URL does not point to a file URL: \(fileURL)" - setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) + guard fileURL.isFileURL else { + setBodyPartError(withReason: .bodyPartURLInvalid(url: fileURL)) return } @@ -255,14 +239,14 @@ public class MultipartFormData { // Check 2 - is file URL reachable? //============================================================ - var isReachable = true - - if #available(OSX 10.10, *) { - isReachable = fileURL.checkPromisedItemIsReachableAndReturnError(nil) - } - - guard isReachable else { - setBodyPartError(code: NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)") + do { + let isReachable = try fileURL.checkPromisedItemIsReachable() + guard isReachable else { + setBodyPartError(withReason: .bodyPartFileNotReachable(at: fileURL)) + return + } + } catch { + setBodyPartError(withReason: .bodyPartFileNotReachableWithError(atURL: fileURL, error: error)) return } @@ -271,13 +255,11 @@ public class MultipartFormData { //============================================================ var isDirectory: ObjCBool = false + let path = fileURL.path - guard let - path = fileURL.path - where NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) && !isDirectory else + guard FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) && !isDirectory.boolValue else { - let failureReason = "The file URL is a directory, not a file: \(fileURL)" - setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) + setBodyPartError(withReason: .bodyPartFileIsDirectory(at: fileURL)) return } @@ -285,22 +267,18 @@ public class MultipartFormData { // Check 4 - can the file size be extracted? //============================================================ - var bodyContentLength: UInt64? + let bodyContentLength: UInt64 do { - if let - path = fileURL.path, - fileSize = try NSFileManager.defaultManager().attributesOfItemAtPath(path)[NSFileSize] as? NSNumber - { - bodyContentLength = fileSize.unsignedLongLongValue + guard let fileSize = try FileManager.default.attributesOfItem(atPath: path)[.size] as? NSNumber else { + setBodyPartError(withReason: .bodyPartFileSizeNotAvailable(at: fileURL)) + return } - } catch { - // No-op - } - guard let length = bodyContentLength else { - let failureReason = "Could not fetch attributes from the file URL: \(fileURL)" - setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) + bodyContentLength = fileSize.uint64Value + } + catch { + setBodyPartError(withReason: .bodyPartFileSizeQueryFailedWithError(forURL: fileURL, error: error)) return } @@ -308,236 +286,206 @@ public class MultipartFormData { // Check 5 - can a stream be created from file URL? //============================================================ - guard let stream = NSInputStream(URL: fileURL) else { - let failureReason = "Failed to create an input stream from the file URL: \(fileURL)" - setBodyPartError(code: NSURLErrorCannotOpenFile, failureReason: failureReason) + guard let stream = InputStream(url: fileURL) else { + setBodyPartError(withReason: .bodyPartInputStreamCreationFailed(for: fileURL)) return } - appendBodyPart(stream: stream, length: length, headers: headers) + append(stream, withLength: bodyContentLength, headers: headers) } - /** - Creates a body part from the stream 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}; filename=#{filename}` (HTTP Header) - - `Content-Type: #{mimeType}` (HTTP Header) - - 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 appendBodyPart( - stream stream: NSInputStream, - length: UInt64, + /// Creates a body part from the stream 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}; filename=#{filename}` (HTTP Header) + /// - `Content-Type: #{mimeType}` (HTTP Header) + /// - 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) { - let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType) - appendBodyPart(stream: stream, length: length, headers: headers) + 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. - - The body part data will be encoded using the following format: - - - HTTP headers - - 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. - */ - public func appendBodyPart(stream stream: NSInputStream, length: UInt64, headers: [String: String]) { + /// Creates a body part with the headers, stream and length and appends it to the multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - HTTP headers + /// - 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. + public func append(_ stream: InputStream, withLength length: UInt64, headers: HTTPHeaders) { let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length) bodyParts.append(bodyPart) } // MARK: - Data Encoding - /** - Encodes all the appended body parts into a single `NSData` object. - - 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. - - - throws: An `NSError` if encoding encounters an error. - - - returns: The encoded `NSData` if encoding is successful. - */ - public func encode() throws -> NSData { + /// 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. + /// + /// - throws: An `AFError` if encoding encounters an error. + /// + /// - returns: The encoded `Data` if encoding is successful. + public func encode() throws -> Data { if let bodyPartError = bodyPartError { throw bodyPartError } - let encoded = NSMutableData() + var encoded = Data() bodyParts.first?.hasInitialBoundary = true bodyParts.last?.hasFinalBoundary = true for bodyPart in bodyParts { - let encodedData = try encodeBodyPart(bodyPart) - encoded.appendData(encodedData) + let encodedData = try encode(bodyPart) + encoded.append(encodedData) } return encoded } - /** - Writes the appended body parts into 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 `NSError` if encoding encounters an error. - */ - public func writeEncodedDataToDisk(fileURL: NSURL) throws { + /// Writes the appended body parts into 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. + public func writeEncodedData(to fileURL: URL) throws { if let bodyPartError = bodyPartError { throw bodyPartError } - if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) { - let failureReason = "A file already exists at the given file URL: \(fileURL)" - throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason) - } else if !fileURL.fileURL { - let failureReason = "The URL does not point to a valid file: \(fileURL)" - throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason) + if FileManager.default.fileExists(atPath: fileURL.path) { + throw AFError.multipartEncodingFailed(reason: .outputStreamFileAlreadyExists(at: fileURL)) + } else if !fileURL.isFileURL { + throw AFError.multipartEncodingFailed(reason: .outputStreamURLInvalid(url: fileURL)) } - let outputStream: NSOutputStream - - if let possibleOutputStream = NSOutputStream(URL: fileURL, append: false) { - outputStream = possibleOutputStream - } else { - let failureReason = "Failed to create an output stream with the given URL: \(fileURL)" - throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorCannotOpenFile, failureReason: failureReason) + guard let outputStream = OutputStream(url: fileURL, append: false) else { + throw AFError.multipartEncodingFailed(reason: .outputStreamCreationFailed(for: fileURL)) } outputStream.open() + defer { outputStream.close() } self.bodyParts.first?.hasInitialBoundary = true self.bodyParts.last?.hasFinalBoundary = true for bodyPart in self.bodyParts { - try writeBodyPart(bodyPart, toOutputStream: outputStream) + try write(bodyPart, to: outputStream) } - - outputStream.close() } // MARK: - Private - Body Part Encoding - private func encodeBodyPart(bodyPart: BodyPart) throws -> NSData { - let encoded = NSMutableData() + private func encode(_ bodyPart: BodyPart) throws -> Data { + var encoded = Data() let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() - encoded.appendData(initialData) + encoded.append(initialData) - let headerData = encodeHeaderDataForBodyPart(bodyPart) - encoded.appendData(headerData) + let headerData = encodeHeaders(for: bodyPart) + encoded.append(headerData) - let bodyStreamData = try encodeBodyStreamDataForBodyPart(bodyPart) - encoded.appendData(bodyStreamData) + let bodyStreamData = try encodeBodyStream(for: bodyPart) + encoded.append(bodyStreamData) if bodyPart.hasFinalBoundary { - encoded.appendData(finalBoundaryData()) + encoded.append(finalBoundaryData()) } return encoded } - private func encodeHeaderDataForBodyPart(bodyPart: BodyPart) -> NSData { + private func encodeHeaders(for bodyPart: BodyPart) -> Data { var headerText = "" for (key, value) in bodyPart.headers { - headerText += "\(key): \(value)\(EncodingCharacters.CRLF)" + headerText += "\(key): \(value)\(EncodingCharacters.crlf)" } - headerText += EncodingCharacters.CRLF + headerText += EncodingCharacters.crlf - return headerText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! + return headerText.data(using: String.Encoding.utf8, allowLossyConversion: false)! } - private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) throws -> NSData { + private func encodeBodyStream(for bodyPart: BodyPart) throws -> Data { let inputStream = bodyPart.bodyStream inputStream.open() + defer { inputStream.close() } - var error: NSError? - let encoded = NSMutableData() + var encoded = Data() while inputStream.hasBytesAvailable { - var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0) + var buffer = [UInt8](repeating: 0, count: streamBufferSize) let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) - if inputStream.streamError != nil { - error = inputStream.streamError - break + if let error = inputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error)) } if bytesRead > 0 { - encoded.appendBytes(buffer, length: bytesRead) - } else if bytesRead < 0 { - let failureReason = "Failed to read from input stream: \(inputStream)" - error = Error.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason) - break + encoded.append(buffer, count: bytesRead) } else { break } } - inputStream.close() - - if let error = error { - throw error - } - return encoded } // MARK: - Private - Writing Body Part to Output Stream - private func writeBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { - try writeInitialBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream) - try writeHeaderDataForBodyPart(bodyPart, toOutputStream: outputStream) - try writeBodyStreamForBodyPart(bodyPart, toOutputStream: outputStream) - try writeFinalBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream) + private func write(_ bodyPart: BodyPart, to outputStream: OutputStream) throws { + try writeInitialBoundaryData(for: bodyPart, to: outputStream) + try writeHeaderData(for: bodyPart, to: outputStream) + try writeBodyStream(for: bodyPart, to: outputStream) + try writeFinalBoundaryData(for: bodyPart, to: outputStream) } - private func writeInitialBoundaryDataForBodyPart( - bodyPart: BodyPart, - toOutputStream outputStream: NSOutputStream) - throws - { + private func writeInitialBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() - return try writeData(initialData, toOutputStream: outputStream) + return try write(initialData, to: outputStream) } - private func writeHeaderDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { - let headerData = encodeHeaderDataForBodyPart(bodyPart) - return try writeData(headerData, toOutputStream: outputStream) + private func writeHeaderData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let headerData = encodeHeaders(for: bodyPart) + return try write(headerData, to: outputStream) } - private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { + private func writeBodyStream(for bodyPart: BodyPart, to outputStream: OutputStream) throws { let inputStream = bodyPart.bodyStream + inputStream.open() + defer { inputStream.close() } while inputStream.hasBytesAvailable { - var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0) + var buffer = [UInt8](repeating: 0, count: streamBufferSize) let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) if let streamError = inputStream.streamError { - throw streamError + throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: streamError)) } if bytesRead > 0 { @@ -545,70 +493,52 @@ public class MultipartFormData { buffer = Array(buffer[0.. 0 { - if outputStream.hasSpaceAvailable { - let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite) + while bytesToWrite > 0, outputStream.hasSpaceAvailable { + let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite) - if let streamError = outputStream.streamError { - throw streamError - } + if let error = outputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .outputStreamWriteFailed(error: error)) + } - if bytesWritten < 0 { - let failureReason = "Failed to write to output stream: \(outputStream)" - throw Error.error(domain: NSURLErrorDomain, code: .OutputStreamWriteFailed, failureReason: failureReason) - } + bytesToWrite -= bytesWritten - bytesToWrite -= bytesWritten - - if bytesToWrite > 0 { - buffer = Array(buffer[bytesWritten.. 0 { + buffer = Array(buffer[bytesWritten.. String { - if let - id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil)?.takeRetainedValue(), - contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() + private func mimeType(forPathExtension pathExtension: String) -> String { + if + let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), + let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() { return contentType as String } @@ -618,42 +548,34 @@ public class MultipartFormData { // MARK: - Private - Content Headers - private func contentHeaders(name name: String) -> [String: String] { - return ["Content-Disposition": "form-data; name=\"\(name)\""] - } + private func contentHeaders(withName name: String, fileName: String? = nil, mimeType: String? = nil) -> [String: String] { + var disposition = "form-data; name=\"\(name)\"" + if let fileName = fileName { disposition += "; filename=\"\(fileName)\"" } - private func contentHeaders(name name: String, mimeType: String) -> [String: String] { - return [ - "Content-Disposition": "form-data; name=\"\(name)\"", - "Content-Type": "\(mimeType)" - ] - } + var headers = ["Content-Disposition": disposition] + if let mimeType = mimeType { headers["Content-Type"] = mimeType } - private func contentHeaders(name name: String, fileName: String, mimeType: String) -> [String: String] { - return [ - "Content-Disposition": "form-data; name=\"\(name)\"; filename=\"\(fileName)\"", - "Content-Type": "\(mimeType)" - ] + return headers } // MARK: - Private - Boundary Encoding - private func initialBoundaryData() -> NSData { - return BoundaryGenerator.boundaryData(boundaryType: .Initial, boundary: boundary) + private func initialBoundaryData() -> Data { + return BoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary) } - private func encapsulatedBoundaryData() -> NSData { - return BoundaryGenerator.boundaryData(boundaryType: .Encapsulated, boundary: boundary) + private func encapsulatedBoundaryData() -> Data { + return BoundaryGenerator.boundaryData(forBoundaryType: .encapsulated, boundary: boundary) } - private func finalBoundaryData() -> NSData { - return BoundaryGenerator.boundaryData(boundaryType: .Final, boundary: boundary) + private func finalBoundaryData() -> Data { + return BoundaryGenerator.boundaryData(forBoundaryType: .final, boundary: boundary) } // MARK: - Private - Errors - private func setBodyPartError(code code: Int, failureReason: String) { + private func setBodyPartError(withReason reason: AFError.MultipartEncodingFailureReason) { guard bodyPartError == nil else { return } - bodyPartError = Error.error(domain: NSURLErrorDomain, code: code, failureReason: failureReason) + bodyPartError = AFError.multipartEncodingFailed(reason: reason) } } diff --git a/Pods/Alamofire/Source/NetworkReachabilityManager.swift b/Pods/Alamofire/Source/NetworkReachabilityManager.swift index 949ed28..c06a60e 100644 --- a/Pods/Alamofire/Source/NetworkReachabilityManager.swift +++ b/Pods/Alamofire/Source/NetworkReachabilityManager.swift @@ -27,15 +27,13 @@ import Foundation import SystemConfiguration -/** - The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and - WiFi network interfaces. - - Reachability can be used to determine background information about why a network operation failed, or to 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 { +/// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and +/// WiFi network interfaces. +/// +/// Reachability can be used to determine background information about why a network operation failed, or to retry +/// network requests when a connection is established. It should not be used to prevent a user from initiating a network +/// request, as it's possible that an initial request may be required to establish reachability. +open class NetworkReachabilityManager { /** Defines the various states of network reachability. @@ -44,49 +42,54 @@ public class NetworkReachabilityManager { - ReachableOnWWAN: The network is reachable over the WWAN connection. - ReachableOnWiFi: The network is reachable over the WiFi connection. */ + + + /// 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 { - case Unknown - case NotReachable - case Reachable(ConnectionType) + case unknown + case notReachable + 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. - */ + /// 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 + case ethernetOrWiFi + case wwan } - /// A closure executed when the network reachability status changes. The closure takes a single argument: the + /// A closure executed when the network reachability status changes. The closure takes a single argument: the /// network reachability status. - public typealias Listener = NetworkReachabilityStatus -> Void + public typealias Listener = (NetworkReachabilityStatus) -> Void // MARK: - Properties /// Whether the network is currently reachable. - public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi } + open var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi } /// Whether the network is currently reachable over the WWAN interface. - public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .Reachable(.WWAN) } + open var isReachableOnWWAN: Bool { return networkReachabilityStatus == .reachable(.wwan) } /// Whether the network is currently reachable over Ethernet or WiFi interface. - public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .Reachable(.EthernetOrWiFi) } + open var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .reachable(.ethernetOrWiFi) } /// The current network reachability status. - public var networkReachabilityStatus: NetworkReachabilityStatus { - guard let flags = self.flags else { return .Unknown } + open var networkReachabilityStatus: NetworkReachabilityStatus { + guard let flags = self.flags else { return .unknown } return networkReachabilityStatusForFlags(flags) } /// The dispatch queue to execute the `listener` closure on. - public var listenerQueue: dispatch_queue_t = dispatch_get_main_queue() + open var listenerQueue: DispatchQueue = DispatchQueue.main /// A closure executed when the network reachability status changes. - public var listener: Listener? + open var listener: Listener? private var flags: SCNetworkReachabilityFlags? { var flags = SCNetworkReachabilityFlags() @@ -103,45 +106,34 @@ public class NetworkReachabilityManager { // MARK: - Initialization - /** - Creates a `NetworkReachabilityManager` instance with the specified host. - - - parameter host: The host used to evaluate network reachability. - - - returns: The new `NetworkReachabilityManager` instance. - */ + /// Creates a `NetworkReachabilityManager` instance with the specified host. + /// + /// - parameter host: The host used to evaluate network reachability. + /// + /// - returns: The new `NetworkReachabilityManager` instance. public convenience init?(host: String) { guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } self.init(reachability: reachability) } - /** - Creates a `NetworkReachabilityManager` instance with the default socket IPv4 or IPv6 address. - - - returns: The new `NetworkReachabilityManager` instance. - */ + /// Creates a `NetworkReachabilityManager` 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?() { - if #available(iOS 9.0, OSX 10.10, *) { - var address = sockaddr_in6() - address.sin6_len = UInt8(sizeofValue(address)) - address.sin6_family = sa_family_t(AF_INET6) + var address = sockaddr_in() + address.sin_len = UInt8(MemoryLayout.size) + address.sin_family = sa_family_t(AF_INET) - guard let reachability = withUnsafePointer(&address, { - SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) - }) else { return nil } + guard let reachability = withUnsafePointer(to: &address, { pointer in + return pointer.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout.size) { + return SCNetworkReachabilityCreateWithAddress(nil, $0) + } + }) else { return nil } - self.init(reachability: reachability) - } else { - var address = sockaddr_in() - address.sin_len = UInt8(sizeofValue(address)) - address.sin_family = sa_family_t(AF_INET) - - guard let reachability = withUnsafePointer(&address, { - SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) - }) else { return nil } - - self.init(reachability: reachability) - } + self.init(reachability: reachability) } private init(reachability: SCNetworkReachability) { @@ -155,19 +147,18 @@ public class NetworkReachabilityManager { // MARK: - Listening - /** - Starts listening for changes in network reachability status. - - - returns: `true` if listening was started successfully, `false` otherwise. - */ - public func startListening() -> Bool { + /// Starts listening for changes in network reachability status. + /// + /// - returns: `true` if listening was started successfully, `false` otherwise. + @discardableResult + open func startListening() -> Bool { var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) - context.info = UnsafeMutablePointer(Unmanaged.passUnretained(self).toOpaque()) + context.info = Unmanaged.passUnretained(self).toOpaque() let callbackEnabled = SCNetworkReachabilitySetCallback( reachability, { (_, flags, info) in - let reachability = Unmanaged.fromOpaque(COpaquePointer(info)).takeUnretainedValue() + let reachability = Unmanaged.fromOpaque(info!).takeUnretainedValue() reachability.notifyListener(flags) }, &context @@ -175,7 +166,7 @@ public class NetworkReachabilityManager { let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue) - dispatch_async(listenerQueue) { + listenerQueue.async { self.previousFlags = SCNetworkReachabilityFlags() self.notifyListener(self.flags ?? SCNetworkReachabilityFlags()) } @@ -183,17 +174,15 @@ public class NetworkReachabilityManager { return callbackEnabled && queueEnabled } - /** - Stops listening for changes in network reachability status. - */ - public func stopListening() { + /// Stops listening for changes in network reachability status. + open func stopListening() { SCNetworkReachabilitySetCallback(reachability, nil, nil) SCNetworkReachabilitySetDispatchQueue(reachability, nil) } // MARK: - Internal - Listener Notification - func notifyListener(flags: SCNetworkReachabilityFlags) { + func notifyListener(_ flags: SCNetworkReachabilityFlags) { guard previousFlags != flags else { return } previousFlags = flags @@ -202,19 +191,19 @@ public class NetworkReachabilityManager { // MARK: - Internal - Network Reachability Status - func networkReachabilityStatusForFlags(flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus { - guard flags.contains(.Reachable) else { return .NotReachable } + func networkReachabilityStatusForFlags(_ flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus { + guard flags.contains(.reachable) else { return .notReachable } - var networkStatus: NetworkReachabilityStatus = .NotReachable + var networkStatus: NetworkReachabilityStatus = .notReachable - if !flags.contains(.ConnectionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) } + if !flags.contains(.connectionRequired) { networkStatus = .reachable(.ethernetOrWiFi) } - if flags.contains(.ConnectionOnDemand) || flags.contains(.ConnectionOnTraffic) { - if !flags.contains(.InterventionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) } + if flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic) { + if !flags.contains(.interventionRequired) { networkStatus = .reachable(.ethernetOrWiFi) } } #if os(iOS) - if flags.contains(.IsWWAN) { networkStatus = .Reachable(.WWAN) } + if flags.contains(.isWWAN) { networkStatus = .reachable(.wwan) } #endif return networkStatus @@ -225,25 +214,23 @@ 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. -*/ +/// 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): + case (.unknown, .unknown): return true - case (.NotReachable, .NotReachable): + case (.notReachable, .notReachable): return true - case let (.Reachable(lhsConnectionType), .Reachable(rhsConnectionType)): + case let (.reachable(lhsConnectionType), .reachable(rhsConnectionType)): return lhsConnectionType == rhsConnectionType default: return false diff --git a/Pods/Alamofire/Source/Notifications.swift b/Pods/Alamofire/Source/Notifications.swift index cece87a..81f6e37 100644 --- a/Pods/Alamofire/Source/Notifications.swift +++ b/Pods/Alamofire/Source/Notifications.swift @@ -24,24 +24,29 @@ import Foundation -/// Contains all the `NSNotification` names posted by Alamofire with descriptions of each notification's payload. -public struct Notifications { - /// Used as a namespace for all `NSURLSessionTask` related notifications. +extension Notification.Name { + /// Used as a namespace for all `URLSessionTask` related notifications. public struct Task { - /// Notification posted when an `NSURLSessionTask` is resumed. The notification `object` contains the resumed - /// `NSURLSessionTask`. - public static let DidResume = "com.alamofire.notifications.task.didResume" + /// 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") - /// Notification posted when an `NSURLSessionTask` is suspended. The notification `object` contains the - /// suspended `NSURLSessionTask`. - public static let DidSuspend = "com.alamofire.notifications.task.didSuspend" + /// 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") - /// Notification posted when an `NSURLSessionTask` is cancelled. The notification `object` contains the - /// cancelled `NSURLSessionTask`. - public static let DidCancel = "com.alamofire.notifications.task.didCancel" + /// 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") - /// Notification posted when an `NSURLSessionTask` is completed. The notification `object` contains the - /// completed `NSURLSessionTask`. - public static let DidComplete = "com.alamofire.notifications.task.didComplete" + /// 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") + } +} + +// MARK: - + +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" } } diff --git a/Pods/Alamofire/Source/ParameterEncoding.swift b/Pods/Alamofire/Source/ParameterEncoding.swift index bfa4d12..42b5b2d 100644 --- a/Pods/Alamofire/Source/ParameterEncoding.swift +++ b/Pods/Alamofire/Source/ParameterEncoding.swift @@ -24,176 +24,153 @@ import Foundation -/** - HTTP method definitions. - - See https://tools.ietf.org/html/rfc7231#section-4.3 -*/ -public enum Method: String { - case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT +/// 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: ParameterEncoding +// MARK: - -/** - Used to specify the way in which a set of parameters are applied to a URL request. +/// A dictionary of parameters to apply to a `URLRequest`. +public typealias Parameters = [String: Any] - - `URL`: Creates a query string to be set as or appended to any existing URL query for `GET`, `HEAD`, - and `DELETE` requests, or set as the body for requests with any other HTTP method. 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`). +/// 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. + /// + /// - throws: An `AFError.parameterEncodingFailed` error if encoding fails. + /// + /// - returns: The encoded request. + func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest +} - - `URLEncodedInURL`: Creates query string to be set as or appended to any existing URL query. Uses the same - implementation as the `.URL` case, but always applies the encoded result to the URL. +// MARK: - - - `JSON`: Uses `NSJSONSerialization` 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`. +/// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP +/// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as +/// the HTTP body depends on the destination of the encoding. +/// +/// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to +/// `application/x-www-form-urlencoded; charset=utf-8`. 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`). +public struct URLEncoding: ParameterEncoding { - - `PropertyList`: Uses `NSPropertyListSerialization` 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`. + // MARK: Helper Types - - `Custom`: Uses the associated closure value to construct a new request given an existing request and - parameters. -*/ -public enum ParameterEncoding { - case URL - case URLEncodedInURL - case JSON - case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions) - case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?)) - - /** - 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. - - - returns: A tuple containing the constructed request and the error that occurred during parameter encoding, - if any. - */ - public func encode( - URLRequest: URLRequestConvertible, - parameters: [String: AnyObject]?) - -> (NSMutableURLRequest, NSError?) - { - var mutableURLRequest = URLRequest.URLRequest - - guard let parameters = parameters else { return (mutableURLRequest, nil) } - - var encodingError: NSError? = nil - - switch self { - case .URL, .URLEncodedInURL: - func query(parameters: [String: AnyObject]) -> String { - var components: [(String, String)] = [] - - for key in parameters.keys.sort(<) { - let value = parameters[key]! - components += queryComponents(key, value) - } - - return (components.map { "\($0)=\($1)" } as [String]).joinWithSeparator("&") - } - - func encodesParametersInURL(method: Method) -> Bool { - switch self { - case .URLEncodedInURL: - return true - default: - break - } - - switch method { - case .GET, .HEAD, .DELETE: - return true - default: - return false - } - } - - if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) { - if let - URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) - where !parameters.isEmpty - { - let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) - URLComponents.percentEncodedQuery = percentEncodedQuery - mutableURLRequest.URL = URLComponents.URL - } - } else { - if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { - mutableURLRequest.setValue( - "application/x-www-form-urlencoded; charset=utf-8", - forHTTPHeaderField: "Content-Type" - ) - } - - mutableURLRequest.HTTPBody = query(parameters).dataUsingEncoding( - NSUTF8StringEncoding, - allowLossyConversion: false - ) - } - case .JSON: - do { - let options = NSJSONWritingOptions() - let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options) - - if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { - mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") - } - - mutableURLRequest.HTTPBody = data - } catch { - encodingError = error as NSError - } - case .PropertyList(let format, let options): - do { - let data = try NSPropertyListSerialization.dataWithPropertyList( - parameters, - format: format, - options: options - ) - - if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { - mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") - } - - mutableURLRequest.HTTPBody = data - } catch { - encodingError = error as NSError - } - case .Custom(let closure): - (mutableURLRequest, encodingError) = closure(mutableURLRequest, parameters) - } - - return (mutableURLRequest, encodingError) + /// 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 } - /** - Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion. + // MARK: Properties - - parameter key: The key of the query component. - - parameter value: The value of the query component. + /// Returns a default `URLEncoding` instance. + public static var `default`: URLEncoding { return URLEncoding() } - - returns: The percent-escaped, URL encoded query string components. - */ - public func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] { + /// 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) } + + /// Returns a `URLEncoding` instance with an `.httpBody` destination. + public static var httpBody: URLEncoding { return URLEncoding(destination: .httpBody) } + + /// The destination defining where the encoded query string is to be applied to the URL request. + public let destination: Destination + + // MARK: Initialization + + /// Creates a `URLEncoding` instance using the specified destination. + /// + /// - parameter destination: The destination defining where the encoded query string is to be applied. + /// + /// - returns: The new `URLEncoding` instance. + public init(destination: Destination = .methodDependent) { + self.destination = destination + } + + // 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) { + guard let url = urlRequest.url else { + throw AFError.parameterEncodingFailed(reason: .missingURL) + } + + if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { + let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) + urlComponents.percentEncodedQuery = percentEncodedQuery + urlRequest.url = urlComponents.url + } + } else { + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false) + } + + return urlRequest + } + + /// Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion. + /// + /// - parameter key: The key of the query component. + /// - parameter value: The value of the query component. + /// + /// - returns: The percent-escaped, URL encoded query string components. + public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] { var components: [(String, String)] = [] - if let dictionary = value as? [String: AnyObject] { + if let dictionary = value as? [String: Any] { for (nestedKey, value) in dictionary { - components += queryComponents("\(key)[\(nestedKey)]", value) + components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value) } - } else if let array = value as? [AnyObject] { + } else if let array = value as? [Any] { for value in array { - components += queryComponents("\(key)[]", value) + components += queryComponents(fromKey: "\(key)[]", value: value) } + } else if let value = value as? NSNumber { + if value.isBool { + components.append((escape(key), escape((value.boolValue ? "1" : "0")))) + } else { + components.append((escape(key), escape("\(value)"))) + } + } else if let bool = value as? Bool { + components.append((escape(key), escape((bool ? "1" : "0")))) } else { components.append((escape(key), escape("\(value)"))) } @@ -201,61 +178,196 @@ public enum 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: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" - - In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow - query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" - should be percent-escaped in the query string. - - - parameter string: The string to be percent-escaped. - - - returns: The percent-escaped string. - */ - public func escape(string: String) -> String { + /// Returns a percent-escaped string following RFC 3986 for a query string key or value. + /// + /// RFC 3986 states that the following characters are "reserved" characters. + /// + /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/" + /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" + /// + /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow + /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" + /// should be percent-escaped in the query string. + /// + /// - parameter string: The string to be percent-escaped. + /// + /// - returns: The percent-escaped string. + public func escape(_ string: String) -> String { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'()*+,;=" - let allowedCharacterSet = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet - allowedCharacterSet.removeCharactersInString(generalDelimitersToEncode + subDelimitersToEncode) + var allowedCharacterSet = CharacterSet.urlQueryAllowed + allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") - var escaped = "" + return string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string + } - //========================================================================================================== - // - // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few - // hundred Chinense 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 - // - //========================================================================================================== + private func query(_ parameters: [String: Any]) -> String { + var components: [(String, String)] = [] - if #available(iOS 8.3, OSX 10.10, *) { - escaped = string.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? string - } else { - let batchSize = 50 - var index = string.startIndex - - while index != string.endIndex { - let startIndex = index - let endIndex = index.advancedBy(batchSize, limit: string.endIndex) - let range = startIndex.. 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: - + +/// 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. + public static var `default`: JSONEncoding { return JSONEncoding() } + + /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options. + public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) } + + /// The options for writing the parameters as JSON data. + public let options: JSONSerialization.WritingOptions + + // MARK: Initialization + + /// Creates a `JSONEncoding` instance using the specified options. + /// + /// - parameter options: The options for writing the parameters as JSON data. + /// + /// - returns: The new `JSONEncoding` instance. + 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() + + guard let parameters = parameters else { return urlRequest } + + do { + let data = try JSONSerialization.data(withJSONObject: parameters, options: options) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return urlRequest + } +} + +// 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/Pods/Alamofire/Source/Request.swift b/Pods/Alamofire/Source/Request.swift index 817cca5..85eb869 100644 --- a/Pods/Alamofire/Source/Request.swift +++ b/Pods/Alamofire/Source/Request.swift @@ -24,490 +24,271 @@ import Foundation -/** - Responsible for sending a request and receiving the response and associated data from the server, as well as - managing its underlying `NSURLSessionTask`. -*/ -public class Request { +/// 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. + /// + /// - parameter urlRequest: The URL request to adapt. + /// + /// - throws: An `Error` if the adaptation encounters an error. + /// + /// - returns: The adapted `URLRequest`. + func adapt(_ urlRequest: URLRequest) throws -> URLRequest +} - // MARK: - Properties +// MARK: - + +/// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not. +public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void + +/// 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 asychronous. 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. + /// + /// - 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) +} + +// MARK: - + +protocol TaskConvertible { + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask +} + +/// A dictionary of headers to apply to a `URLRequest`. +public typealias HTTPHeaders = [String: String] + +// MARK: - + +/// 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 { + + // MARK: Helper Types + + /// A closure executed when monitoring upload or download progress of a request. + public typealias ProgressHandler = (Progress) -> Void + + enum RequestTask { + case data(TaskConvertible?, URLSessionTask?) + case download(TaskConvertible?, URLSessionTask?) + case upload(TaskConvertible?, URLSessionTask?) + case stream(TaskConvertible?, URLSessionTask?) + } + + // MARK: Properties /// The delegate for the underlying task. - public let delegate: TaskDelegate + open internal(set) var delegate: TaskDelegate { + get { + taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } + return taskDelegate + } + set { + taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } + taskDelegate = newValue + } + } /// The underlying task. - public var task: NSURLSessionTask { return delegate.task } + open var task: URLSessionTask? { return delegate.task } /// The session belonging to the underlying task. - public let session: NSURLSession + open let session: URLSession /// The request sent or to be sent to the server. - public var request: NSURLRequest? { return task.originalRequest } + open var request: URLRequest? { return task?.originalRequest } /// The response received from the server, if any. - public var response: NSHTTPURLResponse? { return task.response as? NSHTTPURLResponse } + open var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse } - /// The progress of the request lifecycle. - public var progress: NSProgress { return delegate.progress } + let originalTask: TaskConvertible? var startTime: CFAbsoluteTime? var endTime: CFAbsoluteTime? - // MARK: - Lifecycle + var validations: [() -> Void] = [] - init(session: NSURLSession, task: NSURLSessionTask) { + private var taskDelegate: TaskDelegate + private var taskDelegateLock = NSLock() + + // MARK: Lifecycle + + init(session: URLSession, requestTask: RequestTask, error: Error? = nil) { self.session = session - switch task { - case is NSURLSessionUploadTask: - delegate = UploadTaskDelegate(task: task) - case is NSURLSessionDataTask: - delegate = DataTaskDelegate(task: task) - case is NSURLSessionDownloadTask: - delegate = DownloadTaskDelegate(task: task) - default: - delegate = TaskDelegate(task: task) + 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 } - delegate.queue.addOperationWithBlock { self.endTime = CFAbsoluteTimeGetCurrent() } + delegate.error = error + delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() } } - // MARK: - Authentication + // MARK: Authentication - /** - Associates an HTTP Basic credential with the request. - - - parameter user: The user. - - parameter password: The password. - - parameter persistence: The URL credential persistence. `.ForSession` by default. - - - returns: The request. - */ - public func authenticate( - user user: String, + /// Associates an HTTP Basic credential with the request. + /// + /// - parameter user: The user. + /// - parameter password: The password. + /// - parameter persistence: The URL credential persistence. `.ForSession` by default. + /// + /// - returns: The request. + @discardableResult + open func authenticate( + user: String, password: String, - persistence: NSURLCredentialPersistence = .ForSession) + persistence: URLCredential.Persistence = .forSession) -> Self { - let credential = NSURLCredential(user: user, password: password, persistence: persistence) - + let credential = URLCredential(user: user, password: password, persistence: persistence) return authenticate(usingCredential: credential) } - /** - Associates a specified credential with the request. - - - parameter credential: The credential. - - - returns: The request. - */ - public func authenticate(usingCredential credential: NSURLCredential) -> Self { + /// Associates a specified credential with the request. + /// + /// - parameter credential: The credential. + /// + /// - returns: The request. + @discardableResult + open func authenticate(usingCredential credential: URLCredential) -> Self { delegate.credential = credential - return self } - /** - Returns a base64 encoded basic authentication credential as an authorization header dictionary. + /// Returns a base64 encoded basic authentication credential as an authorization header tuple. + /// + /// - 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 } - - parameter user: The user. - - parameter password: The password. + let credential = data.base64EncodedString(options: []) - - returns: A dictionary with Authorization key and credential value or empty dictionary if encoding fails. - */ - public static func authorizationHeader(user user: String, password: String) -> [String: String] { - guard let data = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding) else { return [:] } - - let credential = data.base64EncodedStringWithOptions([]) - - return ["Authorization": "Basic \(credential)"] + return (key: "Authorization", value: "Basic \(credential)") } - // MARK: - Progress + // MARK: State - /** - Sets a closure to be called periodically during the lifecycle of the request as data is written to or read - from the server. + /// Resumes the request. + open func resume() { + guard let task = task else { delegate.queue.isSuspended = false ; return } - - For uploads, the progress closure returns the bytes written, total bytes written, and total bytes expected - to write. - - For downloads and data tasks, the progress closure returns the bytes read, total bytes read, and total bytes - expected to read. - - - parameter closure: The code to be executed periodically during the lifecycle of the request. - - - returns: The request. - */ - public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self { - if let uploadDelegate = delegate as? UploadTaskDelegate { - uploadDelegate.uploadProgress = closure - } else if let dataDelegate = delegate as? DataTaskDelegate { - dataDelegate.dataProgress = closure - } else if let downloadDelegate = delegate as? DownloadTaskDelegate { - downloadDelegate.downloadProgress = closure - } - - return self - } - - /** - 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 `response` closure will be called with nil `responseData`. - - - parameter closure: The code to be executed periodically during the lifecycle of the request. - - - returns: The request. - */ - public func stream(closure: (NSData -> Void)? = nil) -> Self { - if let dataDelegate = delegate as? DataTaskDelegate { - dataDelegate.dataStream = closure - } - - return self - } - - // MARK: - State - - /** - Resumes the request. - */ - public func resume() { if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } task.resume() - NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidResume, object: task) + + NotificationCenter.default.post( + name: Notification.Name.Task.DidResume, + object: self, + userInfo: [Notification.Key.Task: task] + ) } - /** - Suspends the request. - */ - public func suspend() { + /// Suspends the request. + open func suspend() { + guard let task = task else { return } + task.suspend() - NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidSuspend, object: task) + + NotificationCenter.default.post( + name: Notification.Name.Task.DidSuspend, + object: self, + userInfo: [Notification.Key.Task: task] + ) } - /** - Cancels the request. - */ - public func cancel() { - if let - downloadDelegate = delegate as? DownloadTaskDelegate, - downloadTask = downloadDelegate.downloadTask - { - downloadTask.cancelByProducingResumeData { data in - downloadDelegate.resumeData = data - } - } else { - task.cancel() - } + /// Cancels the request. + open func cancel() { + guard let task = task else { return } - NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidCancel, object: task) - } + task.cancel() - // MARK: - TaskDelegate - - /** - 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. - */ - public class TaskDelegate: NSObject { - - /// The serial operation queue used to execute all operations after the task completes. - public let queue: NSOperationQueue - - let task: NSURLSessionTask - let progress: NSProgress - - var data: NSData? { return nil } - var error: NSError? - - var initialResponseTime: CFAbsoluteTime? - var credential: NSURLCredential? - - init(task: NSURLSessionTask) { - self.task = task - self.progress = NSProgress(totalUnitCount: 0) - self.queue = { - let operationQueue = NSOperationQueue() - operationQueue.maxConcurrentOperationCount = 1 - operationQueue.suspended = true - - if #available(OSX 10.10, *) { - operationQueue.qualityOfService = NSQualityOfService.Utility - } - - return operationQueue - }() - } - - deinit { - queue.cancelAllOperations() - queue.suspended = false - } - - // MARK: - NSURLSessionTaskDelegate - - // MARK: Override Closures - - var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? - var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? - var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)? - var taskDidCompleteWithError: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)? - - // MARK: Delegate Methods - - func URLSession( - session: NSURLSession, - task: NSURLSessionTask, - willPerformHTTPRedirection response: NSHTTPURLResponse, - newRequest request: NSURLRequest, - completionHandler: ((NSURLRequest?) -> Void)) - { - var redirectRequest: NSURLRequest? = request - - if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { - redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) - } - - completionHandler(redirectRequest) - } - - func URLSession( - session: NSURLSession, - task: NSURLSessionTask, - didReceiveChallenge challenge: NSURLAuthenticationChallenge, - completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) - { - var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling - var credential: NSURLCredential? - - 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?.serverTrustPolicyForHost(host), - serverTrust = challenge.protectionSpace.serverTrust - { - if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) { - disposition = .UseCredential - credential = NSURLCredential(forTrust: serverTrust) - } else { - disposition = .CancelAuthenticationChallenge - } - } - } else { - if challenge.previousFailureCount > 0 { - disposition = .RejectProtectionSpace - } else { - credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace) - - if credential != nil { - disposition = .UseCredential - } - } - } - - completionHandler(disposition, credential) - } - - func URLSession( - session: NSURLSession, - task: NSURLSessionTask, - needNewBodyStream completionHandler: ((NSInputStream?) -> Void)) - { - var bodyStream: NSInputStream? - - if let taskNeedNewBodyStream = taskNeedNewBodyStream { - bodyStream = taskNeedNewBodyStream(session, task) - } - - completionHandler(bodyStream) - } - - func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { - if let taskDidCompleteWithError = taskDidCompleteWithError { - taskDidCompleteWithError(session, task, error) - } else { - if let error = error { - self.error = error - - if let - downloadDelegate = self as? DownloadTaskDelegate, - userInfo = error.userInfo as? [String: AnyObject], - resumeData = userInfo[NSURLSessionDownloadTaskResumeData] as? NSData - { - downloadDelegate.resumeData = resumeData - } - } - - queue.suspended = false - } - } - } - - // MARK: - DataTaskDelegate - - class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate { - var dataTask: NSURLSessionDataTask? { return task as? NSURLSessionDataTask } - - private var totalBytesReceived: Int64 = 0 - private var mutableData: NSMutableData - override var data: NSData? { - if dataStream != nil { - return nil - } else { - return mutableData - } - } - - private var expectedContentLength: Int64? - private var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)? - private var dataStream: ((data: NSData) -> Void)? - - override init(task: NSURLSessionTask) { - mutableData = NSMutableData() - super.init(task: task) - } - - // MARK: - NSURLSessionDataDelegate - - // MARK: Override Closures - - var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)? - var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)? - var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)? - var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)? - - // MARK: Delegate Methods - - func URLSession( - session: NSURLSession, - dataTask: NSURLSessionDataTask, - didReceiveResponse response: NSURLResponse, - completionHandler: (NSURLSessionResponseDisposition -> Void)) - { - var disposition: NSURLSessionResponseDisposition = .Allow - - expectedContentLength = response.expectedContentLength - - if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { - disposition = dataTaskDidReceiveResponse(session, dataTask, response) - } - - completionHandler(disposition) - } - - func URLSession( - session: NSURLSession, - dataTask: NSURLSessionDataTask, - didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) - { - dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask) - } - - func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { - if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } - - if let dataTaskDidReceiveData = dataTaskDidReceiveData { - dataTaskDidReceiveData(session, dataTask, data) - } else { - if let dataStream = dataStream { - dataStream(data: data) - } else { - mutableData.appendData(data) - } - - totalBytesReceived += data.length - let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown - - progress.totalUnitCount = totalBytesExpected - progress.completedUnitCount = totalBytesReceived - - dataProgress?( - bytesReceived: Int64(data.length), - totalBytesReceived: totalBytesReceived, - totalBytesExpectedToReceive: totalBytesExpected - ) - } - } - - func URLSession( - session: NSURLSession, - dataTask: NSURLSessionDataTask, - willCacheResponse proposedResponse: NSCachedURLResponse, - completionHandler: ((NSCachedURLResponse?) -> Void)) - { - var cachedResponse: NSCachedURLResponse? = proposedResponse - - if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { - cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse) - } - - completionHandler(cachedResponse) - } + NotificationCenter.default.post( + name: Notification.Name.Task.DidCancel, + object: self, + userInfo: [Notification.Key.Task: task] + ) } } // MARK: - CustomStringConvertible 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. - */ - public var description: String { + /// 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] = [] - if let HTTPMethod = request?.HTTPMethod { + if let HTTPMethod = request?.httpMethod { components.append(HTTPMethod) } - if let URLString = request?.URL?.absoluteString { - components.append(URLString) + if let urlString = request?.url?.absoluteString { + components.append(urlString) } if let response = response { components.append("(\(response.statusCode))") } - return components.joinWithSeparator(" ") + return components.joined(separator: " ") } } // MARK: - CustomDebugStringConvertible 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() + } + func cURLRepresentation() -> String { var components = ["$ curl -i"] - guard let - request = self.request, - URL = request.URL, - host = URL.host + guard let request = self.request, + let url = request.url, + let host = url.host else { return "$ curl command could not be created" } - if let HTTPMethod = request.HTTPMethod where HTTPMethod != "GET" { - components.append("-X \(HTTPMethod)") + if let httpMethod = request.httpMethod, httpMethod != "GET" { + components.append("-X \(httpMethod)") } - if let credentialStorage = self.session.configuration.URLCredentialStorage { - let protectionSpace = NSURLProtectionSpace( + if let credentialStorage = self.session.configuration.urlCredentialStorage { + let protectionSpace = URLProtectionSpace( host: host, - port: URL.port?.integerValue ?? 0, - protocol: URL.scheme, + port: url.port ?? 0, + protocol: url.scheme, realm: host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic ) - if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values { + if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { for credential in credentials { components.append("-u \(credential.user!):\(credential.password!)") } @@ -518,20 +299,20 @@ extension Request: CustomDebugStringConvertible { } } - if session.configuration.HTTPShouldSetCookies { - if let - cookieStorage = session.configuration.HTTPCookieStorage, - cookies = cookieStorage.cookiesForURL(URL) where !cookies.isEmpty + if session.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 ?? String());" } - components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"") + let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" } + components.append("-b \"\(string.substring(to: string.characters.index(before: string.endIndex)))\"") } } - var headers: [NSObject: AnyObject] = [:] + var headers: [AnyHashable: Any] = [:] - if let additionalHeaders = session.configuration.HTTPAdditionalHeaders { - for (field, value) in additionalHeaders where field != "Cookie" { + if let additionalHeaders = session.configuration.httpAdditionalHeaders { + for (field, value) in additionalHeaders where field != AnyHashable("Cookie") { headers[field] = value } } @@ -546,23 +327,274 @@ extension Request: CustomDebugStringConvertible { components.append("-H \"\(field): \(value)\"") } - if let - HTTPBodyData = request.HTTPBody, - HTTPBody = String(data: HTTPBodyData, encoding: NSUTF8StringEncoding) - { - var escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\\\"", withString: "\\\\\"") - escapedBody = escapedBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"") + if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) { + var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"") + escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"") components.append("-d \"\(escapedBody)\"") } - components.append("\"\(URL.absoluteString)\"") + components.append("\"\(url.absoluteString)\"") - return components.joinWithSeparator(" \\\n\t") - } - - /// The textual representation used when written to an output stream, in the form of a cURL command. - public var debugDescription: String { - return cURLRepresentation() + return components.joined(separator: " \\\n\t") } } + +// MARK: - + +/// Specific type of `Request` that manages an underlying `URLSessionDataTask`. +open class DataRequest: Request { + + // MARK: Helper Types + + struct Requestable: TaskConvertible { + let urlRequest: URLRequest + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + let urlRequest = try self.urlRequest.adapt(using: adapter) + return queue.syncResult { session.dataTask(with: urlRequest) } + } + } + + // MARK: Properties + + /// The progress of fetching the response data from the server for the request. + open var progress: Progress { return dataDelegate.progress } + + var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate } + + // MARK: Stream + + /// 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`. + /// + /// - parameter closure: The code to be executed periodically during the lifecycle of the request. + /// + /// - returns: The request. + @discardableResult + open func stream(closure: ((Data) -> Void)? = nil) -> Self { + dataDelegate.dataStream = closure + return self + } + + // MARK: Progress + + /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. + /// + /// - parameter queue: The dispatch queue to execute the closure on. + /// - parameter closure: The code to be executed periodically as data is read from the server. + /// + /// - returns: The request. + @discardableResult + open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { + dataDelegate.progressHandler = (closure, queue) + return self + } +} + +// MARK: - + +/// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`. +open class DownloadRequest: Request { + + // MARK: Helper Types + + /// 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) + + /// 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) { + self.rawValue = rawValue + } + } + + /// 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) + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + let task: URLSessionTask + + switch self { + case let .request(urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.syncResult { session.downloadTask(with: urlRequest) } + case let .resumeData(resumeData): + task = queue.syncResult { session.downloadTask(withResumeData: resumeData) } + } + + return task + } + } + + // MARK: Properties + + /// The resume data of the underlying download task if available after a failure. + open var resumeData: Data? { return downloadDelegate.resumeData } + + /// The progress of downloading the response data from the server for the request. + open var progress: Progress { return downloadDelegate.progress } + + var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate } + + // MARK: State + + /// Cancels the request. + open override func cancel() { + downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 } + + NotificationCenter.default.post( + name: Notification.Name.Task.DidCancel, + object: self, + userInfo: [Notification.Key.Task: task] + ) + } + + // MARK: Progress + + /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. + /// + /// - parameter queue: The dispatch queue to execute the closure on. + /// - parameter closure: The code to be executed periodically as data is read from the server. + /// + /// - returns: The request. + @discardableResult + open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { + downloadDelegate.progressHandler = (closure, queue) + return self + } + + // MARK: Destination + + /// 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. + /// + /// - parameter directory: The search path directory. `.DocumentDirectory` by default. + /// - parameter domain: The search path domain mask. `.UserDomainMask` by default. + /// + /// - 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) + + if !directoryURLs.isEmpty { + return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), []) + } + + return (temporaryURL, []) + } + } +} + +// MARK: - + +/// Specific type of `Request` that manages an underlying `URLSessionUploadTask`. +open class UploadRequest: DataRequest { + + // MARK: Helper Types + + enum Uploadable: TaskConvertible { + case data(Data, URLRequest) + case file(URL, URLRequest) + case stream(InputStream, URLRequest) + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + let task: URLSessionTask + + switch self { + case let .data(data, urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.syncResult { session.uploadTask(with: urlRequest, from: data) } + case let .file(url, urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.syncResult { session.uploadTask(with: urlRequest, fromFile: url) } + case let .stream(_, urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.syncResult { session.uploadTask(withStreamedRequest: urlRequest) } + } + + return task + } + } + + // MARK: Properties + + /// The progress of uploading the payload to the server for the upload request. + open var uploadProgress: Progress { return uploadDelegate.uploadProgress } + + var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate } + + // MARK: Upload Progress + + /// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to + /// the server. + /// + /// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress + /// of data being read from the server. + /// + /// - parameter queue: The dispatch queue to execute the closure on. + /// - parameter closure: The code to be executed periodically as data is sent to the server. + /// + /// - returns: The request. + @discardableResult + open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { + uploadDelegate.uploadProgressHandler = (closure, queue) + return self + } +} + +// MARK: - + +#if !os(watchOS) + +/// Specific type of `Request` that manages an underlying `URLSessionStreamTask`. +open class StreamRequest: Request { + enum Streamable: TaskConvertible { + case stream(hostName: String, port: Int) + case netService(NetService) + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + let task: URLSessionTask + + switch self { + case let .stream(hostName, port): + task = queue.syncResult { session.streamTask(withHostName: hostName, port: port) } + case let .netService(netService): + task = queue.syncResult { session.streamTask(with: netService) } + } + + return task + } + } +} + +#endif diff --git a/Pods/Alamofire/Source/Response.swift b/Pods/Alamofire/Source/Response.swift index dd700bb..f80779c 100644 --- a/Pods/Alamofire/Source/Response.swift +++ b/Pods/Alamofire/Source/Response.swift @@ -24,40 +24,65 @@ import Foundation -/// Used to store all response data returned from a completed `Request`. -public struct Response { +/// Used to store all data associated with an non-serialized response of a data or upload request. +public struct DefaultDataResponse { /// The URL request sent to the server. - public let request: NSURLRequest? + public let request: URLRequest? /// The server's response to the URL request. - public let response: NSHTTPURLResponse? + public let response: HTTPURLResponse? /// The data returned by the server. - public let data: NSData? + public let data: Data? + + /// The error encountered while executing or validating the request. + public let error: Error? + + var _metrics: AnyObject? + + init(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) { + self.request = request + self.response = response + self.data = data + self.error = error + } +} + +// MARK: - + +/// Used to store all data associated with a serialized response of a data or upload request. +public struct DataResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The data returned by the server. + public let data: Data? /// The result of response serialization. - public let result: Result + public let result: Result /// The timeline of the complete lifecycle of the `Request`. public let timeline: Timeline - /** - Initializes the `Response` instance with the specified URL request, URL response, server data and response - serialization result. - - - 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()`. + var _metrics: AnyObject? - - returns: the new `Response` instance. - */ + /// 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: NSURLRequest?, - response: NSHTTPURLResponse?, - data: NSData?, - result: Result, + request: URLRequest?, + response: HTTPURLResponse?, + data: Data?, + result: Result, timeline: Timeline = Timeline()) { self.request = request @@ -68,30 +93,204 @@ public struct Response { } } -// MARK: - CustomStringConvertible +// MARK: - -extension Response: CustomStringConvertible { +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 } -} -// MARK: - CustomDebugStringConvertible - -extension Response: CustomDebugStringConvertible { /// The debug textual representation used when written to an output stream, which includes the URL request, the URL - /// response, the server data and the response serialization result. + /// response, the server data, the response serialization result and the timeline. public var debugDescription: String { var output: [String] = [] output.append(request != nil ? "[Request]: \(request!)" : "[Request]: nil") output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") - output.append("[Data]: \(data?.length ?? 0) bytes") + output.append("[Data]: \(data?.count ?? 0) bytes") output.append("[Result]: \(result.debugDescription)") output.append("[Timeline]: \(timeline.debugDescription)") - return output.joinWithSeparator("\n") + return output.joined(separator: "\n") } } + +// 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? + + var _metrics: AnyObject? + + init( + request: URLRequest?, + response: HTTPURLResponse?, + temporaryURL: URL?, + destinationURL: URL?, + resumeData: Data?, + error: Error?) + { + self.request = request + self.response = response + self.temporaryURL = temporaryURL + self.destinationURL = destinationURL + self.resumeData = resumeData + self.error = error + } +} + +// MARK: - + +/// Used to store all data associated with a serialized response of a download request. +public struct DownloadResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The temporary destination URL of the data returned from the server. + public let temporaryURL: URL? + + /// The final destination URL of the data returned from the server if it was moved. + public let destinationURL: URL? + + /// The resume data generated if the request was cancelled. + public let resumeData: Data? + + /// The result of response serialization. + public let result: Result + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + var _metrics: AnyObject? + + /// 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()) + { + self.request = request + self.response = response + self.temporaryURL = temporaryURL + self.destinationURL = destinationURL + self.resumeData = resumeData + self.result = result + self.timeline = timeline + } +} + +// MARK: - + +extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes whether the result was a + /// success or failure. + public var description: String { + return result.debugDescription + } + + /// 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. + public var debugDescription: String { + var output: [String] = [] + + output.append(request != nil ? "[Request]: \(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") + } +} + +// MARK: - + +protocol Response { + /// The task metrics containing the request / response statistics. + var _metrics: AnyObject? { get set } + mutating func add(_ metrics: AnyObject?) +} + +extension Response { + mutating func add(_ metrics: AnyObject?) { + #if !os(watchOS) + guard #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) else { return } + guard let metrics = metrics as? URLSessionTaskMetrics else { return } + + _metrics = metrics + #endif + } +} + +// MARK: - + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DefaultDataResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DataResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DefaultDownloadResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DownloadResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} diff --git a/Pods/Alamofire/Source/ResponseSerialization.swift b/Pods/Alamofire/Source/ResponseSerialization.swift index 5b7b61f..0bbb373 100644 --- a/Pods/Alamofire/Source/ResponseSerialization.swift +++ b/Pods/Alamofire/Source/ResponseSerialization.swift @@ -24,96 +24,111 @@ import Foundation -// MARK: ResponseSerializer - -/** - The type in which all response serializers must conform to in order to serialize a response. -*/ -public protocol ResponseSerializerType { - /// The type of serialized object to be created by this `ResponseSerializerType`. +/// The type in which all data response serializers must conform to in order to serialize a response. +public protocol DataResponseSerializerProtocol { + /// The type of serialized object to be created by this `DataResponseSerializerType`. associatedtype SerializedObject - /// The type of error to be created by this `ResponseSerializer` if serialization fails. - associatedtype ErrorObject: ErrorType - - /** - A closure used by response handlers that takes a request, response, data and error and returns a result. - */ - var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result { get } + /// 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 } } // MARK: - -/** - A generic `ResponseSerializerType` used to serialize a request, response, and data into a serialized object. -*/ -public struct ResponseSerializer: ResponseSerializerType { - /// The type of serialized object to be created by this `ResponseSerializer`. +/// 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 - /// The type of error to be created by this `ResponseSerializer` if serialization fails. - public typealias ErrorObject = Error + /// 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 - /** - A closure used by response handlers that takes a request, response, data and error and returns a result. - */ - public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result + /// Initializes the `ResponseSerializer` instance with the given serialize response closure. + /// + /// - parameter serializeResponse: The closure used to serialize the response. + /// + /// - returns: The new generic response serializer instance. + public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result) { + self.serializeResponse = serializeResponse + } +} - /** - Initializes the `ResponseSerializer` instance with the given serialize response closure. +// MARK: - - - parameter serializeResponse: The closure used to serialize the response. +/// 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 - - returns: The new generic response serializer instance. - */ - public init(serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result) { + /// 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 } +} + +// MARK: - + +/// 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 + + /// 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 + + /// Initializes the `ResponseSerializer` instance with the given serialize response closure. + /// + /// - parameter serializeResponse: The closure used to serialize the response. + /// + /// - returns: The new generic response serializer instance. + public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result) { self.serializeResponse = serializeResponse } } // MARK: - Default -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. + /// + /// - 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 + ) - /** - Adds a handler to be called once the request has finished. + dataResponse.add(self.delegate.metrics) - - parameter queue: The queue on which the completion handler is dispatched. - - parameter completionHandler: The code to be executed once the request has finished. - - - returns: The request. - */ - public func response( - queue queue: dispatch_queue_t? = nil, - completionHandler: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Void) - -> Self - { - delegate.queue.addOperationWithBlock { - dispatch_async(queue ?? dispatch_get_main_queue()) { - completionHandler(self.request, self.response, self.delegate.data, self.delegate.error) + completionHandler(dataResponse) } } return self } - /** - 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. - - - returns: The request. - */ - public func response( - queue queue: dispatch_queue_t? = nil, + /// 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. + /// + /// - returns: The request. + @discardableResult + public func response( + queue: DispatchQueue? = nil, responseSerializer: T, - completionHandler: Response -> Void) + completionHandler: @escaping (DataResponse) -> Void) -> Self { - delegate.queue.addOperationWithBlock { + delegate.queue.addOperation { let result = responseSerializer.serializeResponse( self.request, self.response, @@ -131,7 +146,7 @@ extension Request { serializationCompletedTime: CFAbsoluteTimeGetCurrent() ) - let response = Response( + var dataResponse = DataResponse( request: self.request, response: self.response, data: self.delegate.data, @@ -139,7 +154,94 @@ extension Request { timeline: timeline ) - dispatch_async(queue ?? dispatch_get_main_queue()) { completionHandler(response) } + dataResponse.add(self.delegate.metrics) + + (queue ?? DispatchQueue.main).async { completionHandler(dataResponse) } + } + + return self + } +} + +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. + /// + /// - 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 + ) + + downloadResponse.add(self.delegate.metrics) + + completionHandler(downloadResponse) + } + } + + return self + } + + /// 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. + /// + /// - 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 + ) + + let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent() + let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime + + let timeline = Timeline( + requestStartTime: self.startTime ?? CFAbsoluteTimeGetCurrent(), + initialResponseTime: initialResponseTime, + requestCompletedTime: requestCompletedTime, + serializationCompletedTime: CFAbsoluteTimeGetCurrent() + ) + + var downloadResponse = DownloadResponse( + request: self.request, + response: self.response, + temporaryURL: self.downloadDelegate.temporaryURL, + destinationURL: self.downloadDelegate.destinationURL, + resumeData: self.downloadDelegate.resumeData, + result: result, + timeline: timeline + ) + + downloadResponse.add(self.delegate.metrics) + + (queue ?? DispatchQueue.main).async { completionHandler(downloadResponse) } } return self @@ -149,111 +251,220 @@ extension Request { // 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!) } - /** - Creates a response serializer that returns the associated data as-is. + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(Data()) } - - returns: A data response serializer. - */ - public static func dataResponseSerializer() -> ResponseSerializer { - return ResponseSerializer { _, response, data, error in - guard error == nil else { return .Failure(error!) } + guard let validData = data else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) + } - if let response = response where response.statusCode == 204 { return .Success(NSData()) } + return .success(validData) + } +} - guard let validData = data else { - let failureReason = "Data could not be serialized. Input data was nil." - let error = Error.error(code: .DataSerializationFailed, failureReason: failureReason) - return .Failure(error) - } - - 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. - - - returns: The request. - */ + /// Adds a handler to be called once the request has finished. + /// + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult public func responseData( - queue queue: dispatch_queue_t? = nil, - completionHandler: Response -> Void) + queue: DispatchQueue? = nil, + completionHandler: @escaping (DataResponse) -> Void) -> Self { - return response(queue: queue, responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler) + return response( + queue: queue, + responseSerializer: DataRequest.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!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + 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))) + } + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseData( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.dataResponseSerializer(), + completionHandler: completionHandler + ) } } // MARK: - String extension Request { - - /** - Creates a response serializer that returns a string 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 encoding: NSStringEncoding? = nil) - -> ResponseSerializer + /// 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 { - return ResponseSerializer { _, response, data, error in - guard error == nil else { return .Failure(error!) } + guard error == nil else { return .failure(error!) } - if let response = response where response.statusCode == 204 { return .Success("") } + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success("") } - guard let validData = data else { - let failureReason = "String could not be serialized. Input data was nil." - let error = Error.error(code: .StringSerializationFailed, failureReason: failureReason) - return .Failure(error) - } - - var convertedEncoding = encoding - - if let encodingName = response?.textEncodingName where convertedEncoding == nil { - convertedEncoding = CFStringConvertEncodingToNSStringEncoding( - CFStringConvertIANACharSetNameToEncoding(encodingName) - ) - } + guard let validData = data else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) + } - let actualEncoding = convertedEncoding ?? NSISOLatin1StringEncoding + var convertedEncoding = encoding - if let string = String(data: validData, encoding: actualEncoding) { - return .Success(string) - } else { - let failureReason = "String could not be serialized with encoding: \(actualEncoding)" - let error = Error.error(code: .StringSerializationFailed, failureReason: failureReason) - return .Failure(error) - } + if let encodingName = response?.textEncodingName as CFString!, convertedEncoding == nil { + convertedEncoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding( + CFStringConvertIANACharSetNameToEncoding(encodingName)) + ) + } + + let actualEncoding = convertedEncoding ?? String.Encoding.isoLatin1 + + if let string = String(data: validData, encoding: actualEncoding) { + return .success(string) + } else { + return .failure(AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding))) + } + } +} + +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. - - - returns: The request. - */ + /// 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. + /// + /// - returns: The request. + @discardableResult public func responseString( - queue queue: dispatch_queue_t? = nil, - encoding: NSStringEncoding? = nil, - completionHandler: Response -> Void) + queue: DispatchQueue? = nil, + encoding: String.Encoding? = nil, + completionHandler: @escaping (DataResponse) -> Void) -> Self { return response( queue: queue, - responseSerializer: Request.stringResponseSerializer(encoding: encoding), + responseSerializer: DataRequest.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. + /// + /// - 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 ) } @@ -262,56 +473,119 @@ extension Request { // MARK: - JSON extension Request { - - /** - Creates a response serializer that returns a JSON object constructed from the response data using - `NSJSONSerialization` with the specified reading options. - - - parameter options: The JSON serialization reading options. `.AllowFragments` by default. - - - returns: A JSON object response serializer. - */ - public static func JSONResponseSerializer( - options options: NSJSONReadingOptions = .AllowFragments) - -> ResponseSerializer + /// 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 { - return ResponseSerializer { _, response, data, error in - guard error == nil else { return .Failure(error!) } + guard error == nil else { return .failure(error!) } - if let response = response where response.statusCode == 204 { return .Success(NSNull()) } + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } - guard let validData = data where validData.length > 0 else { - let failureReason = "JSON could not be serialized. Input data was nil or zero length." - let error = Error.error(code: .JSONSerializationFailed, failureReason: failureReason) - return .Failure(error) - } + guard let validData = data, validData.count > 0 else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) + } - do { - let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: options) - return .Success(JSON) - } catch { - return .Failure(error as NSError) - } + do { + let json = try JSONSerialization.jsonObject(with: validData, options: options) + return .success(json) + } catch { + return .failure(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. `.AllowFragments` by default. - - parameter completionHandler: A closure to be executed once the request has finished. - - - returns: The request. - */ + /// 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. + /// + /// - returns: The request. + @discardableResult public func responseJSON( - queue queue: dispatch_queue_t? = nil, - options: NSJSONReadingOptions = .AllowFragments, - completionHandler: Response -> Void) + queue: DispatchQueue? = nil, + options: JSONSerialization.ReadingOptions = .allowFragments, + completionHandler: @escaping (DataResponse) -> Void) -> Self { return response( queue: queue, - responseSerializer: Request.JSONResponseSerializer(options: options), + responseSerializer: DataRequest.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. + /// + /// - 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 ) } @@ -320,59 +594,123 @@ extension Request { // MARK: - Property List extension Request { - - /** - Creates a response serializer that returns an object constructed from the response data using - `NSPropertyListSerialization` with the specified reading options. - - - parameter options: The property list reading options. `NSPropertyListReadOptions()` by default. - - - returns: A property list object response serializer. - */ - public static func propertyListResponseSerializer( - options options: NSPropertyListReadOptions = NSPropertyListReadOptions()) - -> ResponseSerializer + /// 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. + /// + /// - returns: The result data type. + public static func serializeResponsePropertyList( + options: PropertyListSerialization.ReadOptions, + response: HTTPURLResponse?, + data: Data?, + error: Error?) + -> Result { - return ResponseSerializer { _, response, data, error in - guard error == nil else { return .Failure(error!) } + guard error == nil else { return .failure(error!) } - if let response = response where response.statusCode == 204 { return .Success(NSNull()) } + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } - guard let validData = data where validData.length > 0 else { - let failureReason = "Property list could not be serialized. Input data was nil or zero length." - let error = Error.error(code: .PropertyListSerializationFailed, failureReason: failureReason) - return .Failure(error) - } + guard let validData = data, validData.count > 0 else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) + } - do { - let plist = try NSPropertyListSerialization.propertyListWithData(validData, options: options, format: nil) - return .Success(plist) - } catch { - return .Failure(error as NSError) - } + 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 DataRequest { + /// Creates a response serializer that returns an object constructed from the response data using + /// `PropertyListSerialization` with the specified reading options. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// + /// - returns: A property list object response serializer. + public static func propertyListResponseSerializer( + options: PropertyListSerialization.ReadOptions = []) + -> DataResponseSerializer + { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) } } - /** - Adds a handler to be called once the request has finished. - - - parameter options: The property list reading options. `0` by default. - - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3 - arguments: the URL request, the URL response, the server data and the result - produced while creating the property list. - - - returns: The request. - */ + /// 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. + /// + /// - returns: The request. + @discardableResult public func responsePropertyList( - queue queue: dispatch_queue_t? = nil, - options: NSPropertyListReadOptions = NSPropertyListReadOptions(), - completionHandler: Response -> Void) + queue: DispatchQueue? = nil, + options: PropertyListSerialization.ReadOptions = [], + completionHandler: @escaping (DataResponse) -> Void) -> Self { return response( queue: queue, - responseSerializer: Request.propertyListResponseSerializer(options: options), + responseSerializer: DataRequest.propertyListResponseSerializer(options: options), completionHandler: completionHandler ) } } + +extension DownloadRequest { + /// Creates a response serializer that returns an object constructed from the response data using + /// `PropertyListSerialization` with the specified reading options. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// + /// - returns: A property list object response serializer. + public static func propertyListResponseSerializer( + options: PropertyListSerialization.ReadOptions = []) + -> DownloadResponseSerializer + { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - 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 + ) + } +} + +/// A set of HTTP response status code that do not contain response data. +private let emptyDataStatusCodes: Set = [204, 205] diff --git a/Pods/Alamofire/Source/Result.swift b/Pods/Alamofire/Source/Result.swift index ed1df0f..2293308 100644 --- a/Pods/Alamofire/Source/Result.swift +++ b/Pods/Alamofire/Source/Result.swift @@ -24,24 +24,23 @@ 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) +/// 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: + case .success: return true - case .Failure: + case .failure: return false } } @@ -54,9 +53,9 @@ public enum Result { /// Returns the associated value if the result is a success, `nil` otherwise. public var value: Value? { switch self { - case .Success(let value): + case .success(let value): return value - case .Failure: + case .failure: return nil } } @@ -64,9 +63,9 @@ public enum Result { /// Returns the associated error value if the result is a failure, `nil` otherwise. public var error: Error? { switch self { - case .Success: + case .success: return nil - case .Failure(let error): + case .failure(let error): return error } } @@ -75,13 +74,13 @@ public enum Result { // MARK: - CustomStringConvertible extension Result: CustomStringConvertible { - /// The textual representation used when written to an output stream, which includes whether the result was a + /// 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: + case .success: return "SUCCESS" - case .Failure: + case .failure: return "FAILURE" } } @@ -94,9 +93,9 @@ extension Result: CustomDebugStringConvertible { /// success or failure in addition to the value or error. public var debugDescription: String { switch self { - case .Success(let value): + case .success(let value): return "SUCCESS: \(value)" - case .Failure(let error): + case .failure(let error): return "FAILURE: \(error)" } } diff --git a/Pods/Alamofire/Source/ServerTrustPolicy.swift b/Pods/Alamofire/Source/ServerTrustPolicy.swift index 44ba100..4d5030f 100644 --- a/Pods/Alamofire/Source/ServerTrustPolicy.swift +++ b/Pods/Alamofire/Source/ServerTrustPolicy.swift @@ -25,119 +25,111 @@ import Foundation /// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host. -public class ServerTrustPolicyManager { +open class ServerTrustPolicyManager { /// The dictionary of policies mapped to a particular host. - public let policies: [String: ServerTrustPolicy] + 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. - */ + /// 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. - */ - public func serverTrustPolicyForHost(host: String) -> ServerTrustPolicy? { + /// 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 NSURLSession { +extension URLSession { private struct AssociatedKeys { - static var ManagerKey = "NSURLSession.ServerTrustPolicyManager" + static var managerKey = "URLSession.ServerTrustPolicyManager" } var serverTrustPolicyManager: ServerTrustPolicyManager? { get { - return objc_getAssociatedObject(self, &AssociatedKeys.ManagerKey) as? ServerTrustPolicyManager + return objc_getAssociatedObject(self, &AssociatedKeys.managerKey) as? ServerTrustPolicyManager } set (manager) { - objc_setAssociatedObject(self, &AssociatedKeys.ManagerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + 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. - - - 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. -*/ +/// 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. +/// +/// - 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 PinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool) - case PinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool) - case DisableEvaluation - case CustomEvaluation((serverTrust: SecTrust, host: String) -> Bool) + case performDefaultEvaluation(validateHost: Bool) + 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 certificatesInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecCertificate] { + /// 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.pathsForResourcesOfType(fileExtension, inDirectory: nil) - }.flatten()) + bundle.paths(forResourcesOfType: fileExtension, inDirectory: nil) + }.joined()) for path in paths { - if let - certificateData = NSData(contentsOfFile: path), - certificate = SecCertificateCreateWithData(nil, certificateData) + if + let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData, + let certificate = SecCertificateCreateWithData(nil, certificateData) { certificates.append(certificate) } @@ -146,18 +138,16 @@ public enum ServerTrustPolicy { 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 publicKeysInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecKey] { + /// 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 certificatesInBundle(bundle) { - if let publicKey = publicKeyForCertificate(certificate) { + for certificate in certificates(in: bundle) { + if let publicKey = publicKey(for: certificate) { publicKeys.append(publicKey) } } @@ -167,57 +157,55 @@ public enum ServerTrustPolicy { // 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 evaluateServerTrust(serverTrust: SecTrust, isValidForHost host: String) -> Bool { + /// 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): + case let .performDefaultEvaluation(validateHost): let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) - SecTrustSetPolicies(serverTrust, [policy]) + SecTrustSetPolicies(serverTrust, policy) serverTrustIsValid = trustIsValid(serverTrust) - case let .PinCertificates(pinnedCertificates, validateCertificateChain, validateHost): + case let .pinCertificates(pinnedCertificates, validateCertificateChain, validateHost): if validateCertificateChain { let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) - SecTrustSetPolicies(serverTrust, [policy]) + SecTrustSetPolicies(serverTrust, policy) - SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates) + SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates as CFArray) SecTrustSetAnchorCertificatesOnly(serverTrust, true) serverTrustIsValid = trustIsValid(serverTrust) } else { - let serverCertificatesDataArray = certificateDataForTrust(serverTrust) - let pinnedCertificatesDataArray = certificateDataForCertificates(pinnedCertificates) + let serverCertificatesDataArray = certificateData(for: serverTrust) + let pinnedCertificatesDataArray = certificateData(for: pinnedCertificates) outerLoop: for serverCertificateData in serverCertificatesDataArray { for pinnedCertificateData in pinnedCertificatesDataArray { - if serverCertificateData.isEqualToData(pinnedCertificateData) { + if serverCertificateData == pinnedCertificateData { serverTrustIsValid = true break outerLoop } } } } - case let .PinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost): + case let .pinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost): var certificateChainEvaluationPassed = true if validateCertificateChain { let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) - SecTrustSetPolicies(serverTrust, [policy]) + SecTrustSetPolicies(serverTrust, policy) certificateChainEvaluationPassed = trustIsValid(serverTrust) } if certificateChainEvaluationPassed { - outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeysForTrust(serverTrust) as [AnyObject] { + outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeys(for: serverTrust) as [AnyObject] { for pinnedPublicKey in pinnedPublicKeys as [AnyObject] { if serverPublicKey.isEqual(pinnedPublicKey) { serverTrustIsValid = true @@ -226,10 +214,10 @@ public enum ServerTrustPolicy { } } } - case .DisableEvaluation: + case .disableEvaluation: serverTrustIsValid = true - case let .CustomEvaluation(closure): - serverTrustIsValid = closure(serverTrust: serverTrust, host: host) + case let .customEvaluation(closure): + serverTrustIsValid = closure(serverTrust, host) } return serverTrustIsValid @@ -237,15 +225,16 @@ public enum ServerTrustPolicy { // MARK: - Private - Trust Validation - private func trustIsValid(trust: SecTrust) -> Bool { + private func trustIsValid(_ trust: SecTrust) -> Bool { var isValid = false - var result = SecTrustResultType(kSecTrustResultInvalid) + var result = SecTrustResultType.invalid let status = SecTrustEvaluate(trust, &result) if status == errSecSuccess { - let unspecified = SecTrustResultType(kSecTrustResultUnspecified) - let proceed = SecTrustResultType(kSecTrustResultProceed) + let unspecified = SecTrustResultType.unspecified + let proceed = SecTrustResultType.proceed + isValid = result == unspecified || result == proceed } @@ -255,7 +244,7 @@ public enum ServerTrustPolicy { // MARK: - Private - Certificate Data - private func certificateDataForTrust(trust: SecTrust) -> [NSData] { + private func certificateData(for trust: SecTrust) -> [Data] { var certificates: [SecCertificate] = [] for index in 0.. [NSData] { - return certificates.map { SecCertificateCopyData($0) as NSData } + private func certificateData(for certificates: [SecCertificate]) -> [Data] { + return certificates.map { SecCertificateCopyData($0) as Data } } // MARK: - Private - Public Key Extraction - private static func publicKeysForTrust(trust: SecTrust) -> [SecKey] { + private static func publicKeys(for trust: SecTrust) -> [SecKey] { var publicKeys: [SecKey] = [] for index in 0.. SecKey? { + private static func publicKey(for certificate: SecCertificate) -> SecKey? { var publicKey: SecKey? let policy = SecPolicyCreateBasicX509() var trust: SecTrust? let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust) - if let trust = trust where trustCreationStatus == errSecSuccess { + if let trust = trust, trustCreationStatus == errSecSuccess { publicKey = SecTrustCopyPublicKey(trust) } diff --git a/Pods/Alamofire/Source/SessionDelegate.swift b/Pods/Alamofire/Source/SessionDelegate.swift new file mode 100644 index 0000000..4549731 --- /dev/null +++ b/Pods/Alamofire/Source/SessionDelegate.swift @@ -0,0 +1,681 @@ +// +// SessionDelegate.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 handling all delegate callbacks for the underlying session. +open class SessionDelegate: NSObject { + + // MARK: URLSessionDelegate Overrides + + /// 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, (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, (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, (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, (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, (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, (CachedURLResponse?) -> Void) -> Void)? + + // MARK: URLSessionDownloadDelegate Overrides + + /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didFinishDownloadingTo:)`. + open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)? + + /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)`. + open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + + /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)`. + open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? + + // MARK: URLSessionStreamDelegate Overrides + +#if !os(watchOS) + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:readClosedFor:)`. + open var streamTaskReadClosed: ((URLSession, URLSessionStreamTask) -> Void)? + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:writeClosedFor:)`. + open var streamTaskWriteClosed: ((URLSession, URLSessionStreamTask) -> Void)? + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:betterRouteDiscoveredFor:)`. + open var streamTaskBetterRouteDiscovered: ((URLSession, URLSessionStreamTask) -> Void)? + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:streamTask:didBecome:outputStream:)`. + open var streamTaskDidBecomeInputAndOutputStreams: ((URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void)? + +#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 + } + } + + // MARK: Lifecycle + + /// Initializes the `SessionDelegate` instance. + /// + /// - returns: The new `SessionDelegate` instance. + public override init() { + super.init() + } + + // MARK: NSObject Overrides + + /// 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) + switch selector { + case #selector(URLSessionStreamDelegate.urlSession(_:readClosedFor:)): + return streamTaskReadClosed != nil + case #selector(URLSessionStreamDelegate.urlSession(_:writeClosedFor:)): + return streamTaskWriteClosed != nil + case #selector(URLSessionStreamDelegate.urlSession(_:betterRouteDiscoveredFor:)): + return streamTaskBetterRouteDiscovered != nil + case #selector(URLSessionStreamDelegate.urlSession(_:streamTask:didBecome:outputStream:)): + return streamTaskDidBecomeInputAndOutputStreams != nil + default: + break + } + #endif + + switch selector { + case #selector(URLSessionDelegate.urlSession(_:didBecomeInvalidWithError:)): + return sessionDidBecomeInvalidWithError != nil + case #selector(URLSessionDelegate.urlSession(_:didReceive:completionHandler:)): + return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil) + case #selector(URLSessionTaskDelegate.urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)): + return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil) + case #selector(URLSessionDataDelegate.urlSession(_:dataTask:didReceive:completionHandler:)): + return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil) + default: + return type(of: self).instancesRespond(to: selector) + } + } +} + +// MARK: - URLSessionDelegate + +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) + } + + /// Requests credentials from the delegate in response to a session-level authentication request from the + /// remote server. + /// + /// - 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 + } + + 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 + } + } + } + + completionHandler(disposition, credential) + } + +#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) + } + +#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 + + if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { + redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) + } + + completionHandler(redirectRequest) + } + + /// 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 + } + + 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 + ) + } 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) + } + } + + /// 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 + ) + } + } + +#if !os(watchOS) + + /// 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 + } + +#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 } + + if let taskDidComplete = strongSelf.taskDidComplete { + taskDidComplete(session, task, error) + } else if let delegate = strongSelf[task]?.delegate { + 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 + } + + guard let request = self[task], let sessionManager = sessionManager else { + completeTask(session, task, error) + return + } + + // Run all validations on the request before checking if an error occurred + request.validations.forEach { $0() } + + // Determine whether an error has occurred + var error: Error? = error + + if let taskDelegate = self[task]?.delegate, taskDelegate.error != nil { + error = taskDelegate.error + } + + /// If an error occurred and the retrier is set, asynchronously ask the retrier if the request + /// should be retried. Otherwise, complete the task by notifying the task delegate. + if let retrier = retrier, let error = error { + retrier.should(sessionManager, retry: request, with: error) { [weak self] shouldRetry, delay in + guard shouldRetry else { completeTask(session, task, error) ; return } + + DispatchQueue.utility.after(delay) { [weak self] in + guard let strongSelf = self else { return } + + let retrySucceeded = strongSelf.sessionManager?.retry(request) ?? false + + if retrySucceeded, let task = request.task { + strongSelf[task] = request + return + } else { + completeTask(session, task, error) + } + } + } + } else { + completeTask(session, task, error) + } + } +} + +// MARK: - URLSessionDataDelegate + +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 + + if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { + disposition = dataTaskDidReceiveResponse(session, dataTask, response) + } + + completionHandler(disposition) + } + + /// Tells the delegate that the data task was changed to a download task. + /// + /// - parameter session: The session containing the task that was replaced by a download task. + /// - parameter dataTask: The data task that was replaced by a download task. + /// - parameter downloadTask: The new download task that replaced the data task. + open func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didBecome downloadTask: URLSessionDownloadTask) + { + if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask { + dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask) + } else { + self[downloadTask]?.delegate = DownloadTaskDelegate(task: downloadTask) + } + } + + /// Tells the delegate that the data task has received some of the expected data. + /// + /// - parameter session: The session containing the data task that provided data. + /// - parameter dataTask: The data task that provided data. + /// - parameter data: A data object containing the transferred data. + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + if let dataTaskDidReceiveData = dataTaskDidReceiveData { + dataTaskDidReceiveData(session, dataTask, data) + } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { + delegate.urlSession(session, dataTask: dataTask, didReceive: data) + } + } + + /// Asks the delegate whether the data (or upload) task should store the response in the cache. + /// + /// - parameter session: The session containing the data (or upload) task. + /// - parameter dataTask: The data (or upload) task. + /// - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current + /// caching policy and the values of certain received headers, such as the Pragma + /// and Cache-Control headers. + /// - parameter completionHandler: A block that your handler must call, providing either the original proposed + /// response, a modified version of that response, or NULL to prevent caching the + /// response. If your delegate implements this method, it must call this completion + /// handler; otherwise, your app leaks memory. + open func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse, + completionHandler: @escaping (CachedURLResponse?) -> Void) + { + guard dataTaskWillCacheResponseWithCompletion == nil else { + dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler) + return + } + + if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { + completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) + } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { + delegate.urlSession( + session, + dataTask: dataTask, + willCacheResponse: proposedResponse, + completionHandler: completionHandler + ) + } else { + completionHandler(proposedResponse) + } + } +} + +// MARK: - URLSessionDownloadDelegate + +extension SessionDelegate: URLSessionDownloadDelegate { + /// Tells the delegate that a download task has finished downloading. + /// + /// - parameter session: The session containing the download task that finished. + /// - parameter downloadTask: The download task that finished. + /// - parameter location: A file URL for the temporary file. Because the file is temporary, you must either + /// open the file for reading or move it to a permanent location in your app’s sandbox + /// container directory before returning from this delegate method. + open func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didFinishDownloadingTo location: URL) + { + if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { + downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) + } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { + delegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) + } + } + + /// Periodically informs the delegate about the download’s progress. + /// + /// - parameter session: The session containing the download task. + /// - parameter downloadTask: The download task. + /// - parameter bytesWritten: The number of bytes transferred since the last time this delegate + /// method was called. + /// - parameter totalBytesWritten: The total number of bytes transferred so far. + /// - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length + /// header. If this header was not provided, the value is + /// `NSURLSessionTransferSizeUnknown`. + open func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) + { + if let downloadTaskDidWriteData = downloadTaskDidWriteData { + downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) + } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { + delegate.urlSession( + session, + downloadTask: downloadTask, + didWriteData: bytesWritten, + totalBytesWritten: totalBytesWritten, + totalBytesExpectedToWrite: totalBytesExpectedToWrite + ) + } + } + + /// 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 + ) + } + } +} + +// MARK: - URLSessionStreamDelegate + +#if !os(watchOS) + +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) + } + + /// 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) + } + + /// 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) + } + + /// 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) + } +} + +#endif diff --git a/Pods/Alamofire/Source/SessionManager.swift b/Pods/Alamofire/Source/SessionManager.swift new file mode 100644 index 0000000..1363125 --- /dev/null +++ b/Pods/Alamofire/Source/SessionManager.swift @@ -0,0 +1,776 @@ +// +// SessionManager.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 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 + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + let encodedURLRequest = try encoding.encode(urlRequest, with: parameters) + return request(encodedURLRequest) + } catch { + return request(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 { + do { + let 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(failedWith: error) + } + } + + // MARK: Private - Request Implementation + + private func request(failedWith error: Error) -> DataRequest { + let request = DataRequest(session: session, requestTask: .data(nil, nil), error: error) + 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(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(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. + /// + /// - 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 request = DownloadRequest(session: session, requestTask: .download(downloadable, task)) + + request.downloadDelegate.destination = destination + + delegate[task] = request + + if startRequestsImmediately { request.resume() } + + return request + } catch { + return download(failedWith: error) + } + } + + private func download(failedWith error: Error) -> DownloadRequest { + let download = DownloadRequest(session: session, requestTask: .download(nil, nil), error: error) + 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(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(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(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(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(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(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) + + 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) + + 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) + + DispatchQueue.main.async { + let encodingResult = MultipartFormDataEncodingResult.success( + request: self.upload(fileURL, with: urlRequestWithContentType), + streamingFromDisk: true, + streamFileURL: fileURL + ) + encodingCompletion?(encodingResult) + } + } + } catch { + 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(failedWith: error) + } + } + + private func upload(failedWith error: Error) -> UploadRequest { + let upload = UploadRequest(session: session, requestTask: .upload(nil, nil), error: error) + 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 + 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 + open func stream(with netService: NetService) -> StreamRequest { + return stream(.netService(netService)) + } + + // MARK: Private - Stream Implementation + + 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) + } + } + + 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.startTime = CFAbsoluteTimeGetCurrent() + request.endTime = nil + + task.resume() + + return true + } catch { + request.delegate.error = error + return false + } + } +} diff --git a/Pods/Alamofire/Source/Stream.swift b/Pods/Alamofire/Source/Stream.swift deleted file mode 100644 index 07ebe33..0000000 --- a/Pods/Alamofire/Source/Stream.swift +++ /dev/null @@ -1,182 +0,0 @@ -// -// Stream.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 - -#if !os(watchOS) - -@available(iOS 9.0, OSX 10.11, tvOS 9.0, *) -extension Manager { - private enum Streamable { - case Stream(String, Int) - case NetService(NSNetService) - } - - private func stream(streamable: Streamable) -> Request { - var streamTask: NSURLSessionStreamTask! - - switch streamable { - case .Stream(let hostName, let port): - dispatch_sync(queue) { - streamTask = self.session.streamTaskWithHostName(hostName, port: port) - } - case .NetService(let netService): - dispatch_sync(queue) { - streamTask = self.session.streamTaskWithNetService(netService) - } - } - - let request = Request(session: session, task: streamTask) - - delegate[request.delegate.task] = request.delegate - - if startRequestsImmediately { - request.resume() - } - - return request - } - - /** - Creates a request for bidirectional streaming with the given hostname and port. - - - parameter hostName: The hostname of the server to connect to. - - parameter port: The port of the server to connect to. - - :returns: The created stream request. - */ - public func stream(hostName hostName: String, port: Int) -> Request { - return stream(.Stream(hostName, port)) - } - - /** - Creates a request for bidirectional streaming with the given `NSNetService`. - - - parameter netService: The net service used to identify the endpoint. - - - returns: The created stream request. - */ - public func stream(netService netService: NSNetService) -> Request { - return stream(.NetService(netService)) - } -} - -// MARK: - - -@available(iOS 9.0, OSX 10.11, tvOS 9.0, *) -extension Manager.SessionDelegate: NSURLSessionStreamDelegate { - - // MARK: Override Closures - - /// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:readClosedForStreamTask:`. - public var streamTaskReadClosed: ((NSURLSession, NSURLSessionStreamTask) -> Void)? { - get { - return _streamTaskReadClosed as? (NSURLSession, NSURLSessionStreamTask) -> Void - } - set { - _streamTaskReadClosed = newValue - } - } - - /// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:writeClosedForStreamTask:`. - public var streamTaskWriteClosed: ((NSURLSession, NSURLSessionStreamTask) -> Void)? { - get { - return _streamTaskWriteClosed as? (NSURLSession, NSURLSessionStreamTask) -> Void - } - set { - _streamTaskWriteClosed = newValue - } - } - - /// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:betterRouteDiscoveredForStreamTask:`. - public var streamTaskBetterRouteDiscovered: ((NSURLSession, NSURLSessionStreamTask) -> Void)? { - get { - return _streamTaskBetterRouteDiscovered as? (NSURLSession, NSURLSessionStreamTask) -> Void - } - set { - _streamTaskBetterRouteDiscovered = newValue - } - } - - /// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:streamTask:didBecomeInputStream:outputStream:`. - public var streamTaskDidBecomeInputStream: ((NSURLSession, NSURLSessionStreamTask, NSInputStream, NSOutputStream) -> Void)? { - get { - return _streamTaskDidBecomeInputStream as? (NSURLSession, NSURLSessionStreamTask, NSInputStream, NSOutputStream) -> Void - } - set { - _streamTaskDidBecomeInputStream = newValue - } - } - - // MARK: Delegate Methods - - /** - Tells the delegate that the read side of the connection has been closed. - - - parameter session: The session. - - parameter streamTask: The stream task. - */ - public func URLSession(session: NSURLSession, readClosedForStreamTask streamTask: NSURLSessionStreamTask) { - streamTaskReadClosed?(session, streamTask) - } - - /** - Tells the delegate that the write side of the connection has been closed. - - - parameter session: The session. - - parameter streamTask: The stream task. - */ - public func URLSession(session: NSURLSession, writeClosedForStreamTask streamTask: NSURLSessionStreamTask) { - streamTaskWriteClosed?(session, streamTask) - } - - /** - 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. - */ - public func URLSession(session: NSURLSession, betterRouteDiscoveredForStreamTask streamTask: NSURLSessionStreamTask) { - streamTaskBetterRouteDiscovered?(session, streamTask) - } - - /** - 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. - */ - public func URLSession( - session: NSURLSession, - streamTask: NSURLSessionStreamTask, - didBecomeInputStream inputStream: NSInputStream, - outputStream: NSOutputStream) - { - streamTaskDidBecomeInputStream?(session, streamTask, inputStream, outputStream) - } -} - -#endif diff --git a/Pods/Alamofire/Source/TaskDelegate.swift b/Pods/Alamofire/Source/TaskDelegate.swift new file mode 100644 index 0000000..4a10b65 --- /dev/null +++ b/Pods/Alamofire/Source/TaskDelegate.swift @@ -0,0 +1,449 @@ +// +// TaskDelegate.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 + +/// 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 + + var task: URLSessionTask? { + didSet { reset() } + } + + var data: Data? { return nil } + var error: Error? + + var initialResponseTime: CFAbsoluteTime? + var credential: URLCredential? + var metrics: AnyObject? // URLSessionTaskMetrics + + // MARK: Lifecycle + + init(task: URLSessionTask?) { + self.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 + + if let destination = destination { + let result = destination(location, downloadTask.response as! HTTPURLResponse) + let destination = result.destinationURL + let options = result.options + + do { + destinationURL = destination + + if options.contains(.removePreviousFile) { + if FileManager.default.fileExists(atPath: destination.path) { + try FileManager.default.removeItem(at: destination) + } + } + + if options.contains(.createIntermediateDirectories) { + let directory = destination.deletingLastPathComponent() + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: nil) + } + + try FileManager.default.moveItem(at: location, to: destination) + } 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/Pods/Alamofire/Source/Timeline.swift b/Pods/Alamofire/Source/Timeline.swift index 3610f15..1440989 100644 --- a/Pods/Alamofire/Source/Timeline.swift +++ b/Pods/Alamofire/Source/Timeline.swift @@ -39,29 +39,27 @@ public struct Timeline { 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: NSTimeInterval + public let latency: TimeInterval /// The time interval in seconds from the time the request started to the time the request completed. - public let requestDuration: NSTimeInterval + public let requestDuration: TimeInterval /// The time interval in seconds from the time the request completed to the time response serialization completed. - public let serializationDuration: NSTimeInterval + public let serializationDuration: TimeInterval /// The time interval in seconds from the time the request started to the time response serialization completed. - public let totalDuration: NSTimeInterval + 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. - */ + /// 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, @@ -83,7 +81,7 @@ public struct Timeline { // MARK: - CustomStringConvertible extension Timeline: CustomStringConvertible { - /// The textual representation used when written to an output stream, which includes the latency, the request + /// 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) @@ -91,35 +89,48 @@ extension Timeline: CustomStringConvertible { 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" + "\"Latency\": " + latency + " secs", + "\"Request Duration\": " + requestDuration + " secs", + "\"Serialization Duration\": " + serializationDuration + " secs", + "\"Total Duration\": " + totalDuration + " secs" ] - return "Timeline: { \(timings.joinWithSeparator(", ")) }" + 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 + /// 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" + "\"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.joinWithSeparator(", ")) }" + return "Timeline: { " + timings.joined(separator: ", ") + " }" } } diff --git a/Pods/Alamofire/Source/Upload.swift b/Pods/Alamofire/Source/Upload.swift deleted file mode 100644 index 7b31ba5..0000000 --- a/Pods/Alamofire/Source/Upload.swift +++ /dev/null @@ -1,376 +0,0 @@ -// -// Upload.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 - -extension Manager { - private enum Uploadable { - case Data(NSURLRequest, NSData) - case File(NSURLRequest, NSURL) - case Stream(NSURLRequest, NSInputStream) - } - - private func upload(uploadable: Uploadable) -> Request { - var uploadTask: NSURLSessionUploadTask! - var HTTPBodyStream: NSInputStream? - - switch uploadable { - case .Data(let request, let data): - dispatch_sync(queue) { - uploadTask = self.session.uploadTaskWithRequest(request, fromData: data) - } - case .File(let request, let fileURL): - dispatch_sync(queue) { - uploadTask = self.session.uploadTaskWithRequest(request, fromFile: fileURL) - } - case .Stream(let request, let stream): - dispatch_sync(queue) { - uploadTask = self.session.uploadTaskWithStreamedRequest(request) - } - - HTTPBodyStream = stream - } - - let request = Request(session: session, task: uploadTask) - - if HTTPBodyStream != nil { - request.delegate.taskNeedNewBodyStream = { _, _ in - return HTTPBodyStream - } - } - - delegate[request.delegate.task] = request.delegate - - if startRequestsImmediately { - request.resume() - } - - return request - } - - // MARK: File - - /** - Creates a request for uploading a file to the specified URL request. - - If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - - - parameter URLRequest: The URL request - - parameter file: The file to upload - - - returns: The created upload request. - */ - public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request { - return upload(.File(URLRequest.URLRequest, file)) - } - - /** - Creates a request for uploading a file to the specified URL request. - - If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - - - parameter method: The HTTP method. - - parameter URLString: The URL string. - - parameter headers: The HTTP headers. `nil` by default. - - parameter file: The file to upload - - - returns: The created upload request. - */ - public func upload( - method: Method, - _ URLString: URLStringConvertible, - headers: [String: String]? = nil, - file: NSURL) - -> Request - { - let mutableURLRequest = URLRequest(method, URLString, headers: headers) - return upload(mutableURLRequest, file: file) - } - - // MARK: Data - - /** - Creates a request for uploading data to the specified URL request. - - If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - - - parameter URLRequest: The URL request. - - parameter data: The data to upload. - - - returns: The created upload request. - */ - public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request { - return upload(.Data(URLRequest.URLRequest, data)) - } - - /** - Creates a request for uploading data to the specified URL request. - - If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - - - parameter method: The HTTP method. - - parameter URLString: The URL string. - - parameter headers: The HTTP headers. `nil` by default. - - parameter data: The data to upload - - - returns: The created upload request. - */ - public func upload( - method: Method, - _ URLString: URLStringConvertible, - headers: [String: String]? = nil, - data: NSData) - -> Request - { - let mutableURLRequest = URLRequest(method, URLString, headers: headers) - - return upload(mutableURLRequest, data: data) - } - - // MARK: Stream - - /** - Creates a request for uploading a stream to the specified URL request. - - If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - - - parameter URLRequest: The URL request. - - parameter stream: The stream to upload. - - - returns: The created upload request. - */ - public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request { - return upload(.Stream(URLRequest.URLRequest, stream)) - } - - /** - Creates a request for uploading a stream to the specified URL request. - - If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - - - parameter method: The HTTP method. - - parameter URLString: The URL string. - - parameter headers: The HTTP headers. `nil` by default. - - parameter stream: The stream to upload. - - - returns: The created upload request. - */ - public func upload( - method: Method, - _ URLString: URLStringConvertible, - headers: [String: String]? = nil, - stream: NSInputStream) - -> Request - { - let mutableURLRequest = URLRequest(method, URLString, headers: headers) - - return upload(mutableURLRequest, stream: stream) - } - - // MARK: MultipartFormData - - /// Default memory threshold used when encoding `MultipartFormData`. - public static let MultipartFormDataEncodingMemoryThreshold: UInt64 = 10 * 1024 * 1024 - - /** - 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 `Request` 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: Request, streamingFromDisk: Bool, streamFileURL: NSURL?) - case Failure(ErrorType) - } - - /** - Encodes the `MultipartFormData` and creates a request to upload the result to the specified URL request. - - 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 method: The HTTP method. - - parameter URLString: The URL string. - - parameter headers: The HTTP headers. `nil` by default. - - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. - `MultipartFormDataEncodingMemoryThreshold` by default. - - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. - */ - public func upload( - method: Method, - _ URLString: URLStringConvertible, - headers: [String: String]? = nil, - multipartFormData: MultipartFormData -> Void, - encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, - encodingCompletion: (MultipartFormDataEncodingResult -> Void)?) - { - let mutableURLRequest = URLRequest(method, URLString, headers: headers) - - return upload( - mutableURLRequest, - multipartFormData: multipartFormData, - encodingMemoryThreshold: encodingMemoryThreshold, - encodingCompletion: encodingCompletion - ) - } - - /** - Encodes the `MultipartFormData` and creates a request to upload the result to the specified URL request. - - 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 URLRequest: The URL request. - - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. - `MultipartFormDataEncodingMemoryThreshold` by default. - - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. - */ - public func upload( - URLRequest: URLRequestConvertible, - multipartFormData: MultipartFormData -> Void, - encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, - encodingCompletion: (MultipartFormDataEncodingResult -> Void)?) - { - dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { - let formData = MultipartFormData() - multipartFormData(formData) - - let URLRequestWithContentType = URLRequest.URLRequest - URLRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type") - - let isBackgroundSession = self.session.configuration.identifier != nil - - if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession { - do { - let data = try formData.encode() - let encodingResult = MultipartFormDataEncodingResult.Success( - request: self.upload(URLRequestWithContentType, data: data), - streamingFromDisk: false, - streamFileURL: nil - ) - - dispatch_async(dispatch_get_main_queue()) { - encodingCompletion?(encodingResult) - } - } catch { - dispatch_async(dispatch_get_main_queue()) { - encodingCompletion?(.Failure(error as NSError)) - } - } - } else { - let fileManager = NSFileManager.defaultManager() - let tempDirectoryURL = NSURL(fileURLWithPath: NSTemporaryDirectory()) - let directoryURL = tempDirectoryURL.URLByAppendingPathComponent("com.alamofire.manager/multipart.form.data") - let fileName = NSUUID().UUIDString - let fileURL = directoryURL.URLByAppendingPathComponent(fileName) - - do { - try fileManager.createDirectoryAtURL(directoryURL, withIntermediateDirectories: true, attributes: nil) - try formData.writeEncodedDataToDisk(fileURL) - - dispatch_async(dispatch_get_main_queue()) { - let encodingResult = MultipartFormDataEncodingResult.Success( - request: self.upload(URLRequestWithContentType, file: fileURL), - streamingFromDisk: true, - streamFileURL: fileURL - ) - encodingCompletion?(encodingResult) - } - } catch { - dispatch_async(dispatch_get_main_queue()) { - encodingCompletion?(.Failure(error as NSError)) - } - } - } - } - } -} - -// MARK: - - -extension Request { - - // MARK: - UploadTaskDelegate - - class UploadTaskDelegate: DataTaskDelegate { - var uploadTask: NSURLSessionUploadTask? { return task as? NSURLSessionUploadTask } - var uploadProgress: ((Int64, Int64, Int64) -> Void)! - - // MARK: - NSURLSessionTaskDelegate - - // MARK: Override Closures - - var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)? - - // MARK: Delegate Methods - - func URLSession( - session: NSURLSession, - task: NSURLSessionTask, - didSendBodyData bytesSent: Int64, - totalBytesSent: Int64, - totalBytesExpectedToSend: Int64) - { - if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } - - if let taskDidSendBodyData = taskDidSendBodyData { - taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) - } else { - progress.totalUnitCount = totalBytesExpectedToSend - progress.completedUnitCount = totalBytesSent - - uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend) - } - } - } -} diff --git a/Pods/Alamofire/Source/Validation.swift b/Pods/Alamofire/Source/Validation.swift index e90db2d..c405d02 100644 --- a/Pods/Alamofire/Source/Validation.swift +++ b/Pods/Alamofire/Source/Validation.swift @@ -26,94 +26,33 @@ import Foundation extension Request { - /** - Used to represent whether validation was successful or encountered an error resulting in a failure. + // MARK: Helper Types - - Success: The validation was successful. - - Failure: The validation failed encountering the provided error. - */ + 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(NSError) + case success + case failure(Error) } - /** - A closure used to validate a request that takes a URL request and URL response, and returns whether the - request was valid. - */ - public typealias Validation = (NSURLRequest?, NSHTTPURLResponse) -> 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. - */ - public func validate(validation: Validation) -> Self { - delegate.queue.addOperationWithBlock { - if let - response = self.response where self.delegate.error == nil, - case let .Failure(error) = validation(self.request, response) - { - self.delegate.error = error - } - } - - return self - } - - // MARK: - Status Code - - /** - Validates that the response has a status code in the specified range. - - If validation fails, subsequent calls to response handlers will have an associated error. - - - parameter range: The range of acceptable status codes. - - - returns: The request. - */ - public func validate(statusCode acceptableStatusCode: S) -> Self { - return validate { _, response in - if acceptableStatusCode.contains(response.statusCode) { - return .Success - } else { - let failureReason = "Response status code was unacceptable: \(response.statusCode)" - - let error = NSError( - domain: Error.Domain, - code: Error.Code.StatusCodeValidationFailed.rawValue, - userInfo: [ - NSLocalizedFailureReasonErrorKey: failureReason, - Error.UserInfoKeys.StatusCode: response.statusCode - ] - ) - - return .Failure(error) - } - } - } - - // MARK: - Content-Type - - private struct MIMEType { + fileprivate struct MIMEType { let type: String let subtype: String + var isWildcard: Bool { return type == "*" && subtype == "*" } + init?(_ string: String) { let components: [String] = { - let stripped = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) - let split = stripped.substringToIndex(stripped.rangeOfString(";")?.startIndex ?? stripped.endIndex) - return split.componentsSeparatedByString("/") + let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines) + let split = stripped.substring(to: stripped.range(of: ";")?.lowerBound ?? stripped.endIndex) + return split.components(separatedBy: "/") }() - if let - type = components.first, - subtype = components.last - { + if let type = components.first, let subtype = components.last { self.type = type self.subtype = subtype } else { @@ -121,9 +60,9 @@ extension Request { } } - func matches(MIME: MIMEType) -> Bool { + func matches(_ mime: MIMEType) -> Bool { switch (type, subtype) { - case (MIME.type, MIME.subtype), (MIME.type, "*"), ("*", MIME.subtype), ("*", "*"): + case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"): return true default: return false @@ -131,84 +70,240 @@ extension Request { } } - /** - Validates that the response has a content type in the specified array. + // MARK: Properties - If validation fails, subsequent calls to response handlers will have an associated error. + fileprivate var acceptableStatusCodes: [Int] { return Array(200..<300) } - - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. + fileprivate var acceptableContentTypes: [String] { + if let accept = request?.value(forHTTPHeaderField: "Accept") { + return accept.components(separatedBy: ",") + } - - returns: The request. - */ - public func validate(contentType acceptableContentTypes: S) -> Self { - return validate { _, response in - guard let validData = self.delegate.data where validData.length > 0 else { return .Success } + return ["*/*"] + } - if let - responseContentType = response.MIMEType, - responseMIMEType = MIMEType(responseContentType) - { - for contentType in acceptableContentTypes { - if let acceptableMIMEType = MIMEType(contentType) where acceptableMIMEType.matches(responseMIMEType) { - return .Success - } - } - } else { - for contentType in acceptableContentTypes { - if let MIMEType = MIMEType(contentType) where MIMEType.type == "*" && MIMEType.subtype == "*" { - return .Success - } - } - } + // MARK: Status Code - let contentType: String - let failureReason: String - - if let responseContentType = response.MIMEType { - contentType = responseContentType - - failureReason = ( - "Response content type \"\(responseContentType)\" does not match any acceptable " + - "content types: \(acceptableContentTypes)" - ) - } else { - contentType = "" - failureReason = "Response content type was missing and acceptable content type does not match \"*/*\"" - } - - let error = NSError( - domain: Error.Domain, - code: Error.Code.ContentTypeValidationFailed.rawValue, - userInfo: [ - NSLocalizedFailureReasonErrorKey: failureReason, - Error.UserInfoKeys.ContentType: contentType - ] - ) - - return .Failure(error) + fileprivate func validate( + statusCode acceptableStatusCodes: S, + response: HTTPURLResponse) + -> ValidationResult + where S.Iterator.Element == Int + { + if acceptableStatusCodes.contains(response.statusCode) { + return .success + } else { + let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode) + return .failure(AFError.responseValidationFailed(reason: reason)) } } - // MARK: - Automatic + // MARK: Content Type - /** - Validates that the response has a status code in the default acceptable range of 200...299, and that the content - type matches any specified in the Accept HTTP header field. + 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 } - If validation fails, subsequent calls to response handlers will have an associated error. - - - returns: The request. - */ - public func validate() -> Self { - let acceptableStatusCodes: Range = 200..<300 - let acceptableContentTypes: [String] = { - if let accept = request?.valueForHTTPHeaderField("Accept") { - return accept.componentsSeparatedByString(",") + guard + let responseContentType = response.mimeType, + let responseMIMEType = MIMEType(responseContentType) + else { + for contentType in acceptableContentTypes { + if let mimeType = MIMEType(contentType), mimeType.isWildcard { + return .success + } } - return ["*/*"] + let error: AFError = { + let reason: ErrorReason = .missingContentType(acceptableContentTypes: Array(acceptableContentTypes)) + return AFError.responseValidationFailed(reason: reason) + }() + + return .failure(error) + } + + for contentType in acceptableContentTypes { + if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) { + return .success + } + } + + let error: AFError = { + let reason: ErrorReason = .unacceptableContentType( + acceptableContentTypes: Array(acceptableContentTypes), + responseContentType: responseContentType + ) + + return AFError.responseValidationFailed(reason: reason) }() - return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes) + return .failure(error) + } +} + +// MARK: - + +extension DataRequest { + /// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the + /// request was valid. + public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult + + /// Validates 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. + /// + /// - parameter range: The range of acceptable status codes. + /// + /// - 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) + } + } + + /// Validates that the response has a content type in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. + /// + /// - returns: The request. + @discardableResult + public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { + return validate { [unowned self] _, response, data in + return self.validate(contentType: acceptableContentTypes, response: response, data: data) + } + } + + /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content + /// type matches any specified in the Accept HTTP header field. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - returns: The request. + @discardableResult + public func validate() -> Self { + return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes) + } +} + +// MARK: - + +extension DownloadRequest { + /// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a + /// destination URL, and returns whether the request was valid. + public typealias Validation = ( + _ request: URLRequest?, + _ response: HTTPURLResponse, + _ temporaryURL: URL?, + _ destinationURL: 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. + /// + /// - parameter range: The range of acceptable status codes. + /// + /// - 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) + } + } + + /// Validates that the response has a content type in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. + /// + /// - returns: The request. + @discardableResult + public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { + return validate { [unowned self] _, response, _, _ in + let fileURL = self.downloadDelegate.fileURL + + guard let validFileURL = fileURL else { + return .failure(AFError.responseValidationFailed(reason: .dataFileNil)) + } + + do { + let data = try Data(contentsOf: validFileURL) + return self.validate(contentType: acceptableContentTypes, response: response, data: data) + } catch { + return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL))) + } + } + } + + /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content + /// type matches any specified in the Accept HTTP header field. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - returns: The request. + @discardableResult + public func validate() -> Self { + return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes) } } diff --git a/Pods/Manifest.lock b/Pods/Manifest.lock index 96580b2..d1abbe2 100644 --- a/Pods/Manifest.lock +++ b/Pods/Manifest.lock @@ -1,20 +1,20 @@ PODS: - - Alamofire (3.4.0) + - Alamofire (4.0.1) - BRLOptionParser (0.3.1) - GCDWebServer (3.3.3): - GCDWebServer/Core (= 3.3.3) - GCDWebServer/Core (3.3.3) DEPENDENCIES: - - Alamofire (~> 3.4) + - Alamofire (~> 4.0.1) - BRLOptionParser (~> 0.3.1) - GCDWebServer (~> 3.0) SPEC CHECKSUMS: - Alamofire: c19a627cefd6a95f840401c49ab1f124e07f54ee + Alamofire: 7682d43245de14874acd142ec137b144aa1dd335 BRLOptionParser: a03256a8ff003ca1f5376c55f55f210e085a3958 GCDWebServer: 1c39a1f0763e4eb492bee021e4270fce097d3555 -PODFILE CHECKSUM: 038d7dc431157cfa86a2856ee236c4ed1ddfd26b +PODFILE CHECKSUM: e675030dbd86de38216dc6c44e64ca1458be94bc COCOAPODS: 1.0.1 diff --git a/Pods/Pods.xcodeproj/project.pbxproj b/Pods/Pods.xcodeproj/project.pbxproj index ed1cbc7..13063d4 100644 --- a/Pods/Pods.xcodeproj/project.pbxproj +++ b/Pods/Pods.xcodeproj/project.pbxproj @@ -10,20 +10,17 @@ 00C1D4F2B49242121D01C05655377D07 /* GCDWebServerMultiPartFormRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = EAEC4F2E970093B9815E645E63781C40 /* GCDWebServerMultiPartFormRequest.h */; settings = {ATTRIBUTES = (Public, ); }; }; 06BA2F5A0BF79A08FA2DAB3E0FFD5498 /* BRLOptionParser-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 052330BD03A0DFCDEFF81F8EC5BFEB02 /* BRLOptionParser-dummy.m */; }; 06CE205FB95B45D7ED260AFD00AC79DD /* GCDWebServerErrorResponse.h in Headers */ = {isa = PBXBuildFile; fileRef = 7B884322F7F32E5886E831225EF61A24 /* GCDWebServerErrorResponse.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 095406039B4D371E48D08B38A2975AC8 /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 19863D6E702634433EB92BDFE07633C9 /* Error.swift */; }; + 0C1B4E9FFB8B81E8833A3BAD537B1990 /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 12B556C66780BC3D0BECF011EAF49ECB /* Notifications.swift */; }; + 12118C354EFA36292F82A8D0CFCE45B2 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 781B71F26694E106B9C6014A4D828CFE /* Request.swift */; }; 15660F7531C71B00780160E7BC3A75EF /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 35133A1ADAD65BF87962F819AF44834C /* Cocoa.framework */; }; - 16102E4E35FAA0FC4161282FECE56469 /* Timeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C9A6FB24BE0AEB3FE45BE09CBEC90CA /* Timeline.swift */; }; 1B72926422971A05A1038FEF1F10DA23 /* GCDWebServerFileResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = D35A95B17B77B37E12236498D60B8478 /* GCDWebServerFileResponse.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; 1BF86805992CFF0188743FC58574A612 /* GCDWebServerResponse.h in Headers */ = {isa = PBXBuildFile; fileRef = 7EA43A03295E967E8CE48DC3D41B1FB1 /* GCDWebServerResponse.h */; settings = {ATTRIBUTES = (Public, ); }; }; 1DBE01B20E03413F5811A7E58EB649BD /* GCDWebServerFileResponse.h in Headers */ = {isa = PBXBuildFile; fileRef = EB10970D56AE3E8EC08A3B6CB0ECF896 /* GCDWebServerFileResponse.h */; settings = {ATTRIBUTES = (Public, ); }; }; 2659AF88A6232000AB5213D46D90BF57 /* GCDWebServer-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 675C317EFB4447DD15024A74FF8C9E6C /* GCDWebServer-dummy.m */; }; - 2D3405986FC586FA6C0A5E0B6BA7E64E /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8ED45027AFDE6DFC119E5002ED79602 /* Validation.swift */; }; 2D93C03399B11DAF5988CEC6E4EDDE50 /* Pods-ShadowsocksX-NG-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 24B01D81E3D7058FA14A053EC19874D0 /* Pods-ShadowsocksX-NG-dummy.m */; }; 2FD4F69F155869816E3568D2C0A328CD /* GCDWebServerDataResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = BE05C895D7CA02C6123697B3944C59D3 /* GCDWebServerDataResponse.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; - 34CCDCA848A701466256BC2927DA8856 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4BB13A3408660727BF5A93D796C002D4 /* NetworkReachabilityManager.swift */; }; 34FDA8A310469061BC207ED84D065BBC /* GCDWebServerFunctions.h in Headers */ = {isa = PBXBuildFile; fileRef = A2AB24692BC4901FA1B8CD5A65C8AA62 /* GCDWebServerFunctions.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 3EA8F215C9C1432D74E5CCA4834AA8C0 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79A93CC40664DA60F6E9AAD219A11B49 /* ResponseSerialization.swift */; }; - 4081EA628AF0B73AC51FFB9D7AB3B89E /* Manager.swift in Sources */ = {isa = PBXBuildFile; fileRef = FDEF79B127C0B89EAE92BC708EC435D0 /* Manager.swift */; }; + 3982B850C43B41BA6D25F440F0412E9B /* Timeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = B2E64BA5DE520D1FF8D157D1948EF678 /* Timeline.swift */; }; 44550BF1A67A522A640A51B30DB21069 /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 35133A1ADAD65BF87962F819AF44834C /* Cocoa.framework */; }; 44D5C1A62CB2C6B4C3BC022D80F843D1 /* GCDWebServerRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = FE4DE2F9318899EC55FF739F09547B9F /* GCDWebServerRequest.h */; settings = {ATTRIBUTES = (Public, ); }; }; 466989E9288E7804B50D2D9FDCAD8F19 /* BRLOptionParser.h in Headers */ = {isa = PBXBuildFile; fileRef = 4461C7BE603BCBC96BA24E3E752C6AC0 /* BRLOptionParser.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -32,45 +29,48 @@ 5183D0C1CC83750A1ADE57A638E7F456 /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 71153E50563B065484D16F662AD08EDB /* SystemConfiguration.framework */; }; 53F30F986D39FC6EBE468697B2494ED5 /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 35133A1ADAD65BF87962F819AF44834C /* Cocoa.framework */; }; 59B57964B1FD13F37637947C46E77EA0 /* GCDWebServerConnection.m in Sources */ = {isa = PBXBuildFile; fileRef = 8C6F72ED24E84D8DC9445729D927B6E8 /* GCDWebServerConnection.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; - 5BC19E6E0F199276003F0AF96838BCE5 /* Upload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 97676FEA7A66144B58C43891F45FD408 /* Upload.swift */; }; - 5CB05FBCB32D21E194B5ECF680CB6AE0 /* Download.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EF74B3D95D99D283831DCF22F051B3B /* Download.swift */; }; 5FAE6F4952486D7B0087309AA2F25DB0 /* GCDWebServerConnection.h in Headers */ = {isa = PBXBuildFile; fileRef = 150AAAC15A441418AEA6DFBF159FBEA0 /* GCDWebServerConnection.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 62E8346F03C03E7F4D631361F325689E /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5053AF0338A9A4CC9AABB3AF55A2A41 /* Response.swift */; }; + 62143065F94E53F437DCE5D7A998D66D /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = D86AC40F610A78D1B5E5AC9528E70ADB /* AFError.swift */; }; 64EFFC6E05B9CACD03418CEF01429883 /* GCDWebServerFunctions.m in Sources */ = {isa = PBXBuildFile; fileRef = 8CD28F4DA9E9FD6CDF59B9183753B0AD /* GCDWebServerFunctions.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; 6B25647E430E216994070188D9E2CFF8 /* GCDWebServerDataRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = 056695931D97F3BAC1F31181094FF7F0 /* GCDWebServerDataRequest.h */; settings = {ATTRIBUTES = (Public, ); }; }; 6D2CA7708E200C89F0DAD24F88680D46 /* GCDWebServerHTTPStatusCodes.h in Headers */ = {isa = PBXBuildFile; fileRef = D9D61BAD16772ED8DBCD878F6BBF7025 /* GCDWebServerHTTPStatusCodes.h */; settings = {ATTRIBUTES = (Public, ); }; }; 743CC8268943E23DB0EADC8614FEE9BA /* GCDWebServerURLEncodedFormRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = 56CBA6D73D3D0B47B5D2DCA98FD3514E /* GCDWebServerURLEncodedFormRequest.h */; settings = {ATTRIBUTES = (Public, ); }; }; 749BEB3F21EAFA6D78F5631312D2C7E6 /* GCDWebServer.h in Headers */ = {isa = PBXBuildFile; fileRef = 057330267A99F07C8ADE6135AA1F622F /* GCDWebServer.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 7B48852C4D848FA2DA416A98F6425869 /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2223C268D688D65D7FE92C86F63188D3 /* ServerTrustPolicy.swift */; }; + 7CA5A9BA5246FDA8227233E310029392 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0E8D592A9C0AE4B6C90789AFF29DF516 /* Alamofire.swift */; }; 7D747500B9BEC95D4FA0FEA5BFA6D4D4 /* GCDWebServerFileRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = D7C15E08E56E065130F76FC8DC8C8619 /* GCDWebServerFileRequest.h */; settings = {ATTRIBUTES = (Public, ); }; }; 8316EC11EB8EF857FC8AC924FF540076 /* GCDWebServerErrorResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = 8CC694BC2D5AA3651FE2946D4032D0F5 /* GCDWebServerErrorResponse.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + 86ED08F33B7D357932A9AB743E9D9EA7 /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = FC11D9EFE483BFE3E6CC4AC3CCC0E8D7 /* Response.swift */; }; 8A400F495FB328F47971CEFD020BE9CB /* GCDWebServerStreamedResponse.h in Headers */ = {isa = PBXBuildFile; fileRef = 65715F792D70CDE4E67F1EB98531E233 /* GCDWebServerStreamedResponse.h */; settings = {ATTRIBUTES = (Public, ); }; }; 8B2C601594F026DF642B1F06A77C4CBB /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 35133A1ADAD65BF87962F819AF44834C /* Cocoa.framework */; }; - 8EB11202167FCDDF1257AAAB1D1FB244 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4FB848B724CAC1DF71DB3D6900F463C2 /* Alamofire.swift */; }; + 8D463A0A4C65C02FDD5211F0F3C6F8B8 /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 383ADB6B629F7BC3B7FB986648404A88 /* Alamofire-dummy.m */; }; + 907AB123FBC8BC9340D5B7350CE828DF /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3565E299C44D10C2D206FDCD078A0008 /* SessionDelegate.swift */; }; 936C4E5402529DF91047CB9B84C5C281 /* GCDWebServerURLEncodedFormRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 8C6444C9A87ED6919A7864A0C9D70A4C /* GCDWebServerURLEncodedFormRequest.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; - 9469DF81ECB494E84675969B5E13374C /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 8CDCCB45ECA29E5CF67690354B7D62E3 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 9469DF81ECB494E84675969B5E13374C /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = BB1A40A42CB3E3DE3C7FB21A038462FD /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; 946AF936A5472D7D7EF243D3399A2D44 /* GCDWebServerResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = 432FFBD34AE4D6FE11F7562A7B2E2DF6 /* GCDWebServerResponse.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; 976C070668BB589ABDB7498633967223 /* GCDWebServerStreamedResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = 41B03492069EA8D52FDD5E9F8CC3749D /* GCDWebServerStreamedResponse.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; 9B0EB35B7EB06524DBD6B46D15F9E55B /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 35133A1ADAD65BF87962F819AF44834C /* Cocoa.framework */; }; + A79AC30123B0C2177D67F6ED6A1B3215 /* SessionManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 352C9ACA5D14E48B378FF32021EAD9B4 /* SessionManager.swift */; }; A7AF534B31209659ED4C123BC4D32A31 /* GCDWebServerFileRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 9564AF1CDDA43CCBDDB1A7A9D41FD163 /* GCDWebServerFileRequest.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; - AA314156AC500125F4078EE968DB14C6 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61F7983117C400AC29CB2772079182E2 /* Result.swift */; }; AA5A24F29D4D8831ED55AB74A2F17A71 /* GCDWebServerDataResponse.h in Headers */ = {isa = PBXBuildFile; fileRef = B49FCFC5427009EB0DE924D8E6689486 /* GCDWebServerDataResponse.h */; settings = {ATTRIBUTES = (Public, ); }; }; - ADF19C953CE2A7D0B72EC93A81FCCC26 /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = BDB73E594147C01A752A5AACF0D50DE9 /* Alamofire-dummy.m */; }; - AE4CF87C02C042DF13ED5B21C4FDC1E0 /* Stream.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7E9F59498CDD1D70C29D21C0D6CE6575 /* Stream.swift */; }; + AF158CAAF4DD319009AFC855DC995D90 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = C83162C9BDFB3C0617CF191D660EC2DA /* ParameterEncoding.swift */; }; AFC0F5A350E42EDD292F2B499C13FBFD /* GCDWebServerMultiPartFormRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 5BF25F29EE771444894D4B4BD6A5094A /* GCDWebServerMultiPartFormRequest.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; B117FB3C5DADAA39C6FE0B2E2E0FD8F8 /* GCDWebServerDataRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = E02D3FE330950F96E4826E6785950F95 /* GCDWebServerDataRequest.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; - BE41196F6A3903E59C3306FE3F8B43FE /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08903B6D9CE24A6E780E1F35EAEB9230 /* Notifications.swift */; }; - C0DB70AB368765DC64BFB5FEA75E0696 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7AA44828C94616294316E0C53D00B02 /* ParameterEncoding.swift */; }; + B8154C96802336E5DDA5CEE97C3180A0 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 11B6EC5B2B4F6B09E9967325BF493C9D /* ResponseSerialization.swift */; }; + C0AEA97E7684DDAD56998C0AE198A433 /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 193AA1B44C4CB1CFCCEDD6C9741F5211 /* ServerTrustPolicy.swift */; }; C40F70E70A1D2FAEBFEFE14958C47FBE /* GCDWebServer-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F5FCCAE1F4AE542376E5F228D7463E4F /* GCDWebServer-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; C434F05C1EE617DA4557EF41FBE55B3E /* Pods-proxy_conf_helper-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = CE50445A73ECB9A2ED31A6FF93D45808 /* Pods-proxy_conf_helper-dummy.m */; }; - C7B6DD7C0456C50289A2C381DFE9FA3F /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = ED9FDD5C333260AC0A0141C7AA82A7C8 /* MultipartFormData.swift */; }; + C7A3408350643ADE1018826C766EE356 /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = C9C4A7AA3B3DD74EDA43165A42745D1A /* MultipartFormData.swift */; }; CF7724A299AEAFFC9CF29DE6124520E3 /* Pods-ShadowsocksX-NGTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = D7E8128F302CF60BEF206008CE11F6D3 /* Pods-ShadowsocksX-NGTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; DE37CE3D218BBE39543E834E7BFA857C /* GCDWebServerPrivate.h in Headers */ = {isa = PBXBuildFile; fileRef = CA78677B47A82041B6A0C96CE51F76C2 /* GCDWebServerPrivate.h */; settings = {ATTRIBUTES = (Private, ); }; }; - EFE92E8D3813DD26E78E93EEAF6D7E7E /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8B2BB45AAB2161A1A3D784559749CF9 /* Request.swift */; }; + DF1BBF94997A2F4248B42B25EA919EC2 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1673CAE4B8238FFD59A792823A36A9DF /* Result.swift */; }; + E1F583CB4A68A928CD197250AA752926 /* TaskDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C058E7895E0BD655DB18CD87B39658B /* TaskDelegate.swift */; }; + E2A1C34237B4E928E5F85C097F4C2551 /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2625C48AD777A2B7E26D2A80E9CD94E7 /* DispatchQueue+Alamofire.swift */; }; + E59BF19C0AFA68B741552319FC478C7B /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7E6D819AE4FECE3068ED91259133EAC /* NetworkReachabilityManager.swift */; }; F06A7AC16F49B8271D54543DB8F29199 /* GCDWebServer.m in Sources */ = {isa = PBXBuildFile; fileRef = 3490D661D0DB72BC3A5F94A1C6AE083C /* GCDWebServer.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; F2D887DA7E26C2F5533160A074B05EF0 /* BRLOptionParser.m in Sources */ = {isa = PBXBuildFile; fileRef = BAA6E2FFB996A81C9D31918A563B43FB /* BRLOptionParser.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; F3F3FD9096F43B73CBB52EF0E1CCF73E /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 35133A1ADAD65BF87962F819AF44834C /* Cocoa.framework */; }; F976934F1E382AAA9975FC9E3F439B50 /* Pods-ShadowsocksX-NGTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 46662EB64876AD1C891F548C69A89E89 /* Pods-ShadowsocksX-NGTests-dummy.m */; }; + FFFDD494EE6D1B83DDAF5F2721F685A6 /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6648A20B97426F9940955502FA6FF042 /* Validation.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -102,99 +102,99 @@ 054C3E84057CD06DB85D99E7AD207F48 /* Pods-proxy_conf_helper.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-proxy_conf_helper.debug.xcconfig"; sourceTree = ""; }; 056695931D97F3BAC1F31181094FF7F0 /* GCDWebServerDataRequest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GCDWebServerDataRequest.h; path = GCDWebServer/Requests/GCDWebServerDataRequest.h; sourceTree = ""; }; 057330267A99F07C8ADE6135AA1F622F /* GCDWebServer.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GCDWebServer.h; path = GCDWebServer/Core/GCDWebServer.h; sourceTree = ""; }; - 08903B6D9CE24A6E780E1F35EAEB9230 /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; 089EB7E66F64D3A19BB7681AFCE91031 /* Pods-ShadowsocksX-NG.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-ShadowsocksX-NG.release.xcconfig"; sourceTree = ""; }; - 09F22BD1F05C6C8F13B5F137979CB3FB /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Alamofire.modulemap; sourceTree = ""; }; 0E8A27A8C9BD6FF9AE3DCBC4050CCD76 /* Pods-ShadowsocksX-NGTests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-ShadowsocksX-NGTests-frameworks.sh"; sourceTree = ""; }; + 0E8D592A9C0AE4B6C90789AFF29DF516 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; + 11B6EC5B2B4F6B09E9967325BF493C9D /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; + 12B556C66780BC3D0BECF011EAF49ECB /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; 13333F29A08390FCEFECA0FDCDDC919F /* Pods-ShadowsocksX-NG-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-ShadowsocksX-NG-frameworks.sh"; sourceTree = ""; }; 14A9EC2BB1EC6484018A5EB4B9B2C231 /* Pods-ShadowsocksX-NG-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-ShadowsocksX-NG-umbrella.h"; sourceTree = ""; }; 150AAAC15A441418AEA6DFBF159FBEA0 /* GCDWebServerConnection.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GCDWebServerConnection.h; path = GCDWebServer/Core/GCDWebServerConnection.h; sourceTree = ""; }; - 19863D6E702634433EB92BDFE07633C9 /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Source/Error.swift; sourceTree = ""; }; + 1673CAE4B8238FFD59A792823A36A9DF /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; + 193AA1B44C4CB1CFCCEDD6C9741F5211 /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; 1A8CE48109F7ED7873F4FF9D2D3603AD /* Pods-proxy_conf_helper-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-proxy_conf_helper-acknowledgements.markdown"; sourceTree = ""; }; + 1C058E7895E0BD655DB18CD87B39658B /* TaskDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TaskDelegate.swift; path = Source/TaskDelegate.swift; sourceTree = ""; }; 1F162D37B7B6534A6D80FEE301F586EE /* Pods-ShadowsocksX-NGTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-ShadowsocksX-NGTests-acknowledgements.plist"; sourceTree = ""; }; - 2223C268D688D65D7FE92C86F63188D3 /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; 24B01D81E3D7058FA14A053EC19874D0 /* Pods-ShadowsocksX-NG-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-ShadowsocksX-NG-dummy.m"; sourceTree = ""; }; 24BCEE536E19B38E28CE6933A0D49A2D /* GCDWebServer.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = GCDWebServer.xcconfig; sourceTree = ""; }; + 2625C48AD777A2B7E26D2A80E9CD94E7 /* DispatchQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Alamofire.swift"; path = "Source/DispatchQueue+Alamofire.swift"; sourceTree = ""; }; 28D7F65F9E64735E3320A028DCDDDD90 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 29F1D38D8FBC1D989199E905EA6CA548 /* GCDWebServer.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GCDWebServer.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 3299B1F1F2A682EA4A98D4853A973125 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 2D644FB3545AF46CBD6ED919703E7147 /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; 3358F45A5BEC1A7F725167CD1969EDC8 /* Pods-ShadowsocksX-NG-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-ShadowsocksX-NG-acknowledgements.markdown"; sourceTree = ""; }; 3490D661D0DB72BC3A5F94A1C6AE083C /* GCDWebServer.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GCDWebServer.m; path = GCDWebServer/Core/GCDWebServer.m; sourceTree = ""; }; 35133A1ADAD65BF87962F819AF44834C /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/System/Library/Frameworks/Cocoa.framework; sourceTree = DEVELOPER_DIR; }; - 3EF74B3D95D99D283831DCF22F051B3B /* Download.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Download.swift; path = Source/Download.swift; sourceTree = ""; }; + 352C9ACA5D14E48B378FF32021EAD9B4 /* SessionManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionManager.swift; path = Source/SessionManager.swift; sourceTree = ""; }; + 3565E299C44D10C2D206FDCD078A0008 /* SessionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDelegate.swift; path = Source/SessionDelegate.swift; sourceTree = ""; }; + 383ADB6B629F7BC3B7FB986648404A88 /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; 41B03492069EA8D52FDD5E9F8CC3749D /* GCDWebServerStreamedResponse.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GCDWebServerStreamedResponse.m; path = GCDWebServer/Responses/GCDWebServerStreamedResponse.m; sourceTree = ""; }; 432FFBD34AE4D6FE11F7562A7B2E2DF6 /* GCDWebServerResponse.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GCDWebServerResponse.m; path = GCDWebServer/Core/GCDWebServerResponse.m; sourceTree = ""; }; 4461C7BE603BCBC96BA24E3E752C6AC0 /* BRLOptionParser.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = BRLOptionParser.h; path = BRLOptionParser/BRLOptionParser.h; sourceTree = ""; }; 46662EB64876AD1C891F548C69A89E89 /* Pods-ShadowsocksX-NGTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-ShadowsocksX-NGTests-dummy.m"; sourceTree = ""; }; - 4BB13A3408660727BF5A93D796C002D4 /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; 4BD69E62A30DA9C6468DE578D50E5FB0 /* GCDWebServerRequest.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GCDWebServerRequest.m; path = GCDWebServer/Core/GCDWebServerRequest.m; sourceTree = ""; }; - 4C9A6FB24BE0AEB3FE45BE09CBEC90CA /* Timeline.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeline.swift; path = Source/Timeline.swift; sourceTree = ""; }; - 4FB848B724CAC1DF71DB3D6900F463C2 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; - 513FB2C889EFE0F24ADC4AB3C5C68FD6 /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; 52F51F94701ABD692BFFC9F92AE2E115 /* Pods-ShadowsocksX-NG-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-ShadowsocksX-NG-acknowledgements.plist"; sourceTree = ""; }; 56CBA6D73D3D0B47B5D2DCA98FD3514E /* GCDWebServerURLEncodedFormRequest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GCDWebServerURLEncodedFormRequest.h; path = GCDWebServer/Requests/GCDWebServerURLEncodedFormRequest.h; sourceTree = ""; }; 5BF25F29EE771444894D4B4BD6A5094A /* GCDWebServerMultiPartFormRequest.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GCDWebServerMultiPartFormRequest.m; path = GCDWebServer/Requests/GCDWebServerMultiPartFormRequest.m; sourceTree = ""; }; 5D84D92D27CE8A6F5C45E8A03155C1CF /* Pods-proxy_conf_helper-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-proxy_conf_helper-frameworks.sh"; sourceTree = ""; }; + 5DD6170F5D4F70A833509C495183FBA3 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 5E949AC812278EA6428E8B1B3F4567E5 /* libBRLOptionParser.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libBRLOptionParser.a; sourceTree = BUILT_PRODUCTS_DIR; }; - 61F7983117C400AC29CB2772079182E2 /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; 622DEEE18C4E0A0DD196A4D2D8853154 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 65715F792D70CDE4E67F1EB98531E233 /* GCDWebServerStreamedResponse.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GCDWebServerStreamedResponse.h; path = GCDWebServer/Responses/GCDWebServerStreamedResponse.h; sourceTree = ""; }; + 6648A20B97426F9940955502FA6FF042 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; 675C317EFB4447DD15024A74FF8C9E6C /* GCDWebServer-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "GCDWebServer-dummy.m"; sourceTree = ""; }; 71153E50563B065484D16F662AD08EDB /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SystemConfiguration.framework; path = Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/System/Library/Frameworks/SystemConfiguration.framework; sourceTree = DEVELOPER_DIR; }; + 781B71F26694E106B9C6014A4D828CFE /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; 78FDF9432C1735D2CE78FC0BBD37B6D3 /* GCDWebServer.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = GCDWebServer.modulemap; sourceTree = ""; }; - 79A93CC40664DA60F6E9AAD219A11B49 /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; 7B884322F7F32E5886E831225EF61A24 /* GCDWebServerErrorResponse.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GCDWebServerErrorResponse.h; path = GCDWebServer/Responses/GCDWebServerErrorResponse.h; sourceTree = ""; }; - 7E9F59498CDD1D70C29D21C0D6CE6575 /* Stream.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Stream.swift; path = Source/Stream.swift; sourceTree = ""; }; 7EA43A03295E967E8CE48DC3D41B1FB1 /* GCDWebServerResponse.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GCDWebServerResponse.h; path = GCDWebServer/Core/GCDWebServerResponse.h; sourceTree = ""; }; + 8020307C336BF75396517D172B6CCBA0 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Alamofire.modulemap; sourceTree = ""; }; 83323A1A2936BBA3D386DCC078E3821E /* Pods-ShadowsocksX-NGTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-ShadowsocksX-NGTests-acknowledgements.markdown"; sourceTree = ""; }; 8C6444C9A87ED6919A7864A0C9D70A4C /* GCDWebServerURLEncodedFormRequest.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GCDWebServerURLEncodedFormRequest.m; path = GCDWebServer/Requests/GCDWebServerURLEncodedFormRequest.m; sourceTree = ""; }; 8C6F72ED24E84D8DC9445729D927B6E8 /* GCDWebServerConnection.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GCDWebServerConnection.m; path = GCDWebServer/Core/GCDWebServerConnection.m; sourceTree = ""; }; 8CC694BC2D5AA3651FE2946D4032D0F5 /* GCDWebServerErrorResponse.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GCDWebServerErrorResponse.m; path = GCDWebServer/Responses/GCDWebServerErrorResponse.m; sourceTree = ""; }; 8CD28F4DA9E9FD6CDF59B9183753B0AD /* GCDWebServerFunctions.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GCDWebServerFunctions.m; path = GCDWebServer/Core/GCDWebServerFunctions.m; sourceTree = ""; }; - 8CDCCB45ECA29E5CF67690354B7D62E3 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; 8CDD45C6D7A038F415A78787317E931A /* Pods-proxy_conf_helper-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-proxy_conf_helper-resources.sh"; sourceTree = ""; }; 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; 9564AF1CDDA43CCBDDB1A7A9D41FD163 /* GCDWebServerFileRequest.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GCDWebServerFileRequest.m; path = GCDWebServer/Requests/GCDWebServerFileRequest.m; sourceTree = ""; }; - 97676FEA7A66144B58C43891F45FD408 /* Upload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Upload.swift; path = Source/Upload.swift; sourceTree = ""; }; 98522BF2EB25C0255284080F9CA3E195 /* Pods-ShadowsocksX-NG.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-ShadowsocksX-NG.debug.xcconfig"; sourceTree = ""; }; 9B8B5CBA357BDB968C73E8F58DFBC74C /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 9BA2A0099476E08B6CC8026BDF0C603E /* Pods-ShadowsocksX-NGTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-ShadowsocksX-NGTests.debug.xcconfig"; sourceTree = ""; }; A2AB24692BC4901FA1B8CD5A65C8AA62 /* GCDWebServerFunctions.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GCDWebServerFunctions.h; path = GCDWebServer/Core/GCDWebServerFunctions.h; sourceTree = ""; }; - A5053AF0338A9A4CC9AABB3AF55A2A41 /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; A5055B8EFFFBEDE50909E935D4BCA446 /* Pods-proxy_conf_helper.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-proxy_conf_helper.release.xcconfig"; sourceTree = ""; }; A51D2862E977EC32406F9AB39ECEC3BF /* GCDWebServer-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "GCDWebServer-prefix.pch"; sourceTree = ""; }; A628D7F35A0F9EBD66407BDCC9C92D20 /* Pods_ShadowsocksX_NGTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_ShadowsocksX_NGTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; AE6E689502E4366B125481CD898B947E /* Pods-proxy_conf_helper-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-proxy_conf_helper-acknowledgements.plist"; sourceTree = ""; }; + B2E64BA5DE520D1FF8D157D1948EF678 /* Timeline.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeline.swift; path = Source/Timeline.swift; sourceTree = ""; }; B30805F63C611810B322187824EBC4A5 /* Pods-ShadowsocksX-NGTests-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-ShadowsocksX-NGTests-resources.sh"; sourceTree = ""; }; B49FCFC5427009EB0DE924D8E6689486 /* GCDWebServerDataResponse.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GCDWebServerDataResponse.h; path = GCDWebServer/Responses/GCDWebServerDataResponse.h; sourceTree = ""; }; - B8B20CB588CB77EA9A11425CA9AC4402 /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; - B8B2BB45AAB2161A1A3D784559749CF9 /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; - B8ED45027AFDE6DFC119E5002ED79602 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; + B7E6D819AE4FECE3068ED91259133EAC /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; BA947346171BBF9CB75B49AF462D0A14 /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; BAA6E2FFB996A81C9D31918A563B43FB /* BRLOptionParser.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = BRLOptionParser.m; path = BRLOptionParser/BRLOptionParser.m; sourceTree = ""; }; - BDB73E594147C01A752A5AACF0D50DE9 /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; + BB1A40A42CB3E3DE3C7FB21A038462FD /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; BE05C895D7CA02C6123697B3944C59D3 /* GCDWebServerDataResponse.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GCDWebServerDataResponse.m; path = GCDWebServer/Responses/GCDWebServerDataResponse.m; sourceTree = ""; }; BE672B43951C625CA5F89E448A620AB0 /* Pods-ShadowsocksX-NGTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = "Pods-ShadowsocksX-NGTests.modulemap"; sourceTree = ""; }; BE93E2446670327B7B8B5F4713BB6AF3 /* BRLOptionParser-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "BRLOptionParser-prefix.pch"; sourceTree = ""; }; C12AC1F78F621586EC3C233BD8CF4BE0 /* BRLOptionParser.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = BRLOptionParser.xcconfig; sourceTree = ""; }; + C18C5D68D2A979595D2A50A1D65A8AF2 /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; + C83162C9BDFB3C0617CF191D660EC2DA /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; + C9C4A7AA3B3DD74EDA43165A42745D1A /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; CA78677B47A82041B6A0C96CE51F76C2 /* GCDWebServerPrivate.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GCDWebServerPrivate.h; path = GCDWebServer/Core/GCDWebServerPrivate.h; sourceTree = ""; }; CE50445A73ECB9A2ED31A6FF93D45808 /* Pods-proxy_conf_helper-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-proxy_conf_helper-dummy.m"; sourceTree = ""; }; D35A95B17B77B37E12236498D60B8478 /* GCDWebServerFileResponse.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GCDWebServerFileResponse.m; path = GCDWebServer/Responses/GCDWebServerFileResponse.m; sourceTree = ""; }; D534FA8B75596A674095DAA7CA3B08D1 /* libPods-proxy_conf_helper.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-proxy_conf_helper.a"; sourceTree = BUILT_PRODUCTS_DIR; }; - D7AA44828C94616294316E0C53D00B02 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; D7C15E08E56E065130F76FC8DC8C8619 /* GCDWebServerFileRequest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GCDWebServerFileRequest.h; path = GCDWebServer/Requests/GCDWebServerFileRequest.h; sourceTree = ""; }; D7E8128F302CF60BEF206008CE11F6D3 /* Pods-ShadowsocksX-NGTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-ShadowsocksX-NGTests-umbrella.h"; sourceTree = ""; }; + D86AC40F610A78D1B5E5AC9528E70ADB /* AFError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AFError.swift; path = Source/AFError.swift; sourceTree = ""; }; D9D61BAD16772ED8DBCD878F6BBF7025 /* GCDWebServerHTTPStatusCodes.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GCDWebServerHTTPStatusCodes.h; path = GCDWebServer/Core/GCDWebServerHTTPStatusCodes.h; sourceTree = ""; }; DC250BF8313F337272DBC9DE1FB6DB6B /* Pods-ShadowsocksX-NG.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = "Pods-ShadowsocksX-NG.modulemap"; sourceTree = ""; }; E02D3FE330950F96E4826E6785950F95 /* GCDWebServerDataRequest.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GCDWebServerDataRequest.m; path = GCDWebServer/Requests/GCDWebServerDataRequest.m; sourceTree = ""; }; EA41BEE3B4D9F1A89F0135CA91A7F472 /* Pods-ShadowsocksX-NG-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-ShadowsocksX-NG-resources.sh"; sourceTree = ""; }; EAEC4F2E970093B9815E645E63781C40 /* GCDWebServerMultiPartFormRequest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GCDWebServerMultiPartFormRequest.h; path = GCDWebServer/Requests/GCDWebServerMultiPartFormRequest.h; sourceTree = ""; }; EB10970D56AE3E8EC08A3B6CB0ECF896 /* GCDWebServerFileResponse.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GCDWebServerFileResponse.h; path = GCDWebServer/Responses/GCDWebServerFileResponse.h; sourceTree = ""; }; - ED9FDD5C333260AC0A0141C7AA82A7C8 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; F5FCCAE1F4AE542376E5F228D7463E4F /* GCDWebServer-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "GCDWebServer-umbrella.h"; sourceTree = ""; }; F67191B1F87DA238C4D87250DFBE43DD /* Pods-ShadowsocksX-NGTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-ShadowsocksX-NGTests.release.xcconfig"; sourceTree = ""; }; FB6A7098E32F88CAD8F6D0BB8E334D4C /* Pods_ShadowsocksX_NG.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_ShadowsocksX_NG.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - FDEF79B127C0B89EAE92BC708EC435D0 /* Manager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Manager.swift; path = Source/Manager.swift; sourceTree = ""; }; + FC11D9EFE483BFE3E6CC4AC3CCC0E8D7 /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; FE4DE2F9318899EC55FF739F09547B9F /* GCDWebServerRequest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GCDWebServerRequest.h; path = GCDWebServer/Core/GCDWebServerRequest.h; sourceTree = ""; }; /* End PBXFileReference section */ @@ -289,6 +289,20 @@ path = "../Target Support Files/BRLOptionParser"; sourceTree = ""; }; + 5719BC2FF455313AC86A7D2916E845F7 /* Support Files */ = { + isa = PBXGroup; + children = ( + 8020307C336BF75396517D172B6CCBA0 /* Alamofire.modulemap */, + C18C5D68D2A979595D2A50A1D65A8AF2 /* Alamofire.xcconfig */, + 383ADB6B629F7BC3B7FB986648404A88 /* Alamofire-dummy.m */, + 2D644FB3545AF46CBD6ED919703E7147 /* Alamofire-prefix.pch */, + BB1A40A42CB3E3DE3C7FB21A038462FD /* Alamofire-umbrella.h */, + 5DD6170F5D4F70A833509C495183FBA3 /* Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/Alamofire"; + sourceTree = ""; + }; 5CB7C42D8E0E0A453DB6D57A2A3D7D0D /* BRLOptionParser */ = { isa = PBXGroup; children = ( @@ -309,6 +323,31 @@ name = "Targets Support Files"; sourceTree = ""; }; + 796243293F74BCF483A785C91F203289 /* Alamofire */ = { + isa = PBXGroup; + children = ( + D86AC40F610A78D1B5E5AC9528E70ADB /* AFError.swift */, + 0E8D592A9C0AE4B6C90789AFF29DF516 /* Alamofire.swift */, + 2625C48AD777A2B7E26D2A80E9CD94E7 /* DispatchQueue+Alamofire.swift */, + C9C4A7AA3B3DD74EDA43165A42745D1A /* MultipartFormData.swift */, + B7E6D819AE4FECE3068ED91259133EAC /* NetworkReachabilityManager.swift */, + 12B556C66780BC3D0BECF011EAF49ECB /* Notifications.swift */, + C83162C9BDFB3C0617CF191D660EC2DA /* ParameterEncoding.swift */, + 781B71F26694E106B9C6014A4D828CFE /* Request.swift */, + FC11D9EFE483BFE3E6CC4AC3CCC0E8D7 /* Response.swift */, + 11B6EC5B2B4F6B09E9967325BF493C9D /* ResponseSerialization.swift */, + 1673CAE4B8238FFD59A792823A36A9DF /* Result.swift */, + 193AA1B44C4CB1CFCCEDD6C9741F5211 /* ServerTrustPolicy.swift */, + 3565E299C44D10C2D206FDCD078A0008 /* SessionDelegate.swift */, + 352C9ACA5D14E48B378FF32021EAD9B4 /* SessionManager.swift */, + 1C058E7895E0BD655DB18CD87B39658B /* TaskDelegate.swift */, + B2E64BA5DE520D1FF8D157D1948EF678 /* Timeline.swift */, + 6648A20B97426F9940955502FA6FF042 /* Validation.swift */, + 5719BC2FF455313AC86A7D2916E845F7 /* Support Files */, + ); + path = Alamofire; + sourceTree = ""; + }; 7DB346D0F39D3F0E887471402A8071AB = { isa = PBXGroup; children = ( @@ -415,20 +454,6 @@ path = "Target Support Files/Pods-proxy_conf_helper"; sourceTree = ""; }; - C2A43CD82466765ED8498B1EC34EC0C6 /* Support Files */ = { - isa = PBXGroup; - children = ( - 09F22BD1F05C6C8F13B5F137979CB3FB /* Alamofire.modulemap */, - B8B20CB588CB77EA9A11425CA9AC4402 /* Alamofire.xcconfig */, - BDB73E594147C01A752A5AACF0D50DE9 /* Alamofire-dummy.m */, - 513FB2C889EFE0F24ADC4AB3C5C68FD6 /* Alamofire-prefix.pch */, - 8CDCCB45ECA29E5CF67690354B7D62E3 /* Alamofire-umbrella.h */, - 3299B1F1F2A682EA4A98D4853A973125 /* Info.plist */, - ); - name = "Support Files"; - path = "../Target Support Files/Alamofire"; - sourceTree = ""; - }; D648CE86F139C7CCFD55D5B8A03BE74B /* Frameworks */ = { isa = PBXGroup; children = ( @@ -437,31 +462,6 @@ name = Frameworks; sourceTree = ""; }; - D7DCF6D052263CB41B6E1B5671B9993B /* Alamofire */ = { - isa = PBXGroup; - children = ( - 4FB848B724CAC1DF71DB3D6900F463C2 /* Alamofire.swift */, - 3EF74B3D95D99D283831DCF22F051B3B /* Download.swift */, - 19863D6E702634433EB92BDFE07633C9 /* Error.swift */, - FDEF79B127C0B89EAE92BC708EC435D0 /* Manager.swift */, - ED9FDD5C333260AC0A0141C7AA82A7C8 /* MultipartFormData.swift */, - 4BB13A3408660727BF5A93D796C002D4 /* NetworkReachabilityManager.swift */, - 08903B6D9CE24A6E780E1F35EAEB9230 /* Notifications.swift */, - D7AA44828C94616294316E0C53D00B02 /* ParameterEncoding.swift */, - B8B2BB45AAB2161A1A3D784559749CF9 /* Request.swift */, - A5053AF0338A9A4CC9AABB3AF55A2A41 /* Response.swift */, - 79A93CC40664DA60F6E9AAD219A11B49 /* ResponseSerialization.swift */, - 61F7983117C400AC29CB2772079182E2 /* Result.swift */, - 2223C268D688D65D7FE92C86F63188D3 /* ServerTrustPolicy.swift */, - 7E9F59498CDD1D70C29D21C0D6CE6575 /* Stream.swift */, - 4C9A6FB24BE0AEB3FE45BE09CBEC90CA /* Timeline.swift */, - 97676FEA7A66144B58C43891F45FD408 /* Upload.swift */, - B8ED45027AFDE6DFC119E5002ED79602 /* Validation.swift */, - C2A43CD82466765ED8498B1EC34EC0C6 /* Support Files */, - ); - path = Alamofire; - sourceTree = ""; - }; E00B0204545DC7ACDAFF792113E8C436 /* GCDWebServer */ = { isa = PBXGroup; children = ( @@ -474,7 +474,7 @@ EBE480E49DAE4107333DC7987926D6E4 /* Pods */ = { isa = PBXGroup; children = ( - D7DCF6D052263CB41B6E1B5671B9993B /* Alamofire */, + 796243293F74BCF483A785C91F203289 /* Alamofire */, 5CB7C42D8E0E0A453DB6D57A2A3D7D0D /* BRLOptionParser */, E00B0204545DC7ACDAFF792113E8C436 /* GCDWebServer */, ); @@ -563,7 +563,7 @@ isa = PBXNativeTarget; buildConfigurationList = 3CFB42910790CF0BDBCCEBAACD6B9367 /* Build configuration list for PBXNativeTarget "Alamofire" */; buildPhases = ( - 95CC2C7E06DC188A05DAAEE9CAA555A3 /* Sources */, + 120C4E824DDCCA024C170A491FF221A5 /* Sources */, 86631BCDD6995CFD2A8A7716F3673282 /* Frameworks */, EFDF3B631BBB965A372347705CA14854 /* Headers */, ); @@ -653,7 +653,15 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0730; - LastUpgradeCheck = 0730; + LastUpgradeCheck = 0700; + TargetAttributes = { + 79C040AFDDCE1BCBF6D8B5EB0B85887F = { + LastSwiftMigration = 0800; + }; + F69966EE760BB16DE7009DBE04D8B18D = { + LastSwiftMigration = 0800; + }; + }; }; buildConfigurationList = 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */; compatibilityVersion = "Xcode 3.2"; @@ -686,6 +694,31 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + 120C4E824DDCCA024C170A491FF221A5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 62143065F94E53F437DCE5D7A998D66D /* AFError.swift in Sources */, + 8D463A0A4C65C02FDD5211F0F3C6F8B8 /* Alamofire-dummy.m in Sources */, + 7CA5A9BA5246FDA8227233E310029392 /* Alamofire.swift in Sources */, + E2A1C34237B4E928E5F85C097F4C2551 /* DispatchQueue+Alamofire.swift in Sources */, + C7A3408350643ADE1018826C766EE356 /* MultipartFormData.swift in Sources */, + E59BF19C0AFA68B741552319FC478C7B /* NetworkReachabilityManager.swift in Sources */, + 0C1B4E9FFB8B81E8833A3BAD537B1990 /* Notifications.swift in Sources */, + AF158CAAF4DD319009AFC855DC995D90 /* ParameterEncoding.swift in Sources */, + 12118C354EFA36292F82A8D0CFCE45B2 /* Request.swift in Sources */, + 86ED08F33B7D357932A9AB743E9D9EA7 /* Response.swift in Sources */, + B8154C96802336E5DDA5CEE97C3180A0 /* ResponseSerialization.swift in Sources */, + DF1BBF94997A2F4248B42B25EA919EC2 /* Result.swift in Sources */, + C0AEA97E7684DDAD56998C0AE198A433 /* ServerTrustPolicy.swift in Sources */, + 907AB123FBC8BC9340D5B7350CE828DF /* SessionDelegate.swift in Sources */, + A79AC30123B0C2177D67F6ED6A1B3215 /* SessionManager.swift in Sources */, + E1F583CB4A68A928CD197250AA752926 /* TaskDelegate.swift in Sources */, + 3982B850C43B41BA6D25F440F0412E9B /* Timeline.swift in Sources */, + FFFDD494EE6D1B83DDAF5F2721F685A6 /* Validation.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; 4EAA284BFC07AC421BF366F1EB9B757F /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; @@ -724,31 +757,6 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 95CC2C7E06DC188A05DAAEE9CAA555A3 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ADF19C953CE2A7D0B72EC93A81FCCC26 /* Alamofire-dummy.m in Sources */, - 8EB11202167FCDDF1257AAAB1D1FB244 /* Alamofire.swift in Sources */, - 5CB05FBCB32D21E194B5ECF680CB6AE0 /* Download.swift in Sources */, - 095406039B4D371E48D08B38A2975AC8 /* Error.swift in Sources */, - 4081EA628AF0B73AC51FFB9D7AB3B89E /* Manager.swift in Sources */, - C7B6DD7C0456C50289A2C381DFE9FA3F /* MultipartFormData.swift in Sources */, - 34CCDCA848A701466256BC2927DA8856 /* NetworkReachabilityManager.swift in Sources */, - BE41196F6A3903E59C3306FE3F8B43FE /* Notifications.swift in Sources */, - C0DB70AB368765DC64BFB5FEA75E0696 /* ParameterEncoding.swift in Sources */, - EFE92E8D3813DD26E78E93EEAF6D7E7E /* Request.swift in Sources */, - 62E8346F03C03E7F4D631361F325689E /* Response.swift in Sources */, - 3EA8F215C9C1432D74E5CCA4834AA8C0 /* ResponseSerialization.swift in Sources */, - AA314156AC500125F4078EE968DB14C6 /* Result.swift in Sources */, - 7B48852C4D848FA2DA416A98F6425869 /* ServerTrustPolicy.swift in Sources */, - AE4CF87C02C042DF13ED5B21C4FDC1E0 /* Stream.swift in Sources */, - 16102E4E35FAA0FC4161282FECE56469 /* Timeline.swift in Sources */, - 5BC19E6E0F199276003F0AF96838BCE5 /* Upload.swift in Sources */, - 2D3405986FC586FA6C0A5E0B6BA7E64E /* Validation.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; 9C086154608D1205F5A92B4645B6E785 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; @@ -781,14 +789,14 @@ /* End PBXTargetDependency section */ /* Begin XCBuildConfiguration section */ - 371E0500757286AB22CAE64ADAE8D83B /* Debug */ = { + 179A484411D601715E6EB758424482A4 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 9BA2A0099476E08B6CC8026BDF0C603E /* Pods-ShadowsocksX-NGTests.debug.xcconfig */; + baseConfigurationReference = C18C5D68D2A979595D2A50A1D65A8AF2 /* Alamofire.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = "-"; COMBINE_HIDPI_IMAGES = YES; CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = dwarf; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; @@ -796,24 +804,56 @@ ENABLE_STRICT_OBJC_MSGSEND = YES; FRAMEWORK_VERSION = A; GCC_NO_COMMON_BLOCKS = YES; - INFOPLIST_FILE = "Target Support Files/Pods-ShadowsocksX-NGTests/Info.plist"; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks"; + MACOSX_DEPLOYMENT_TARGET = 10.11; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = Alamofire; + SDKROOT = macosx; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 46F4EEF8E3C7148427E518702ACE51CA /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 089EB7E66F64D3A19BB7681AFCE91031 /* Pods-ShadowsocksX-NG.release.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = "-"; + COMBINE_HIDPI_IMAGES = YES; + 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; + FRAMEWORK_VERSION = A; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-ShadowsocksX-NG/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks"; MACH_O_TYPE = staticlib; - MACOSX_DEPLOYMENT_TARGET = 10.10; - MODULEMAP_FILE = "Target Support Files/Pods-ShadowsocksX-NGTests/Pods-ShadowsocksX-NGTests.modulemap"; - MTL_ENABLE_DEBUG_INFO = YES; + MACOSX_DEPLOYMENT_TARGET = 10.11; + MODULEMAP_FILE = "Target Support Files/Pods-ShadowsocksX-NG/Pods-ShadowsocksX-NG.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; OTHER_LDFLAGS = ""; OTHER_LIBTOOLFLAGS = ""; PODS_ROOT = "$(SRCROOT)"; PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = Pods_ShadowsocksX_NGTests; + PRODUCT_NAME = Pods_ShadowsocksX_NG; SDKROOT = macosx; SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; - name = Debug; + name = Release; }; 4888EEFBEA04FABA2120470F4B676BBD /* Release */ = { isa = XCBuildConfiguration; @@ -853,46 +893,11 @@ }; name = Release; }; - 4F1BC9CB0D8B1AB0DE3307D170A516B0 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 089EB7E66F64D3A19BB7681AFCE91031 /* Pods-ShadowsocksX-NG.release.xcconfig */; - buildSettings = { - CODE_SIGN_IDENTITY = "-"; - COMBINE_HIDPI_IMAGES = YES; - 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; - FRAMEWORK_VERSION = A; - GCC_NO_COMMON_BLOCKS = YES; - INFOPLIST_FILE = "Target Support Files/Pods-ShadowsocksX-NG/Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks"; - MACH_O_TYPE = staticlib; - MACOSX_DEPLOYMENT_TARGET = 10.10; - MODULEMAP_FILE = "Target Support Files/Pods-ShadowsocksX-NG/Pods-ShadowsocksX-NG.modulemap"; - MTL_ENABLE_DEBUG_INFO = NO; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = Pods_ShadowsocksX_NG; - SDKROOT = macosx; - SKIP_INSTALL = YES; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; 4F25746D417AD7959CEFE5D13B9045BF /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 054C3E84057CD06DB85D99E7AD207F48 /* Pods-proxy_conf_helper.debug.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = "-"; - COMBINE_HIDPI_IMAGES = YES; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; EXECUTABLE_PREFIX = lib; @@ -910,40 +915,9 @@ }; name = Debug; }; - 81B3096945D568104AC14EE4F805950B /* Release */ = { + 66E018521CC39B874E17650E877662C0 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = B8B20CB588CB77EA9A11425CA9AC4402 /* Alamofire.xcconfig */; - buildSettings = { - CODE_SIGN_IDENTITY = "-"; - COMBINE_HIDPI_IMAGES = YES; - 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; - FRAMEWORK_VERSION = A; - GCC_NO_COMMON_BLOCKS = YES; - GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks"; - MACOSX_DEPLOYMENT_TARGET = 10.9; - MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; - MTL_ENABLE_DEBUG_INFO = NO; - PRODUCT_BUNDLE_IDENTIFIER = "${PRODUCT_BUNDLE_IDENTIFIER}"; - PRODUCT_NAME = Alamofire; - SDKROOT = macosx; - SKIP_INSTALL = YES; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; - 82B1EC5E8815E78991717D970C44B8D8 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = B8B20CB588CB77EA9A11425CA9AC4402 /* Alamofire.xcconfig */; + baseConfigurationReference = 9BA2A0099476E08B6CC8026BDF0C603E /* Pods-ShadowsocksX-NGTests.debug.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = "-"; COMBINE_HIDPI_IMAGES = YES; @@ -956,45 +930,13 @@ ENABLE_STRICT_OBJC_MSGSEND = YES; FRAMEWORK_VERSION = A; GCC_NO_COMMON_BLOCKS = YES; - GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks"; - MACOSX_DEPLOYMENT_TARGET = 10.9; - MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; - MTL_ENABLE_DEBUG_INFO = YES; - PRODUCT_BUNDLE_IDENTIFIER = "${PRODUCT_BUNDLE_IDENTIFIER}"; - PRODUCT_NAME = Alamofire; - SDKROOT = macosx; - SKIP_INSTALL = YES; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; - 8A2A1FB2B9F55A664E92C5F52B674F7B /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = F67191B1F87DA238C4D87250DFBE43DD /* Pods-ShadowsocksX-NGTests.release.xcconfig */; - buildSettings = { - CODE_SIGN_IDENTITY = "-"; - COMBINE_HIDPI_IMAGES = YES; - 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; - FRAMEWORK_VERSION = A; - GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = "Target Support Files/Pods-ShadowsocksX-NGTests/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks"; MACH_O_TYPE = staticlib; - MACOSX_DEPLOYMENT_TARGET = 10.10; + MACOSX_DEPLOYMENT_TARGET = 10.11; MODULEMAP_FILE = "Target Support Files/Pods-ShadowsocksX-NGTests/Pods-ShadowsocksX-NGTests.modulemap"; - MTL_ENABLE_DEBUG_INFO = NO; + MTL_ENABLE_DEBUG_INFO = YES; OTHER_LDFLAGS = ""; OTHER_LIBTOOLFLAGS = ""; PODS_ROOT = "$(SRCROOT)"; @@ -1005,14 +947,49 @@ VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; - name = Release; + name = Debug; + }; + 6C331DEA6276195F599807BBC932074D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 98522BF2EB25C0255284080F9CA3E195 /* Pods-ShadowsocksX-NG.debug.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = "-"; + COMBINE_HIDPI_IMAGES = YES; + 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; + FRAMEWORK_VERSION = A; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-ShadowsocksX-NG/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MACOSX_DEPLOYMENT_TARGET = 10.11; + MODULEMAP_FILE = "Target Support Files/Pods-ShadowsocksX-NG/Pods-ShadowsocksX-NG.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_ShadowsocksX_NG; + SDKROOT = macosx; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 3.0; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; }; 92B477579DE5EFCC17E358B57A3A599E /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = C12AC1F78F621586EC3C233BD8CF4BE0 /* BRLOptionParser.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = "-"; - COMBINE_HIDPI_IMAGES = YES; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; EXECUTABLE_PREFIX = lib; @@ -1051,7 +1028,6 @@ MACOSX_DEPLOYMENT_TARGET = 10.7; MODULEMAP_FILE = "Target Support Files/GCDWebServer/GCDWebServer.modulemap"; MTL_ENABLE_DEBUG_INFO = YES; - PRODUCT_BUNDLE_IDENTIFIER = "${PRODUCT_BUNDLE_IDENTIFIER}"; PRODUCT_NAME = GCDWebServer; SDKROOT = macosx; SKIP_INSTALL = YES; @@ -1065,7 +1041,6 @@ baseConfigurationReference = A5055B8EFFFBEDE50909E935D4BCA446 /* Pods-proxy_conf_helper.release.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = "-"; - COMBINE_HIDPI_IMAGES = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_STRICT_OBJC_MSGSEND = YES; EXECUTABLE_PREFIX = lib; @@ -1105,7 +1080,6 @@ MACOSX_DEPLOYMENT_TARGET = 10.7; MODULEMAP_FILE = "Target Support Files/GCDWebServer/GCDWebServer.modulemap"; MTL_ENABLE_DEBUG_INFO = NO; - PRODUCT_BUNDLE_IDENTIFIER = "${PRODUCT_BUNDLE_IDENTIFIER}"; PRODUCT_NAME = GCDWebServer; SDKROOT = macosx; SKIP_INSTALL = YES; @@ -1119,7 +1093,6 @@ baseConfigurationReference = C12AC1F78F621586EC3C233BD8CF4BE0 /* BRLOptionParser.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = "-"; - COMBINE_HIDPI_IMAGES = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_STRICT_OBJC_MSGSEND = YES; EXECUTABLE_PREFIX = lib; @@ -1136,9 +1109,9 @@ }; name = Release; }; - CD7B15AF2FF01E3412E8AA0B13161458 /* Debug */ = { + BA46F8D5DD91E1BC7016CD04C4BDF87E /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 98522BF2EB25C0255284080F9CA3E195 /* Pods-ShadowsocksX-NG.debug.xcconfig */; + baseConfigurationReference = C18C5D68D2A979595D2A50A1D65A8AF2 /* Alamofire.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = "-"; COMBINE_HIDPI_IMAGES = YES; @@ -1151,26 +1124,57 @@ ENABLE_STRICT_OBJC_MSGSEND = YES; FRAMEWORK_VERSION = A; GCC_NO_COMMON_BLOCKS = YES; - INFOPLIST_FILE = "Target Support Files/Pods-ShadowsocksX-NG/Info.plist"; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks"; - MACH_O_TYPE = staticlib; - MACOSX_DEPLOYMENT_TARGET = 10.10; - MODULEMAP_FILE = "Target Support Files/Pods-ShadowsocksX-NG/Pods-ShadowsocksX-NG.modulemap"; + MACOSX_DEPLOYMENT_TARGET = 10.11; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; MTL_ENABLE_DEBUG_INFO = YES; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = Pods_ShadowsocksX_NG; + PRODUCT_NAME = Alamofire; SDKROOT = macosx; SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 3.0; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Debug; }; + BD0EE8DAC69BCFCB8E530D37B3D16A7A /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = F67191B1F87DA238C4D87250DFBE43DD /* Pods-ShadowsocksX-NGTests.release.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = "-"; + COMBINE_HIDPI_IMAGES = YES; + 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; + FRAMEWORK_VERSION = A; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-ShadowsocksX-NGTests/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MACOSX_DEPLOYMENT_TARGET = 10.11; + MODULEMAP_FILE = "Target Support Files/Pods-ShadowsocksX-NGTests/Pods-ShadowsocksX-NGTests.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_ShadowsocksX_NGTests; + SDKROOT = macosx; + SKIP_INSTALL = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; DA2E206EB90DF75A25332AE4AA713F31 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { @@ -1246,8 +1250,8 @@ 3CFB42910790CF0BDBCCEBAACD6B9367 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { isa = XCConfigurationList; buildConfigurations = ( - 82B1EC5E8815E78991717D970C44B8D8 /* Debug */, - 81B3096945D568104AC14EE4F805950B /* Release */, + BA46F8D5DD91E1BC7016CD04C4BDF87E /* Debug */, + 179A484411D601715E6EB758424482A4 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; @@ -1255,8 +1259,8 @@ 4AC88E06DEFEEDAF5DAA6F0F774D05D4 /* Build configuration list for PBXNativeTarget "Pods-ShadowsocksX-NG" */ = { isa = XCConfigurationList; buildConfigurations = ( - CD7B15AF2FF01E3412E8AA0B13161458 /* Debug */, - 4F1BC9CB0D8B1AB0DE3307D170A516B0 /* Release */, + 6C331DEA6276195F599807BBC932074D /* Debug */, + 46F4EEF8E3C7148427E518702ACE51CA /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; @@ -1264,8 +1268,8 @@ 757EEB566CE14B3A8210DD4A32EBDD7A /* Build configuration list for PBXNativeTarget "Pods-ShadowsocksX-NGTests" */ = { isa = XCConfigurationList; buildConfigurations = ( - 371E0500757286AB22CAE64ADAE8D83B /* Debug */, - 8A2A1FB2B9F55A664E92C5F52B674F7B /* Release */, + 66E018521CC39B874E17650E877662C0 /* Debug */, + BD0EE8DAC69BCFCB8E530D37B3D16A7A /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; diff --git a/Pods/Target Support Files/Alamofire/Info.plist b/Pods/Target Support Files/Alamofire/Info.plist index 99b3951..b672cd7 100644 --- a/Pods/Target Support Files/Alamofire/Info.plist +++ b/Pods/Target Support Files/Alamofire/Info.plist @@ -2,25 +2,25 @@ - CFBundleDevelopmentRegion - en - CFBundleExecutable - ${EXECUTABLE_NAME} - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - ${PRODUCT_NAME} - CFBundlePackageType - FMWK - CFBundleShortVersionString - 3.4.0 - CFBundleSignature - ???? - CFBundleVersion - ${CURRENT_PROJECT_VERSION} - NSPrincipalClass - + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 4.0.1 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + diff --git a/Pods/Target Support Files/GCDWebServer/Info.plist b/Pods/Target Support Files/GCDWebServer/Info.plist index fbb6307..234e351 100644 --- a/Pods/Target Support Files/GCDWebServer/Info.plist +++ b/Pods/Target Support Files/GCDWebServer/Info.plist @@ -2,25 +2,25 @@ - CFBundleDevelopmentRegion - en - CFBundleExecutable - ${EXECUTABLE_NAME} - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - ${PRODUCT_NAME} - CFBundlePackageType - FMWK - CFBundleShortVersionString - 3.3.3 - CFBundleSignature - ???? - CFBundleVersion - ${CURRENT_PROJECT_VERSION} - NSPrincipalClass - + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 3.3.3 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + diff --git a/ShadowsocksX-NG.xcodeproj/project.pbxproj b/ShadowsocksX-NG.xcodeproj/project.pbxproj index d160b0b..9ce7166 100644 --- a/ShadowsocksX-NG.xcodeproj/project.pbxproj +++ b/ShadowsocksX-NG.xcodeproj/project.pbxproj @@ -415,9 +415,11 @@ TargetAttributes = { 9B0BFFE41D0460A70040E62B = { CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 0800; }; 9B0BFFF31D0460A70040E62B = { CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 0800; TestTargetID = 9B0BFFE41D0460A70040E62B; }; 9B3FFF431D09CD3B0019A709 = { @@ -826,11 +828,12 @@ "$(SDKROOT)/usr/lib/system", "$(PROJECT_DIR)/ShadowsocksX-NG", ); - MACOSX_DEPLOYMENT_TARGET = 10.10; + MACOSX_DEPLOYMENT_TARGET = 10.11; PRODUCT_BUNDLE_IDENTIFIER = "com.qiuyuzhou.ShadowsocksX-NG"; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "ShadowsocksX-NG/ShadowsocksX-NG-Bridging-Header.h"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 3.0; }; name = Debug; }; @@ -852,10 +855,11 @@ "$(SDKROOT)/usr/lib/system", "$(PROJECT_DIR)/ShadowsocksX-NG", ); - MACOSX_DEPLOYMENT_TARGET = 10.10; + MACOSX_DEPLOYMENT_TARGET = 10.11; PRODUCT_BUNDLE_IDENTIFIER = "com.qiuyuzhou.ShadowsocksX-NG"; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "ShadowsocksX-NG/ShadowsocksX-NG-Bridging-Header.h"; + SWIFT_VERSION = 3.0; }; name = Release; }; @@ -869,6 +873,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = "com.qiuyuzhou.ShadowsocksX-NGTests"; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/ShadowsocksX-NG.app/Contents/MacOS/ShadowsocksX-NG"; }; name = Debug; @@ -883,6 +888,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = "com.qiuyuzhou.ShadowsocksX-NGTests"; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/ShadowsocksX-NG.app/Contents/MacOS/ShadowsocksX-NG"; }; name = Release; diff --git a/ShadowsocksX-NG/AdvPreferencesWindowController.swift b/ShadowsocksX-NG/AdvPreferencesWindowController.swift index 806a4e4..e53a707 100644 --- a/ShadowsocksX-NG/AdvPreferencesWindowController.swift +++ b/ShadowsocksX-NG/AdvPreferencesWindowController.swift @@ -19,9 +19,9 @@ class AdvPreferencesWindowController: NSWindowController, NSWindowDelegate { //------------------------------------------------------------ // NSWindowDelegate - func windowWillClose(notification: NSNotification) { - NSNotificationCenter.defaultCenter() - .postNotificationName(NOTIFY_ADV_CONF_CHANGED, object: nil) + func windowWillClose(_ notification: Notification) { + NotificationCenter.default + .post(name: Notification.Name(rawValue: NOTIFY_ADV_CONF_CHANGED), object: nil) } } diff --git a/ShadowsocksX-NG/AppDelegate.swift b/ShadowsocksX-NG/AppDelegate.swift index 4fec4d6..53c4a1f 100644 --- a/ShadowsocksX-NG/AppDelegate.swift +++ b/ShadowsocksX-NG/AppDelegate.swift @@ -39,46 +39,46 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele var statusItem: NSStatusItem! - func applicationDidFinishLaunching(aNotification: NSNotification) { + func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application - NSUserNotificationCenter.defaultUserNotificationCenter().delegate = self + NSUserNotificationCenter.default.delegate = self // Prepare ss-local InstallSSLocal() // Prepare defaults - let defaults = NSUserDefaults.standardUserDefaults() - defaults.registerDefaults([ + let defaults = UserDefaults.standard + defaults.register(defaults: [ "ShadowsocksOn": true, "ShadowsocksRunningMode": "auto", - "LocalSocks5.ListenPort": NSNumber(unsignedShort: 1086), + "LocalSocks5.ListenPort": NSNumber(value: 1086 as UInt16), "LocalSocks5.ListenAddress": "127.0.0.1", "PacServer.ListenAddress": "127.0.0.1", - "PacServer.ListenPort":NSNumber(unsignedShort: 8090), - "LocalSocks5.Timeout": NSNumber(unsignedInteger: 60), - "LocalSocks5.EnableUDPRelay": NSNumber(bool: false), - "LocalSocks5.EnableVerboseMode": NSNumber(bool: false), + "PacServer.ListenPort":NSNumber(value: 8090 as UInt16), + "LocalSocks5.Timeout": NSNumber(value: 60 as UInt), + "LocalSocks5.EnableUDPRelay": NSNumber(value: false as Bool), + "LocalSocks5.EnableVerboseMode": NSNumber(value: false as Bool), "GFWListURL": "https://raw.githubusercontent.com/gfwlist/gfwlist/master/gfwlist.txt", - "AutoConfigureNetworkServices": NSNumber(bool: true) + "AutoConfigureNetworkServices": NSNumber(value: true as Bool) ]) - statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(20) + statusItem = NSStatusBar.system().statusItem(withLength: 20) let image = NSImage(named: "menu_icon") - image?.template = true + image?.isTemplate = true statusItem.image = image statusItem.menu = statusMenu - let notifyCenter = NSNotificationCenter.defaultCenter() - notifyCenter.addObserverForName(NOTIFY_ADV_PROXY_CONF_CHANGED, object: nil, queue: nil - , usingBlock: { + let notifyCenter = NotificationCenter.default + notifyCenter.addObserver(forName: NSNotification.Name(rawValue: NOTIFY_ADV_PROXY_CONF_CHANGED), object: nil, queue: nil + , using: { (note) in self.applyConfig() } ) - notifyCenter.addObserverForName(NOTIFY_SERVER_PROFILES_CHANGED, object: nil, queue: nil - , usingBlock: { + notifyCenter.addObserver(forName: NSNotification.Name(rawValue: NOTIFY_SERVER_PROFILES_CHANGED), object: nil, queue: nil + , using: { (note) in let profileMgr = ServerProfileManager.instance if profileMgr.activeProfileId == nil && @@ -91,17 +91,17 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele SyncSSLocal() } ) - notifyCenter.addObserverForName(NOTIFY_ADV_CONF_CHANGED, object: nil, queue: nil - , usingBlock: { + notifyCenter.addObserver(forName: NSNotification.Name(rawValue: NOTIFY_ADV_CONF_CHANGED), object: nil, queue: nil + , using: { (note) in SyncSSLocal() self.applyConfig() } ) - notifyCenter.addObserverForName("NOTIFY_FOUND_SS_URL", object: nil, queue: nil) { - (note: NSNotification) in - if let userInfo = note.userInfo { - let urls: [NSURL] = userInfo["urls"] as! [NSURL] + notifyCenter.addObserver(forName: NSNotification.Name(rawValue: "NOTIFY_FOUND_SS_URL"), object: nil, queue: nil) { + (note: Notification) in + if let userInfo = (note as NSNotification).userInfo { + let urls: [URL] = userInfo["urls"] as! [URL] let mgr = ServerProfileManager.instance var isChanged = false @@ -109,7 +109,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele for url in urls { let profielDict = ParseSSURL(url) if let profielDict = profielDict { - let profile = ServerProfile.fromDictionary(profielDict) + let profile = ServerProfile.fromDictionary(profielDict as [String : AnyObject]) mgr.profiles.append(profile) isChanged = true @@ -125,8 +125,8 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele " Encription Method: \(profile.method)".localized userNote.soundName = NSUserNotificationDefaultSoundName - NSUserNotificationCenter.defaultUserNotificationCenter() - .deliverNotification(userNote); + NSUserNotificationCenter.default + .deliver(userNote); } } @@ -138,7 +138,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele } // Handle ss url scheme - NSAppleEventManager.sharedAppleEventManager().setEventHandler(self + NSAppleEventManager.shared().setEventHandler(self , andSelector: #selector(self.handleURLEvent) , forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL)) @@ -152,19 +152,19 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele SyncSSLocal() } - func applicationWillTerminate(aNotification: NSNotification) { + func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application StopSSLocal() ProxyConfHelper.disableProxy("hi") - let defaults = NSUserDefaults.standardUserDefaults() - defaults.setBool(false, forKey: "ShadowsocksOn") + let defaults = UserDefaults.standard + defaults.set(false, forKey: "ShadowsocksOn") ProxyConfHelper.stopPACServer() } func applyConfig() { - let defaults = NSUserDefaults.standardUserDefaults() - let isOn = defaults.boolForKey("ShadowsocksOn") - let mode = defaults.stringForKey("ShadowsocksRunningMode") + let defaults = UserDefaults.standard + let isOn = defaults.bool(forKey: "ShadowsocksOn") + let mode = defaults.string(forKey: "ShadowsocksRunningMode") if isOn { StartSSLocal() @@ -181,22 +181,22 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele } } - @IBAction func toggleRunning(sender: NSMenuItem) { - let defaults = NSUserDefaults.standardUserDefaults() - var isOn = defaults.boolForKey("ShadowsocksOn") + @IBAction func toggleRunning(_ sender: NSMenuItem) { + let defaults = UserDefaults.standard + var isOn = defaults.bool(forKey: "ShadowsocksOn") isOn = !isOn - defaults.setBool(isOn, forKey: "ShadowsocksOn") + defaults.set(isOn, forKey: "ShadowsocksOn") updateMainMenu() applyConfig() } - @IBAction func updateGFWList(sender: NSMenuItem) { + @IBAction func updateGFWList(_ sender: NSMenuItem) { UpdatePACFromGFWList() } - @IBAction func editUserRulesForPAC(sender: NSMenuItem) { + @IBAction func editUserRulesForPAC(_ sender: NSMenuItem) { if editUserRulesWinCtrl != nil { editUserRulesWinCtrl.close() } @@ -204,11 +204,11 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele editUserRulesWinCtrl = ctrl ctrl.showWindow(self) - NSApp.activateIgnoringOtherApps(true) + NSApp.activate(ignoringOtherApps: true) ctrl.window?.makeKeyAndOrderFront(self) } - @IBAction func showQRCodeForCurrentServer(sender: NSMenuItem) { + @IBAction func showQRCodeForCurrentServer(_ sender: NSMenuItem) { var errMsg: String? if let profile = ServerProfileManager.instance.getActiveProfile() { if profile.isValid() { @@ -219,7 +219,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele qrcodeWinCtrl = SWBQRCodeWindowController(windowNibName: "SWBQRCodeWindowController") qrcodeWinCtrl.qrCode = profile.URL()!.absoluteString qrcodeWinCtrl.showWindow(self) - NSApp.activateIgnoringOtherApps(true) + NSApp.activate(ignoringOtherApps: true) qrcodeWinCtrl.window?.makeKeyAndOrderFront(nil) return @@ -233,41 +233,41 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele userNote.title = errMsg userNote.soundName = NSUserNotificationDefaultSoundName - NSUserNotificationCenter.defaultUserNotificationCenter() - .deliverNotification(userNote); + NSUserNotificationCenter.default + .deliver(userNote); } - @IBAction func scanQRCodeFromScreen(sender: NSMenuItem) { + @IBAction func scanQRCodeFromScreen(_ sender: NSMenuItem) { ScanQRCodeOnScreen() } - @IBAction func toggleLaunghAtLogin(sender: NSMenuItem) { + @IBAction func toggleLaunghAtLogin(_ sender: NSMenuItem) { launchAtLoginController.launchAtLogin = !launchAtLoginController.launchAtLogin; updateLaunchAtLoginMenu() } - @IBAction func selectPACMode(sender: NSMenuItem) { - let defaults = NSUserDefaults.standardUserDefaults() + @IBAction func selectPACMode(_ sender: NSMenuItem) { + let defaults = UserDefaults.standard defaults.setValue("auto", forKey: "ShadowsocksRunningMode") updateRunningModeMenu() applyConfig() } - @IBAction func selectGlobalMode(sender: NSMenuItem) { - let defaults = NSUserDefaults.standardUserDefaults() + @IBAction func selectGlobalMode(_ sender: NSMenuItem) { + let defaults = UserDefaults.standard defaults.setValue("global", forKey: "ShadowsocksRunningMode") updateRunningModeMenu() applyConfig() } - @IBAction func selectManualMode(sender: NSMenuItem) { - let defaults = NSUserDefaults.standardUserDefaults() + @IBAction func selectManualMode(_ sender: NSMenuItem) { + let defaults = UserDefaults.standard defaults.setValue("manual", forKey: "ShadowsocksRunningMode") updateRunningModeMenu() applyConfig() } - @IBAction func editServerPreferences(sender: NSMenuItem) { + @IBAction func editServerPreferences(_ sender: NSMenuItem) { if preferencesWinCtrl != nil { preferencesWinCtrl.close() } @@ -275,11 +275,11 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele preferencesWinCtrl = ctrl ctrl.showWindow(self) - NSApp.activateIgnoringOtherApps(true) + NSApp.activate(ignoringOtherApps: true) ctrl.window?.makeKeyAndOrderFront(self) } - @IBAction func editAdvPreferences(sender: NSMenuItem) { + @IBAction func editAdvPreferences(_ sender: NSMenuItem) { if advPreferencesWinCtrl != nil { advPreferencesWinCtrl.close() } @@ -287,21 +287,21 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele advPreferencesWinCtrl = ctrl ctrl.showWindow(self) - NSApp.activateIgnoringOtherApps(true) + NSApp.activate(ignoringOtherApps: true) ctrl.window?.makeKeyAndOrderFront(self) } - @IBAction func editProxyPreferences(sender: NSObject) { + @IBAction func editProxyPreferences(_ sender: NSObject) { if proxyPreferencesWinCtrl != nil { proxyPreferencesWinCtrl.close() } proxyPreferencesWinCtrl = ProxyPreferencesController(windowNibName: "ProxyPreferencesController") proxyPreferencesWinCtrl.showWindow(self) - NSApp.activateIgnoringOtherApps(true) + NSApp.activate(ignoringOtherApps: true) proxyPreferencesWinCtrl.window?.makeKeyAndOrderFront(self) } - @IBAction func selectServer(sender: NSMenuItem) { + @IBAction func selectServer(_ sender: NSMenuItem) { let index = sender.tag let spMgr = ServerProfileManager.instance let newProfile = spMgr.profiles[index] @@ -312,22 +312,22 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele } } - @IBAction func showLogs(sender: NSMenuItem) { - let ws = NSWorkspace.sharedWorkspace() - if let appUrl = ws.URLForApplicationWithBundleIdentifier("com.apple.Console") { - try! ws.launchApplicationAtURL(appUrl - ,options: .Default + @IBAction func showLogs(_ sender: NSMenuItem) { + let ws = NSWorkspace.shared() + if let appUrl = ws.urlForApplication(withBundleIdentifier: "com.apple.Console") { + try! ws.launchApplication(at: appUrl + ,options: .default ,configuration: [NSWorkspaceLaunchConfigurationArguments: "~/Library/Logs/ss-local.log"]) } } - @IBAction func feedback(sender: NSMenuItem) { - NSWorkspace.sharedWorkspace().openURL(NSURL(string: "https://github.com/qiuyuzhou/ShadowsocksX-NG/issues")!) + @IBAction func feedback(_ sender: NSMenuItem) { + NSWorkspace.shared().open(URL(string: "https://github.com/qiuyuzhou/ShadowsocksX-NG/issues")!) } - @IBAction func showAbout(sender: NSMenuItem) { + @IBAction func showAbout(_ sender: NSMenuItem) { NSApp.orderFrontStandardAboutPanel(sender); - NSApp.activateIgnoringOtherApps(true) + NSApp.activate(ignoringOtherApps: true) } func updateLaunchAtLoginMenu() { @@ -339,8 +339,8 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele } func updateRunningModeMenu() { - let defaults = NSUserDefaults.standardUserDefaults() - let mode = defaults.stringForKey("ShadowsocksRunningMode") + let defaults = UserDefaults.standard + let mode = defaults.string(forKey: "ShadowsocksRunningMode") if mode == "auto" { proxyMenuItem.title = "Proxy - Auto By PAC".localized autoModeMenuItem.state = 1 @@ -360,8 +360,8 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele } func updateMainMenu() { - let defaults = NSUserDefaults.standardUserDefaults() - let isOn = defaults.boolForKey("ShadowsocksOn") + let defaults = UserDefaults.standard + let isOn = defaults.bool(forKey: "ShadowsocksOn") if isOn { runningStatusMenuItem.title = "Shadowsocks: On".localized toggleRunningMenuItem.title = "Turn Shadowsocks Off".localized @@ -395,7 +395,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele item.state = 1 } if !p.isValid() { - item.enabled = false + item.isEnabled = false } item.action = #selector(AppDelegate.selectServer) @@ -403,19 +403,19 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele i += 1 } if !mgr.profiles.isEmpty { - serversMenuItem.submenu?.addItem(NSMenuItem.separatorItem()) + serversMenuItem.submenu?.addItem(NSMenuItem.separator()) } - serversMenuItem.submenu?.addItem(showQRItem) - serversMenuItem.submenu?.addItem(scanQRItem) - serversMenuItem.submenu?.addItem(NSMenuItem.separatorItem()) - serversMenuItem.submenu?.addItem(preferencesItem) + serversMenuItem.submenu?.addItem(showQRItem!) + serversMenuItem.submenu?.addItem(scanQRItem!) + serversMenuItem.submenu?.addItem(NSMenuItem.separator()) + serversMenuItem.submenu?.addItem(preferencesItem!) } - func handleURLEvent(event: NSAppleEventDescriptor, withReplyEvent replyEvent: NSAppleEventDescriptor) { - if let urlString = event.paramDescriptorForKeyword(AEKeyword(keyDirectObject))?.stringValue { - if let url = NSURL(string: urlString) { - NSNotificationCenter.defaultCenter().postNotificationName( - "NOTIFY_FOUND_SS_URL", object: nil + func handleURLEvent(_ event: NSAppleEventDescriptor, withReplyEvent replyEvent: NSAppleEventDescriptor) { + if let urlString = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue { + if let url = URL(string: urlString) { + NotificationCenter.default.post( + name: Notification.Name(rawValue: "NOTIFY_FOUND_SS_URL"), object: nil , userInfo: [ "ruls": [url], "source": "url", @@ -427,8 +427,8 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele //------------------------------------------------------------ // NSUserNotificationCenterDelegate - func userNotificationCenter(center: NSUserNotificationCenter - , shouldPresentNotification notification: NSUserNotification) -> Bool { + func userNotificationCenter(_ center: NSUserNotificationCenter + , shouldPresent notification: NSUserNotification) -> Bool { return true } } diff --git a/ShadowsocksX-NG/LaunchAgentUtils.swift b/ShadowsocksX-NG/LaunchAgentUtils.swift index ca0deac..ad44279 100644 --- a/ShadowsocksX-NG/LaunchAgentUtils.swift +++ b/ShadowsocksX-NG/LaunchAgentUtils.swift @@ -14,8 +14,8 @@ let LAUNCH_AGENT_DIR = "/Library/LaunchAgents/" let LAUNCH_AGENT_CONF_NAME = "com.qiuyuzhou.shadowsocksX-NG.local.plist" -func getFileSHA1Sum(filepath: String) -> String { - if let data = NSData(contentsOfFile: filepath) { +func getFileSHA1Sum(_ filepath: String) -> String { + if let data = try? Data(contentsOf: URL(fileURLWithPath: filepath)) { return data.sha1() } return "" @@ -30,16 +30,16 @@ func generateSSLocalLauchAgentPlist() -> Bool { let plistFilepath = launchAgentDirPath + LAUNCH_AGENT_CONF_NAME // Ensure launch agent directory is existed. - let fileMgr = NSFileManager.defaultManager() - if !fileMgr.fileExistsAtPath(launchAgentDirPath) { - try! fileMgr.createDirectoryAtPath(launchAgentDirPath, withIntermediateDirectories: true, attributes: nil) + let fileMgr = FileManager.default + if !fileMgr.fileExists(atPath: launchAgentDirPath) { + try! fileMgr.createDirectory(atPath: launchAgentDirPath, withIntermediateDirectories: true, attributes: nil) } let oldSha1Sum = getFileSHA1Sum(plistFilepath) - let defaults = NSUserDefaults.standardUserDefaults() - let enableUdpRelay = defaults.boolForKey("LocalSocks5.EnableUDPRelay") - let enableVerboseMode = defaults.boolForKey("LocalSocks5.EnableVerboseMode") + let defaults = UserDefaults.standard + let enableUdpRelay = defaults.bool(forKey: "LocalSocks5.EnableUDPRelay") + let enableVerboseMode = defaults.bool(forKey: "LocalSocks5.EnableVerboseMode") var arguments = [sslocalPath, "-c", "ss-local-config.json"] if enableUdpRelay { @@ -59,7 +59,7 @@ func generateSSLocalLauchAgentPlist() -> Bool { "ProgramArguments": arguments, "EnvironmentVariables": ["DYLD_LIBRARY_PATH": NSHomeDirectory() + APP_SUPPORT_DIR] ] - dict.writeToFile(plistFilepath, atomically: true) + dict.write(toFile: plistFilepath, atomically: true) let Sha1Sum = getFileSHA1Sum(plistFilepath) if oldSha1Sum != Sha1Sum { return true @@ -69,9 +69,9 @@ func generateSSLocalLauchAgentPlist() -> Bool { } func ReloadConfSSLocal() { - let bundle = NSBundle.mainBundle() - let installerPath = bundle.pathForResource("reload_conf_ss_local.sh", ofType: nil) - let task = NSTask.launchedTaskWithLaunchPath(installerPath!, arguments: [""]) + let bundle = Bundle.main + let installerPath = bundle.path(forResource: "reload_conf_ss_local.sh", ofType: nil) + let task = Process.launchedProcess(launchPath: installerPath!, arguments: [""]) task.waitUntilExit() if task.terminationStatus == 0 { NSLog("Start ss-local succeeded.") @@ -81,9 +81,9 @@ func ReloadConfSSLocal() { } func StartSSLocal() { - let bundle = NSBundle.mainBundle() - let installerPath = bundle.pathForResource("start_ss_local.sh", ofType: nil) - let task = NSTask.launchedTaskWithLaunchPath(installerPath!, arguments: [""]) + let bundle = Bundle.main + let installerPath = bundle.path(forResource: "start_ss_local.sh", ofType: nil) + let task = Process.launchedProcess(launchPath: installerPath!, arguments: [""]) task.waitUntilExit() if task.terminationStatus == 0 { NSLog("Start ss-local succeeded.") @@ -93,9 +93,9 @@ func StartSSLocal() { } func StopSSLocal() { - let bundle = NSBundle.mainBundle() - let installerPath = bundle.pathForResource("stop_ss_local.sh", ofType: nil) - let task = NSTask.launchedTaskWithLaunchPath(installerPath!, arguments: [""]) + let bundle = Bundle.main + let installerPath = bundle.path(forResource: "stop_ss_local.sh", ofType: nil) + let task = Process.launchedProcess(launchPath: installerPath!, arguments: [""]) task.waitUntilExit() if task.terminationStatus == 0 { NSLog("Stop ss-local succeeded.") @@ -105,14 +105,14 @@ func StopSSLocal() { } func InstallSSLocal() { - let fileMgr = NSFileManager.defaultManager() + let fileMgr = FileManager.default let homeDir = NSHomeDirectory() let appSupportDir = homeDir+APP_SUPPORT_DIR - if !fileMgr.fileExistsAtPath(appSupportDir + "ss-local-\(SS_LOCAL_VERSION)/ss-local") - || !fileMgr.fileExistsAtPath(appSupportDir + "libcrypto.1.0.0.dylib") { - let bundle = NSBundle.mainBundle() - let installerPath = bundle.pathForResource("install_ss_local.sh", ofType: nil) - let task = NSTask.launchedTaskWithLaunchPath(installerPath!, arguments: [""]) + if !fileMgr.fileExists(atPath: appSupportDir + "ss-local-\(SS_LOCAL_VERSION)/ss-local") + || !fileMgr.fileExists(atPath: appSupportDir + "libcrypto.1.0.0.dylib") { + let bundle = Bundle.main + let installerPath = bundle.path(forResource: "install_ss_local.sh", ofType: nil) + let task = Process.launchedProcess(launchPath: installerPath!, arguments: [""]) task.waitUntilExit() if task.terminationStatus == 0 { NSLog("Install ss-local succeeded.") @@ -122,13 +122,13 @@ func InstallSSLocal() { } } -func writeSSLocalConfFile(conf:[String:AnyObject]) -> Bool { +func writeSSLocalConfFile(_ conf:[String:AnyObject]) -> Bool { do { let filepath = NSHomeDirectory() + APP_SUPPORT_DIR + "ss-local-config.json" - let data: NSData = try NSJSONSerialization.dataWithJSONObject(conf, options: .PrettyPrinted) + let data: Data = try JSONSerialization.data(withJSONObject: conf, options: .prettyPrinted) let oldSum = getFileSHA1Sum(filepath) - try data.writeToFile(filepath, options: .DataWritingAtomic) + try data.write(to: URL(fileURLWithPath: filepath), options: .atomic) let newSum = getFileSHA1Sum(filepath) if oldSum == newSum { @@ -145,7 +145,7 @@ func writeSSLocalConfFile(conf:[String:AnyObject]) -> Bool { func removeSSLocalConfFile() { do { let filepath = NSHomeDirectory() + APP_SUPPORT_DIR + "ss-local-config.json" - try NSFileManager.defaultManager().removeItemAtPath(filepath) + try FileManager.default.removeItem(atPath: filepath) } catch { } @@ -158,7 +158,7 @@ func SyncSSLocal() { if mgr.activeProfileId != nil { changed = changed || writeSSLocalConfFile((mgr.getActiveProfile()?.toJsonConfig())!) - let on = NSUserDefaults.standardUserDefaults().boolForKey("ShadowsocksOn") + let on = UserDefaults.standard.bool(forKey: "ShadowsocksOn") if on { StartSSLocal() ReloadConfSSLocal() diff --git a/ShadowsocksX-NG/PACUtils.swift b/ShadowsocksX-NG/PACUtils.swift index 592b756..8834383 100644 --- a/ShadowsocksX-NG/PACUtils.swift +++ b/ShadowsocksX-NG/PACUtils.swift @@ -21,59 +21,61 @@ let GFWListFilePath = PACRulesDirPath + "gfwlist.txt" func SyncPac() { var needGenerate = false - let nowSocks5Port = NSUserDefaults.standardUserDefaults().integerForKey("LocalSocks5.ListenPort") - let oldSocks5Port = NSUserDefaults.standardUserDefaults().integerForKey("LocalSocks5.ListenPort.Old") + let nowSocks5Port = UserDefaults.standard.integer(forKey: "LocalSocks5.ListenPort") + let oldSocks5Port = UserDefaults.standard.integer(forKey: "LocalSocks5.ListenPort.Old") if nowSocks5Port != oldSocks5Port { needGenerate = true - NSUserDefaults.standardUserDefaults().setInteger(nowSocks5Port, forKey: "LocalSocks5.ListenPort.Old") + UserDefaults.standard.set(nowSocks5Port, forKey: "LocalSocks5.ListenPort.Old") } - let fileMgr = NSFileManager.defaultManager() - if !fileMgr.fileExistsAtPath(PACRulesDirPath) { + let fileMgr = FileManager.default + if !fileMgr.fileExists(atPath: PACRulesDirPath) { needGenerate = true } if needGenerate { - GeneratePACFile() + if !GeneratePACFile() { + NSLog("GeneratePACFile failed!") + } } } func GeneratePACFile() -> Bool { - let fileMgr = NSFileManager.defaultManager() + let fileMgr = FileManager.default // Maker the dir if rulesDirPath is not exesited. - if !fileMgr.fileExistsAtPath(PACRulesDirPath) { - if fileMgr.fileExistsAtPath(OldErrorPACRulesDirPath) { - try! fileMgr.moveItemAtPath(OldErrorPACRulesDirPath, toPath: PACRulesDirPath) + if !fileMgr.fileExists(atPath: PACRulesDirPath) { + if fileMgr.fileExists(atPath: OldErrorPACRulesDirPath) { + try! fileMgr.moveItem(atPath: OldErrorPACRulesDirPath, toPath: PACRulesDirPath) } else { - try! fileMgr.createDirectoryAtPath(PACRulesDirPath + try! fileMgr.createDirectory(atPath: PACRulesDirPath , withIntermediateDirectories: true, attributes: nil) } } // If gfwlist.txt is not exsited, copy from bundle - if !fileMgr.fileExistsAtPath(GFWListFilePath) { - let src = NSBundle.mainBundle().pathForResource("gfwlist", ofType: "txt") - try! fileMgr.copyItemAtPath(src!, toPath: GFWListFilePath) + if !fileMgr.fileExists(atPath: GFWListFilePath) { + let src = Bundle.main.path(forResource: "gfwlist", ofType: "txt") + try! fileMgr.copyItem(atPath: src!, toPath: GFWListFilePath) } // If user-rule.txt is not exsited, copy from bundle - if !fileMgr.fileExistsAtPath(PACUserRuleFilePath) { - let src = NSBundle.mainBundle().pathForResource("user-rule", ofType: "txt") - try! fileMgr.copyItemAtPath(src!, toPath: PACUserRuleFilePath) + if !fileMgr.fileExists(atPath: PACUserRuleFilePath) { + let src = Bundle.main.path(forResource: "user-rule", ofType: "txt") + try! fileMgr.copyItem(atPath: src!, toPath: PACUserRuleFilePath) } - let socks5Port = NSUserDefaults.standardUserDefaults().integerForKey("LocalSocks5.ListenPort") + let socks5Port = UserDefaults.standard.integer(forKey: "LocalSocks5.ListenPort") do { - let gfwlist = try String(contentsOfFile: GFWListFilePath, encoding: NSUTF8StringEncoding) - if let data = NSData(base64EncodedString: gfwlist, options: .IgnoreUnknownCharacters) { - let str = String(data: data, encoding: NSUTF8StringEncoding) - var lines = str!.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) + let gfwlist = try String(contentsOfFile: GFWListFilePath, encoding: String.Encoding.utf8) + if let data = Data(base64Encoded: gfwlist, options: .ignoreUnknownCharacters) { + let str = String(data: data, encoding: String.Encoding.utf8) + var lines = str!.components(separatedBy: CharacterSet.newlines) do { - let userRuleStr = try String(contentsOfFile: PACUserRuleFilePath, encoding: NSUTF8StringEncoding) - let userRuleLines = userRuleStr.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) + let userRuleStr = try String(contentsOfFile: PACUserRuleFilePath, encoding: String.Encoding.utf8) + let userRuleLines = userRuleStr.components(separatedBy: CharacterSet.newlines) lines += userRuleLines } catch { @@ -94,25 +96,25 @@ func GeneratePACFile() -> Bool { do { // rule lines to json array - let rulesJsonData: NSData - = try NSJSONSerialization.dataWithJSONObject(lines, options: .PrettyPrinted) - let rulesJsonStr = String(data: rulesJsonData, encoding: NSUTF8StringEncoding) + let rulesJsonData: Data + = try JSONSerialization.data(withJSONObject: lines, options: .prettyPrinted) + let rulesJsonStr = String(data: rulesJsonData, encoding: String.Encoding.utf8) // Get raw pac js - let jsPath = NSBundle.mainBundle().URLForResource("abp", withExtension: "js") - let jsData = NSData(contentsOfURL: jsPath!) - var jsStr = String(data: jsData!, encoding: NSUTF8StringEncoding) + let jsPath = Bundle.main.url(forResource: "abp", withExtension: "js") + let jsData = try? Data(contentsOf: jsPath!) + var jsStr = String(data: jsData!, encoding: String.Encoding.utf8) // Replace rules placeholder in pac js - jsStr = jsStr!.stringByReplacingOccurrencesOfString("__RULES__" - , withString: rulesJsonStr!) + jsStr = jsStr!.replacingOccurrences(of: "__RULES__" + , with: rulesJsonStr!) // Replace __SOCKS5PORT__ palcholder in pac js - let result = jsStr!.stringByReplacingOccurrencesOfString("__SOCKS5PORT__" - , withString: "\(socks5Port)") + let result = jsStr!.replacingOccurrences(of: "__SOCKS5PORT__" + , with: "\(socks5Port)") // Write the pac js to file. - try result.dataUsingEncoding(NSUTF8StringEncoding)? - .writeToFile(PACFilePath, options: .DataWritingAtomic) + try result.data(using: String.Encoding.utf8)? + .write(to: URL(fileURLWithPath: PACFilePath), options: .atomic) return true } catch { @@ -128,28 +130,28 @@ func GeneratePACFile() -> Bool { func UpdatePACFromGFWList() { // Make the dir if rulesDirPath is not exesited. - if !NSFileManager.defaultManager().fileExistsAtPath(PACRulesDirPath) { + if !FileManager.default.fileExists(atPath: PACRulesDirPath) { do { - try NSFileManager.defaultManager().createDirectoryAtPath(PACRulesDirPath + try FileManager.default.createDirectory(atPath: PACRulesDirPath , withIntermediateDirectories: true, attributes: nil) } catch { } } - let url = NSUserDefaults.standardUserDefaults().stringForKey("GFWListURL") - Alamofire.request(.GET, url!) + let url = UserDefaults.standard.string(forKey: "GFWListURL") + Alamofire.request(url!) .responseString { response in if response.result.isSuccess { if let v = response.result.value { do { - try v.writeToFile(GFWListFilePath, atomically: true, encoding: NSUTF8StringEncoding) + try v.write(toFile: GFWListFilePath, atomically: true, encoding: String.Encoding.utf8) if GeneratePACFile() { // Popup a user notification let notification = NSUserNotification() notification.title = "PAC has been updated by latest GFW List.".localized - NSUserNotificationCenter.defaultUserNotificationCenter() - .deliverNotification(notification) + NSUserNotificationCenter.default + .deliver(notification) } } catch { @@ -159,8 +161,8 @@ func UpdatePACFromGFWList() { // Popup a user notification let notification = NSUserNotification() notification.title = "Failed to download latest GFW List.".localized - NSUserNotificationCenter.defaultUserNotificationCenter() - .deliverNotification(notification) + NSUserNotificationCenter.default + .deliver(notification) } } } diff --git a/ShadowsocksX-NG/PreferencesWindowController.swift b/ShadowsocksX-NG/PreferencesWindowController.swift index 086acd7..b24939c 100644 --- a/ShadowsocksX-NG/PreferencesWindowController.swift +++ b/ShadowsocksX-NG/PreferencesWindowController.swift @@ -29,7 +29,7 @@ class PreferencesWindowController: NSWindowController @IBOutlet weak var removeButton: NSButton! let tableViewDragType: String = "ss.server.profile.data" - var defaults: NSUserDefaults! + var defaults: UserDefaults! var profileMgr: ServerProfileManager! var editingProfile: ServerProfile! @@ -39,10 +39,10 @@ class PreferencesWindowController: NSWindowController super.windowDidLoad() // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file. - defaults = NSUserDefaults.standardUserDefaults() + defaults = UserDefaults.standard profileMgr = ServerProfileManager.instance - methodTextField.addItemsWithObjectValues([ + methodTextField.addItems(withObjectValues: [ "aes-128-cfb", "aes-192-cfb", "aes-256-cfb", @@ -61,10 +61,10 @@ class PreferencesWindowController: NSWindowController } override func awakeFromNib() { - profilesTableView.registerForDraggedTypes([tableViewDragType]) + profilesTableView.register(forDraggedTypes: [tableViewDragType]) } - @IBAction func addProfile(sender: NSButton) { + @IBAction func addProfile(_ sender: NSButton) { if editingProfile != nil && !editingProfile.isValid(){ shakeWindows() return @@ -74,8 +74,8 @@ class PreferencesWindowController: NSWindowController profile.remark = "New Server".localized profileMgr.profiles.append(profile) - let index = NSIndexSet(index: profileMgr.profiles.count-1) - profilesTableView.insertRowsAtIndexes(index, withAnimation: .EffectFade) + let index = IndexSet(integer: profileMgr.profiles.count-1) + profilesTableView.insertRows(at: index, withAnimation: .effectFade) self.profilesTableView.scrollRowToVisible(self.profileMgr.profiles.count-1) self.profilesTableView.selectRowIndexes(index, byExtendingSelection: false) @@ -83,18 +83,18 @@ class PreferencesWindowController: NSWindowController updateProfileBoxVisible() } - @IBAction func removeProfile(sender: NSButton) { + @IBAction func removeProfile(_ sender: NSButton) { let index = profilesTableView.selectedRow if index >= 0 { profilesTableView.beginUpdates() - profileMgr.profiles.removeAtIndex(index) - profilesTableView.removeRowsAtIndexes(NSIndexSet(index: index), withAnimation: .EffectFade) + profileMgr.profiles.remove(at: index) + profilesTableView.removeRows(at: IndexSet(integer: index), withAnimation: .effectFade) profilesTableView.endUpdates() } updateProfileBoxVisible() } - @IBAction func ok(sender: NSButton) { + @IBAction func ok(_ sender: NSButton) { if editingProfile != nil { if !editingProfile.isValid() { // TODO Shake window? @@ -106,15 +106,15 @@ class PreferencesWindowController: NSWindowController window?.performClose(nil) - NSNotificationCenter.defaultCenter() - .postNotificationName(NOTIFY_SERVER_PROFILES_CHANGED, object: nil) + NotificationCenter.default + .post(name: Notification.Name(rawValue: NOTIFY_SERVER_PROFILES_CHANGED), object: nil) } - @IBAction func cancel(sender: NSButton) { + @IBAction func cancel(_ sender: NSButton) { window?.performClose(self) } - @IBAction func copyCurrentProfileURL2Pasteboard(sender: NSButton) { + @IBAction func copyCurrentProfileURL2Pasteboard(_ sender: NSButton) { let index = profilesTableView.selectedRow if index >= 0 { let profile = profileMgr.profiles[index] @@ -122,9 +122,9 @@ class PreferencesWindowController: NSWindowController if let url = ssURL { // Then copy url to pasteboard // TODO Why it not working?? It's ok in objective-c - let pboard = NSPasteboard.generalPasteboard() + let pboard = NSPasteboard.general() pboard.clearContents() - let rs = pboard.writeObjects([url]) + let rs = pboard.writeObjects([url as NSPasteboardWriting]) if rs { NSLog("copy to pasteboard success") } else { @@ -136,37 +136,37 @@ class PreferencesWindowController: NSWindowController func updateProfileBoxVisible() { if profileMgr.profiles.count <= 1 { - removeButton.enabled = false + removeButton.isEnabled = false }else{ - removeButton.enabled = true + removeButton.isEnabled = true } if profileMgr.profiles.isEmpty { - profileBox.hidden = true + profileBox.isHidden = true } else { - profileBox.hidden = false + profileBox.isHidden = false } } - func bindProfile(index:Int) { + func bindProfile(_ index:Int) { NSLog("bind profile \(index)") if index >= 0 && index < profileMgr.profiles.count { editingProfile = profileMgr.profiles[index] - hostTextField.bind("value", toObject: editingProfile, withKeyPath: "serverHost" + hostTextField.bind("value", to: editingProfile, withKeyPath: "serverHost" , options: [NSContinuouslyUpdatesValueBindingOption: true]) - portTextField.bind("value", toObject: editingProfile, withKeyPath: "serverPort" + portTextField.bind("value", to: editingProfile, withKeyPath: "serverPort" , options: [NSContinuouslyUpdatesValueBindingOption: true]) - methodTextField.bind("value", toObject: editingProfile, withKeyPath: "method" + methodTextField.bind("value", to: editingProfile, withKeyPath: "method" , options: [NSContinuouslyUpdatesValueBindingOption: true]) - passwordTextField.bind("value", toObject: editingProfile, withKeyPath: "password" + passwordTextField.bind("value", to: editingProfile, withKeyPath: "password" , options: [NSContinuouslyUpdatesValueBindingOption: true]) - remarkTextField.bind("value", toObject: editingProfile, withKeyPath: "remark" + remarkTextField.bind("value", to: editingProfile, withKeyPath: "remark" , options: [NSContinuouslyUpdatesValueBindingOption: true]) - otaCheckBoxBtn.bind("value", toObject: editingProfile, withKeyPath: "ota" + otaCheckBoxBtn.bind("value", to: editingProfile, withKeyPath: "ota" , options: [NSContinuouslyUpdatesValueBindingOption: true]) } else { editingProfile = nil @@ -182,7 +182,7 @@ class PreferencesWindowController: NSWindowController } } - func getDataAtRow(index:Int) -> (String, Bool) { + func getDataAtRow(_ index:Int) -> (String, Bool) { let profile = profileMgr.profiles[index] let isActive = (profileMgr.activeProfileId == profile.uuid) if !profile.remark.isEmpty { @@ -195,16 +195,16 @@ class PreferencesWindowController: NSWindowController //-------------------------------------------------- // For NSTableViewDataSource - func numberOfRowsInTableView(tableView: NSTableView) -> Int { + func numberOfRows(in tableView: NSTableView) -> Int { if let mgr = profileMgr { return mgr.profiles.count } return 0 } - func tableView(tableView: NSTableView - , objectValueForTableColumn tableColumn: NSTableColumn? - , row: Int) -> AnyObject? { + func tableView(_ tableView: NSTableView + , objectValueFor tableColumn: NSTableColumn? + , row: Int) -> Any? { let (title, isActive) = getDataAtRow(row) @@ -222,26 +222,26 @@ class PreferencesWindowController: NSWindowController // Drag & Drop reorder rows - func tableView(tableView: NSTableView, pasteboardWriterForRow row: Int) -> NSPasteboardWriting? { + func tableView(_ tableView: NSTableView, pasteboardWriterForRow row: Int) -> NSPasteboardWriting? { let item = NSPasteboardItem() item.setString(String(row), forType: tableViewDragType) return item } - func tableView(tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int + func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int , proposedDropOperation dropOperation: NSTableViewDropOperation) -> NSDragOperation { - if dropOperation == .Above { - return .Move + if dropOperation == .above { + return .move } - return .None + return NSDragOperation() } - func tableView(tableView: NSTableView, acceptDrop info: NSDraggingInfo + func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo , row: Int, dropOperation: NSTableViewDropOperation) -> Bool { if let mgr = profileMgr { var oldIndexes = [Int]() - info.enumerateDraggingItemsWithOptions([], forView: tableView, classes: [NSPasteboardItem.self], searchOptions: [:]) { - if let str = ($0.0.item as! NSPasteboardItem).stringForType(self.tableViewDragType), index = Int(str) { + info.enumerateDraggingItems(options: [], for: tableView, classes: [NSPasteboardItem.self], searchOptions: [:]) { + if let str = ($0.0.item as! NSPasteboardItem).string(forType: self.tableViewDragType), let index = Int(str) { oldIndexes.append(index) } } @@ -254,14 +254,14 @@ class PreferencesWindowController: NSWindowController tableView.beginUpdates() for oldIndex in oldIndexes { if oldIndex < row { - let o = mgr.profiles.removeAtIndex(oldIndex + oldIndexOffset) - mgr.profiles.insert(o, atIndex:row - 1) - tableView.moveRowAtIndex(oldIndex + oldIndexOffset, toIndex: row - 1) + let o = mgr.profiles.remove(at: oldIndex + oldIndexOffset) + mgr.profiles.insert(o, at:row - 1) + tableView.moveRow(at: oldIndex + oldIndexOffset, to: row - 1) oldIndexOffset -= 1 } else { - let o = mgr.profiles.removeAtIndex(oldIndex) - mgr.profiles.insert(o, atIndex:row + newIndexOffset) - tableView.moveRowAtIndex(oldIndex, toIndex: row + newIndexOffset) + let o = mgr.profiles.remove(at: oldIndex) + mgr.profiles.insert(o, at:row + newIndexOffset) + tableView.moveRow(at: oldIndex, to: row + newIndexOffset) newIndexOffset += 1 } } @@ -275,12 +275,12 @@ class PreferencesWindowController: NSWindowController //-------------------------------------------------- // For NSTableViewDelegate - func tableView(tableView: NSTableView - , shouldEditTableColumn tableColumn: NSTableColumn?, row: Int) -> Bool { + func tableView(_ tableView: NSTableView + , shouldEdit tableColumn: NSTableColumn?, row: Int) -> Bool { return false } - func tableView(tableView: NSTableView, shouldSelectRow row: Int) -> Bool { + func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool { if row < 0 { editingProfile = nil return true @@ -294,12 +294,12 @@ class PreferencesWindowController: NSWindowController return true } - func tableViewSelectionDidChange(notification: NSNotification) { + func tableViewSelectionDidChange(_ notification: Notification) { if profilesTableView.selectedRow >= 0 { bindProfile(profilesTableView.selectedRow) } else { if !profileMgr.profiles.isEmpty { - let index = NSIndexSet(index: profileMgr.profiles.count - 1) + let index = IndexSet(integer: profileMgr.profiles.count - 1) profilesTableView.selectRowIndexes(index, byExtendingSelection: false) } } @@ -313,15 +313,15 @@ class PreferencesWindowController: NSWindowController let frame:CGRect = (window?.frame)! let shakeAnimation = CAKeyframeAnimation() - let shakePath = CGPathCreateMutable() - CGPathMoveToPoint(shakePath, nil, NSMinX(frame), NSMinY(frame)) + let shakePath = CGMutablePath() + shakePath.move(to: CGPoint(x:NSMinX(frame), y:NSMinY(frame))) for _ in 1...numberOfShakes{ - CGPathAddLineToPoint(shakePath, nil, NSMinX(frame) - frame.size.width * CGFloat(vigourOfShake), NSMinY(frame)) - CGPathAddLineToPoint(shakePath, nil, NSMinX(frame) + frame.size.width * CGFloat(vigourOfShake), NSMinY(frame)) + shakePath.addLine(to: CGPoint(x: NSMinX(frame) - frame.size.width * CGFloat(vigourOfShake), y: NSMinY(frame))) + shakePath.addLine(to: CGPoint(x: NSMinX(frame) + frame.size.width * CGFloat(vigourOfShake), y: NSMinY(frame))) } - CGPathCloseSubpath(shakePath) + shakePath.closeSubpath() shakeAnimation.path = shakePath shakeAnimation.duration = CFTimeInterval(durationOfShake) window?.animations = ["frameOrigin":shakeAnimation] diff --git a/ShadowsocksX-NG/ProxyPreferencesController.swift b/ShadowsocksX-NG/ProxyPreferencesController.swift index a28f787..4c215d6 100644 --- a/ShadowsocksX-NG/ProxyPreferencesController.swift +++ b/ShadowsocksX-NG/ProxyPreferencesController.swift @@ -23,71 +23,73 @@ class ProxyPreferencesController: NSWindowController, NSTableViewDataSource, NST super.windowDidLoad() // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file. - let defaults = NSUserDefaults.standardUserDefaults() - self.setValue(defaults.boolForKey("AutoConfigureNetworkServices"), forKey: "autoConfigureNetworkServices") + let defaults = UserDefaults.standard + self.setValue(defaults.bool(forKey: "AutoConfigureNetworkServices"), forKey: "autoConfigureNetworkServices") - if let services = defaults.arrayForKey("Proxy4NetworkServices") { + if let services = defaults.array(forKey: "Proxy4NetworkServices") { selectedNetworkServices = NSMutableSet(array: services) } else { selectedNetworkServices = NSMutableSet() } - networkServices = ProxyConfTool.networkServicesList() + networkServices = ProxyConfTool.networkServicesList() as NSArray! tableView.reloadData() } - @IBAction func ok(sender: NSObject){ + @IBAction func ok(_ sender: NSObject){ ProxyConfHelper.disableProxy("hi") - let defaults = NSUserDefaults.standardUserDefaults() + let defaults = UserDefaults.standard defaults.setValue(selectedNetworkServices.allObjects, forKeyPath: "Proxy4NetworkServices") - defaults.setBool(autoConfigureNetworkServices, forKey: "AutoConfigureNetworkServices") + defaults.set(autoConfigureNetworkServices, forKey: "AutoConfigureNetworkServices") defaults.synchronize() window?.performClose(self) - NSNotificationCenter.defaultCenter() - .postNotificationName(NOTIFY_ADV_PROXY_CONF_CHANGED, object: nil) + NotificationCenter.default + .post(name: Notification.Name(rawValue: NOTIFY_ADV_PROXY_CONF_CHANGED), object: nil) } - @IBAction func cancel(sender: NSObject){ + @IBAction func cancel(_ sender: NSObject){ window?.performClose(self) } //-------------------------------------------------- // For NSTableViewDataSource - func numberOfRowsInTableView(tableView: NSTableView) -> Int { + func numberOfRows(in tableView: NSTableView) -> Int { if networkServices != nil { return networkServices.count } return 0; } - func tableView(tableView: NSTableView, objectValueForTableColumn tableColumn: NSTableColumn? - , row: Int) -> AnyObject? { + func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn? + , row: Int) -> Any? { let cell = tableColumn!.dataCell as! NSButtonCell - let key = networkServices[row]["key"] as! String - if selectedNetworkServices.containsObject(key) { + let networkService = networkServices[row] as! [String: Any] + let key = networkService["key"] as! String + if selectedNetworkServices.contains(key) { cell.state = 1 } else { cell.state = 0 } - let userDefinedName = networkServices[row]["userDefinedName"] as! String + let userDefinedName = networkService["userDefinedName"] as! String cell.title = userDefinedName return cell } - func tableView(tableView: NSTableView, setObjectValue object: AnyObject? - , forTableColumn tableColumn: NSTableColumn?, row: Int) { - let key = networkServices[row]["key"] as! String + func tableView(_ tableView: NSTableView, setObjectValue object: Any? + , for tableColumn: NSTableColumn?, row: Int) { + let networkService = networkServices[row] as! [String: Any] + let key = networkService["key"] as! String // NSLog("%d", object!.integerValue) - if object!.integerValue == 1 { - selectedNetworkServices.addObject(key) + if (object! as AnyObject).intValue == 1 { + selectedNetworkServices.add(key) } else { - selectedNetworkServices.removeObject(key) + selectedNetworkServices.remove(key) } } } diff --git a/ShadowsocksX-NG/ServerProfile.swift b/ShadowsocksX-NG/ServerProfile.swift index c71d717..c63085d 100644 --- a/ShadowsocksX-NG/ServerProfile.swift +++ b/ShadowsocksX-NG/ServerProfile.swift @@ -21,18 +21,18 @@ class ServerProfile: NSObject { var ota: Bool = false // onetime authentication override init() { - uuid = NSUUID().UUIDString + uuid = UUID().uuidString } init(uuid: String) { self.uuid = uuid } - static func fromDictionary(data:[String:AnyObject]) -> ServerProfile { + static func fromDictionary(_ data:[String:AnyObject]) -> ServerProfile { let cp = { (profile: ServerProfile) in profile.serverHost = data["ServerHost"] as! String - profile.serverPort = (data["ServerPort"] as! NSNumber).unsignedShortValue + profile.serverPort = (data["ServerPort"] as! NSNumber).uint16Value profile.method = data["Method"] as! String profile.password = data["Password"] as! String if let remark = data["Remark"] { @@ -56,33 +56,33 @@ class ServerProfile: NSObject { func toDictionary() -> [String:AnyObject] { var d = [String:AnyObject]() - d["Id"] = uuid - d["ServerHost"] = serverHost - d["ServerPort"] = NSNumber(unsignedShort:serverPort) - d["Method"] = method - d["Password"] = password - d["Remark"] = remark - d["OTA"] = ota + d["Id"] = uuid as AnyObject? + d["ServerHost"] = serverHost as AnyObject? + d["ServerPort"] = NSNumber(value: serverPort as UInt16) + d["Method"] = method as AnyObject? + d["Password"] = password as AnyObject? + d["Remark"] = remark as AnyObject? + d["OTA"] = ota as AnyObject? return d } func toJsonConfig() -> [String: AnyObject] { - var conf: [String: AnyObject] = ["server": serverHost, - "server_port": NSNumber(unsignedShort: serverPort), - "password": password, - "method": method,] + var conf: [String: AnyObject] = ["server": serverHost as AnyObject, + "server_port": NSNumber(value: serverPort as UInt16), + "password": password as AnyObject, + "method": method as AnyObject,] - let defaults = NSUserDefaults.standardUserDefaults() - conf["local_port"] = NSNumber(unsignedShort: UInt16(defaults.integerForKey("LocalSocks5.ListenPort"))) - conf["local_address"] = defaults.stringForKey("LocalSocks5.ListenAddress") - conf["timeout"] = NSNumber(unsignedInt: UInt32(defaults.integerForKey("LocalSocks5.Timeout"))) - conf["auth"] = NSNumber(bool: ota) + let defaults = UserDefaults.standard + conf["local_port"] = NSNumber(value: UInt16(defaults.integer(forKey: "LocalSocks5.ListenPort")) as UInt16) + conf["local_address"] = defaults.string(forKey: "LocalSocks5.ListenAddress") as AnyObject? + conf["timeout"] = NSNumber(value: UInt32(defaults.integer(forKey: "LocalSocks5.Timeout")) as UInt32) + conf["auth"] = NSNumber(value: ota as Bool) return conf } func isValid() -> Bool { - func validateIpAddress(ipToValidate: String) -> Bool { + func validateIpAddress(_ ipToValidate: String) -> Bool { var sin = sockaddr_in() var sin6 = sockaddr_in6() @@ -99,10 +99,10 @@ class ServerProfile: NSObject { return false; } - func validateDomainName(value: String) -> Bool { + func validateDomainName(_ value: String) -> Bool { let validHostnameRegex = "^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$" - if (value.rangeOfString(validHostnameRegex, options: .RegularExpressionSearch) != nil) { + if (value.range(of: validHostnameRegex, options: .regularExpression) != nil) { return true } else { return false @@ -120,13 +120,13 @@ class ServerProfile: NSObject { return true } - func URL() -> NSURL? { + func URL() -> Foundation.URL? { let parts = "\(method):\(password)@\(serverHost):\(serverPort)" - let base64String = parts.dataUsingEncoding(NSUTF8StringEncoding)? - .base64EncodedStringWithOptions(NSDataBase64EncodingOptions()) + let base64String = parts.data(using: String.Encoding.utf8)? + .base64EncodedString(options: NSData.Base64EncodingOptions()) if var s = base64String { - s = s.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "=")) - return NSURL(string: "ss://\(s)") + s = s.trimmingCharacters(in: CharacterSet(charactersIn: "=")) + return Foundation.URL(string: "ss://\(s)") } return nil } diff --git a/ShadowsocksX-NG/ServerProfileManager.swift b/ShadowsocksX-NG/ServerProfileManager.swift index f3be6c8..61b62c7 100644 --- a/ShadowsocksX-NG/ServerProfileManager.swift +++ b/ShadowsocksX-NG/ServerProfileManager.swift @@ -15,45 +15,45 @@ class ServerProfileManager: NSObject { var profiles:[ServerProfile] var activeProfileId: String? - private override init() { + fileprivate override init() { profiles = [ServerProfile]() - let defaults = NSUserDefaults.standardUserDefaults() - if let _profiles = defaults.arrayForKey("ServerProfiles") { + let defaults = UserDefaults.standard + if let _profiles = defaults.array(forKey: "ServerProfiles") { for _profile in _profiles { let profile = ServerProfile.fromDictionary(_profile as! [String : AnyObject]) profiles.append(profile) } } - activeProfileId = defaults.stringForKey("ActiveServerProfileId") + activeProfileId = defaults.string(forKey: "ActiveServerProfileId") } - func setActiveProfiledId(id: String) { + func setActiveProfiledId(_ id: String) { activeProfileId = id - let defaults = NSUserDefaults.standardUserDefaults() - defaults.setObject(id, forKey: "ActiveServerProfileId") + let defaults = UserDefaults.standard + defaults.set(id, forKey: "ActiveServerProfileId") } func save() { - let defaults = NSUserDefaults.standardUserDefaults() + let defaults = UserDefaults.standard var _profiles = [AnyObject]() for profile in profiles { if profile.isValid() { let _profile = profile.toDictionary() - _profiles.append(_profile) + _profiles.append(_profile as AnyObject) } } - defaults.setObject(_profiles, forKey: "ServerProfiles") + defaults.set(_profiles, forKey: "ServerProfiles") if getActiveProfile() == nil { activeProfileId = nil } if activeProfileId != nil { - defaults.setObject(activeProfileId, forKey: "ActiveServerProfileId") + defaults.set(activeProfileId, forKey: "ActiveServerProfileId") writeSSLocalConfFile((getActiveProfile()?.toJsonConfig())!) } else { - defaults.removeObjectForKey("ActiveServerProfileId") + defaults.removeObject(forKey: "ActiveServerProfileId") removeSSLocalConfFile() } } diff --git a/ShadowsocksX-NG/UserRulesController.swift b/ShadowsocksX-NG/UserRulesController.swift index 3e020cc..f378ca3 100644 --- a/ShadowsocksX-NG/UserRulesController.swift +++ b/ShadowsocksX-NG/UserRulesController.swift @@ -15,36 +15,36 @@ class UserRulesController: NSWindowController { override func windowDidLoad() { super.windowDidLoad() - let fileMgr = NSFileManager.defaultManager() - if !fileMgr.fileExistsAtPath(PACUserRuleFilePath) { - let src = NSBundle.mainBundle().pathForResource("user-rule", ofType: "txt") - try! fileMgr.copyItemAtPath(src!, toPath: PACUserRuleFilePath) + let fileMgr = FileManager.default + if !fileMgr.fileExists(atPath: PACUserRuleFilePath) { + let src = Bundle.main.path(forResource: "user-rule", ofType: "txt") + try! fileMgr.copyItem(atPath: src!, toPath: PACUserRuleFilePath) } - let str = try? String(contentsOfFile: PACUserRuleFilePath, encoding: NSUTF8StringEncoding) + let str = try? String(contentsOfFile: PACUserRuleFilePath, encoding: String.Encoding.utf8) userRulesView.string = str } - @IBAction func didCancel(sender: AnyObject) { + @IBAction func didCancel(_ sender: AnyObject) { window?.performClose(self) } - @IBAction func didOK(sender: AnyObject) { + @IBAction func didOK(_ sender: AnyObject) { if let str = userRulesView.string { do { - try str.dataUsingEncoding(NSUTF8StringEncoding)?.writeToFile(PACUserRuleFilePath, options: .DataWritingAtomic) + try str.data(using: String.Encoding.utf8)?.write(to: URL(fileURLWithPath: PACUserRuleFilePath), options: .atomic) if GeneratePACFile() { // Popup a user notification let notification = NSUserNotification() notification.title = "PAC has been updated by User Rules.".localized - NSUserNotificationCenter.defaultUserNotificationCenter() - .deliverNotification(notification) + NSUserNotificationCenter.default + .deliver(notification) } else { let notification = NSUserNotification() notification.title = "It's failed to update PAC by User Rules.".localized - NSUserNotificationCenter.defaultUserNotificationCenter() - .deliverNotification(notification) + NSUserNotificationCenter.default + .deliver(notification) } } catch {} } diff --git a/ShadowsocksX-NG/Utils.swift b/ShadowsocksX-NG/Utils.swift index d14670b..74c0f54 100644 --- a/ShadowsocksX-NG/Utils.swift +++ b/ShadowsocksX-NG/Utils.swift @@ -11,17 +11,17 @@ import Foundation extension String { var localized: String { - return NSLocalizedString(self, tableName: nil, bundle: NSBundle.mainBundle(), value: "", comment: "") + return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "") } } -extension NSData { +extension Data { func sha1() -> String { let data = self - var digest = [UInt8](count:Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0) - CC_SHA1(data.bytes, CC_LONG(data.length), &digest) + var digest = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH)) + CC_SHA1((data as NSData).bytes, CC_LONG(data.count), &digest) let hexBytes = digest.map { String(format: "%02hhx", $0) } - return hexBytes.joinWithSeparator("") + return hexBytes.joined(separator: "") } -} \ No newline at end of file +} diff --git a/ShadowsocksX-NGTests/ShadowsocksX_NGTests.swift b/ShadowsocksX-NGTests/ShadowsocksX_NGTests.swift index a7da392..4bab66f 100644 --- a/ShadowsocksX-NGTests/ShadowsocksX_NGTests.swift +++ b/ShadowsocksX-NGTests/ShadowsocksX_NGTests.swift @@ -28,7 +28,7 @@ class ShadowsocksX_NGTests: XCTestCase { func testPerformanceExample() { // This is an example of a performance test case. - self.measureBlock { + self.measure { // Put the code you want to measure the time of here. } }