README.md 59.5 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)](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

## Features

M
- [x]  
Mattt Thompson 已提交
13 14
- [x] Chainable Request / Response methods
- [x] URL / JSON / plist Parameter Encoding
15
- [x] Upload File / Data / Stream / MultipartFormData
M
- [x]  
Mattt Thompson 已提交
16 17 18
- [x] Download using Request or Resume data
- [x] Authentication with NSURLCredential
- [x] HTTP Response Validation
19
- [x] TLS Certificate and Public Key Pinning
M
- [x]  
Mattt Thompson 已提交
20 21 22
- [x] Progress Closure & NSProgress
- [x] cURL Debug Output
- [x] Comprehensive Unit Test Coverage
R
rojotek 已提交
23
- [x] [Complete Documentation](http://cocoadocs.org/docsets/Alamofire)
24

25 26 27 28 29
## 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.
30
* [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.
31

32 33
## Requirements

34
- iOS 9.0+ / Mac OS X 10.11+ / tvOS 9.0+ / watchOS 2.0+
35
- Xcode 8.0 beta 6+
36

37 38
## Migration Guides

39
- Alamofire 4.0 Migration Guide - COMING SOON!
40
- [Alamofire 3.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md)
41
- [Alamofire 2.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%202.0%20Migration%20Guide.md)
42

M
Mattt Thompson 已提交
43 44 45 46 47 48 49 50
## 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.

51 52
## Installation

53
> **Embedded frameworks require a minimum deployment target of iOS 8 or OS X Mavericks (10.9).**
M
Mattt Thompson 已提交
54
>
55
> 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.
56

57 58
### CocoaPods

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

```bash
62
$ gem install cocoapods
63 64
```

65 66
> CocoaPods 0.39.0+ is required to build Alamofire 3.0.0+.

67 68 69 70
To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`:

```ruby
source 'https://github.com/CocoaPods/Specs.git'
71
platform :ios, '9.0'
72
use_frameworks!
73

L
Luis Ferro 已提交
74 75 76
target '<Your Target Name>' do
    pod 'Alamofire', '~> 3.4'
end
77 78 79 80 81 82 83 84 85 86
```

Then, run the following command:

```bash
$ pod install
```

### Carthage

87
[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.
88 89 90 91 92 93 94 95 96 97 98

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
99
github "Alamofire/Alamofire" ~> 3.4
100 101
```

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

104 105 106 107
### Manually

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

108
#### Embedded Framework
109

110 111 112 113 114 115 116
- 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:
117 118 119 120 121

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

122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
- 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.

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

- And that's it!

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

142 143
---

M
Mattt Thompson 已提交
144 145
## Usage

M
Mattt Thompson 已提交
146
### Making a Request
M
Mattt Thompson 已提交
147 148

```swift
M
Mattt Thompson 已提交
149 150
import Alamofire

T
tmnb 已提交
151
Alamofire.request(.GET, "https://httpbin.org/get")
M
Mattt Thompson 已提交
152 153
```

M
Mattt Thompson 已提交
154
### Response Handling
M
Mattt Thompson 已提交
155 156

```swift
T
tmnb 已提交
157
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
158 159 160 161 162 163 164 165 166 167
         .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

             if let JSON = response.result.value {
                 print("JSON: \(JSON)")
             }
         }
M
Mattt Thompson 已提交
168 169
```

M
Mattt Thompson 已提交
170 171
> 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.

M
Mattt Thompson 已提交
172
> 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.
M
Mattt Thompson 已提交
173

174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
### 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)
         }
```

#### Automatic Validation

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

M
Mattt Thompson 已提交
206 207 208 209 210
### Response Serialization

**Built-in Response Methods**

- `response()`
211
- `responseData()`
M
Mattt Thompson 已提交
212 213 214 215
- `responseString(encoding: NSStringEncoding)`
- `responseJSON(options: NSJSONReadingOptions)`
- `responsePropertyList(options: NSPropertyListReadOptions)`

216
#### Response Handler
217 218

```swift
T
tmnb 已提交
219
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
220
         .validate()
221
         .response { request, response, data, error in
222 223 224 225 226 227 228
             print(request)
             print(response)
             print(data)
             print(error)
          }
```

S
Sergey Zolotarev 已提交
229
> 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.
230 231 232 233

#### Response Data Handler

```swift
T
tmnb 已提交
234
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
235
         .validate()
236 237 238 239 240 241 242
         .responseData { response in
             print(response.request)
             print(response.response)
             print(response.result)
          }
```

243
#### Response String Handler
M
Mattt Thompson 已提交
244 245

```swift
T
tmnb 已提交
246
Alamofire.request(.GET, "https://httpbin.org/get")
247
         .validate()
248 249 250
         .responseString { response in
             print("Success: \(response.result.isSuccess)")
             print("Response String: \(response.result.value)")
M
Mattt Thompson 已提交
251 252 253
         }
```

254
#### Response JSON Handler
M
Mattt Thompson 已提交
255 256

```swift
T
tmnb 已提交
257
Alamofire.request(.GET, "https://httpbin.org/get")
258
         .validate()
259 260
         .responseJSON { response in
             debugPrint(response)
M
Mattt Thompson 已提交
261 262 263
         }
```

M
Mattt Thompson 已提交
264 265 266 267 268
#### Chained Response Handlers

Response handlers can even be chained:

```swift
T
tmnb 已提交
269
Alamofire.request(.GET, "https://httpbin.org/get")
270
         .validate()
271 272
         .responseString { response in
             print("Response String: \(response.result.value)")
M
Mattt Thompson 已提交
273
         }
274 275
         .responseJSON { response in
             print("Response JSON: \(response.result.value)")
M
Mattt Thompson 已提交
276 277 278
         }
```

M
Mattt Thompson 已提交
279 280
### HTTP Methods

M
Mattt Thompson 已提交
281
`Alamofire.Method` lists the HTTP methods defined in [RFC 7231 §4.3](http://tools.ietf.org/html/rfc7231#section-4.3):
M
Mattt Thompson 已提交
282 283 284

```swift
public enum Method: String {
285
    case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT
M
Mattt Thompson 已提交
286 287 288 289 290 291
}
```

These values can be passed as the first argument of the `Alamofire.request` method:

```swift
T
tmnb 已提交
292
Alamofire.request(.POST, "https://httpbin.org/post")
M
Mattt Thompson 已提交
293

T
tmnb 已提交
294
Alamofire.request(.PUT, "https://httpbin.org/put")
M
Mattt Thompson 已提交
295

T
tmnb 已提交
296
Alamofire.request(.DELETE, "https://httpbin.org/delete")
M
Mattt Thompson 已提交
297 298
```

M
Mattt Thompson 已提交
299 300 301 302 303
### Parameters

#### GET Request With URL-Encoded Parameters

```swift
T
tmnb 已提交
304 305
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
// https://httpbin.org/get?foo=bar
M
Mattt Thompson 已提交
306 307 308
```

#### POST Request With URL-Encoded Parameters
M
Mattt Thompson 已提交
309 310 311 312 313 314 315 316 317 318 319 320

```swift
let parameters = [
    "foo": "bar",
    "baz": ["a", 1],
    "qux": [
        "x": 1,
        "y": 2,
        "z": 3
    ]
]

T
tmnb 已提交
321
Alamofire.request(.POST, "https://httpbin.org/post", parameters: parameters)
M
Mattt Thompson 已提交
322
// HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3
M
Mattt Thompson 已提交
323 324 325 326
```

### Parameter Encoding

M
Mattt Thompson 已提交
327
Parameters can also be encoded as JSON, Property List, or any custom format, using the `ParameterEncoding` enum:
M
Mattt Thompson 已提交
328

M
Mattt Thompson 已提交
329 330 331
```swift
enum ParameterEncoding {
    case URL
332
    case URLEncodedInURL
333
    case JSON
334 335
    case PropertyList(format: NSPropertyListFormat, options: NSPropertyListWriteOptions)
    case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?))
M
Mattt Thompson 已提交
336

337
    func encode(request: NSURLRequest, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?)
M
Mattt Thompson 已提交
338 339 340 341
    { ... }
}
```

A
Aaron Brager 已提交
342
- `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`)._
343
- `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.
M
Mattt Thompson 已提交
344 345 346 347
- `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.

M
Mattt Thompson 已提交
348 349 350
#### Manual Parameter Encoding of an NSURLRequest

```swift
T
tmnb 已提交
351
let URL = NSURL(string: "https://httpbin.org/get")!
352
var request = NSMutableURLRequest(URL: URL)
M
Mattt Thompson 已提交
353 354 355

