README.md 74.1 KB
Newer Older
M
Mattt Thompson 已提交
1
![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/assets/alamofire.png)
M
Mattt Thompson 已提交
2

3
[![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg?branch=master)](https://travis-ci.org/Alamofire/Alamofire)
4
[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg)
5 6 7
[![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)
[![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat)](http://twitter.com/AlamofireSF)
8

M
Mattt Thompson 已提交
9
Alamofire is an HTTP networking library written in Swift.
10

11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
- [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)

33 34
## Features

35
- [x] Chainable Request / Response Methods
M
- [x]  
Mattt Thompson 已提交
36
- [x] URL / JSON / plist Parameter Encoding
37
- [x] Upload File / Data / Stream / MultipartFormData
38 39
- [x] Download File using Request or Resume Data
- [x] Authentication with URLCredential
M
- [x]  
Mattt Thompson 已提交
40
- [x] HTTP Response Validation
41 42 43
- [x] Upload and Download Progress Closures with Progress
- [x] cURL Command Output
- [x] Dynamically Adapt and Retry Requests
44
- [x] TLS Certificate and Public Key Pinning
45 46
- [x] Network Reachability
- [x] Comprehensive Unit and Integration Test Coverage
R
rojotek 已提交
47
- [x] [Complete Documentation](http://cocoadocs.org/docsets/Alamofire)
48

49 50 51 52
## 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.

53 54
- [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.
55

56 57
## Requirements

58
- iOS 9.0+ / Mac OS X 10.11+ / tvOS 9.0+ / watchOS 2.0+
59
- Xcode 8.0+
C
Christian Noon 已提交
60
- Swift 3.0+
61

62 63
## Migration Guides

64
- [Alamofire 4.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md)
65
- [Alamofire 3.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md)
66
- [Alamofire 2.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%202.0%20Migration%20Guide.md)
67

M
Mattt Thompson 已提交
68 69 70 71 72 73 74 75
## Communication

- If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/alamofire). (Tag 'alamofire')
- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/alamofire).
- If you **found a bug**, open an issue.
- If you **have a feature request**, open an issue.
- If you **want to contribute**, submit a pull request.

76 77
## Installation

78 79
### CocoaPods

80
[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command:
81 82

```bash
83
$ gem install cocoapods
84 85
```

86
> CocoaPods 1.0.0+ is required to build Alamofire 4.0.0+.
87

88 89 90 91
To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`:

```ruby
source 'https://github.com/CocoaPods/Specs.git'
92
platform :ios, '10.0'
93
use_frameworks!
94

L
Luis Ferro 已提交
95
target '<Your Target Name>' do
96
    pod 'Alamofire', '~> 4.0'
L
Luis Ferro 已提交
97
end
98 99 100 101 102 103 104 105 106 107
```

Then, run the following command:

```bash
$ pod install
```

### Carthage

108
[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.
109 110 111 112 113 114 115 116 117 118 119

You can install Carthage with [Homebrew](http://brew.sh/) using the following command:

```bash
$ brew update
$ brew install carthage
```

To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`:

```ogdl
120
github "Alamofire/Alamofire" ~> 4.0
121 122
```

V
vlad 已提交
123
Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project.
124

125 126 127 128
### Manually

If you prefer not to use either of the aforementioned dependency managers, you can integrate Alamofire into your project manually.

129
#### Embedded Framework
130

131 132 133 134 135 136 137
- Open up Terminal, `cd` into your top-level project directory, and run the following command "if" your project is not initialized as a git repository:

```bash
$ git init
```

- Add Alamofire as a git [submodule](http://git-scm.com/docs/git-submodule) by running the following command:
138 139 140 141 142

```bash
$ git submodule add https://github.com/Alamofire/Alamofire.git
```

143 144 145 146 147 148 149 150 151 152 153 154 155 156
- Open the new `Alamofire` folder, and drag the `Alamofire.xcodeproj` into the Project Navigator of your application's Xcode project.

    > It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter.

- Select the `Alamofire.xcodeproj` in the Project Navigator and verify the deployment target matches that of your application target.
- Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar.
- In the tab bar at the top of that window, open the "General" panel.
- Click on the `+` button under the "Embedded Binaries" section.
- You will see two different `Alamofire.xcodeproj` folders each with two different versions of the `Alamofire.framework` nested inside a `Products` folder.

    > It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`. 
    
- Select the top `Alamofire.framework` for iOS and the bottom one for OS X.

157
    > 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`.
158 159 160

- And that's it!

161
> The `Alamofire.framework` is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device.
162

163 164
---

M
Mattt Thompson 已提交
165 166
## Usage

M
Mattt Thompson 已提交
167
### Making a Request
M
Mattt Thompson 已提交
168 169

```swift
M
Mattt Thompson 已提交
170 171
import Alamofire

172
Alamofire.request("https://httpbin.org/get")
M
Mattt Thompson 已提交
173 174
```

M
Mattt Thompson 已提交
175
### Response Handling
M
Mattt Thompson 已提交
176

177
Handling the `Response` of a `Request` made in Alamofire involves chaining a response handler onto the `Request`.
178

179 180 181 182 183 184 185 186 187 188 189
```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)")
    }
}
M
Mattt Thompson 已提交
190 191
```

192 193
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.

M
Mattt Thompson 已提交
194 195
> 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.

196
Alamofire contains five different response handlers by default including:
M
Mattt Thompson 已提交
197

198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
```swift
// Response Handler - Unserialized Response
func response(
    queue: DispatchQueue?, 
    completionHandler: (DefaultDownloadResponse) -> Void) 
    -> Self

// Response Data Handler - Serialized into Data
func responseData(
    queue: DispatchQueue?, 
    completionHandler: @escaping (DataResponse<Data>) -> Void) 
    -> Self

// Response String Handler - Serialized into String
func responseString(
    queue: DispatchQueue?, 
    encoding: String.Encoding?, 
    completionHandler: @escaping (DataResponse<String>) -> Void)
    -> Self

// Response JSON Handler - Serialized into Any
func responseJSON(
    queue: DispatchQueue?, 
    completionHandler: @escaping (DataResponse<Any>) -> Void)
    -> Self

// Response PropertyList (plist) Handler - Serialized into Any
func responsePropertyList(
    queue: DispatchQueue?, 
    completionHandler: @escaping (DataResponse<Any>) -> 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.
234

235
#### Response Handler
236

237
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`.
238 239

```swift
240 241 242 243 244 245 246 247 248
Alamofire.request("https://httpbin.org/get").response { response in
    print("Request: \(response.request)")
    print("Response: \(response.response)")
    print("Error: \(response.data)")
    
    if let data = data, let utf8Text = String(data: data, encoding: .utf8) {
    	print("Data: \(utf8Text)")
    }
}
249 250
```

251
> We strongly encourage you to leverage the other response serializers taking advantage of `Response` and `Result` types.
252

253 254 255
#### 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`.
256 257

```swift
258 259 260 261 262 263 264
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)")
    }
}
265 266
```

267
#### Response String Handler
M
Mattt Thompson 已提交
268

269
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`.
M
Mattt Thompson 已提交
270

271 272 273 274 275 276
```swift
Alamofire.request("https://httpbin.org/get").responseString { response in
    print("Success: \(response.result.isSuccess)")
    print("Response String: \(response.result.value)")
}
```
M
Mattt Thompson 已提交
277

278 279 280 281 282
> 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`.
283 284

```swift
285 286 287 288 289 290 291
Alamofire.request("https://httpbin.org/get").responseJSON { response in
    debugPrint(response)

    if let json = response.result.value {
        print("JSON: \(json)")
    }
}
292 293
```

294
> All JSON serialization is handled by the `JSONSerialization` API in the `Foundation` framework.
295

296 297 298
#### Chained Response Handlers

Response handlers can even be chained:
299 300

```swift
301 302 303 304 305 306 307
Alamofire.request("https://httpbin.org/get")
    .responseString { response in
        print("Response String: \(response.result.value)")
    }
    .responseJSON { response in
        print("Response JSON: \(response.result.value)")
    }
308 309
```

310 311 312 313 314
> 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

Reponse handlers by default are executed on the main dispatch queue. However, a custom dispatch queue can be provided instead.
M
Mattt Thompson 已提交
315 316

```swift
317 318 319 320 321
let utilityQueue = DispatchQueue.global(qos: .utility)

Alamofire.request("https://httpbin.org/get").responseJSON(queue: utilityQueue) { response in
    print("Executing response handler on utility queue")
}
M
Mattt Thompson 已提交
322 323
```

324 325 326 327 328
### 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
M
Mattt Thompson 已提交
329 330

```swift
331 332 333 334 335 336 337 338 339 340 341
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)
	    }
    }
M
Mattt Thompson 已提交
342 343
```

344
#### Automatic Validation
M
Mattt Thompson 已提交
345

346
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.
M
Mattt Thompson 已提交
347 348

```swift
349 350 351 352 353 354 355 356
Alamofire.request("https://httpbin.org/get").validate().responseJSON { response in
    switch response.result {
    case .Success:
        print("Validation Successful")
    case .Failure(let error):
        print(error)
    }
}
M
Mattt Thompson 已提交
357 358
```

359 360 361 362 363 364
### 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.

M
Mattt Thompson 已提交
365 366
### HTTP Methods

367
The `HTTPMethod` enumeration lists the HTTP methods defined in [RFC 7231 §4.3](http://tools.ietf.org/html/rfc7231#section-4.3):
M
Mattt Thompson 已提交
368 369

```swift
370 371 372 373 374 375 376 377 378 379
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"
M
Mattt Thompson 已提交
380 381 382
}
```

383
These values can be passed as the `method` argument to the `Alamofire.request` API:
M
Mattt Thompson 已提交
384 385

```swift
386
Alamofire.request("https://httpbin.org/get") // method defaults to `.get`
M
Mattt Thompson 已提交
387

388 389 390
Alamofire.request("https://httpbin.org/post", method: .post)
Alamofire.request("https://httpbin.org/put", method: .put)
Alamofire.request("https://httpbin.org/delete", method: .delete)
M
Mattt Thompson 已提交
391 392
```

393 394 395 396 397 398 399 400 401 402 403 404 405
> 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.
M
Mattt Thompson 已提交
406

407 408 409
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
M
Mattt Thompson 已提交
410 411

```swift
412 413 414 415 416 417 418
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))

T
tmnb 已提交
419
// https://httpbin.org/get?foo=bar
M
Mattt Thompson 已提交
420 421
```

422
##### POST Request With URL-Encoded Parameters
M
Mattt Thompson 已提交
423 424

```swift
425
let parameters: Parameters = [
M
Mattt Thompson 已提交
426 427 428 429 430 431 432 433 434
    "foo": "bar",
    "baz": ["a", 1],
    "qux": [
        "x": 1,
        "y": 2,
        "z": 3
    ]
]

435 436 437 438 439
// 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)

M
Mattt Thompson 已提交
440
// HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3
M
Mattt Thompson 已提交
441 442
```

443
#### JSON Encoding
M
Mattt Thompson 已提交
444

445 446 447
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
M
Mattt Thompson 已提交
448

M
Mattt Thompson 已提交
449
```swift
450 451 452 453 454 455
let parameters: Parameters = [
    "foo": [1,2,3],
    "bar": [
        "baz": "qux"
    ]
]
M
Mattt Thompson 已提交
456

457 458 459 460 461
// 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"}}
M
Mattt Thompson 已提交
462 463
```

464 465 466
#### 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`.
M
Mattt Thompson 已提交
467

468 469 470
#### 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`.
M
Mattt Thompson 已提交
471 472

```swift
473 474
struct JSONStringArrayEncoding: ParameterEncoding {
	private let array: [String]
M
Mattt Thompson 已提交
475

476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
    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
    }
}
M
Mattt Thompson 已提交
494 495
```

496 497 498
#### Manual Parameter Encoding of a URLRequest

The `ParameterEncoding` APIs can be used outside of making network requests.
M
Mattt Thompson 已提交
499 500

```swift
501 502
let url = URL(string: "https://httpbin.org/get")!
var urlRequest = URLRequest(url: url)
M
Mattt Thompson 已提交
503

504 505
let parameters: Parameters = ["foo": "bar"]
let encodedURLRequest = try URLEncoding.queryString.encode(urlRequest, with: parameters)
M
Mattt Thompson 已提交
506 507
```

508 509 510 511 512
### HTTP Headers

Adding a custom HTTP header to a `Request` is supported directly in the global `request` method. This makes it easy to attach HTTP headers to a `Request` that can be constantly changing.

```swift
513
let headers: HTTPHeaders = [
F
fewspider 已提交
514
    "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
515
    "Accept": "application/json"
516 517
]

518 519 520
Alamofire.request("https://httpbin.org/headers", headers: headers).responseJSON { response in
    debugPrint(response)
}
521 522
```

523
> 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.
524

525
The default Alamofire `SessionManager` provides a default set of headers for every `Request`. These include:
526

527 528 529
- `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 9.3.0) Alamofire/3.4.2`, per [RFC 7231 §5.5.3](https://tools.ietf.org/html/rfc7231#section-5.5.3).
530

531
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.
M
Mattt Thompson 已提交
532

533
### Authentication
M
Mattt Thompson 已提交
534

535
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).
M
Mattt Thompson 已提交
536

537
**Supported Authentication Schemes**
M
Mattt Thompson 已提交
538

539 540 541 542
- [HTTP Basic](http://en.wikipedia.org/wiki/Basic_access_authentication)
- [HTTP Digest](http://en.wikipedia.org/wiki/Digest_access_authentication)
- [Kerberos](http://en.wikipedia.org/wiki/Kerberos_%28protocol%29)
- [NTLM](http://en.wikipedia.org/wiki/NT_LAN_Manager)
M
Mattt Thompson 已提交
543

544 545 546
#### HTTP Basic Authentication

The `authenticate` method on a `Request` will automatically provide a `URLCredential` to a `URLAuthenticationChallenge` when appropriate:
M
Mattt Thompson 已提交
547 548

```swift
549 550 551 552 553 554 555 556
let user = "user"
let password = "password"

Alamofire.request("https://httpbin.org/basic-auth/\(user)/\(password)")
    .authenticate(user: user, password: password)
    .responseJSON { response in
        debugPrint(response)
    }
M
Mattt Thompson 已提交
557 558
```

559
Depending upon your server implementation, an `Authorization` header may also be appropriate:
M
Mattt Thompson 已提交
560 561

```swift
562 563 564 565 566 567 568 569
let user = "user"
let password = "password"

var headers: HTTPHeaders = [:]

if let authorizationHeader = Request.authorizationHeader(user: user, password: password) {
    headers[authorizationHeader.key] = authorizationHeader.value
}
570

571 572 573 574
Alamofire.request("https://httpbin.org/basic-auth/user/password", headers: headers)
    .responseJSON { response in
        debugPrint(response)
    }
M
Mattt Thompson 已提交
575 576
```

577
#### Authentication with URLCredential
578 579

```swift
580 581 582 583 584 585 586 587 588
let user = "user"
let password = "password"

let credential = URLCredential(user: user, password: password, persistence: .forSession)

Alamofire.request("https://httpbin.org/basic-auth/\(user)/\(password)")
    .authenticate(usingCredential: credential)
    .responseJSON { response in
        debugPrint(response)
589 590 591
    }
```

592
> 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.
M
Mattt Thompson 已提交
593

594
### Downloading Data to a File
M
Mattt Thompson 已提交
595

596
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 download 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.
M
Mattt Thompson 已提交
597

598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
```swift
Alamofire.download("https://httpbin.org/image/png").responseData { response in
	if let data = response.result.value {
	    let image = UIImage(data: data)
	}
}
```

> The `Alamofire.download` APIs should also be used if you need to download data while your app is in the background. For more information, please see the [Session Manager Configurations](#session-manager-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.
M
Mattt Thompson 已提交
614 615

```swift
616 617 618
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
	let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
	let fileURL = documentsURL.appendPathComponent("pig.png")
M
Mattt Thompson 已提交
619

620 621 622 623 624 625 626 627 628
    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)
	}
629
}
M
Mattt Thompson 已提交
630 631
```

632
You can also use the suggested download destination API.
M
Mattt Thompson 已提交
633 634

```swift
635 636
let destination = DownloadRequest.suggestedDownloadDestination(directory: .documentDirectory)
Alamofire.download("https://httpbin.org/image/png", to: destination)
637
```
M
Mattt Thompson 已提交
638

639 640 641
#### Download Progress

Many times it can be helpful to report download progress to the user. Any `DownloadRequest` can report download progress using the `downloadProgress` APIs.
M
Mattt Thompson 已提交
642 643

```swift
644 645 646 647 648 649 650 651 652 653
// Reports Progress with `Progress` instance
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)
    	}
    }
654

655 656 657 658 659 660 661 662 663 664
// Reports Progress with `Int64	` Values
Alamofire.download("https://httpbin.org/image/png")
    .downloadProgress { bytesRead, totalBytesReceived, totalBytesExpectedToRead in
        print("Download Progress: \(bytesRead), \(totalBytesReceived), \(totalBytesExpectedToRead) bytes")
    }
    .responseData { response in
    	if let data = response.result.value {
	        let image = UIImage(data: data)
    	}
    }
M
Mattt Thompson 已提交
665 666
```

667
Both of the `downloadProgress` APIs also take a `queue` parameter which defines which `DispatchQueue` the download progress closure should be called on.
668 669

```swift
670 671 672 673 674 675 676 677 678 679 680 681
// Reports progress on the utility queue
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)
    	}
    }
682 683
```

684 685 686
#### 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.
687 688

```swift
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
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(resourceWithin: 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
        	}
        }
719 720 721 722
    }
}
```

723
### Uploading Data to a Server
M
Mattt Thompson 已提交
724

725
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.
M
Mattt Thompson 已提交
726

727
> 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.
M
Mattt Thompson 已提交
728

729
#### Uploading Data
730

M
Mattt Thompson 已提交
731
```swift
732
let imageData = UIPNGRepresentation(image)!
M
Mattt Thompson 已提交
733

734 735 736
Alamofire.upload(imageData, to: "https://httpbin.org/post").responseJSON { response in
    debugPrint(response)
}
M
Mattt Thompson 已提交
737 738
```

739
#### Uploading a File
740 741

```swift
742
let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov")
743

744 745 746 747
Alamofire.upload(fileURL, to: "https://httpbin.org/post").responseJSON { response in
    debugPrint(response)
}
```
748

749
#### Uploading Multipart Form Data
750

751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
```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)
    	}
    }
)
769 770
```

771 772 773
#### 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.
M
Mattt Thompson 已提交
774 775

```swift
776
let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov")
M
Mattt Thompson 已提交
777

778 779 780 781 782 783 784 785 786 787 788
// Reports Progress with `Progress` instance
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)
    }
M
Mattt Thompson 已提交
789

790 791 792 793 794 795 796 797 798 799 800
// Reports Progress with `Int64	` Values
Alamofire.upload(fileURL, to: "https://httpbin.org/post")
    .uploadProgress { bytesSent, totalBytesSent, totalBytesExpectedToSend in // main queue by default
        print("Upload Progress: \(bytesSent), \(totalBytesSent), \(totalBytesExpectedToSend) bytes")
    }
    .downloadProgress { bytesRead, totalBytesReceived, totalBytesExpectedToRead in // main queue by default
        print("Download Progress: \(bytesRead), \(totalBytesReceived), \(totalBytesExpectedToRead) bytes")
    }
    .responseJSON { response in
        debugPrint(response)
    }
M
Mattt Thompson 已提交
801 802
```

803 804 805
### Statistical Metrics

#### Timeline
806

807
Alamofire collects timings throughout the lifecycle of a `Request` and creates a `Timeline` object exposed as a property on all response types.
808 809

```swift
810 811 812
Alamofire.request("https://httpbin.org/get").responseJSON { response in
    print(response.timeline)
}
813 814 815 816 817 818 819 820 821
```

The above reports the following `Timeline` info:

- `Latency`: 0.428 seconds
- `Request Duration`: 0.428 seconds
- `Serialization Duration`: 0.001 seconds
- `Total Duration`: 0.429 seconds

822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
#### URL Session Task Metrics

In iOS and tvOS 10 and macOS 10.12, Apple introduced the new [URLSessionTaskMetrics](https://developer.apple.com/reference/foundation/urlsessiontaskmetrics) APIs. The task metrics encapsulate some fantastic statistical information about the request and response execution. The API is very similar to the `Timeline`, but provides many more statistics that Alamofire doesn't have access to compute. The metrics can be accessed through any response type.

```swift
Alamofire.request("https://httpbin.org/get").responseJSON { response in
	print(response.metrics)
}
```

It's important to note that these APIs are only available on iOS and tvOS 10 and macOS 10.12. Therefore, depending on your deployment target, you may need to use these inside availability checks:

```swift
Alamofire.request("https://httpbin.org/get").responseJSON { response in
    if #available(iOS 10.0. *) {
		print(response.metrics)
    }
}
```

### cURL Command Output

Debugging platform issues can be frustrating. Thankfully, Alamofire `Request` objects conform to both the `CustomStringConvertible` and `CustomDebugStringConvertible` protocols to provide some VERY helpful debugging tools.

#### CustomStringConvertible
M
Mattt Thompson 已提交
847 848

```swift
849
let request = Alamofire.request("https://httpbin.org/ip")
M
Mattt Thompson 已提交
850

851
print(request)
T
tmnb 已提交
852
// GET https://httpbin.org/ip (200)
M
Mattt Thompson 已提交
853 854
```

855
#### CustomDebugStringConvertible
M
Mattt Thompson 已提交
856 857

```swift
858
let request = Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"])
859
debugPrint(request)
M
Mattt Thompson 已提交
860 861
```

862
Outputs:
M
Mattt Thompson 已提交
863

864
```bash
M
Mattt Thompson 已提交
865
$ curl -i \
866 867
	-H "User-Agent: Alamofire/4.0.0" \
	-H "Accept-Encoding: gzip;q=1.0, compress;q=0.5" \
M
Mattt Thompson 已提交
868
	-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" \
T
tmnb 已提交
869
	"https://httpbin.org/get?foo=bar"
M
Mattt Thompson 已提交
870 871
```

M
Mattt Thompson 已提交
872 873 874
---

## Advanced Usage
M
Mattt Thompson 已提交
875

876
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.
M
Mattt Thompson 已提交
877

M
Mattt Thompson 已提交
878
**Recommended Reading**
M
Mattt Thompson 已提交
879

M
Mattt Thompson 已提交
880
- [URL Loading System Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html)
881 882 883
- [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)
M
Mattt Thompson 已提交
884

885
### Session Manager
M
Mattt Thompson 已提交
886

887
Top-level convenience methods like `Alamofire.request` use a default instance of `Alamofire.SessionManager`, which is configured with the default `URLSessionConfiguration`.
M
Mattt Thompson 已提交
888 889 890 891

As such, the following two statements are equivalent:

```swift
892
Alamofire.request("https://httpbin.org/get")
M
Mattt Thompson 已提交
893 894 895
```

```swift
896 897
let sessionManager = Alamofire.SessionManager.default
sessionManager.request("https://httpbin.org/get")
M
Mattt Thompson 已提交
898 899
```

900
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`).
M
Mattt Thompson 已提交
901

902
#### Creating a Session Manager with Default Configuration
M
Mattt Thompson 已提交
903 904

```swift
905 906
let configuration = URLSessionConfiguration.default
let sessionManager = Alamofire.SessionManager(configuration: configuration)
M
Mattt Thompson 已提交
907 908
```

909
#### Creating a Session Manager with Background Configuration
M
Mattt Thompson 已提交
910 911

```swift
912 913
let configuration = URLSessionConfiguration.background(withIdentifier: "com.example.app.background")
let sessionManager = Alamofire.SessionManager(configuration: configuration)
M
Mattt Thompson 已提交
914 915
```

916
#### Creating a Session Manager with Ephemeral Configuration
M
Mattt Thompson 已提交
917 918

```swift
919 920
let configuration = URLSessionConfiguration.ephemeral
let sessionManager = Alamofire.SessionManager(configuration: configuration)
M
Mattt Thompson 已提交
921 922
```

923
#### Modifying the Session Configuration
M
Mattt Thompson 已提交
924 925

```swift
926
var defaultHeaders = Alamofire.SessionManager.default.defaultHTTPHeaders
M
Mattt Thompson 已提交
927 928
defaultHeaders["DNT"] = "1 (Do Not Track Enabled)"

929 930
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = defaultHeaders
M
Mattt Thompson 已提交
931

932
let sessionManager = Alamofire.SessionManager(configuration: configuration)
M
Mattt Thompson 已提交
933 934
```

935
> 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.
M
Mattt Thompson 已提交
936

937
### Session Delegate
M
Mattt Thompson 已提交
938

939
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.
940

941
#### Override Closures
942

943
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:
944 945

```swift
946 947
/// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`.
open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))?
948

949 950
/// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`.
open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)?
951

952 953
/// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`.
open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)?
954

955 956
/// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`.
open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)?
957 958
```

959 960
The following is a short example of how to use the `taskWillPerformHTTPRedirection` to avoid following redirects to any `apple.com` domains.

961
```swift
962 963
let sessionManager = Alamofire.SessionManager(configuration: URLSessionConfiguration.default)
let delegate: Alamofire.SessionDelegate = sessionManager.delegate
964

965 966 967 968 969 970 971 972 973
delegate.taskWillPerformHTTPRedirection = { session, task, response, request in
    var finalRequest = request

    if
        let originalRequest = task.originalRequest,
        let urlString = originalRequest.url?.urlString,
        urlString.contains("apple.com")
    {
        finalRequest = originalRequest
974
    }
975 976

    return finalRequest
977 978 979
}
```

980
#### Subclassing
981

982
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.
983 984

```swift
985 986 987 988 989 990 991 992 993
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)")
994

995 996 997 998 999 1000 1001
        super.urlSession(
            session,
            task: task,
            willPerformHTTPRedirection: response,
            newRequest: request,
            completionHandler: completionHandler
        )
1002 1003
    }
}
1004
```
1005

1006
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.
1007

1008
> 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.
1009

1010
### Request
1011

1012
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.
1013

1014
Each subclass has specialized methods such as `authenticate`, `validate`, `responseJSON` and `uploadProgress` that each return the caller instance in order to facilitate method chaining.
1015

1016
Requests can be suspended, resumed and cancelled:
1017

1018 1019 1020
- `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.
1021

1022
### Routing Requests
M
Mattt Thompson 已提交
1023

1024
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 `URLStringConvertible` and `URLRequestConvertible` protocols along with the `Router` design pattern are here to help.
M
Mattt Thompson 已提交
1025

1026 1027 1028
#### URLStringConvertible

Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to construct URL requests internally. `String`, `URL`, and `URLComponents` conform to `URLStringConvertible` by default, allowing any of them to be passed as `urlString` parameters to the `request`, `upload`, and `download` methods:
1029

1030 1031 1032
```swift
let urlString = "https://httpbin.org/post"
Alamofire.request(urlString, method: .post)
1033

1034 1035
let url = URL(string: urlString)!
Alamofire.request(url, method: .post)
1036

1037
let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true)
1038 1039 1040 1041
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.
M
Mattt Thompson 已提交
1042

1043
##### Type-Safe Routing
M
Mattt Thompson 已提交
1044 1045

```swift
1046
extension User: URLStringConvertible {
1047
    static let baseURLString = "https://example.com"
M
Mattt Thompson 已提交
1048

1049
    var urlString: String {
1050
        return User.baseURLString + "/users/\(username)/"
M
Mattt Thompson 已提交
1051 1052 1053 1054 1055
    }
}
```

```swift
1056
let user = User(username: "mattt")
1057
Alamofire.request(user) // https://example.com/users/mattt
M
Mattt Thompson 已提交
1058 1059
```

1060
#### URLRequestConvertible
M
Mattt Thompson 已提交
1061

1062
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(resource:)`, `upload(resource:)`, and `download(resource:)` methods directly (this is the recommended way to specify custom HTTP body for individual requests):
1063 1064

```swift
1065 1066 1067
let url = URL(string: "https://httpbin.org/post")!
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
1068 1069

let parameters = ["foo": "bar"]
1070 1071

do {
1072
    urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
1073 1074 1075 1076
} catch {
    // No-op
}

1077
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
1078

1079
Alamofire.request(resource: urlRequest)
1080
```
M
Mattt Thompson 已提交
1081

1082
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.
M
Mattt Thompson 已提交
1083

1084
##### API Parameter Abstraction
M
Mattt Thompson 已提交
1085 1086 1087

```swift
enum Router: URLRequestConvertible {
1088
    case search(query: String, page: Int)
M
Mattt Thompson 已提交
1089

1090 1091
    static let baseURLString = "https://example.com"
    static let perPage = 50
M
Mattt Thompson 已提交
1092 1093 1094

    // MARK: URLRequestConvertible

1095 1096
    var urlRequest: URLRequest {
        let result: (path: String, parameters: Parameters) = {
M
Mattt Thompson 已提交
1097
            switch self {
1098
            case let .search(query, page) where page > 0:
M
Mattt Thompson 已提交
1099
                return ("/search", ["q": query, "offset": Router.perPage * page])
1100
            case let .search(query, _):
M
Mattt Thompson 已提交
1101 1102 1103 1104
                return ("/search", ["q": query])
            }
        }()

1105 1106
        let url = URL(string: Router.baseURLString)!
        let urlRequest = URLRequest(url: url.appendingPathComponent(result.path))
M
Mattt Thompson 已提交
1107

1108 1109 1110 1111 1112
        do {
            return try URLEncoding.default.encode(urlRequest, with: result.parameters)
        } catch {
            return urlRequest
        }
M
Mattt Thompson 已提交
1113 1114 1115 1116
    }
}
```

1117
```swift
1118
Alamofire.request(Router.search(query: "foo bar", page: 1)) // ?q=foo%20bar&offset=50
1119 1120
```

1121
##### CRUD & Authorization
M
Mattt Thompson 已提交
1122 1123

```swift
1124 1125
import Alamofire

M
Mattt Thompson 已提交
1126
enum Router: URLRequestConvertible {
1127 1128 1129 1130
    case createUser(parameters: Parameters)
    case readUser(username: String)
    case updateUser(username: String, parameters: Parameters)
    case destroyUser(username: String)
M
Mattt Thompson 已提交
1131

1132
    static let baseURLString = "https://example.com"
M
Mattt Thompson 已提交
1133

1134
    var method: HTTPMethod {
M
Mattt Thompson 已提交
1135
        switch self {
1136 1137 1138 1139 1140 1141 1142 1143
        case .createUser:
            return .post
        case .readUser:
            return .get
        case .updateUser:
            return .put
        case .destroyUser:
            return .delete
M
Mattt Thompson 已提交
1144 1145 1146 1147 1148
        }
    }

    var path: String {
        switch self {
1149
        case .createUser:
M
Mattt Thompson 已提交
1150
            return "/users"
1151
        case .readUser(let username):
M
Mattt Thompson 已提交
1152
            return "/users/\(username)"
1153
        case .updateUser(let username, _):
M
Mattt Thompson 已提交
1154
            return "/users/\(username)"
1155
        case .destroyUser(let username):
M
Mattt Thompson 已提交
1156 1157 1158 1159 1160 1161
            return "/users/\(username)"
        }
    }

    // MARK: URLRequestConvertible

1162 1163
    var urlRequest: URLRequest {
        let url = URL(string: Router.baseURLString)!
M
Mattt Thompson 已提交
1164

1165 1166
        var urlRequest = URLRequest(url: url.appendingPathComponent(path))
        urlRequest.httpMethod = method.rawValue
M
Mattt Thompson 已提交
1167

1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
        do {
            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
            }
        } catch {
            // No-op
M
Mattt Thompson 已提交
1179
        }
1180 1181

        return urlRequest
M
Mattt Thompson 已提交
1182 1183 1184 1185
    }
}
```

1186 1187 1188 1189
```swift
Alamofire.request(Router.ReadUser("mattt")) // GET /users/mattt
```

1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
### 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) -> URLRequest {
	    var urlRequest = urlRequest

	    if urlRequest.urlString.hasPrefix("https://httpbin.org") {
		    urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization")
	    }

	    return urlRequest
	}
}
1218
```
1219

1220
```swift
1221 1222 1223
let sessionManager = SessionManager()
sessionManager.adapter = AccessTokenAdapter(accessToken: "1234")

1224
sessionManager.request("https://httpbin.org/get")
1225 1226 1227 1228
```

#### RequestRetrier

1229
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.
1230

1231
> **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.
1232 1233 1234

> 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.

1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
```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

1267 1268 1269 1270 1271
    func adapt(_ urlRequest: URLRequest) -> URLRequest {
        if let url = urlRequest.url, url.urlString.hasPrefix(baseURLString) {
            var urlRequest = urlRequest
            urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization")
            return urlRequest
1272 1273 1274 1275 1276 1277 1278
        }

        return urlRequest
    }

    // MARK: - RequestRetrier

1279
    func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) {
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
        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

1307
    private func refreshTokens(completion: @escaping RefreshCompletion) {
1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
        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"
        ]

1321 1322 1323
        sessionManager.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default)
            .responseJSON { [weak self] response in
                guard let strongSelf = self else { return }
1324

1325 1326 1327 1328 1329
                if let json = response.result.value as? [String: String] {
                    completion(true, json["access_token"], json["refresh_token"])
                } else {
                    completion(false, nil, nil)
                }
1330

1331 1332
                strongSelf.isRefreshing = false
            }
1333 1334
    }
}
1335
```
1336

1337
```swift
1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
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"

