README.md 36.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)](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 8
[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)
[![License](https://img.shields.io/cocoapods/l/Alamofire.svg?style=flat&color=gray)](http://cocoadocs.org/docsets/Alamofire)
[![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)
9

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

## Features

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

## Requirements

- iOS 7.0+ / Mac OS X 10.9+
29
- Xcode 6.4
30

M
Mattt Thompson 已提交
31 32 33 34 35 36 37 38
## 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.

39 40
## Installation

M
Mattt Thompson 已提交
41 42
> **Embedded frameworks require a minimum deployment target of iOS 8 or OS X Mavericks.**
>
43
> To use Alamofire with a project targeting iOS 7, you must include all Swift files located inside the `Source` directory directly in your project. See the ['Source File'](#source-file) section for additional instructions.
44

45 46 47 48
### CocoaPods

[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects.

49
CocoaPods 0.36 adds supports for Swift and embedded frameworks. You can install it with the following command:
50 51

```bash
52
$ gem install cocoapods
53 54 55 56 57 58 59
```

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

```ruby
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
60
use_frameworks!
61

62
pod 'Alamofire', '~> 1.3'
63 64 65 66 67 68 69 70 71 72
```

Then, run the following command:

```bash
$ pod install
```

### Carthage

J
Josh Brown 已提交
73
[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that automates the process of adding frameworks to your Cocoa application.
74 75 76 77 78 79 80 81 82 83 84

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
85
github "Alamofire/Alamofire" >= 1.3
86 87 88 89 90 91
```

### Manually

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

92
#### Embedded Framework
93 94 95 96 97 98 99

- Add Alamofire as a [submodule](http://git-scm.com/docs/git-submodule) by opening the Terminal, `cd`-ing into your top-level project directory, and entering the following command:

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

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
- 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!

> 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.
119 120 121

#### Source File

122
For application targets that do not support embedded frameworks, such as iOS 7, Alamofire can be integrated by adding all the Swift files located inside the `Source` directory (`Source/*.swift`) directly into your project. Note that you will no longer need to `import Alamofire` since you are not actually loading a framework. Additionally, any of the calling conventions described in the ['Usage'](#usage) section with the `Alamofire` prefix would instead omit it (for example, `Alamofire.request` becomes `request`), since this functionality is incorporated into the top-level namespace.
123

124 125
---

M
Mattt Thompson 已提交
126 127
## Usage

M
Mattt Thompson 已提交
128
### Making a Request
M
Mattt Thompson 已提交
129 130

```swift
M
Mattt Thompson 已提交
131 132
import Alamofire

M
Mattt Thompson 已提交
133 134 135
Alamofire.request(.GET, "http://httpbin.org/get")
```

M
Mattt Thompson 已提交
136
### Response Handling
M
Mattt Thompson 已提交
137 138

```swift
139
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
140 141 142 143 144
         .response { request, response, data, error in
              println(request)
              println(response)
              println(error)
          }
M
Mattt Thompson 已提交
145 146
```

M
Mattt Thompson 已提交
147 148
> 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 已提交
149
> 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 已提交
150 151 152 153 154 155 156 157 158 159

### Response Serialization

**Built-in Response Methods**

- `response()`
- `responseString(encoding: NSStringEncoding)`
- `responseJSON(options: NSJSONReadingOptions)`
- `responsePropertyList(options: NSPropertyListReadOptions)`

M
Mattt Thompson 已提交
160
####  Response String Handler
M
Mattt Thompson 已提交
161 162 163

```swift
Alamofire.request(.GET, "http://httpbin.org/get")
164 165
         .responseString { _, _, string, _ in
             println(string)
M
Mattt Thompson 已提交
166 167 168
         }
```

M
Mattt Thompson 已提交
169
####  Response JSON Handler
M
Mattt Thompson 已提交
170 171

```swift
M
Mattt Thompson 已提交
172
Alamofire.request(.GET, "http://httpbin.org/get")
173 174
         .responseJSON { _, _, JSON, _ in
             println(JSON)
M
Mattt Thompson 已提交
175 176 177
         }
```

M
Mattt Thompson 已提交
178 179 180 181 182 183
#### Chained Response Handlers

Response handlers can even be chained:

```swift
Alamofire.request(.GET, "http://httpbin.org/get")
184 185
         .responseString { _, _, string, _ in
             println(string)
M
Mattt Thompson 已提交
186
         }
187 188
         .responseJSON { _, _, JSON, _ in
             println(JSON)
M
Mattt Thompson 已提交
189 190 191
         }
```

M
Mattt Thompson 已提交
192 193
### HTTP Methods

M
Mattt Thompson 已提交
194
`Alamofire.Method` lists the HTTP methods defined in [RFC 7231 §4.3](http://tools.ietf.org/html/rfc7231#section-4.3):
M
Mattt Thompson 已提交
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219

```swift
public enum Method: String {
    case OPTIONS = "OPTIONS"
    case GET = "GET"
    case HEAD = "HEAD"
    case POST = "POST"
    case PUT = "PUT"
    case PATCH = "PATCH"
    case DELETE = "DELETE"
    case TRACE = "TRACE"
    case CONNECT = "CONNECT"
}
```

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

```swift
Alamofire.request(.POST, "http://httpbin.org/post")

Alamofire.request(.PUT, "http://httpbin.org/put")

Alamofire.request(.DELETE, "http://httpbin.org/delete")
```

M
Mattt Thompson 已提交
220 221 222 223 224 225 226 227 228 229
### Parameters

#### GET Request With URL-Encoded Parameters

```swift
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
// http://httpbin.org/get?foo=bar
```

#### POST Request With URL-Encoded Parameters
M
Mattt Thompson 已提交
230 231 232 233 234 235 236 237 238 239 240 241

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

M
Mattt Thompson 已提交
242
Alamofire.request(.POST, "http://httpbin.org/post", parameters: parameters)
M
Mattt Thompson 已提交
243
// HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3
M
Mattt Thompson 已提交
244 245 246 247
```

### Parameter Encoding

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

M
Mattt Thompson 已提交
250 251 252
```swift
enum ParameterEncoding {
    case URL
253
    case JSON
254 255
    case PropertyList(format: NSPropertyListFormat, options: NSPropertyListWriteOptions)
    case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?))
M
Mattt Thompson 已提交
256

257
    func encode(request: NSURLRequest, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?)
M
Mattt Thompson 已提交
258 259 260 261
    { ... }
}
```

A
Aaron Brager 已提交
262
- `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`)._
M
Mattt Thompson 已提交
263 264 265 266
- `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 已提交
267 268 269
#### Manual Parameter Encoding of an NSURLRequest

```swift
270
let URL = NSURL(string: "http://httpbin.org/get")!
M
Mattt Thompson 已提交
271 272 273 274
var request = NSURLRequest(URL: URL)

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

M
Mattt Thompson 已提交
278
#### POST Request with JSON-encoded Parameters
M
Mattt Thompson 已提交
279 280

```swift
M
Mattt Thompson 已提交
281 282 283 284 285 286 287
let parameters = [
    "foo": [1,2,3],
    "bar": [
        "baz": "qux"
    ]
]

288
Alamofire.request(.POST, "http://httpbin.org/post", parameters: parameters, encoding: .JSON)
M
Mattt Thompson 已提交
289
// HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}}
M
Mattt Thompson 已提交
290 291
```

292 293 294 295 296 297 298 299
### 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 已提交
300
    "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
301 302 303 304 305 306 307 308 309
    "Content-Type": "application/x-www-form-urlencoded"
]

Alamofire.request(.GET, "http://httpbin.org/get", headers: headers)
         .responseJSON { _, _, JSON, _ in
             println(JSON)
         }
```

M
Mattt Thompson 已提交
310
### Caching
M
Mattt Thompson 已提交
311

M
Mattt Thompson 已提交
312
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 已提交
313 314 315

### Uploading

M
Mattt Thompson 已提交
316
**Supported Upload Types**
M
Mattt Thompson 已提交
317 318 319 320

- File
- Data
- Stream
321
- MultipartFormData
M
Mattt Thompson 已提交
322 323 324 325

#### Uploading a File

```swift
326
let fileURL = NSBundle.mainBundle().URLForResource("Default", withExtension: "png")
327
Alamofire.upload(.POST, "http://httpbin.org/post", file: fileURL)
M
Mattt Thompson 已提交
328 329
```

330
#### Uploading with Progress
M
Mattt Thompson 已提交
331 332

```swift
333
Alamofire.upload(.POST, "http://httpbin.org/post", file: fileURL)
334
         .progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
M
Mattt Thompson 已提交
335 336
             println(totalBytesWritten)
         }
337
         .responseJSON { request, response, JSON, error in
M
Mattt Thompson 已提交
338 339
             println(JSON)
         }
M
Mattt Thompson 已提交
340 341
```

342 343 344 345 346 347 348 349 350 351 352 353 354
#### Uploading MultipartFormData

```swift
Alamofire.upload(
    .POST,
    URLString: "http://httpbin.org/post",
    multipartFormData: { multipartFormData in
        multipartFormData.appendBodyPart(fileURL: unicornImageURL, name: "unicorn")
        multipartFormData.appendBodyPart(fileURL: rainbowImageURL, name: "rainbow")
    },
    encodingCompletion: { encodingResult in
    	switch encodingResult {
    	case .Success(let upload, _, _):
355 356 357
            upload.responseJSON { request, response, JSON, error in
                println(JSON)
            }
358
    	case .Failure(let encodingError):
359
    	    println(encodingError)
360 361 362 363 364
    	}
    }
)
```

M
Mattt Thompson 已提交
365 366
### Downloading

M
Mattt Thompson 已提交
367
**Supported Download Types**
M
Mattt Thompson 已提交
368 369 370 371 372 373 374

- Request
- Resume Data

#### Downloading a File

```swift
375
Alamofire.download(.GET, "http://httpbin.org/stream/100") { temporaryURL, response in
376 377
    let fileManager = NSFileManager.defaultManager()
    if let directoryURL = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as? NSURL {
M
Mattt Thompson 已提交
378
        let pathComponent = response.suggestedFilename
379
        return directoryURL.URLByAppendingPathComponent(pathComponent!)
M
Mattt Thompson 已提交
380 381 382
    }

    return temporaryURL
383
}
M
Mattt Thompson 已提交
384 385
```

M
Mattt Thompson 已提交
386
#### Using the Default Download Destination
M
Mattt Thompson 已提交
387 388

```swift
389 390 391
let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: destination)
```
M
Mattt Thompson 已提交
392 393 394 395

#### Downloading a File w/Progress

```swift
396
Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: destination)
397
         .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
M
Mattt Thompson 已提交
398 399
             println(totalBytesRead)
         }
400
         .response { request, response, _, error in
M
Mattt Thompson 已提交
401 402 403 404 405 406
             println(response)
         }
```

### Authentication

M
Mattt Thompson 已提交
407 408
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 已提交
409
**Supported Authentication Schemes**
M
Mattt Thompson 已提交
410

M
Mattt Thompson 已提交
411 412 413 414
- [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 已提交
415 416 417

#### HTTP Basic Authentication

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

M
Mattt Thompson 已提交
420 421 422 423 424
```swift
let user = "user"
let password = "password"

Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)")
M
Mattt Thompson 已提交
425
         .authenticate(user: user, password: password)
426
         .response { request, response, _, error in
M
Mattt Thompson 已提交
427 428
             println(response)
         }
M
Mattt Thompson 已提交
429 430
```

431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
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)!
let base64Credentials = credentialData.base64EncodedStringWithOptions(nil)

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

Alamofire.request(.GET, "http://httpbin.org/basic-auth/user/password", headers: headers)
         .responseJSON { _, _, JSON, _ in
             println(JSON)
         }
```

M
Mattt Thompson 已提交
448
#### Authentication with NSURLCredential
M
Mattt Thompson 已提交
449 450 451 452 453

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

454
let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)
M
Mattt Thompson 已提交
455 456

Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)")
M
Mattt Thompson 已提交
457
         .authenticate(usingCredential: credential)
458
         .response { request, response, _, error in
M
Mattt Thompson 已提交
459 460
             println(response)
         }
M
Mattt Thompson 已提交
461 462
```

M
Mattt Thompson 已提交
463 464
### Validation

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

M
Mattt Thompson 已提交
467
#### Manual Validation
M
Mattt Thompson 已提交
468 469 470 471 472

```swift
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
         .validate(statusCode: 200..<300)
         .validate(contentType: ["application/json"])
473
         .response { _, _, _, error in
474
             println(error)
M
Mattt Thompson 已提交
475 476 477
         }
```

M
Mattt Thompson 已提交
478
#### Automatic Validation
M
Mattt Thompson 已提交
479 480 481 482 483 484

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, "http://httpbin.org/get", parameters: ["foo": "bar"])
         .validate()
485 486
         .response { _, _, _, error in
             println(error)
M
Mattt Thompson 已提交
487 488 489
         }
```

M
Mattt Thompson 已提交
490 491 492 493 494 495 496 497 498 499 500 501
### Printable

```swift
let request = Alamofire.request(.GET, "http://httpbin.org/ip")

println(request)
// GET http://httpbin.org/ip (200)
```

### DebugPrintable

```swift
502
let request = Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
M
Mattt Thompson 已提交
503 504 505 506 507 508

debugPrintln(request)
```

#### Output (cURL)

509
```bash
M
Mattt Thompson 已提交
510 511 512 513 514 515 516
$ 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" \
	"http://httpbin.org/get?foo=bar"
```

M
Mattt Thompson 已提交
517 518 519
---

## Advanced Usage
M
Mattt Thompson 已提交
520

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

M
Mattt Thompson 已提交
524
**Recommended Reading**
M
Mattt Thompson 已提交
525

M
Mattt Thompson 已提交
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
- [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
Alamofire.request(.GET, "http://httpbin.org/get")
```

```swift
let manager = Alamofire.Manager.sharedInstance
manager.request(NSURLRequest(URL: NSURL(string: "http://httpbin.org/get")))
```

M
Mattt Thompson 已提交
546
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 已提交
547 548 549 550 551 552 553 554 555 556 557

#### Creating a Manager with Default Configuration

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

#### Creating a Manager with Background Configuration

```swift
M
Mattt Thompson 已提交
558
let configuration = NSURLSessionConfiguration.backgroundSessionConfiguration("com.example.app.background")
M
Mattt Thompson 已提交
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
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.

Methods like `authenticate`, `validate`, and `response` return the caller in order to facilitate chaining.

Requests can be suspended, resumed, and cancelled:

- `suspend()`: Suspends the underlying task and dispatch queue
- `resume()`: Resumes the underlying task and dispatch queue. If the owning manager does not have `startRequestsImmediately` set to `true`, the request must call `resume()` in order to start.
- `cancel()`: Cancels the underlying task, producing an error that is passed to any registered response handlers.

595 596 597 598
### Response Serialization

#### Creating a Custom Response Serializer

M
Mattt Thompson 已提交
599 600 601
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:
602 603 604

```swift
extension Request {
605 606
    public static func XMLResponseSerializer() -> GenericResponseSerializer<ONOXMLDocument> {
        return GenericResponseSerializer { request, response, data in
607 608 609 610 611
            if data == nil {
                return (nil, nil)
            }

            var XMLSerializationError: NSError?
612
            let XML = ONOXMLDocument(data: data!, error: &XMLSerializationError)
613 614 615 616 617

            return (XML, XMLSerializationError)
        }
    }

618 619
    public func responseXMLDocument(completionHandler: (NSURLRequest, NSHTTPURLResponse?, ONOXMLDocument?, NSError?) -> Void) -> Self {
        return response(responseSerializer: Request.XMLResponseSerializer(), completionHandler: completionHandler)
620 621 622 623 624 625 626 627 628 629
    }
}
```

#### Generic Response Object Serialization

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

```swift
@objc public protocol ResponseObjectSerializable {
630
    init?(response: NSHTTPURLResponse, representation: AnyObject)
631 632
}

633
extension Request {
634
    public func responseObject<T: ResponseObjectSerializable>(completionHandler: (NSURLRequest, NSHTTPURLResponse?, T?, NSError?) -> Void) -> Self {
635 636 637
        let responseSerializer = GenericResponseSerializer<T> { request, response, data in
            let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
            let (JSON: AnyObject?, serializationError) = JSONResponseSerializer.serializeResponse(request, response, data)
638 639 640

            if let response = response, JSON: AnyObject = JSON {
                return (T(response: response, representation: JSON), nil)
641 642 643 644 645
            } else {
                return (nil, serializationError)
            }
        }

646
        return response(responseSerializer: responseSerializer, completionHandler: completionHandler)
647 648 649 650 651
    }
}
```

```swift
652
final class User: ResponseObjectSerializable {
653 654 655
    let username: String
    let name: String

656
    @objc required init?(response: NSHTTPURLResponse, representation: AnyObject) {
657 658
        self.username = response.URL!.lastPathComponent!
        self.name = representation.valueForKeyPath("name") as! String
659 660 661 662 663 664
    }
}
```

```swift
Alamofire.request(.GET, "http://example.com/users/mattt")
665
         .responseObject { (_, _, user: User?, _) in
666 667 668 669 670 671 672 673
             println(user)
         }
```

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

```swift
@objc public protocol ResponseCollectionSerializable {
674
    static func collection(#response: NSHTTPURLResponse, representation: AnyObject) -> [Self]
675 676 677 678
}

extension Alamofire.Request {
    public func responseCollection<T: ResponseCollectionSerializable>(completionHandler: (NSURLRequest, NSHTTPURLResponse?, [T]?, NSError?) -> Void) -> Self {
679
        let responseSerializer = GenericResponseSerializer<[T]> { request, response, data in
680
            let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
681
            let (JSON: AnyObject?, serializationError) = JSONSerializer.serializeResponse(request, response, data)
682 683 684

            if let response = response, JSON: AnyObject = JSON {
                return (T.collection(response: response, representation: JSON), nil)
685 686 687 688 689
            } else {
                return (nil, serializationError)
            }
        }

690
        return response(responseSerializer: responseSerializer, completionHandler: completionHandler)
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 719 720
```swift
@objc final class User: ResponseObjectSerializable, ResponseCollectionSerializable {
    let username: String
    let name: String

    required init?(response: NSHTTPURLResponse, representation: AnyObject) {
        self.username = response.URL!.lastPathComponent!
        self.name = representation.valueForKeyPath("name") as! String
    }

    static func collection(#response: NSHTTPURLResponse, representation: AnyObject) -> [User] {
        var users: [User] = []

        if let representation = representation as? [[String: AnyObject]] {
            for userRepresentation in representation {
                if let user = User(response: response, representation: userRepresentation) {
                    users.append(user)
                }
            }
        }

        return users
    }
}
```

721 722
```swift
Alamofire.request(.GET, "http://example.com/users")
723
         .responseCollection { (_, _, users: [User]?, _) in
724 725 726 727
             println(users)
         }
```

M
Mattt Thompson 已提交
728 729
### URLStringConvertible

730
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 已提交
731

732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
```swift
let string = NSString(string: "http://httpbin.org/post")
Alamofire.request(.POST, string)

let URL = NSURL(string: string)!
Alamofire.request(.POST, URL)

let URLRequest = NSURLRequest(URL: URL)
Alamofire.request(.POST, URLRequest) // overrides `HTTPMethod` of `URLRequest`

let URLComponents = NSURLComponents(URL: URL, resolvingAgainstBaseURL: true)
Alamofire.request(.POST, URLComponents)
```

Applications interacting with web applications in a significant manner are encouraged to have custom types conform to `URLStringConvertible` as a convenient way to map domain-specific models to server resources.
M
Mattt Thompson 已提交
747 748 749 750

#### Type-Safe Routing

```swift
751
extension User: URLStringConvertible {
M
Mattt Thompson 已提交
752 753 754
    static let baseURLString = "http://example.com"

    var URLString: String {
755
        return User.baseURLString + "/users/\(username)/"
M
Mattt Thompson 已提交
756 757 758 759 760
    }
}
```

```swift
761 762
let user = User(username: "mattt")
Alamofire.request(.GET, user) // http://example.com/users/mattt
M
Mattt Thompson 已提交
763 764 765 766
```

### URLRequestConvertible

767 768 769 770 771 772 773 774 775 776 777 778 779 780
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 header fields or HTTP body for individual requests):

```swift
let URL = NSURL(string: "http://httpbin.org/post")!
let mutableURLRequest = NSMutableURLRequest(URL: URL)
mutableURLRequest.HTTPMethod = "POST"

let parameters = ["foo": "bar"]
var JSONSerializationError: NSError? = nil
mutableURLRequest.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: &JSONSerializationError)
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")

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

782
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 已提交
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804

#### API Parameter Abstraction

```swift
enum Router: URLRequestConvertible {
    static let baseURLString = "http://example.com"
    static let perPage = 50

    case Search(query: String, page: Int)

    // MARK: URLRequestConvertible

    var URLRequest: NSURLRequest {
        let (path: String, parameters: [String: AnyObject]?) = {
            switch self {
            case .Search(let query, let page) where page > 1:
                return ("/search", ["q": query, "offset": Router.perPage * page])
            case .Search(let query, _):
                return ("/search", ["q": query])
            }
        }()

805
        let URL = NSURL(string: Router.baseURLString)!
M
Mattt Thompson 已提交
806 807 808 809 810 811 812 813
        let URLRequest = NSURLRequest(URL: URL.URLByAppendingPathComponent(path))
        let encoding = Alamofire.ParameterEncoding.URL

        return encoding.encode(URLRequest, parameters: parameters).0
    }
}
```

814
```swift
815
Alamofire.request(Router.Search(query: "foo bar", page: 1)) // ?q=foo%20bar&offset=50
816 817
```

M
Mattt Thompson 已提交
818 819 820 821 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 847 848 849 850 851 852 853 854 855 856 857 858
#### CRUD & Authorization

```swift
enum Router: URLRequestConvertible {
    static let baseURLString = "http://example.com"
    static var OAuthToken: String?

    case CreateUser([String: AnyObject])
    case ReadUser(String)
    case UpdateUser(String, [String: AnyObject])
    case DestroyUser(String)

    var method: Alamofire.Method {
        switch self {
        case .CreateUser:
            return .POST
        case .ReadUser:
            return .GET
        case .UpdateUser:
            return .PUT
        case .DestroyUser:
            return .DELETE
        }
    }

    var path: String {
        switch self {
        case .CreateUser:
            return "/users"
        case .ReadUser(let username):
            return "/users/\(username)"
        case .UpdateUser(let username, _):
            return "/users/\(username)"
        case .DestroyUser(let username):
            return "/users/\(username)"
        }
    }

    // MARK: URLRequestConvertible

    var URLRequest: NSURLRequest {
859
        let URL = NSURL(string: Router.baseURLString)!
A
Arnaud Mesureur 已提交
860
        let mutableURLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path))
J
John Beynon 已提交
861
        mutableURLRequest.HTTPMethod = method.rawValue
M
Mattt Thompson 已提交
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878

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

879 880 881 882
```swift
Alamofire.request(Router.ReadUser("mattt")) // GET /users/mattt
```

883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
### 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(
    configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
    serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
)
```

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.

M
Mattt Thompson 已提交
936
* * *
M
Mattt Thompson 已提交
937

M
Mattt Thompson 已提交
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
## FAQ

### When should I use Alamofire?

If you're starting a new project in Swift, and want to take full advantage of its conventions and language features, Alamofire is a great choice. Although not as fully-featured as AFNetworking, Alamofire is much nicer to work with, and should satisfy the vast majority of networking use cases.

> It's important to note that two libraries aren't mutually exclusive: AFNetworking and Alamofire can peacefully exist in the same code base.

### When should I use AFNetworking?

AFNetworking remains the premiere networking library available for OS X and iOS, and can easily be used in Swift, just like any other Objective-C code. AFNetworking is stable and reliable, and isn't going anywhere.

Use AFNetworking for any of the following:

- UIKit extensions, such as asynchronously loading images to `UIImageView`
- Network reachability monitoring, using `AFNetworkReachabilityManager`

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

* * *

M
Mattt Thompson 已提交
961
## Credits
M
Mattt Thompson 已提交
962

963 964 965 966 967
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 已提交
968 969 970

## License

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