README.md 28.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

M
Mattt Thompson 已提交
3
[![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg)](https://travis-ci.org/Alamofire/Alamofire)
K
Kyle Fuller 已提交
4

M
Mattt Thompson 已提交
5
Alamofire is an HTTP networking library written in Swift, from the [creator](https://github.com/mattt) of [AFNetworking](https://github.com/afnetworking/afnetworking).
6 7 8

## Features

M
- [x]  
Mattt Thompson 已提交
9 10 11 12 13 14 15 16 17 18
- [x] Chainable Request / Response methods
- [x] URL / JSON / plist Parameter Encoding
- [x] Upload File / Data / Stream
- [x] Download using Request or Resume data
- [x] Authentication with NSURLCredential
- [x] HTTP Response Validation
- [x] Progress Closure & NSProgress
- [x] cURL Debug Output
- [x] Comprehensive Unit Test Coverage
- [x] Complete Documentation
19 20 21 22

## Requirements

- iOS 7.0+ / Mac OS X 10.9+
M
Mattt Thompson 已提交
23
- Xcode 6.1
24

M
Mattt Thompson 已提交
25 26 27 28 29 30 31 32
## 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.

33 34
## Installation

M
Mattt Thompson 已提交
35 36 37
> **Embedded frameworks require a minimum deployment target of iOS 8 or OS X Mavericks.**
>
> To use Alamofire with a project targeting iOS 7, you must include the `Alamofire.swift` source file directly in your project. See the ['Source File'](#source-file) section for instructions.
38 39
>
> For Swift 1.2 using the Xcode 6.3 Beta, use the [xcode-6.3 branch](https://github.com/Alamofire/Alamofire/tree/xcode-6.3).
40

41 42 43 44
### CocoaPods

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

45
CocoaPods 0.36 adds supports for Swift and embedded frameworks. You can install it with the following command:
46 47

```bash
48
$ gem install cocoapods
49 50 51 52 53 54 55
```

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'
56
use_frameworks!
57

R
rborkow 已提交
58
pod 'Alamofire', '~> 1.1'
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
```

Then, run the following command:

```bash
$ pod install
```

### Carthage

Carthage is a decentralized dependency manager that automates the process of adding frameworks to your Cocoa application.

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
github "Alamofire/Alamofire" >= 1.1
```

### Manually

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

### Embedded Framework

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

- Open the `Alamofire` folder, and drag `Alamofire.xcodeproj` into the file navigator of your app project.
- In Xcode, navigate to the target configuration window by clicking on the blue project icon, and selecting the application target under the "Targets" heading in the sidebar.
- Ensure that the deployment target of Alamofire.framework matches that of the application target.
- In the tab bar at the top of that window, open the "Build Phases" panel.
- Expand the "Target Dependencies" group, and add `Alamofire.framework`.
- Click on the `+` button at the top left of the panel and select "New Copy Files Phase". Rename this new phase to "Copy Frameworks", set the "Destination" to "Frameworks", and add `Alamofire.framework`.

#### Source File

For application targets that do not support embedded frameworks, such as iOS 7, Alamofire can be integrated by adding the `Alamofire.swift` source file directly into your project. Note that any 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.
106

107 108
---

M
Mattt Thompson 已提交
109 110
## Usage

M
Mattt Thompson 已提交
111
### Making a Request
M
Mattt Thompson 已提交
112 113

```swift
M
Mattt Thompson 已提交
114 115
import Alamofire

M
Mattt Thompson 已提交
116 117 118
Alamofire.request(.GET, "http://httpbin.org/get")
```

M
Mattt Thompson 已提交
119
### Response Handling
M
Mattt Thompson 已提交
120 121

```swift
122
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
M
Mattt Thompson 已提交
123 124 125 126 127 128 129
         .response { (request, response, data, error) in
                     println(request)
                     println(response)
                     println(error)
                   }
```

M
Mattt Thompson 已提交
130 131
> 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 已提交
132
> 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 已提交
133 134 135 136 137 138 139 140 141 142

### Response Serialization

**Built-in Response Methods**

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

M
Mattt Thompson 已提交
143
####  Response String Handler
M
Mattt Thompson 已提交
144 145 146 147 148 149 150 151

```swift
Alamofire.request(.GET, "http://httpbin.org/get")
         .responseString { (_, _, string, _) in
                  println(string)
         }
```

M
Mattt Thompson 已提交
152
####  Response JSON Handler
M
Mattt Thompson 已提交
153 154

```swift
M
Mattt Thompson 已提交
155 156
Alamofire.request(.GET, "http://httpbin.org/get")
         .responseJSON { (_, _, JSON, _) in
L
Lars-Jørgen Kristiansen 已提交
157
                  println(JSON)
M
Mattt Thompson 已提交
158 159 160
         }
```

M
Mattt Thompson 已提交
161 162 163 164 165 166 167 168 169 170
#### Chained Response Handlers

Response handlers can even be chained:

```swift
Alamofire.request(.GET, "http://httpbin.org/get")
         .responseString { (_, _, string, _) in
                  println(string)
         }
         .responseJSON { (_, _, JSON, _) in
L
Lars-Jørgen Kristiansen 已提交
171
                  println(JSON)
M
Mattt Thompson 已提交
172 173 174
         }
```

M
Mattt Thompson 已提交
175 176
### HTTP Methods

M
Mattt Thompson 已提交
177
`Alamofire.Method` lists the HTTP methods defined in [RFC 7231 §4.3](http://tools.ietf.org/html/rfc7231#section-4.3):
M
Mattt Thompson 已提交
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

```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 已提交
203 204 205 206 207 208 209 210 211 212
### 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 已提交
213 214 215 216 217 218 219 220 221 222 223 224

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

M
Mattt Thompson 已提交
225
Alamofire.request(.POST, "http://httpbin.org/post", parameters: parameters)
M
Mattt Thompson 已提交
226
// HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3
M
Mattt Thompson 已提交
227 228 229 230
```

### Parameter Encoding

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

M
Mattt Thompson 已提交
233 234 235
```swift
enum ParameterEncoding {
    case URL
236
    case JSON
M
Mattt Thompson 已提交
237 238 239 240 241 242 243 244 245 246
    case PropertyList(format: NSPropertyListFormat,
                      options: NSPropertyListWriteOptions)

    func encode(request: NSURLRequest,
                parameters: [String: AnyObject]?) ->
                    (NSURLRequest, NSError?)
    { ... }
}
```

M
Mattt Thompson 已提交
247
- `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, 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 已提交
248 249 250 251
- `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 已提交
252 253 254
#### Manual Parameter Encoding of an NSURLRequest

```swift
255
let URL = NSURL(string: "http://httpbin.org/get")!
M
Mattt Thompson 已提交
256 257 258 259 260 261 262
var request = NSURLRequest(URL: URL)

let parameters = ["foo": "bar"]
let encoding = Alamofire.ParameterEncoding.URL
(request, _) = encoding.encode(request, parameters)
```

M
Mattt Thompson 已提交
263
#### POST Request with JSON-encoded Parameters
M
Mattt Thompson 已提交
264 265

```swift
M
Mattt Thompson 已提交
266 267 268 269 270 271 272
let parameters = [
    "foo": [1,2,3],
    "bar": [
        "baz": "qux"
    ]
]

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

M
Mattt Thompson 已提交
277
### Caching
M
Mattt Thompson 已提交
278

M
Mattt Thompson 已提交
279
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 已提交
280 281 282

### Uploading

M
Mattt Thompson 已提交
283
**Supported Upload Types**
M
Mattt Thompson 已提交
284 285 286 287 288 289 290 291 292 293 294 295

- File
- Data
- Stream

#### Uploading a File

```swift
let fileURL = NSBundle.mainBundle()
                      .URLForResource("Default",
                                      withExtension: "png")

296
Alamofire.upload(.POST, "http://httpbin.org/post", file: fileURL)
M
Mattt Thompson 已提交
297 298 299 300 301
```

#### Uploading w/Progress

```swift
302
Alamofire.upload(.POST, "http://httpbin.org/post", file: fileURL)
M
Mattt Thompson 已提交
303 304 305 306 307 308
         .progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
             println(totalBytesWritten)
         }
         .responseJSON { (request, response, JSON, error) in
             println(JSON)
         }
M
Mattt Thompson 已提交
309 310 311 312
```

### Downloading

M
Mattt Thompson 已提交
313
**Supported Download Types**
M
Mattt Thompson 已提交
314 315 316 317 318 319 320

- Request
- Resume Data

#### Downloading a File

```swift
321
Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: { (temporaryURL, response) in
M
Mattt Thompson 已提交
322 323 324 325 326 327
    if let directoryURL = NSFileManager.defaultManager()
                          .URLsForDirectory(.DocumentDirectory,
                                            inDomains: .UserDomainMask)[0]
                          as? NSURL {
        let pathComponent = response.suggestedFilename

328
        return directoryURL.URLByAppendingPathComponent(pathComponent!)
M
Mattt Thompson 已提交
329 330 331 332 333 334
    }

    return temporaryURL
})
```

M
Mattt Thompson 已提交
335
#### Using the Default Download Destination
M
Mattt Thompson 已提交
336 337

```swift
338
let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
M
Mattt Thompson 已提交
339

340 341
Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: destination)
```
M
Mattt Thompson 已提交
342 343 344 345

#### Downloading a File w/Progress

```swift
346
Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: destination)
M
Mattt Thompson 已提交
347 348 349 350 351 352 353 354 355 356
         .progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in
             println(totalBytesRead)
         }
         .response { (request, response, _, error) in
             println(response)
         }