1353
sessionManager.request(urlString).validate().responseJSON { response in
1354 1355 1356 1357 1358 1359
    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. 

1360
> If you needed them to execute in the same order they were created, you could sort them by their task identifiers. 
1361 1362 1363 1364 1365

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.

1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
### Custom Response Serialization

#### Handling Errors

Before implementing custom response serializers or object serialization methods, it's important to be prepared to handle any errors that may occur. The recommended way of handling these errors is by creating your own enumeration that conforms to `Error`. 

For example, here's a simple `BackendError` which will be used in later examples:

```swift
enum BackendError: Error {
    case network(error: Error)
    case dataSerialization(reason: String)
    case jsonSerialization(error: Error)
    case objectSerialization(reason: String)
    case xmlSerialization(error: Error)
}
```

#### 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<ONOXMLDocument> {
        return DataResponseSerializer { request, response, data, error in
            guard error == nil else { return .failure(BackendError.network(error: error!)) }

            guard let validData = data else {
                return .failure(BackendError.dataSerialization(reason: "Input data was nil."))
            }

            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<ONOXMLDocument>) -> 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<T: ResponseObjectSerializable>(
        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 jsonResponseSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments)
            let result = jsonResponseSerializer.serializeResponse(request, response, data, error)

            switch result {
            case .success(let value):
                if let response = response, let responseObject = T(response: response, representation: value) {
                    return .success(responseObject)
                } else {
                    return .failure(BackendError.objectSerialization(reason: "JSON could not be serialized: \(value)"))
                }
            case .failure(let error):
                return .failure(BackendError.jsonSerialization(error: error))
            }
        }

        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<User>) 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<T: ResponseCollectionSerializable>(
        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, error)

            switch result {
            case .success(let value):
                if let response = response {
                    return .success(T.collection(from: response, withRepresentation: value))
                } else {
                    let reason = "Response collection could not be serialized due to nil response"
                    return .failure(BackendError.objectSerialization(reason: reason))
                }
            case .failure(let error):
                return .failure(BackendError.jsonSerialization(error: error))
            }
        }

        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)") }
    }
}
```

1581 1582 1583 1584 1585 1586 1587 1588 1589
### 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.

```swift
1590
let serverTrustPolicy = ServerTrustPolicy.pinCertificates(
1591 1592 1593 1594 1595 1596 1597 1598
    certificates: ServerTrustPolicy.certificatesInBundle(),
    validateCertificateChain: true,
    validateHost: true
)
```

There are many different cases of server trust evaluation giving you complete control over the validation process:

1599 1600 1601 1602 1603
* `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.
1604 1605 1606 1607 1608 1609 1610