let parameters = ["foo": "bar"]
let encoding = Alamofire.ParameterEncoding.URL
P
Petr Korolev 已提交
356
(request, _) = encoding.encode(request, parameters: parameters)
M
Mattt Thompson 已提交
357 358
```

M
Mattt Thompson 已提交
359
#### POST Request with JSON-encoded Parameters
M
Mattt Thompson 已提交
360 361

```swift
M
Mattt Thompson 已提交
362 363 364 365 366 367 368
let parameters = [
    "foo": [1,2,3],
    "bar": [
        "baz": "qux"
    ]
]

T
tmnb 已提交
369
Alamofire.request(.POST, "https://httpbin.org/post", parameters: parameters, encoding: .JSON)
M
Mattt Thompson 已提交
370
// HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}}
M
Mattt Thompson 已提交
371 372
```

373 374 375 376 377 378 379 380
### 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 = [
F
fewspider 已提交
381
    "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
382
    "Accept": "application/json"
383 384
]

T
tmnb 已提交
385
Alamofire.request(.GET, "https://httpbin.org/get", headers: headers)
386 387
         .responseJSON { response in
             debugPrint(response)
388 389 390
         }
```

M
Mattt Thompson 已提交
391
### Caching
M
Mattt Thompson 已提交
392

M
Mattt Thompson 已提交
393
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).
M
Mattt Thompson 已提交
394 395 396

