README.md 9.6 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
Alamofire is an HTTP networking library written in Swift. Think of it as [AFNetworking](https://github.com/afnetworking/afnetworking), reimagined for the conventions of this new language.
4

M
Mattt Thompson 已提交
5
Of course, AFNetworking remains the premiere networking library available for Mac 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.** But for anyone looking for something a little more idiomatic to Swift, Alamofire may be right up your alley. (It's not a mutually-exclusive choice, either! AFNetworking & Alamofire will peacefully co-exist within the same codebase.)
6 7 8 9 10 11 12 13 14 15 16 17 18

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

## Features

- Chainable Request / Response methods
- URL / JSON / plist Parameter Encoding
- Upload File / Data / Stream
- Download using Request or Resume data
- Authentication with NSURLCredential
- Progress Closure & NSProgress
- cURL Debug Output

M
Mattt Thompson 已提交
19 20
### Planned for 1.0 Release*

M
Mattt Thompson 已提交
21
_* Coming very soon_
M
Mattt Thompson 已提交
22

M
Mattt Thompson 已提交
23
- Comprehensive Unit Test Coverage
M
Mattt Thompson 已提交
24 25 26 27
- Complete Documentation
- HTTP Response Validation
- TLS Chain Validation

28 29
## Requirements

M
Mattt Thompson 已提交
30
- Xcode 6.0
31 32 33 34
- iOS 7.0+ / Mac OS X 10.9+

## Installation

35 36
_The infrastructure and best practices for distributing Swift libraries is currently in flux during this beta period of the language and Xcode... which is to say, the current installation process kinda sucks. _

M
Mattt Thompson 已提交
37
1. Add Alamofire as a submodule by opening the Terminal, `cd`-ing into your top-level project directory, and entering the command `git submodule add https://github.com/Alamofire/Alamofire.git`
38 39 40 41 42 43
2. Open the `Alamofire` folder, and drag `Alamofire.xcodeproj` into the file navigator of your Xcode project.
3. 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.
4. In the tab bar at the top of that window, open the "Build Phases" panel.
5. Expand the "Link Binary with Libraries" group, and add `Alamofire.framework`.
6. 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`.

44 45 46

---

M
Mattt Thompson 已提交
47 48 49 50 51 52 53 54 55 56 57
## Usage

### GET Request

```swift
Alamofire.request(.GET, "http://httpbin.org/get")
```

#### With Parameters

```swift
58
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
M
Mattt Thompson 已提交
59 60 61 62 63
```

#### With Response Handling

```swift
64
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
M
Mattt Thompson 已提交
65 66 67 68 69 70 71 72 73 74
         .response { (request, response, data, error) in
                     println(request)
                     println(response)
                     println(error)
                   }
```

#### With Response String Handling

```swift
75
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
M
Mattt Thompson 已提交
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 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
         .responseString { (request, response, string, error) in
                  println(string)
         }
```

### HTTP Methods

The `Alamofire.Method` `enum` lists the HTTP methods defined in RFC 2616 §9:

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

### POST Request

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

M
Mattt Thompson 已提交
122
Alamofire.request(.POST, "http://httpbin.org/post", parameters: parameters)
M
Mattt Thompson 已提交
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
```

This sends the following HTTP Body:

```
foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3
```

Alamofire has built-in support for encoding parameters as URL query / URI form encoded, JSON, and Property List, using the `Alamofire.ParameterEncoding` `enum`:

### Parameter Encoding

```swift
enum ParameterEncoding {
    case URL
138
    case JSON
M
Mattt Thompson 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
    case PropertyList(format: NSPropertyListFormat,
                      options: NSPropertyListWriteOptions)

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

#### Manual Parameter Encoding of an NSURLRequest

```swift
let URL = NSURL(string: "http://httpbin.org/get")
var request = NSURLRequest(URL: URL)

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

### POST Request with JSON Response

```swift
163
Alamofire.request(.POST, "http://httpbin.org/post", parameters: parameters, encoding: .JSON)
M
Mattt Thompson 已提交
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
         .responseJSON {(request, response, JSON, error) in
            println(JSON)
         }
```

#### Built-In Response Methods

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

### Uploading

#### Supported Upload Types

- File
- Data
- Stream
- Multipart (Coming Soon)

#### Uploading a File

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

192
Alamofire.upload(.POST, "http://httpbin.org/post", file: fileURL)
M
Mattt Thompson 已提交
193 194 195 196 197
```

#### Uploading w/Progress

```swift
198
Alamofire.upload(.POST, "http://httpbin.org/post", file: fileURL)
M
Mattt Thompson 已提交
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
        .progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
            println(totalBytesWritten)
        }
        .responseJSON { (request, response, JSON, error) in
            println(JSON)
        }
```

### Downloading

#### Supported Download Types

- Request
- Resume Data

#### Downloading a File

```swift
217
Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: { (temporaryURL, response) in
M
Mattt Thompson 已提交
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
    if let directoryURL = NSFileManager.defaultManager()
                          .URLsForDirectory(.DocumentDirectory,
                                            inDomains: .UserDomainMask)[0]
                          as? NSURL {
        let pathComponent = response.suggestedFilename

        return directoryURL.URLByAppendingPathComponent(pathComponent)
    }

    return temporaryURL
})
```

#### Using the Default Download Destination Closure Function

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

236 237
Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: destination)
```
M
Mattt Thompson 已提交
238 239 240 241

#### Downloading a File w/Progress

```swift
242
Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: destination)
M
Mattt Thompson 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
         .progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in
             println(totalBytesRead)
         }
         .response { (request, response, _, error) in
             println(response)
         }
```

### Authentication

#### Supported Authentication Schemes

- HTTP Basic
- HTTP Digest
- Kerberos
- NTLM

#### HTTP Basic Authentication

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

Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)")
    .authenticate(HTTPBasic: user, password: password)
    .response {(request, response, _, error) in
        println(response)
    }
```

#### Authenticating with NSURLCredential & NSURLProtectionSpace

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

279 280
let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)
let protectionSpace = NSURLProtectionSpace(host: "httpbin.org", port: 0, `protocol`: "https", realm: nil, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
M
Mattt Thompson 已提交
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
```

```swift
Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)")
    .authenticate(usingCredential: credential, forProtectionSpace: protectionSpace)
    .response {(request, response, _, error) in
        println(response)
}
```

### Printable

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

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

### DebugPrintable

```swift
303
let request = Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
M
Mattt Thompson 已提交
304 305 306 307 308 309 310 311 312 313 314 315 316 317

debugPrintln(request)
```

#### Output (cURL)

```
$ 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 已提交
318 319 320 321 322 323
### More Complex Use Cases

Much of the functionality described above is provided as a convenience API on top of something more extensible, closer to the Foundation URL Loading System. For more complex usage, such as creating a `NSURLSession` with a custom configuration or passing `NSURLRequest` objects directly, Alamofire provides API that can accommodate that.

See the implementation of the `Alamofire.Manager` and `Alamofire.Request` classes for details on what's possible. Documentation and additional API refinement are forthcoming in future releases.

M
Mattt Thompson 已提交
324 325 326 327 328 329 330 331 332 333 334 335 336
---

## Contact

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

### Creator

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

## License

Alamofire is released under an MIT license. See LICENSE for more information.