#### Server Trust Policy Manager

The `ServerTrustPolicyManager` is responsible for storing an internal mapping of server trust policies to a particular host. This allows Alamofire to evaluate each host against a different server trust policy. 

```swift
let serverTrustPolicies: [String: ServerTrustPolicy] = [
1611
    "test.example.com": .pinCertificates(
1612 1613 1614 1615
        certificates: ServerTrustPolicy.certificatesInBundle(),
        validateCertificateChain: true,
        validateHost: true
    ),
1616
    "insecure.expired-apis.com": .disableEvaluation
1617 1618
]

1619
let sessionManager = SessionManager(
1620 1621 1622 1623
    serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
)
```

1624
> Make sure to keep a reference to the new `SessionManager` instance, otherwise your requests will all get cancelled when your `sessionManager` is deallocated.
1625

1626 1627 1628 1629 1630 1631 1632 1633 1634
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.

1635 1636 1637 1638 1639 1640
##### Subclassing Server Trust Policy Manager

If you find yourself needing more flexible server trust policy matching behavior (i.e. wildcarded domains), then subclass the `ServerTrustPolicyManager` and override the `serverTrustPolicyForHost` method with your own custom implementation.

```swift
class CustomServerTrustPolicyManager: ServerTrustPolicyManager {
1641
    override func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? {
1642 1643 1644 1645 1646 1647 1648 1649 1650
        var policy: ServerTrustPolicy?

        // Implement your custom domain matching behavior...

        return policy
    }
}
```