### Uploading

M
Mattt Thompson 已提交
397
**Supported Upload Types**
M
Mattt Thompson 已提交
398 399 400 401

- File
- Data
- Stream
402
- MultipartFormData
M
Mattt Thompson 已提交
403 404 405 406

#### Uploading a File

```swift
407
let fileURL = NSBundle.mainBundle().URLForResource("Default", withExtension: "png")
T
tmnb 已提交
408
Alamofire.upload(.POST, "https://httpbin.org/post", file: fileURL)
M
Mattt Thompson 已提交
409 410
```

411
#### Uploading with Progress
M
Mattt Thompson 已提交
412 413

```swift
T
tmnb 已提交
414
Alamofire.upload(.POST, "https://httpbin.org/post", file: fileURL)
415
         .progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
416
             print(totalBytesWritten)
417 418 419

             // This closure is NOT called on the main queue for performance
             // reasons. To update your ui, dispatch to the main queue.
420
             dispatch_async(dispatch_get_main_queue()) {
421 422
                 print("Total bytes written on main queue: \(totalBytesWritten)")
             }
M
Mattt Thompson 已提交
423
         }
424
         .validate()
425 426
         .responseJSON { response in
             debugPrint(response)
M
Mattt Thompson 已提交
427
         }
M
Mattt Thompson 已提交
428 429
```

430 431 432 433 434
#### Uploading MultipartFormData

```swift
Alamofire.upload(
    .POST,
T
tmnb 已提交
435
    "https://httpbin.org/post",
436 437 438 439 440 441 442
    multipartFormData: { multipartFormData in
        multipartFormData.appendBodyPart(fileURL: unicornImageURL, name: "unicorn")
        multipartFormData.appendBodyPart(fileURL: rainbowImageURL, name: "rainbow")
    },
    encodingCompletion: { encodingResult in
    	switch encodingResult {
    	case .Success(let upload, _, _):
443 444
            upload.responseJSON { response in
                debugPrint(response)
445
            }
446
    	case .Failure(let encodingError):
447
    	    print(encodingError)
448 449 450 451 452
    	}
    }
)
```

M
Mattt Thompson 已提交
453 454
### Downloading

M
Mattt Thompson 已提交
455
**Supported Download Types**
M
Mattt Thompson 已提交
456 457 458 459 460 461 462

- Request
- Resume Data

#### Downloading a File

```swift
T
tmnb 已提交
463
Alamofire.download(.GET, "https://httpbin.org/stream/100") { temporaryURL, response in
464
    let fileManager = NSFileManager.defaultManager()
465 466
    let directoryURL = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
    let pathComponent = response.suggestedFilename
M
Mattt Thompson 已提交
467

468
    return directoryURL.URLByAppendingPathComponent(pathComponent!)
469
}
M
Mattt Thompson 已提交
470 471
```