```

### Authentication

M
Mattt Thompson 已提交
357 358
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 已提交
359
**Supported Authentication Schemes**
M
Mattt Thompson 已提交
360

M
Mattt Thompson 已提交
361 362 363 364
- [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 已提交
365 366 367 368 369 370 371 372

#### HTTP Basic Authentication

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

Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)")
M
Mattt Thompson 已提交
373 374 375 376
         .authenticate(user: user, password: password)
         .response {(request, response, _, error) in
             println(response)
         }
M
Mattt Thompson 已提交
377 378
```

M
Mattt Thompson 已提交
379
#### Authentication with NSURLCredential
M
Mattt Thompson 已提交
380 381 382 383 384

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

385
let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)
M
Mattt Thompson 已提交
386 387

Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)")
M
Mattt Thompson 已提交
388 389 390 391
         .authenticate(usingCredential: credential)
         .response {(request, response, _, error) in
             println(response)
         }
M
Mattt Thompson 已提交
392 393
```

M
Mattt Thompson 已提交
394 395
### Validation

M
Mattt Thompson 已提交
396 397
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 已提交
398
#### Manual Validation
M
Mattt Thompson 已提交
399 400 401 402 403 404 405 406 407 408

```swift
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
         .validate(statusCode: 200..<300)
         .validate(contentType: ["application/json"])
         .response { (_, _, _, error) in
                  println(error)
         }