1651 1652
#### Validating the Host

1653
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.
1654 1655 1656 1657 1658

> It is recommended that `validateHost` always be set to `true` in production environments.

#### Validating the Certificate Chain

D
dersvenhesse 已提交
1659
Pinning certificates and public keys both have the option of validating the certificate chain using the `validateCertificateChain` parameter. By setting this value to `true`, the full certificate chain will be evaluated in addition to performing a byte equality check against the pinned certificates or public keys. A value of `false` will skip the certificate chain validation, but will still perform the byte equality check.
1660 1661 1662 1663 1664

There are several cases where it may make sense to disable certificate chain validation. The most common use cases for disabling validation are self-signed and expired certificates. The evaluation would always fail in both of these cases, but the byte equality check will still ensure you are receiving the certificate you expect from the server.

> It is recommended that `validateCertificateChain` always be set to `true` in production environments.

1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
#### App Transport Security

With the addition of App Transport Security (ATS) in iOS 9, it is possible that using a custom `ServerTrustPolicyManager` with several `ServerTrustPolicy` objects will have no effect. If you continuously see `CFNetwork SSLHandshake failed (-9806)` errors, you have probably run into this problem. Apple's ATS system overrides the entire challenge system unless you configure the ATS settings in your app's plist to disable enough of it to allow your app to evaluate the server trust.