M
Mattt Thompson 已提交
472
#### Using the Default Download Destination
M
Mattt Thompson 已提交
473 474

```swift
475
let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
T
tmnb 已提交
476
Alamofire.download(.GET, "https://httpbin.org/stream/100", destination: destination)
477
```
M
Mattt Thompson 已提交
478 479 480 481

#### Downloading a File w/Progress

```swift
T
tmnb 已提交
482
Alamofire.download(.GET, "https://httpbin.org/stream/100", destination: destination)
483
         .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
484
             print(totalBytesRead)
485 486 487

             // This closure is NOT called on the main queue for performance
             // reasons. To update your ui, dispatch to the main queue.
488
             dispatch_async(dispatch_get_main_queue()) {
489 490
                 print("Total bytes read on main queue: \(totalBytesRead)")
             }
M
Mattt Thompson 已提交
491
         }
492 493 494 495 496 497
         .response { _, _, _, error in
             if let error = error {
                 print("Failed with error: \(error)")
             } else {
                 print("Downloaded file successfully")
             }
M
Mattt Thompson 已提交
498 499 500
         }
```

501 502 503
#### Accessing Resume Data for Failed Downloads

```swift
T
tmnb 已提交
504
Alamofire.download(.GET, "https://httpbin.org/stream/100", destination: destination)
505
         .response { _, _, data, _ in
506
             if let
507
                 data = data,
508 509 510 511 512 513 514 515 516 517 518 519
                 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
T
tmnb 已提交
520
let download = Alamofire.download(.GET, "https://httpbin.org/stream/100", destination: destination)
521
download.response { _, _, _, _ in
522 523
    if let
        resumeData = download.resumeData,
524
        resumeDataString = NSString(data: resumeData, encoding: NSUTF8StringEncoding)
525 526 527 528 529 530 531 532
    {
        print("Resume Data: \(resumeDataString)")
    } else {
        print("Resume Data was empty")
    }
}
```

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

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

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

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

#### HTTP Basic Authentication

546 547
The `authenticate` method on a `Request` will automatically provide an `NSURLCredential` to an `NSURLAuthenticationChallenge` when appropriate:

M
Mattt Thompson 已提交
548 549 550 551 552
```swift
let user = "user"
let password = "password"

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

559 560 561 562 563 564 565
Depending upon your server implementation, an `Authorization` header may also be appropriate:

```swift
let user = "user"
let password = "password"

let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
566
let base64Credentials = credentialData.base64EncodedStringWithOptions([])
567 568 569

let headers = ["Authorization": "Basic \(base64Credentials)"]

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

M
Mattt Thompson 已提交
576
#### Authentication with NSURLCredential
M
Mattt Thompson 已提交
577 578 579 580 581

```swift
let user = "user"
let password = "password"

582
let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)
M
Mattt Thompson 已提交
583 584

Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)")
M
Mattt Thompson 已提交
585
         .authenticate(usingCredential: credential)
586 587
         .responseJSON { response in
             debugPrint(response)
M
Mattt Thompson 已提交
588
         }
M
Mattt Thompson 已提交
589 590
```

591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
### Timeline

Alamofire collects timings throughout the lifecycle of a `Request` and creates a `Timeline` object exposed as a property on a `Response`.

```swift
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
         .validate()
         .responseJSON { response in
             print(response.timeline)
         }
```

The above reports the following `Timeline` info:

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

M
Mattt Thompson 已提交
610 611 612
### Printable

```swift
T
tmnb 已提交
613
let request = Alamofire.request(.GET, "https://httpbin.org/ip")
M
Mattt Thompson 已提交
614

615
print(request)
T
tmnb 已提交
616
// GET https://httpbin.org/ip (200)
M
Mattt Thompson 已提交
617 618 619 620 621
```

### DebugPrintable

```swift
T
tmnb 已提交
622
let request = Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
M
Mattt Thompson 已提交
623

624
debugPrint(request)
M
Mattt Thompson 已提交
625 626 627 628
```

#### Output (cURL)