```

M
Mattt Thompson 已提交
409
#### Automatic Validation
M
Mattt Thompson 已提交
410 411 412 413 414 415 416 417 418 419 420

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()
         .response { (_, _, _, error) in
                  println(error)
         }
```

M
Mattt Thompson 已提交
421 422 423 424 425 426 427 428 429 430 431 432
### Printable

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

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

### DebugPrintable

```swift
433
let request = Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
M
Mattt Thompson 已提交
434 435 436 437 438 439

debugPrintln(request)
```

#### Output (cURL)

440
```bash
M
Mattt Thompson 已提交
441 442 443 444 445 446 447
$ 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 已提交
448 449 450
---

## Advanced Usage
M
Mattt Thompson 已提交
451

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

M
Mattt Thompson 已提交
455
**Recommended Reading**
M
Mattt Thompson 已提交
456

M
Mattt Thompson 已提交
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
- [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 已提交
477
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 已提交
478 479 480 481 482 483 484 485 486 487 488

#### 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 已提交
489
let configuration = NSURLSessionConfiguration.backgroundSessionConfiguration("com.example.app.background")
M
Mattt Thompson 已提交
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
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.

526 527 528 529
### Response Serialization

#### Creating a Custom Response Serializer

M
Mattt Thompson 已提交
530 531 532
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:
533 534 535 536 537 538 539 540 541 542

```swift
extension Request {
    class func XMLResponseSerializer() -> Serializer {
        return { (request, response, data) in
            if data == nil {
                return (nil, nil)
            }

            var XMLSerializationError: NSError?
543
            let XML = ONOXMLDocument(data: data, &XMLSerializationError)
544 545 546 547 548

            return (XML, XMLSerializationError)
        }
    }

549
    func responseXMLDocument(completionHandler: (NSURLRequest, NSHTTPURLResponse?, ONOXMLDocument?, NSError?) -> Void) -> Self {
550
        return response(serializer: Request.XMLResponseSerializer(), completionHandler: { (request, response, XML, error) in
551
            completionHandler(request, response, XML as? ONOXMLDocument, error)
552 553 554 555 556 557 558 559 560 561 562
        })
    }
}
```

#### Generic Response Object Serialization

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

```swift
@objc public protocol ResponseObjectSerializable {
563
    init?(response: NSHTTPURLResponse, representation: AnyObject)
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
}