If you run into this problem (high probability with self-signed certificates), you can work around this issue by adding the following to your `Info.plist`.

```xml
<dict>
	<key>NSAppTransportSecurity</key>
	<dict>
		<key>NSExceptionDomains</key>
		<dict>
			<key>example.com</key>
			<dict>
				<key>NSExceptionAllowsInsecureHTTPLoads</key>
				<true/>
				<key>NSExceptionRequiresForwardSecrecy</key>
				<false/>
				<key>NSIncludesSubdomains</key>
				<true/>
1685 1686 1687
				<!-- Optional: Specify minimum TLS version -->
				<key>NSTemporaryExceptionMinimumTLSVersion</key>
				<string>TLSv1.2</string>
1688 1689 1690 1691 1692 1693
			</dict>
		</dict>
	</dict>
</dict>
```

1694
Whether you need to set the `NSExceptionRequiresForwardSecrecy` to `NO` depends on whether your TLS connection is using an allowed cipher suite. In certain cases, it will need to be set to `NO`. The `NSExceptionAllowsInsecureHTTPLoads` MUST be set to `YES` in order to allow the `SessionDelegate` to receive challenge callbacks. Once the challenge callbacks are being called, the `ServerTrustPolicyManager` will take over the server trust evaluation. You may also need to specify the `NSTemporaryExceptionMinimumTLSVersion` if you're trying to connect to a host that only supports TLS versions less than `1.2`.
1695 1696 1697