629
```bash
M
Mattt Thompson 已提交
630 631 632 633
$ curl -i \
	-H "User-Agent: Alamofire" \
	-H "Accept-Encoding: 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" \
T
tmnb 已提交
634
	"https://httpbin.org/get?foo=bar"
M
Mattt Thompson 已提交
635 636
```

M
Mattt Thompson 已提交
637 638 639
---

## Advanced Usage
M
Mattt Thompson 已提交
640

M
Mattt Thompson 已提交
641
> Alamofire is built on `NSURLSession` and the Foundation URL Loading System. To make the most of
M
Mattt Thompson 已提交
642
this framework, it is recommended that you be familiar with the concepts and capabilities of the underlying networking stack.
M
Mattt Thompson 已提交
643

M
Mattt Thompson 已提交
644
**Recommended Reading**
M
Mattt Thompson 已提交
645

M
Mattt Thompson 已提交
646 647 648 649 650 651 652 653 654 655 656 657
- [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)

### Manager

Top-level convenience methods like `Alamofire.request` use a shared instance of `Alamofire.Manager`, which is configured with the default `NSURLSessionConfiguration`.

As such, the following two statements are equivalent:

```swift
T
tmnb 已提交
658
Alamofire.request(.GET, "https://httpbin.org/get")
M
Mattt Thompson 已提交
659 660 661 662
```

```swift
let manager = Alamofire.Manager.sharedInstance
T
tmnb 已提交
663
manager.request(NSURLRequest(URL: NSURL(string: "https://httpbin.org/get")!))
M
Mattt Thompson 已提交
664 665
```

M
Mattt Thompson 已提交
666
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`).
M
Mattt Thompson 已提交
667 668 669 670 671 672 673 674 675 676 677

#### Creating a Manager with Default Configuration

```swift
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
let manager = Alamofire.Manager(configuration: configuration)
```

#### Creating a Manager with Background Configuration

```swift
D
David F. Muir V 已提交
678
let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("com.example.app.background")
M
Mattt Thompson 已提交
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
let manager = Alamofire.Manager(configuration: configuration)
```

#### Creating a Manager with Ephemeral Configuration

```swift
let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
let manager = Alamofire.Manager(configuration: configuration)
```

#### Modifying Session Configuration

```swift
var defaultHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:]
defaultHeaders["DNT"] = "1 (Do Not Track Enabled)"

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = defaultHeaders

let manager = Alamofire.Manager(configuration: configuration)
```

> This is **not** recommended for `Authorization` or `Content-Type` headers. Instead, use `URLRequestConvertible` and `ParameterEncoding`, respectively.

### Request

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.

707
Methods like `authenticate`, `validate` and `responseData` return the caller in order to facilitate chaining.
M
Mattt Thompson 已提交
708 709 710 711 712 713 714

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.

715 716
### Response Serialization

717 718 719 720 721
#### Handling Errors

Before implementing custom response serializers or object serialization methods, it's important to be prepared to handle any errors that may occur. Alamofire recommends handling these through the use of either your own `NSError` creation methods, or a simple `enum` that conforms to `ErrorType`. For example, this `BackendError` type, which will be used in later examples:

```swift
722
public enum BackendError: ErrorType {
723 724 725 726 727 728 729 730
    case Network(error: NSError)
    case DataSerialization(reason: String)
    case JSONSerialization(error: NSError)
    case ObjectSerialization(reason: String)
    case XMLSerialization(error: NSError)
}
```

731 732
#### Creating a Custom Response Serializer

M
Mattt Thompson 已提交
733 734 735
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:
736 737 738

```swift
extension Request {
739
    public static func XMLResponseSerializer() -> ResponseSerializer<ONOXMLDocument, BackendError> {
740
        return ResponseSerializer { request, response, data, error in
741
            guard error == nil else { return .Failure(.Network(error: error!)) }
742

743
            guard let validData = data else {
744
                return .Failure(.DataSerialization(reason: "Data could not be serialized. Input data was nil."))
745 746
            }

747 748
            do {
                let XML = try ONOXMLDocument(data: validData)
749
                return .Success(XML)
750
            } catch {
751
                return .Failure(.XMLSerialization(error: error as NSError))
752
            }
753 754 755
        }
    }

756
    public func responseXMLDocument(completionHandler: Response<ONOXMLDocument, BackendError> -> Void) -> Self {
757
        return response(responseSerializer: Request.XMLResponseSerializer(), completionHandler: completionHandler)
758 759 760 761 762 763 764 765 766
    }
}
```

#### Generic Response Object Serialization

Generics can be used to provide automatic, type-safe response object serialization.

```swift
767
public protocol ResponseObjectSerializable {
768
    init?(response: NSHTTPURLResponse, representation: AnyObject)
769 770
}