extension Alamofire.Request {
    public func responseObject<T: ResponseObjectSerializable>(completionHandler: (NSURLRequest, NSHTTPURLResponse?, T?, NSError?) -> Void) -> Self {
        let serializer: Serializer = { (request, response, data) in
            let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
            let (JSON: AnyObject?, serializationError) = JSONSerializer(request, response, data)
            if response != nil && JSON != nil {
                return (T(response: response!, representation: JSON!), nil)
            } else {
                return (nil, serializationError)
            }
        }

        return response(serializer: serializer, completionHandler: { (request, response, object, error) in
579
            completionHandler(request, response, object as? T, error)
580 581 582 583 584 585
        })
    }
}
```

```swift
586
final class User: ResponseObjectSerializable {
587 588 589
    let username: String
    let name: String

590
    required init?(response: NSHTTPURLResponse, representation: AnyObject) {
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
        self.username = response.URL!.lastPathComponent
        self.name = representation.valueForKeyPath("name") as String
    }
}
```

```swift
Alamofire.request(.GET, "http://example.com/users/mattt")
         .responseObject { (_, _, user: User?, _) in
             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 {
    class func collection(#response: NSHTTPURLResponse, representation: AnyObject) -> [Self]
}

extension Alamofire.Request {
    public func responseCollection<T: ResponseCollectionSerializable>(completionHandler: (NSURLRequest, NSHTTPURLResponse?, [T]?, NSError?) -> Void) -> Self {
        let serializer: Serializer = { (request, response, data) in
            let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
            let (JSON: AnyObject?, serializationError) = JSONSerializer(request, response, data)
            if response != nil && JSON != nil {
                return (T.collection(response: response!, representation: JSON!), nil)
            } else {
                return (nil, serializationError)
            }
        }

        return response(serializer: serializer, completionHandler: { (request, response, object, error) in
            completionHandler(request, response, object as? [T], error)
        })
    }
}
```

M
Mattt Thompson 已提交
630 631
### URLStringConvertible

632
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 已提交
633

634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
```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 已提交
649 650 651 652

#### Type-Safe Routing

```swift
653
extension User: URLStringConvertible {
M
Mattt Thompson 已提交
654 655 656
    static let baseURLString = "http://example.com"

    var URLString: String {
657
        return User.baseURLString + "/users/\(username)/"
M
Mattt Thompson 已提交
658 659 660 661 662
    }
}
```

```swift
663 664
let user = User(username: "mattt")
Alamofire.request(.GET, user) // http://example.com/users/mattt
M
Mattt Thompson 已提交
665 666 667 668
```

### URLRequestConvertible

669 670 671 672 673 674 675 676 677 678 679 680 681 682
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 已提交
683

684
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 已提交
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706

#### 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])
            }
        }()

707
        let URL = NSURL(string: Router.baseURLString)!
M
Mattt Thompson 已提交
708 709 710 711 712 713 714 715
        let URLRequest = NSURLRequest(URL: URL.URLByAppendingPathComponent(path))
        let encoding = Alamofire.ParameterEncoding.URL

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

716 717 718 719
```swift
Alamofire.request(Router.Search(query: "foo bar", page: 1)) // ?q=foo+bar&offset=50
```

M
Mattt Thompson 已提交
720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
#### 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 {
761
        let URL = NSURL(string: Router.baseURLString)!
A
Arnaud Mesureur 已提交
762
        let mutableURLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path))
J
John Beynon 已提交
763
        mutableURLRequest.HTTPMethod = method.rawValue
M
Mattt Thompson 已提交
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780

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

781 782 783 784
```swift
Alamofire.request(Router.ReadUser("mattt")) // GET /users/mattt
```

M
Mattt Thompson 已提交
785
* * *
M
Mattt Thompson 已提交
786

M
Mattt Thompson 已提交
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
## 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`
- TLS verification, using `AFSecurityManager`
- Situations requiring `NSOperation` or `NSURLConnection`, using `AFURLConnectionOperation`
- Network reachability monitoring, using `AFNetworkReachabilityManager`
- Multipart HTTP request construction, using `AFHTTPRequestSerializer`

### 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 已提交
813 814 815 816 817 818 819 820 821 822
## Contact

Follow AFNetworking on Twitter ([@AFNetworking](https://twitter.com/AFNetworking))

### Creator

- [Mattt Thompson](http://github.com/mattt) ([@mattt](https://twitter.com/mattt))

## License

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