> It is recommended to always use valid certificates in production environments.

1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711
### Network Reachability

The `NetworkReachabilityManager` listens for reachability changes of hosts and addresses for both WWAN and WiFi network interfaces.

```swift
let manager = NetworkReachabilityManager(host: "www.apple.com")

manager?.listener = { status in
    print("Network Status Changed: \(status)")
}

manager?.startListening()
```

1712 1713
> Make sure to remember to retain the `manager` in the above example, or no status changes will be reported.

1714 1715
There are some important things to remember when using network reachability to determine what to do next.

1716 1717 1718 1719 1720 1721
- **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."
1722 1723 1724

> It is recommended to check out [WWDC 2012 Session 706, "Networking Best Practices"](https://developer.apple.com/videos/play/wwdc2012-706/) for more info.

1725 1726
---

1727
## Open Radars
1728

1729
The following radars have some affect on the current implementation of Alamofire.
1730

1731 1732 1733 1734
- [`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`
1735

1736 1737 1738 1739 1740 1741
## FAQ

### What's the origin of the name Alamofire?

Alamofire is named after the [Alamo Fire flower](https://aggie-horticulture.tamu.edu/wildseed/alamofire.html), a hybrid variant of the Bluebonnet, the official state flower of Texas.

1742 1743 1744 1745 1746 1747
### 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`.

1748
---
M
Mattt Thompson 已提交
1749

M
Mattt Thompson 已提交
1750
## Credits
M
Mattt Thompson 已提交
1751

1752 1753 1754 1755 1756
Alamofire is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). You can follow them on Twitter at [@AlamofireSF](https://twitter.com/AlamofireSF) for project updates and releases.

### Security Disclosure

If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker.
M
Mattt Thompson 已提交
1757

1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771
## 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 enthusiam 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.

<a href='https://pledgie.com/campaigns/31474'><img alt='Click here to lend your support to: Alamofire Software Foundation and make a donation at pledgie.com !' src='https://pledgie.com/campaigns/31474.png?skin_name=chrome' border='0' ></a>

M
Mattt Thompson 已提交
1772 1773
## License

M
Mattt Thompson 已提交
1774
Alamofire is released under the MIT license. See LICENSE for details.