771
extension Request {
772 773 774
    public func responseObject<T: ResponseObjectSerializable>(completionHandler: Response<T, BackendError> -> Void) -> Self {
        let responseSerializer = ResponseSerializer<T, BackendError> { request, response, data, error in
            guard error == nil else { return .Failure(.Network(error: error!)) }
775

776
            let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
777
            let result = JSONResponseSerializer.serializeResponse(request, response, data, error)
778 779 780 781 782 783 784 785 786

            switch result {
            case .Success(let value):
                if let
                    response = response,
                    responseObject = T(response: response, representation: value)
                {
                    return .Success(responseObject)
                } else {
787
                    return .Failure(.ObjectSerialization(reason: "JSON could not be serialized into response object: \(value)"))
788
                }
789
            case .Failure(let error):
790
                return .Failure(.JSONSerialization(error: error))
791 792 793
            }
        }

794
        return response(responseSerializer: responseSerializer, completionHandler: completionHandler)
795 796 797 798 799
    }
}
```

```swift
800
final class User: ResponseObjectSerializable {
801 802 803
    let username: String
    let name: String

804
    init?(response: NSHTTPURLResponse, representation: AnyObject) {
805 806
        self.username = response.URL!.lastPathComponent!
        self.name = representation.valueForKeyPath("name") as! String
807 808 809 810 811
    }
}
```

```swift
812
Alamofire.request(.GET, "https://example.com/users/mattt")
813
         .responseObject { (response: Response<User, BackendError>) in
814
             debugPrint(response)
815 816 817 818 819 820
         }
```

The same approach can also be used to handle endpoints that return a representation of a collection of objects:

```swift
821 822
public protocol ResponseCollectionSerializable {
    static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Self]
823 824
}

825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
extension ResponseCollectionSerializable where Self: ResponseObjectSerializable {
    static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Self] {
        var collection = [Self]()
        
        if let representation = representation as? [[String: AnyObject]] {
            for itemRepresentation in representation {
                if let item = Self(response: response, representation: itemRepresentation) {
                    collection.append(item)
                }
            }
        }
        
        return collection
    }
}

841
extension Alamofire.Request {
842 843 844
    public func responseCollection<T: ResponseCollectionSerializable>(completionHandler: Response<[T], BackendError> -> Void) -> Self {
        let responseSerializer = ResponseSerializer<[T], BackendError> { request, response, data, error in
            guard error == nil else { return .Failure(.Network(error: error!)) }
845

846
            let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
847
            let result = JSONSerializer.serializeResponse(request, response, data, error)
848 849 850 851 852 853

            switch result {
            case .Success(let value):
                if let response = response {
                    return .Success(T.collection(response: response, representation: value))
                } else {
854
                    return .Failure(. ObjectSerialization(reason: "Response collection could not be serialized due to nil response"))
855
                }
856
            case .Failure(let error):
857
                return .Failure(.JSONSerialization(error: error))
858 859 860
            }
        }

861
        return response(responseSerializer: responseSerializer, completionHandler: completionHandler)
862 863 864 865
    }
}
```

866
```swift
867
final class User: ResponseObjectSerializable, ResponseCollectionSerializable {
868 869 870
    let username: String
    let name: String

871
    init?(response: NSHTTPURLResponse, representation: AnyObject) {
872 873 874 875 876 877
        self.username = response.URL!.lastPathComponent!
        self.name = representation.valueForKeyPath("name") as! String
    }
}
```

878 879
```swift
Alamofire.request(.GET, "http://example.com/users")
880
         .responseCollection { (response: Response<[User], BackendError>) in
881
             debugPrint(response)
882 883 884
         }
```

M
Mattt Thompson 已提交
885 886
### URLStringConvertible

887
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:
M
Mattt Thompson 已提交
888

889
```swift
T
tmnb 已提交
890
let string = NSString(string: "https://httpbin.org/post")
891 892 893 894 895 896 897 898 899 900 901 902 903
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.
M
Mattt Thompson 已提交
904 905 906 907

#### Type-Safe Routing

```swift
908
extension User: URLStringConvertible {
M
Mattt Thompson 已提交
909 910 911
    static let baseURLString = "http://example.com"

    var URLString: String {
912
        return User.baseURLString + "/users/\(username)/"
M
Mattt Thompson 已提交
913 914 915 916 917
    }
}
```

```swift
918 919
let user = User(username: "mattt")
Alamofire.request(.GET, user) // http://example.com/users/mattt
M
Mattt Thompson 已提交
920 921 922 923
```

### URLRequestConvertible

924
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):
925 926

```swift
T
tmnb 已提交
927
let URL = NSURL(string: "https://httpbin.org/post")!
928 929 930 931
let mutableURLRequest = NSMutableURLRequest(URL: URL)
mutableURLRequest.HTTPMethod = "POST"

let parameters = ["foo": "bar"]
932 933 934 935 936 937 938

do {
    mutableURLRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions())
} catch {
    // No-op
}

939 940 941 942
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")

Alamofire.request(mutableURLRequest)
```
M
Mattt Thompson 已提交
943

944
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 已提交
945 946 947 948 949 950 951 952 953 954 955 956

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

957 958
    var URLRequest: NSMutableURLRequest {
        let result: (path: String, parameters: [String: AnyObject]) = {
M
Mattt Thompson 已提交
959
            switch self {
960
            case .Search(let query, let page) where page > 0:
M
Mattt Thompson 已提交
961 962 963 964 965 966
                return ("/search", ["q": query, "offset": Router.perPage * page])
            case .Search(let query, _):
                return ("/search", ["q": query])
            }
        }()

967
        let URL = NSURL(string: Router.baseURLString)!
968
        let URLRequest = NSURLRequest(URL: URL.URLByAppendingPathComponent(result.path))
M
Mattt Thompson 已提交
969 970
        let encoding = Alamofire.ParameterEncoding.URL

971
        return encoding.encode(URLRequest, parameters: result.parameters).0
M
Mattt Thompson 已提交
972 973 974 975
    }
}
```

976
```swift
977
Alamofire.request(Router.Search(query: "foo bar", page: 1)) // ?q=foo%20bar&offset=50
978 979
```

M
Mattt Thompson 已提交
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
#### 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

1020
    var URLRequest: NSMutableURLRequest {
1021
        let URL = NSURL(string: Router.baseURLString)!
A
Arnaud Mesureur 已提交
1022
        let mutableURLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path))
J
John Beynon 已提交
1023
        mutableURLRequest.HTTPMethod = method.rawValue
M
Mattt Thompson 已提交
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040

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

1041 1042 1043 1044
```swift
Alamofire.request(Router.ReadUser("mattt")) // GET /users/mattt
```

1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
### 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.

#### 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 NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`.
public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)?

/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`.
public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)?

/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`.
public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)?
```

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

delegate.taskWillPerformHTTPRedirection = { session, task, response, request in
    var finalRequest = request

    if let originalRequest = task.originalRequest where originalRequest.URLString.containsString("apple.com") {
		finalRequest = originalRequest
	}

	return finalRequest
}
```

#### Subclassing

Another way to override the default implementation of the `SessionDelegate` is to subclass it. Subclassing allows you completely customize the behavior of the API or to create a proxy for the API and still use the default implementation. Creating a proxy allows you to log events, emit notifications, provide pre and post hook implementations, etc. Here's a quick example of subclassing the `SessionDelegate` and logging a message when a redirect occurs.

```swift
class LoggingSessionDelegate: Manager.SessionDelegate {
    override func URLSession(
        session: NSURLSession,
        task: NSURLSessionTask,
        willPerformHTTPRedirection response: NSHTTPURLResponse,
        newRequest request: NSURLRequest,
        completionHandler: NSURLRequest? -> Void)
    {
        print("URLSession will perform HTTP redirection to request: \(request)")

        super.URLSession(
            session,
            task: task,
            willPerformHTTPRedirection: response,
            newRequest: request,
            completionHandler: completionHandler
        )
    }
}
```

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

1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 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 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 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 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
### 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
	}
}

let sessionManager = SessionManager()
sessionManager.adapter = AccessTokenAdapter(accessToken: "1234")

sessionManager.request("https://httpbin.org/get", withMethod: .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 a short example of how you could implement a refresh flow for OAuth2 access tokens.

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

    public func adapt(_ urlRequest: URLRequest) -> URLRequest {
        if urlRequest.urlString.hasPrefix(baseURLString) {
            var mutableURLRequest = urlRequest
            mutableURLRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization")
            return mutableURLRequest
        }

        return urlRequest
    }

    // MARK: - RequestRetrier

    public func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: 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: 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, withMethod: .post, parameters: parameters, encoding: .json).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
        }
    }
}

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"

manager.request(urlString, withMethod: .get).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 instead 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.

> Please note that 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.

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 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
### 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
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
    certificates: ServerTrustPolicy.certificatesInBundle(),
    validateCertificateChain: true,
    validateHost: true
)
```

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

* `PerformDefaultEvaluation`: Uses the default server trust evaluation while allowing you to control whether to validate the host provided by the challenge. 
* `PinCertificates`: Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned certificates match one of the server certificates.
* `PinPublicKeys`: Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned public keys match one of the server certificate public keys.
* `DisableEvaluation`: Disables all evaluation which in turn will always consider any server trust as valid.
* `CustomEvaluation`: Uses the associated closure to evaluate the validity of the server trust thus giving you complete control over the validation process. Use with caution.

#### Server Trust Policy Manager

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

```swift
let serverTrustPolicies: [String: ServerTrustPolicy] = [
    "test.example.com": .PinCertificates(
        certificates: ServerTrustPolicy.certificatesInBundle(),
        validateCertificateChain: true,
        validateHost: true
    ),
    "insecure.expired-apis.com": .DisableEvaluation
]

let manager = Manager(
    serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
)
```

1325 1326
> Make sure to keep a reference to the new `Manager` instance, otherwise your requests will all get cancelled when your `manager` is deallocated.

1327 1328 1329 1330 1331 1332 1333 1334 1335
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.

1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
##### Subclassing Server Trust Policy Manager

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

```swift
class CustomServerTrustPolicyManager: ServerTrustPolicyManager {
    override func serverTrustPolicyForHost(host: String) -> ServerTrustPolicy? {
        var policy: ServerTrustPolicy?

        // Implement your custom domain matching behavior...

        return policy
    }
}
```

1352 1353 1354 1355 1356 1357 1358 1359
#### Validating the Host

The `.PerformDefaultEvaluation`, `.PinCertificates` and `.PinPublicKeys` server trust policies all take a `validateHost` parameter. Setting the value to `true` will cause the server trust evaluation to verify that hostname in the certificate matches the hostname of the challenge. If they do not match, evaluation will fail. A `validateHost` value of `false` will still evaluate the full certificate chain, but will not validate the hostname of the leaf certificate.

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

#### Validating the Certificate Chain

D
dersvenhesse 已提交
1360
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.
1361 1362 1363 1364 1365

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.

1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
#### 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/>
1386 1387 1388
				<!-- Optional: Specify minimum TLS version -->
				<key>NSTemporaryExceptionMinimumTLSVersion</key>
				<string>TLSv1.2</string>
1389 1390 1391 1392 1393 1394
			</dict>
		</dict>
	</dict>
</dict>
```

1395
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`.
1396 1397 1398

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

1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
### 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()
```

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

1415 1416 1417 1418 1419 1420 1421
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.
D
dersvenhesse 已提交
1422
  * 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."
1423 1424 1425

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

1426 1427
---

1428 1429 1430 1431
## Open Rdars

The following rdars have some affect on the current implementation of Alamofire.

1432
* [rdar://21349340](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case
1433
* [rdar://26761490](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage
1434

1435 1436 1437 1438 1439 1440
## 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.

1441
---
M
Mattt Thompson 已提交
1442

M
Mattt Thompson 已提交
1443
## Credits
M
Mattt Thompson 已提交
1444

1445 1446 1447 1448 1449
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 已提交
1450

1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
## 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 已提交
1465 1466
## License

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