[Swift] Update samples to use latest Alamofire

In order to run the integration tests, we needed to generate updated
clients.
This commit is contained in:
Jack Wink 2016-07-30 12:19:06 -07:00
parent f2ebb08b33
commit be6c661fa0
66 changed files with 3381 additions and 1718 deletions

View File

@ -9,5 +9,5 @@ Pod::Spec.new do |s|
s.homepage = 'https://github.com/swagger-api/swagger-codegen' s.homepage = 'https://github.com/swagger-api/swagger-codegen'
s.summary = 'PetstoreClient' s.summary = 'PetstoreClient'
s.source_files = 'PetstoreClient/Classes/Swaggers/**/*.swift' s.source_files = 'PetstoreClient/Classes/Swaggers/**/*.swift'
s.dependency 'Alamofire', '~> 3.1.5' s.dependency 'Alamofire', '~> 3.4.1'
end end

View File

@ -108,13 +108,13 @@ public class PetAPI: APIBase {
- OAuth: - OAuth:
- type: oauth2 - type: oauth2
- name: petstore_auth - name: petstore_auth
- examples: [{contentType=application/json, example={ - examples: [{example={
"name" : "Puma", "name" : "Puma",
"type" : "Dog", "type" : "Dog",
"color" : "Black", "color" : "Black",
"gender" : "Female", "gender" : "Female",
"breed" : "Mixed" "breed" : "Mixed"
}}] }, contentType=application/json}]
- parameter status: (query) Status values that need to be considered for filter (optional, default to available) - parameter status: (query) Status values that need to be considered for filter (optional, default to available)
@ -157,20 +157,20 @@ public class PetAPI: APIBase {
- OAuth: - OAuth:
- type: oauth2 - type: oauth2
- name: petstore_auth - name: petstore_auth
- examples: [{contentType=application/json, example=[ { - examples: [{example=[ {
"photoUrls" : [ "aeiou" ], "tags" : [ {
"name" : "doggie", "id" : 123456789,
"name" : "aeiou"
} ],
"id" : 123456789, "id" : 123456789,
"category" : { "category" : {
"name" : "aeiou", "id" : 123456789,
"id" : 123456789 "name" : "aeiou"
}, },
"tags" : [ { "status" : "aeiou",
"name" : "aeiou", "name" : "doggie",
"id" : 123456789 "photoUrls" : [ "aeiou" ]
} ], } ], contentType=application/json}, {example=<Pet>
"status" : "aeiou"
} ]}, {contentType=application/xml, example=<Pet>
<id>123456</id> <id>123456</id>
<name>doggie</name> <name>doggie</name>
<photoUrls> <photoUrls>
@ -179,21 +179,21 @@ public class PetAPI: APIBase {
<tags> <tags>
</tags> </tags>
<status>string</status> <status>string</status>
</Pet>}] </Pet>, contentType=application/xml}]
- examples: [{contentType=application/json, example=[ { - examples: [{example=[ {
"photoUrls" : [ "aeiou" ], "tags" : [ {
"name" : "doggie", "id" : 123456789,
"name" : "aeiou"
} ],
"id" : 123456789, "id" : 123456789,
"category" : { "category" : {
"name" : "aeiou", "id" : 123456789,
"id" : 123456789 "name" : "aeiou"
}, },
"tags" : [ { "status" : "aeiou",
"name" : "aeiou", "name" : "doggie",
"id" : 123456789 "photoUrls" : [ "aeiou" ]
} ], } ], contentType=application/json}, {example=<Pet>
"status" : "aeiou"
} ]}, {contentType=application/xml, example=<Pet>
<id>123456</id> <id>123456</id>
<name>doggie</name> <name>doggie</name>
<photoUrls> <photoUrls>
@ -202,7 +202,7 @@ public class PetAPI: APIBase {
<tags> <tags>
</tags> </tags>
<status>string</status> <status>string</status>
</Pet>}] </Pet>, contentType=application/xml}]
- parameter tags: (query) Tags to filter by (optional) - parameter tags: (query) Tags to filter by (optional)
@ -242,26 +242,26 @@ public class PetAPI: APIBase {
Find pet by ID Find pet by ID
- GET /pet/{petId} - GET /pet/{petId}
- Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions
- OAuth:
- type: oauth2
- name: petstore_auth
- API Key: - API Key:
- type: apiKey api_key - type: apiKey api_key
- name: api_key - name: api_key
- examples: [{contentType=application/json, example={ - OAuth:
"photoUrls" : [ "aeiou" ], - type: oauth2
"name" : "doggie", - name: petstore_auth
- examples: [{example={
"tags" : [ {
"id" : 123456789,
"name" : "aeiou"
} ],
"id" : 123456789, "id" : 123456789,
"category" : { "category" : {
"name" : "aeiou", "id" : 123456789,
"id" : 123456789 "name" : "aeiou"
}, },
"tags" : [ { "status" : "aeiou",
"name" : "aeiou", "name" : "doggie",
"id" : 123456789 "photoUrls" : [ "aeiou" ]
} ], }, contentType=application/json}, {example=<Pet>
"status" : "aeiou"
}}, {contentType=application/xml, example=<Pet>
<id>123456</id> <id>123456</id>
<name>doggie</name> <name>doggie</name>
<photoUrls> <photoUrls>
@ -270,21 +270,21 @@ public class PetAPI: APIBase {
<tags> <tags>
</tags> </tags>
<status>string</status> <status>string</status>
</Pet>}] </Pet>, contentType=application/xml}]
- examples: [{contentType=application/json, example={ - examples: [{example={
"photoUrls" : [ "aeiou" ], "tags" : [ {
"name" : "doggie", "id" : 123456789,
"name" : "aeiou"
} ],
"id" : 123456789, "id" : 123456789,
"category" : { "category" : {
"name" : "aeiou", "id" : 123456789,
"id" : 123456789 "name" : "aeiou"
}, },
"tags" : [ { "status" : "aeiou",
"name" : "aeiou", "name" : "doggie",
"id" : 123456789 "photoUrls" : [ "aeiou" ]
} ], }, contentType=application/json}, {example=<Pet>
"status" : "aeiou"
}}, {contentType=application/xml, example=<Pet>
<id>123456</id> <id>123456</id>
<name>doggie</name> <name>doggie</name>
<photoUrls> <photoUrls>
@ -293,7 +293,7 @@ public class PetAPI: APIBase {
<tags> <tags>
</tags> </tags>
<status>string</status> <status>string</status>
</Pet>}] </Pet>, contentType=application/xml}]
- parameter petId: (path) ID of pet that needs to be fetched - parameter petId: (path) ID of pet that needs to be fetched

View File

@ -67,12 +67,12 @@ public class StoreAPI: APIBase {
- API Key: - API Key:
- type: apiKey api_key - type: apiKey api_key
- name: api_key - name: api_key
- examples: [{contentType=application/json, example={ - examples: [{example={
"key" : 123 "key" : 123
}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] }, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}]
- examples: [{contentType=application/json, example={ - examples: [{example={
"key" : 123 "key" : 123
}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] }, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}]
- returns: RequestBuilder<[String:Int32]> - returns: RequestBuilder<[String:Int32]>
*/ */
@ -108,36 +108,36 @@ public class StoreAPI: APIBase {
Find purchase order by ID Find purchase order by ID
- GET /store/order/{orderId} - GET /store/order/{orderId}
- For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
- examples: [{contentType=application/json, example={ - examples: [{example={
"petId" : 123456789,
"quantity" : 123,
"id" : 123456789, "id" : 123456789,
"shipDate" : "2000-01-23T04:56:07.000+00:00", "petId" : 123456789,
"complete" : true, "complete" : true,
"status" : "aeiou" "status" : "aeiou",
}}, {contentType=application/xml, example=<Order> "quantity" : 123,
"shipDate" : "2000-01-23T04:56:07.000+00:00"
}, contentType=application/json}, {example=<Order>
<id>123456</id> <id>123456</id>
<petId>123456</petId> <petId>123456</petId>
<quantity>0</quantity> <quantity>0</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate> <shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>string</status> <status>string</status>
<complete>true</complete> <complete>true</complete>
</Order>}] </Order>, contentType=application/xml}]
- examples: [{contentType=application/json, example={ - examples: [{example={
"petId" : 123456789,
"quantity" : 123,
"id" : 123456789, "id" : 123456789,
"shipDate" : "2000-01-23T04:56:07.000+00:00", "petId" : 123456789,
"complete" : true, "complete" : true,
"status" : "aeiou" "status" : "aeiou",
}}, {contentType=application/xml, example=<Order> "quantity" : 123,
"shipDate" : "2000-01-23T04:56:07.000+00:00"
}, contentType=application/json}, {example=<Order>
<id>123456</id> <id>123456</id>
<petId>123456</petId> <petId>123456</petId>
<quantity>0</quantity> <quantity>0</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate> <shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>string</status> <status>string</status>
<complete>true</complete> <complete>true</complete>
</Order>}] </Order>, contentType=application/xml}]
- parameter orderId: (path) ID of pet that needs to be fetched - parameter orderId: (path) ID of pet that needs to be fetched
@ -176,36 +176,36 @@ public class StoreAPI: APIBase {
Place an order for a pet Place an order for a pet
- POST /store/order - POST /store/order
- -
- examples: [{contentType=application/json, example={ - examples: [{example={
"petId" : 123456789,
"quantity" : 123,
"id" : 123456789, "id" : 123456789,
"shipDate" : "2000-01-23T04:56:07.000+00:00", "petId" : 123456789,
"complete" : true, "complete" : true,
"status" : "aeiou" "status" : "aeiou",
}}, {contentType=application/xml, example=<Order> "quantity" : 123,
"shipDate" : "2000-01-23T04:56:07.000+00:00"
}, contentType=application/json}, {example=<Order>
<id>123456</id> <id>123456</id>
<petId>123456</petId> <petId>123456</petId>
<quantity>0</quantity> <quantity>0</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate> <shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>string</status> <status>string</status>
<complete>true</complete> <complete>true</complete>
</Order>}] </Order>, contentType=application/xml}]
- examples: [{contentType=application/json, example={ - examples: [{example={
"petId" : 123456789,
"quantity" : 123,
"id" : 123456789, "id" : 123456789,
"shipDate" : "2000-01-23T04:56:07.000+00:00", "petId" : 123456789,
"complete" : true, "complete" : true,
"status" : "aeiou" "status" : "aeiou",
}}, {contentType=application/xml, example=<Order> "quantity" : 123,
"shipDate" : "2000-01-23T04:56:07.000+00:00"
}, contentType=application/json}, {example=<Order>
<id>123456</id> <id>123456</id>
<petId>123456</petId> <petId>123456</petId>
<quantity>0</quantity> <quantity>0</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate> <shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>string</status> <status>string</status>
<complete>true</complete> <complete>true</complete>
</Order>}] </Order>, contentType=application/xml}]
- parameter body: (body) order placed for purchasing the pet (optional) - parameter body: (body) order placed for purchasing the pet (optional)

View File

@ -167,16 +167,16 @@ public class UserAPI: APIBase {
Get user by user name Get user by user name
- GET /user/{username} - GET /user/{username}
- -
- examples: [{contentType=application/json, example={ - examples: [{example={
"firstName" : "aeiou",
"lastName" : "aeiou",
"password" : "aeiou",
"userStatus" : 123,
"phone" : "aeiou",
"id" : 123456789, "id" : 123456789,
"lastName" : "aeiou",
"phone" : "aeiou",
"username" : "aeiou",
"email" : "aeiou", "email" : "aeiou",
"username" : "aeiou" "userStatus" : 123,
}}, {contentType=application/xml, example=<User> "firstName" : "aeiou",
"password" : "aeiou"
}, contentType=application/json}, {example=<User>
<id>123456</id> <id>123456</id>
<username>string</username> <username>string</username>
<firstName>string</firstName> <firstName>string</firstName>
@ -185,17 +185,17 @@ public class UserAPI: APIBase {
<password>string</password> <password>string</password>
<phone>string</phone> <phone>string</phone>
<userStatus>0</userStatus> <userStatus>0</userStatus>
</User>}] </User>, contentType=application/xml}]
- examples: [{contentType=application/json, example={ - examples: [{example={
"firstName" : "aeiou",
"lastName" : "aeiou",
"password" : "aeiou",
"userStatus" : 123,
"phone" : "aeiou",
"id" : 123456789, "id" : 123456789,
"lastName" : "aeiou",
"phone" : "aeiou",
"username" : "aeiou",
"email" : "aeiou", "email" : "aeiou",
"username" : "aeiou" "userStatus" : 123,
}}, {contentType=application/xml, example=<User> "firstName" : "aeiou",
"password" : "aeiou"
}, contentType=application/json}, {example=<User>
<id>123456</id> <id>123456</id>
<username>string</username> <username>string</username>
<firstName>string</firstName> <firstName>string</firstName>
@ -204,7 +204,7 @@ public class UserAPI: APIBase {
<password>string</password> <password>string</password>
<phone>string</phone> <phone>string</phone>
<userStatus>0</userStatus> <userStatus>0</userStatus>
</User>}] </User>, contentType=application/xml}]
- parameter username: (path) The name that needs to be fetched. Use user1 for testing. - parameter username: (path) The name that needs to be fetched. Use user1 for testing.
@ -244,8 +244,8 @@ public class UserAPI: APIBase {
Logs user into the system Logs user into the system
- GET /user/login - GET /user/login
- -
- examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}]
- examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}]
- parameter username: (query) The user name for login (optional) - parameter username: (query) The user name for login (optional)
- parameter password: (query) The password for login in clear text (optional) - parameter password: (query) The password for login in clear text (optional)

View File

@ -90,7 +90,7 @@ class AlamofireRequestBuilder<T>: RequestBuilder<T> {
switch T.self { switch T.self {
case is NSData.Type: case is NSData.Type:
validatedRequest.responseData({ (dataResponse) in validatedRequest.responseData(completionHandler: { (dataResponse) in
cleanupRequest() cleanupRequest()
if (dataResponse.result.isFailure) { if (dataResponse.result.isFailure) {

View File

@ -1,4 +1,4 @@
Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

View File

@ -1,7 +1,7 @@
![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/assets/alamofire.png) ![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/assets/alamofire.png)
[![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg)](https://travis-ci.org/Alamofire/Alamofire) [![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg)](https://travis-ci.org/Alamofire/Alamofire)
[![Cocoapods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg) [![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg)
[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![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) [![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) [![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat)](http://twitter.com/AlamofireSF)
@ -22,10 +22,17 @@ Alamofire is an HTTP networking library written in Swift.
- [x] Comprehensive Unit Test Coverage - [x] Comprehensive Unit Test Coverage
- [x] [Complete Documentation](http://cocoadocs.org/docsets/Alamofire) - [x] [Complete Documentation](http://cocoadocs.org/docsets/Alamofire)
## 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.
* [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.
## Requirements ## Requirements
- iOS 8.0+ / Mac OS X 10.9+ / tvOS 9.0+ / watchOS 2.0+ - iOS 8.0+ / Mac OS X 10.9+ / tvOS 9.0+ / watchOS 2.0+
- Xcode 7.2+ - Xcode 7.3+
## Migration Guides ## Migration Guides
@ -60,10 +67,12 @@ To integrate Alamofire into your Xcode project using CocoaPods, specify it in yo
```ruby ```ruby
source 'https://github.com/CocoaPods/Specs.git' source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0' platform :ios, '9.0'
use_frameworks! use_frameworks!
pod 'Alamofire', '~> 3.0' target '<Your Target Name>' do
pod 'Alamofire', '~> 3.4'
end
``` ```
Then, run the following command: Then, run the following command:
@ -86,7 +95,7 @@ $ brew install carthage
To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`:
```ogdl ```ogdl
github "Alamofire/Alamofire" ~> 3.0 github "Alamofire/Alamofire" ~> 3.4
``` ```
Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project. Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project.
@ -161,6 +170,38 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
> 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. > 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.
### 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)
}
}
```
### Response Serialization ### Response Serialization
**Built-in Response Methods** **Built-in Response Methods**
@ -175,6 +216,7 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
```swift ```swift
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.validate()
.response { request, response, data, error in .response { request, response, data, error in
print(request) print(request)
print(response) print(response)
@ -183,12 +225,13 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
} }
``` ```
> 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 responser serializers taking advantage of `Response` and `Result` types. > 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.
#### Response Data Handler #### Response Data Handler
```swift ```swift
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.validate()
.responseData { response in .responseData { response in
print(response.request) print(response.request)
print(response.response) print(response.response)
@ -200,6 +243,7 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
```swift ```swift
Alamofire.request(.GET, "https://httpbin.org/get") Alamofire.request(.GET, "https://httpbin.org/get")
.validate()
.responseString { response in .responseString { response in
print("Success: \(response.result.isSuccess)") print("Success: \(response.result.isSuccess)")
print("Response String: \(response.result.value)") print("Response String: \(response.result.value)")
@ -210,6 +254,7 @@ Alamofire.request(.GET, "https://httpbin.org/get")
```swift ```swift
Alamofire.request(.GET, "https://httpbin.org/get") Alamofire.request(.GET, "https://httpbin.org/get")
.validate()
.responseJSON { response in .responseJSON { response in
debugPrint(response) debugPrint(response)
} }
@ -221,6 +266,7 @@ Response handlers can even be chained:
```swift ```swift
Alamofire.request(.GET, "https://httpbin.org/get") Alamofire.request(.GET, "https://httpbin.org/get")
.validate()
.responseString { response in .responseString { response in
print("Response String: \(response.result.value)") print("Response String: \(response.result.value)")
} }
@ -332,7 +378,7 @@ Adding a custom HTTP header to a `Request` is supported directly in the global `
```swift ```swift
let headers = [ let headers = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Content-Type": "application/x-www-form-urlencoded" "Accept": "application/json"
] ]
Alamofire.request(.GET, "https://httpbin.org/get", headers: headers) Alamofire.request(.GET, "https://httpbin.org/get", headers: headers)
@ -374,6 +420,7 @@ Alamofire.upload(.POST, "https://httpbin.org/post", file: fileURL)
print("Total bytes written on main queue: \(totalBytesWritten)") print("Total bytes written on main queue: \(totalBytesWritten)")
} }
} }
.validate()
.responseJSON { response in .responseJSON { response in
debugPrint(response) debugPrint(response)
} }
@ -540,38 +587,25 @@ Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)")
} }
``` ```
### Validation ### Timeline
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. Alamofire collects timings throughout the lifecycle of a `Request` and creates a `Timeline` object exposed as a property on a `Response`.
#### 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 ```swift
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.validate() .validate()
.responseJSON { response in .responseJSON { response in
switch response.result { print(response.timeline)
case .Success:
print("Validation Successful")
case .Failure(let error):
print(error)
}
} }
``` ```
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
### Printable ### Printable
```swift ```swift
@ -679,6 +713,20 @@ Requests can be suspended, resumed, and cancelled:
### Response Serialization ### Response Serialization
#### Handling Errors
Before implementing custom response serializers or object serialization methods, it's important to be prepared to handle any errors that may occur. 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
enum BackendError: ErrorType {
case Network(error: NSError)
case DataSerialization(reason: String)
case JSONSerialization(error: NSError)
case ObjectSerialization(reason: String)
case XMLSerialization(error: NSError)
}
```
#### Creating a Custom Response Serializer #### Creating a Custom Response Serializer
Alamofire provides built-in response serialization for strings, JSON, and property lists, but others can be added in extensions on `Alamofire.Request`. Alamofire provides built-in response serialization for strings, JSON, and property lists, but others can be added in extensions on `Alamofire.Request`.
@ -687,26 +735,24 @@ For example, here's how a response handler using [Ono](https://github.com/mattt/
```swift ```swift
extension Request { extension Request {
public static func XMLResponseSerializer() -> ResponseSerializer<ONOXMLDocument, NSError> { public static func XMLResponseSerializer() -> ResponseSerializer<ONOXMLDocument, BackendError> {
return ResponseSerializer { request, response, data, error in return ResponseSerializer { request, response, data, error in
guard error == nil else { return .Failure(error!) } guard error == nil else { return .Failure(.Network(error: error!)) }
guard let validData = data else { guard let validData = data else {
let failureReason = "Data could not be serialized. Input data was nil." return .Failure(.DataSerialization(reason: "Data could not be serialized. Input data was nil."))
let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
return .Failure(error)
} }
do { do {
let XML = try ONOXMLDocument(data: validData) let XML = try ONOXMLDocument(data: validData)
return .Success(XML) return .Success(XML)
} catch { } catch {
return .Failure(error as NSError) return .Failure(.XMLSerialization(error: error as NSError))
} }
} }
} }
public func responseXMLDocument(completionHandler: Response<ONOXMLDocument, NSError> -> Void) -> Self { public func responseXMLDocument(completionHandler: Response<ONOXMLDocument, BackendError> -> Void) -> Self {
return response(responseSerializer: Request.XMLResponseSerializer(), completionHandler: completionHandler) return response(responseSerializer: Request.XMLResponseSerializer(), completionHandler: completionHandler)
} }
} }
@ -722,9 +768,9 @@ public protocol ResponseObjectSerializable {
} }
extension Request { extension Request {
public func responseObject<T: ResponseObjectSerializable>(completionHandler: Response<T, NSError> -> Void) -> Self { public func responseObject<T: ResponseObjectSerializable>(completionHandler: Response<T, BackendError> -> Void) -> Self {
let responseSerializer = ResponseSerializer<T, NSError> { request, response, data, error in let responseSerializer = ResponseSerializer<T, BackendError> { request, response, data, error in
guard error == nil else { return .Failure(error!) } guard error == nil else { return .Failure(.Network(error: error!)) }
let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments) let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
let result = JSONResponseSerializer.serializeResponse(request, response, data, error) let result = JSONResponseSerializer.serializeResponse(request, response, data, error)
@ -737,12 +783,10 @@ extension Request {
{ {
return .Success(responseObject) return .Success(responseObject)
} else { } else {
let failureReason = "JSON could not be serialized into response object: \(value)" return .Failure(.ObjectSerialization(reason: "JSON could not be serialized into response object: \(value)"))
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
return .Failure(error)
} }
case .Failure(let error): case .Failure(let error):
return .Failure(error) return .Failure(.JSONSerialization(error: error))
} }
} }
@ -765,7 +809,7 @@ final class User: ResponseObjectSerializable {
```swift ```swift
Alamofire.request(.GET, "https://example.com/users/mattt") Alamofire.request(.GET, "https://example.com/users/mattt")
.responseObject { (response: Response<User, NSError>) in .responseObject { (response: Response<User, BackendError>) in
debugPrint(response) debugPrint(response)
} }
``` ```
@ -777,10 +821,26 @@ public protocol ResponseCollectionSerializable {
static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Self] static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Self]
} }
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
}
}
extension Alamofire.Request { extension Alamofire.Request {
public func responseCollection<T: ResponseCollectionSerializable>(completionHandler: Response<[T], NSError> -> Void) -> Self { public func responseCollection<T: ResponseCollectionSerializable>(completionHandler: Response<[T], BackendError> -> Void) -> Self {
let responseSerializer = ResponseSerializer<[T], NSError> { request, response, data, error in let responseSerializer = ResponseSerializer<[T], BackendError> { request, response, data, error in
guard error == nil else { return .Failure(error!) } guard error == nil else { return .Failure(.Network(error: error!)) }
let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments) let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
let result = JSONSerializer.serializeResponse(request, response, data, error) let result = JSONSerializer.serializeResponse(request, response, data, error)
@ -790,12 +850,10 @@ extension Alamofire.Request {
if let response = response { if let response = response {
return .Success(T.collection(response: response, representation: value)) return .Success(T.collection(response: response, representation: value))
} else { } else {
let failureReason = "Response collection could not be serialized due to nil response" return .Failure(. ObjectSerialization(reason: "Response collection could not be serialized due to nil response"))
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
return .Failure(error)
} }
case .Failure(let error): case .Failure(let error):
return .Failure(error) return .Failure(.JSONSerialization(error: error))
} }
} }
@ -813,26 +871,12 @@ final class User: ResponseObjectSerializable, ResponseCollectionSerializable {
self.username = response.URL!.lastPathComponent! self.username = response.URL!.lastPathComponent!
self.name = representation.valueForKeyPath("name") as! String self.name = representation.valueForKeyPath("name") as! String
} }
static func collection(response 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
}
} }
``` ```
```swift ```swift
Alamofire.request(.GET, "http://example.com/users") Alamofire.request(.GET, "http://example.com/users")
.responseCollection { (response: Response<[User], NSError>) in .responseCollection { (response: Response<[User], BackendError>) in
debugPrint(response) debugPrint(response)
} }
``` ```
@ -912,7 +956,7 @@ enum Router: URLRequestConvertible {
var URLRequest: NSMutableURLRequest { var URLRequest: NSMutableURLRequest {
let result: (path: String, parameters: [String: AnyObject]) = { let result: (path: String, parameters: [String: AnyObject]) = {
switch self { switch self {
case .Search(let query, let page) where page > 1: case .Search(let query, let page) where page > 0:
return ("/search", ["q": query, "offset": Router.perPage * page]) return ("/search", ["q": query, "offset": Router.perPage * page])
case .Search(let query, _): case .Search(let query, _):
return ("/search", ["q": query]) return ("/search", ["q": query])
@ -997,6 +1041,74 @@ enum Router: URLRequestConvertible {
Alamofire.request(Router.ReadUser("mattt")) // GET /users/mattt Alamofire.request(Router.ReadUser("mattt")) // GET /users/mattt
``` ```
### 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.
### Security ### 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`. 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`.
@ -1075,7 +1187,7 @@ The `.PerformDefaultEvaluation`, `.PinCertificates` and `.PinPublicKeys` server
#### Validating the Certificate Chain #### Validating the Certificate Chain
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 certficates or public keys. A value of `false` will skip the certificate chain validation, but will still perform the byte equality check. 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.
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. 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.
@ -1114,19 +1226,41 @@ Whether you need to set the `NSExceptionRequiresForwardSecrecy` to `NO` depends
> It is recommended to always use valid certificates in production environments. > It is recommended to always use valid certificates in production environments.
### 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()
```
> Make sure to remember to retain the `manager` in the above example, or no status changes will be reported.
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.
* 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."
> It is recommended to check out [WWDC 2012 Session 706, "Networking Best Practices"](https://developer.apple.com/videos/play/wwdc2012-706/) for more info.
--- ---
## 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.
## Open Rdars ## Open Rdars
The following rdars have some affect on the current implementation of Alamofire. The following rdars have some affect on the current implementation of Alamofire.
* [rdar://21349340](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case * [rdar://21349340](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case
* [rdar://26761490](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage
## FAQ ## FAQ
@ -1144,6 +1278,20 @@ Alamofire is owned and maintained by the [Alamofire Software Foundation](http://
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. 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.
## 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>
## License ## License
Alamofire is released under the MIT license. See LICENSE for details. Alamofire is released under the MIT license. See LICENSE for details.

View File

@ -1,6 +1,7 @@
//
// Alamofire.swift // Alamofire.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation

View File

@ -1,6 +1,7 @@
//
// Download.swift // Download.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -211,6 +213,8 @@ extension Request {
totalBytesWritten: Int64, totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64) totalBytesExpectedToWrite: Int64)
{ {
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let downloadTaskDidWriteData = downloadTaskDidWriteData { if let downloadTaskDidWriteData = downloadTaskDidWriteData {
downloadTaskDidWriteData( downloadTaskDidWriteData(
session, session,

View File

@ -1,6 +1,7 @@
//
// Error.swift // Error.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -39,6 +41,15 @@ public struct Error {
case PropertyListSerializationFailed = -6007 case PropertyListSerializationFailed = -6007
} }
/// Custom keys contained within certain NSError `userInfo` dictionaries generated by Alamofire.
public struct UserInfoKeys {
/// The content type user info key for a `.ContentTypeValidationFailed` error stored as a `String` value.
public static let ContentType = "ContentType"
/// The status code user info key for a `.StatusCodeValidationFailed` error stored as an `Int` value.
public static let StatusCode = "StatusCode"
}
/** /**
Creates an `NSError` with the given error code and failure reason. Creates an `NSError` with the given error code and failure reason.
@ -47,6 +58,7 @@ public struct Error {
- returns: An `NSError` with the given error code and failure reason. - returns: An `NSError` with the given error code and failure reason.
*/ */
@available(*, deprecated=3.4.0)
public static func errorWithCode(code: Code, failureReason: String) -> NSError { public static func errorWithCode(code: Code, failureReason: String) -> NSError {
return errorWithCode(code.rawValue, failureReason: failureReason) return errorWithCode(code.rawValue, failureReason: failureReason)
} }
@ -59,8 +71,18 @@ public struct Error {
- returns: An `NSError` with the given error code and failure reason. - returns: An `NSError` with the given error code and failure reason.
*/ */
@available(*, deprecated=3.4.0)
public static func errorWithCode(code: Int, failureReason: String) -> NSError { public static func errorWithCode(code: Int, failureReason: String) -> NSError {
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
return NSError(domain: Domain, code: code, userInfo: userInfo) return NSError(domain: Domain, code: code, userInfo: userInfo)
} }
static func error(domain domain: String = Error.Domain, code: Code, failureReason: String) -> NSError {
return error(domain: domain, code: code.rawValue, failureReason: failureReason)
}
static func error(domain domain: String = Error.Domain, code: Int, failureReason: String) -> NSError {
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
return NSError(domain: domain, code: code, userInfo: userInfo)
}
} }

View File

@ -1,6 +1,7 @@
//
// Manager.swift // Manager.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -56,17 +58,40 @@ public class Manager {
// User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3
let userAgent: String = { let userAgent: String = {
if let info = NSBundle.mainBundle().infoDictionary { if let info = NSBundle.mainBundle().infoDictionary {
let executable: AnyObject = info[kCFBundleExecutableKey as String] ?? "Unknown" let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown"
let bundle: AnyObject = info[kCFBundleIdentifierKey as String] ?? "Unknown" let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown"
let version: AnyObject = info[kCFBundleVersionKey as String] ?? "Unknown" let version = info[kCFBundleVersionKey as String] as? String ?? "Unknown"
let os: AnyObject = NSProcessInfo.processInfo().operatingSystemVersionString ?? "Unknown"
var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString let osNameVersion: String = {
let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString let versionString: String
if CFStringTransform(mutableUserAgent, UnsafeMutablePointer<CFRange>(nil), transform, false) { if #available(OSX 10.10, *) {
return mutableUserAgent as String let version = NSProcessInfo.processInfo().operatingSystemVersion
versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"
} else {
versionString = "10.9"
} }
let osName: String = {
#if os(iOS)
return "iOS"
#elseif os(watchOS)
return "watchOS"
#elseif os(tvOS)
return "tvOS"
#elseif os(OSX)
return "OS X"
#elseif os(Linux)
return "Linux"
#else
return "Unknown"
#endif
}()
return "\(osName) \(versionString)"
}()
return "\(executable)/\(bundle) (\(version); \(osNameVersion))"
} }
return "Alamofire" return "Alamofire"
@ -143,11 +168,11 @@ public class Manager {
delegate: SessionDelegate, delegate: SessionDelegate,
serverTrustPolicyManager: ServerTrustPolicyManager? = nil) serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{ {
guard delegate === session.delegate else { return nil }
self.delegate = delegate self.delegate = delegate
self.session = session self.session = session
guard delegate === session.delegate else { return nil }
commonInit(serverTrustPolicyManager: serverTrustPolicyManager) commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
} }
@ -218,18 +243,18 @@ public class Manager {
/** /**
Responsible for handling all delegate callbacks for the underlying session. Responsible for handling all delegate callbacks for the underlying session.
*/ */
public final class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate { public class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
private var subdelegates: [Int: Request.TaskDelegate] = [:] private var subdelegates: [Int: Request.TaskDelegate] = [:]
private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
subscript(task: NSURLSessionTask) -> Request.TaskDelegate? { /// Access the task delegate for the specified task in a thread-safe manner.
public subscript(task: NSURLSessionTask) -> Request.TaskDelegate? {
get { get {
var subdelegate: Request.TaskDelegate? var subdelegate: Request.TaskDelegate?
dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] } dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] }
return subdelegate return subdelegate
} }
set { set {
dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue } dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue }
} }
@ -254,6 +279,9 @@ public class Manager {
/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`. /// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`.
public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
/// Overrides all behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:` and requires the caller to call the `completionHandler`.
public var sessionDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`. /// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`.
public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)? public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)?
@ -281,6 +309,11 @@ public class Manager {
didReceiveChallenge challenge: NSURLAuthenticationChallenge, didReceiveChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void))
{ {
guard sessionDidReceiveChallengeWithCompletion == nil else {
sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler)
return
}
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
var credential: NSURLCredential? var credential: NSURLCredential?
@ -321,11 +354,23 @@ public class Manager {
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`. /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`.
public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)?
/// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:` and
/// requires the caller to call the `completionHandler`.
public var taskWillPerformHTTPRedirectionWithCompletion: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest, NSURLRequest? -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`. /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`.
public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
/// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:` and
/// requires the caller to call the `completionHandler`.
public var taskDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`. /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`.
public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream!)? public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)?
/// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:` and
/// requires the caller to call the `completionHandler`.
public var taskNeedNewBodyStreamWithCompletion: ((NSURLSession, NSURLSessionTask, NSInputStream? -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.
public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)? public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)?
@ -351,8 +396,13 @@ public class Manager {
task: NSURLSessionTask, task: NSURLSessionTask,
willPerformHTTPRedirection response: NSHTTPURLResponse, willPerformHTTPRedirection response: NSHTTPURLResponse,
newRequest request: NSURLRequest, newRequest request: NSURLRequest,
completionHandler: ((NSURLRequest?) -> Void)) completionHandler: NSURLRequest? -> Void)
{ {
guard taskWillPerformHTTPRedirectionWithCompletion == nil else {
taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler)
return
}
var redirectRequest: NSURLRequest? = request var redirectRequest: NSURLRequest? = request
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
@ -374,10 +424,16 @@ public class Manager {
session: NSURLSession, session: NSURLSession,
task: NSURLSessionTask, task: NSURLSessionTask,
didReceiveChallenge challenge: NSURLAuthenticationChallenge, didReceiveChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)
{ {
guard taskDidReceiveChallengeWithCompletion == nil else {
taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler)
return
}
if let taskDidReceiveChallenge = taskDidReceiveChallenge { if let taskDidReceiveChallenge = taskDidReceiveChallenge {
completionHandler(taskDidReceiveChallenge(session, task, challenge)) let result = taskDidReceiveChallenge(session, task, challenge)
completionHandler(result.0, result.1)
} else if let delegate = self[task] { } else if let delegate = self[task] {
delegate.URLSession( delegate.URLSession(
session, session,
@ -400,8 +456,13 @@ public class Manager {
public func URLSession( public func URLSession(
session: NSURLSession, session: NSURLSession,
task: NSURLSessionTask, task: NSURLSessionTask,
needNewBodyStream completionHandler: ((NSInputStream?) -> Void)) needNewBodyStream completionHandler: NSInputStream? -> Void)
{ {
guard taskNeedNewBodyStreamWithCompletion == nil else {
taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler)
return
}
if let taskNeedNewBodyStream = taskNeedNewBodyStream { if let taskNeedNewBodyStream = taskNeedNewBodyStream {
completionHandler(taskNeedNewBodyStream(session, task)) completionHandler(taskNeedNewBodyStream(session, task))
} else if let delegate = self[task] { } else if let delegate = self[task] {
@ -452,6 +513,8 @@ public class Manager {
delegate.URLSession(session, task: task, didCompleteWithError: error) delegate.URLSession(session, task: task, didCompleteWithError: error)
} }
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidComplete, object: task)
self[task] = nil self[task] = nil
} }
@ -462,6 +525,10 @@ public class Manager {
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`. /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`.
public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)? public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)?
/// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:` and
/// requires caller to call the `completionHandler`.
public var dataTaskDidReceiveResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSURLResponse, NSURLSessionResponseDisposition -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`. /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`.
public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)? public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)?
@ -469,7 +536,11 @@ public class Manager {
public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)? public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`. /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`.
public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse!)? public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)?
/// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:` and
/// requires caller to call the `completionHandler`.
public var dataTaskWillCacheResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse, NSCachedURLResponse? -> Void) -> Void)?
// MARK: Delegate Methods // MARK: Delegate Methods
@ -487,8 +558,13 @@ public class Manager {
session: NSURLSession, session: NSURLSession,
dataTask: NSURLSessionDataTask, dataTask: NSURLSessionDataTask,
didReceiveResponse response: NSURLResponse, didReceiveResponse response: NSURLResponse,
completionHandler: ((NSURLSessionResponseDisposition) -> Void)) completionHandler: NSURLSessionResponseDisposition -> Void)
{ {
guard dataTaskDidReceiveResponseWithCompletion == nil else {
dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler)
return
}
var disposition: NSURLSessionResponseDisposition = .Allow var disposition: NSURLSessionResponseDisposition = .Allow
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
@ -550,8 +626,13 @@ public class Manager {
session: NSURLSession, session: NSURLSession,
dataTask: NSURLSessionDataTask, dataTask: NSURLSessionDataTask,
willCacheResponse proposedResponse: NSCachedURLResponse, willCacheResponse proposedResponse: NSCachedURLResponse,
completionHandler: ((NSCachedURLResponse?) -> Void)) completionHandler: NSCachedURLResponse? -> Void)
{ {
guard dataTaskWillCacheResponseWithCompletion == nil else {
dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler)
return
}
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse))
} else if let delegate = self[dataTask] as? Request.DataTaskDelegate { } else if let delegate = self[dataTask] as? Request.DataTaskDelegate {
@ -674,17 +755,21 @@ public class Manager {
// MARK: - NSObject // MARK: - NSObject
public override func respondsToSelector(selector: Selector) -> Bool { public override func respondsToSelector(selector: Selector) -> Bool {
switch selector { #if !os(OSX)
case "URLSession:didBecomeInvalidWithError:": if selector == #selector(NSURLSessionDelegate.URLSessionDidFinishEventsForBackgroundURLSession(_:)) {
return sessionDidBecomeInvalidWithError != nil
case "URLSession:didReceiveChallenge:completionHandler:":
return sessionDidReceiveChallenge != nil
case "URLSessionDidFinishEventsForBackgroundURLSession:":
return sessionDidFinishEventsForBackgroundURLSession != nil return sessionDidFinishEventsForBackgroundURLSession != nil
case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:": }
return taskWillPerformHTTPRedirection != nil #endif
case "URLSession:dataTask:didReceiveResponse:completionHandler:":
return dataTaskDidReceiveResponse != nil switch selector {
case #selector(NSURLSessionDelegate.URLSession(_:didBecomeInvalidWithError:)):
return sessionDidBecomeInvalidWithError != nil
case #selector(NSURLSessionDelegate.URLSession(_:didReceiveChallenge:completionHandler:)):
return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil)
case #selector(NSURLSessionTaskDelegate.URLSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)):
return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil)
case #selector(NSURLSessionDataDelegate.URLSession(_:dataTask:didReceiveResponse:completionHandler:)):
return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil)
default: default:
return self.dynamicType.instancesRespondToSelector(selector) return self.dynamicType.instancesRespondToSelector(selector)
} }

View File

@ -1,6 +1,7 @@
//
// MultipartFormData.swift // MultipartFormData.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -217,7 +219,7 @@ public class MultipartFormData {
appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType) appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType)
} else { } else {
let failureReason = "Failed to extract the fileName of the provided URL: \(fileURL)" let failureReason = "Failed to extract the fileName of the provided URL: \(fileURL)"
setBodyPartError(Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)) setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
} }
} }
@ -245,8 +247,7 @@ public class MultipartFormData {
guard fileURL.fileURL else { guard fileURL.fileURL else {
let failureReason = "The file URL does not point to a file URL: \(fileURL)" let failureReason = "The file URL does not point to a file URL: \(fileURL)"
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
setBodyPartError(error)
return return
} }
@ -261,8 +262,7 @@ public class MultipartFormData {
} }
guard isReachable else { guard isReachable else {
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)") setBodyPartError(code: NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)")
setBodyPartError(error)
return return
} }
@ -277,8 +277,7 @@ public class MultipartFormData {
where NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) && !isDirectory else where NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) && !isDirectory else
{ {
let failureReason = "The file URL is a directory, not a file: \(fileURL)" let failureReason = "The file URL is a directory, not a file: \(fileURL)"
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
setBodyPartError(error)
return return
} }
@ -301,8 +300,7 @@ public class MultipartFormData {
guard let length = bodyContentLength else { guard let length = bodyContentLength else {
let failureReason = "Could not fetch attributes from the file URL: \(fileURL)" let failureReason = "Could not fetch attributes from the file URL: \(fileURL)"
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
setBodyPartError(error)
return return
} }
@ -312,8 +310,7 @@ public class MultipartFormData {
guard let stream = NSInputStream(URL: fileURL) else { guard let stream = NSInputStream(URL: fileURL) else {
let failureReason = "Failed to create an input stream from the file URL: \(fileURL)" let failureReason = "Failed to create an input stream from the file URL: \(fileURL)"
let error = Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason) setBodyPartError(code: NSURLErrorCannotOpenFile, failureReason: failureReason)
setBodyPartError(error)
return return
} }
@ -413,10 +410,10 @@ public class MultipartFormData {
if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) { if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) {
let failureReason = "A file already exists at the given file URL: \(fileURL)" let failureReason = "A file already exists at the given file URL: \(fileURL)"
throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason)
} else if !fileURL.fileURL { } else if !fileURL.fileURL {
let failureReason = "The URL does not point to a valid file: \(fileURL)" let failureReason = "The URL does not point to a valid file: \(fileURL)"
throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason)
} }
let outputStream: NSOutputStream let outputStream: NSOutputStream
@ -425,10 +422,9 @@ public class MultipartFormData {
outputStream = possibleOutputStream outputStream = possibleOutputStream
} else { } else {
let failureReason = "Failed to create an output stream with the given URL: \(fileURL)" let failureReason = "Failed to create an output stream with the given URL: \(fileURL)"
throw Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason) throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorCannotOpenFile, failureReason: failureReason)
} }
outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
outputStream.open() outputStream.open()
self.bodyParts.first?.hasInitialBoundary = true self.bodyParts.first?.hasInitialBoundary = true
@ -439,7 +435,6 @@ public class MultipartFormData {
} }
outputStream.close() outputStream.close()
outputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
} }
// MARK: - Private - Body Part Encoding // MARK: - Private - Body Part Encoding
@ -476,7 +471,6 @@ public class MultipartFormData {
private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) throws -> NSData { private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) throws -> NSData {
let inputStream = bodyPart.bodyStream let inputStream = bodyPart.bodyStream
inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
inputStream.open() inputStream.open()
var error: NSError? var error: NSError?
@ -495,7 +489,7 @@ public class MultipartFormData {
encoded.appendBytes(buffer, length: bytesRead) encoded.appendBytes(buffer, length: bytesRead)
} else if bytesRead < 0 { } else if bytesRead < 0 {
let failureReason = "Failed to read from input stream: \(inputStream)" let failureReason = "Failed to read from input stream: \(inputStream)"
error = Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason) error = Error.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason)
break break
} else { } else {
break break
@ -503,7 +497,6 @@ public class MultipartFormData {
} }
inputStream.close() inputStream.close()
inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
if let error = error { if let error = error {
throw error throw error
@ -537,7 +530,6 @@ public class MultipartFormData {
private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
let inputStream = bodyPart.bodyStream let inputStream = bodyPart.bodyStream
inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
inputStream.open() inputStream.open()
while inputStream.hasBytesAvailable { while inputStream.hasBytesAvailable {
@ -556,14 +548,13 @@ public class MultipartFormData {
try writeBuffer(&buffer, toOutputStream: outputStream) try writeBuffer(&buffer, toOutputStream: outputStream)
} else if bytesRead < 0 { } else if bytesRead < 0 {
let failureReason = "Failed to read from input stream: \(inputStream)" let failureReason = "Failed to read from input stream: \(inputStream)"
throw Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason) throw Error.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason)
} else { } else {
break break
} }
} }
inputStream.close() inputStream.close()
inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
} }
private func writeFinalBoundaryDataForBodyPart( private func writeFinalBoundaryDataForBodyPart(
@ -598,7 +589,7 @@ public class MultipartFormData {
if bytesWritten < 0 { if bytesWritten < 0 {
let failureReason = "Failed to write to output stream: \(outputStream)" let failureReason = "Failed to write to output stream: \(outputStream)"
throw Error.errorWithCode(.OutputStreamWriteFailed, failureReason: failureReason) throw Error.error(domain: NSURLErrorDomain, code: .OutputStreamWriteFailed, failureReason: failureReason)
} }
bytesToWrite -= bytesWritten bytesToWrite -= bytesWritten
@ -661,9 +652,8 @@ public class MultipartFormData {
// MARK: - Private - Errors // MARK: - Private - Errors
private func setBodyPartError(error: NSError) { private func setBodyPartError(code code: Int, failureReason: String) {
if bodyPartError == nil { guard bodyPartError == nil else { return }
bodyPartError = error bodyPartError = Error.error(domain: NSURLErrorDomain, code: code, failureReason: failureReason)
}
} }
} }

View File

@ -0,0 +1,244 @@
//
// NetworkReachabilityManager.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#if !os(watchOS)
import Foundation
import SystemConfiguration
/**
The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and
WiFi network interfaces.
Reachability can be used to determine background information about why a network operation failed, or to retry
network requests when a connection is established. It should not be used to prevent a user from initiating a network
request, as it's possible that an initial request may be required to establish reachability.
*/
public class NetworkReachabilityManager {
/**
Defines the various states of network reachability.
- Unknown: It is unknown whether the network is reachable.
- NotReachable: The network is not reachable.
- ReachableOnWWAN: The network is reachable over the WWAN connection.
- ReachableOnWiFi: The network is reachable over the WiFi connection.
*/
public enum NetworkReachabilityStatus {
case Unknown
case NotReachable
case Reachable(ConnectionType)
}
/**
Defines the various connection types detected by reachability flags.
- EthernetOrWiFi: The connection type is either over Ethernet or WiFi.
- WWAN: The connection type is a WWAN connection.
*/
public enum ConnectionType {
case EthernetOrWiFi
case WWAN
}
/// A closure executed when the network reachability status changes. The closure takes a single argument: the
/// network reachability status.
public typealias Listener = NetworkReachabilityStatus -> Void
// MARK: - Properties
/// Whether the network is currently reachable.
public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi }
/// Whether the network is currently reachable over the WWAN interface.
public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .Reachable(.WWAN) }
/// Whether the network is currently reachable over Ethernet or WiFi interface.
public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .Reachable(.EthernetOrWiFi) }
/// The current network reachability status.
public var networkReachabilityStatus: NetworkReachabilityStatus {
guard let flags = self.flags else { return .Unknown }
return networkReachabilityStatusForFlags(flags)
}
/// The dispatch queue to execute the `listener` closure on.
public var listenerQueue: dispatch_queue_t = dispatch_get_main_queue()
/// A closure executed when the network reachability status changes.
public var listener: Listener?
private var flags: SCNetworkReachabilityFlags? {
var flags = SCNetworkReachabilityFlags()
if SCNetworkReachabilityGetFlags(reachability, &flags) {
return flags
}
return nil
}
private let reachability: SCNetworkReachability
private var previousFlags: SCNetworkReachabilityFlags
// MARK: - Initialization
/**
Creates a `NetworkReachabilityManager` instance with the specified host.
- parameter host: The host used to evaluate network reachability.
- returns: The new `NetworkReachabilityManager` instance.
*/
public convenience init?(host: String) {
guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil }
self.init(reachability: reachability)
}
/**
Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0.
Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing
status of the device, both IPv4 and IPv6.
- returns: The new `NetworkReachabilityManager` instance.
*/
public convenience init?() {
var address = sockaddr_in()
address.sin_len = UInt8(sizeofValue(address))
address.sin_family = sa_family_t(AF_INET)
guard let reachability = withUnsafePointer(&address, {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}) else { return nil }
self.init(reachability: reachability)
}
private init(reachability: SCNetworkReachability) {
self.reachability = reachability
self.previousFlags = SCNetworkReachabilityFlags()
}
deinit {
stopListening()
}
// MARK: - Listening
/**
Starts listening for changes in network reachability status.
- returns: `true` if listening was started successfully, `false` otherwise.
*/
public func startListening() -> Bool {
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
context.info = UnsafeMutablePointer(Unmanaged.passUnretained(self).toOpaque())
let callbackEnabled = SCNetworkReachabilitySetCallback(
reachability,
{ (_, flags, info) in
let reachability = Unmanaged<NetworkReachabilityManager>.fromOpaque(COpaquePointer(info)).takeUnretainedValue()
reachability.notifyListener(flags)
},
&context
)
let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue)
dispatch_async(listenerQueue) {
self.previousFlags = SCNetworkReachabilityFlags()
self.notifyListener(self.flags ?? SCNetworkReachabilityFlags())
}
return callbackEnabled && queueEnabled
}
/**
Stops listening for changes in network reachability status.
*/
public func stopListening() {
SCNetworkReachabilitySetCallback(reachability, nil, nil)
SCNetworkReachabilitySetDispatchQueue(reachability, nil)
}
// MARK: - Internal - Listener Notification
func notifyListener(flags: SCNetworkReachabilityFlags) {
guard previousFlags != flags else { return }
previousFlags = flags
listener?(networkReachabilityStatusForFlags(flags))
}
// MARK: - Internal - Network Reachability Status
func networkReachabilityStatusForFlags(flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus {
guard flags.contains(.Reachable) else { return .NotReachable }
var networkStatus: NetworkReachabilityStatus = .NotReachable
if !flags.contains(.ConnectionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) }
if flags.contains(.ConnectionOnDemand) || flags.contains(.ConnectionOnTraffic) {
if !flags.contains(.InterventionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) }
}
#if os(iOS)
if flags.contains(.IsWWAN) { networkStatus = .Reachable(.WWAN) }
#endif
return networkStatus
}
}
// MARK: -
extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {}
/**
Returns whether the two network reachability status values are equal.
- parameter lhs: The left-hand side value to compare.
- parameter rhs: The right-hand side value to compare.
- returns: `true` if the two values are equal, `false` otherwise.
*/
public func ==(
lhs: NetworkReachabilityManager.NetworkReachabilityStatus,
rhs: NetworkReachabilityManager.NetworkReachabilityStatus)
-> Bool
{
switch (lhs, rhs) {
case (.Unknown, .Unknown):
return true
case (.NotReachable, .NotReachable):
return true
case let (.Reachable(lhsConnectionType), .Reachable(rhsConnectionType)):
return lhsConnectionType == rhsConnectionType
default:
return false
}
}
#endif

View File

@ -0,0 +1,47 @@
//
// Notifications.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// Contains all the `NSNotification` names posted by Alamofire with descriptions of each notification's payload.
public struct Notifications {
/// Used as a namespace for all `NSURLSessionTask` related notifications.
public struct Task {
/// Notification posted when an `NSURLSessionTask` is resumed. The notification `object` contains the resumed
/// `NSURLSessionTask`.
public static let DidResume = "com.alamofire.notifications.task.didResume"
/// Notification posted when an `NSURLSessionTask` is suspended. The notification `object` contains the
/// suspended `NSURLSessionTask`.
public static let DidSuspend = "com.alamofire.notifications.task.didSuspend"
/// Notification posted when an `NSURLSessionTask` is cancelled. The notification `object` contains the
/// cancelled `NSURLSessionTask`.
public static let DidCancel = "com.alamofire.notifications.task.didCancel"
/// Notification posted when an `NSURLSessionTask` is completed. The notification `object` contains the
/// completed `NSURLSessionTask`.
public static let DidComplete = "com.alamofire.notifications.task.didComplete"
}
}

View File

@ -1,6 +1,7 @@
//
// ParameterEncoding.swift // ParameterEncoding.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -69,8 +71,8 @@ public enum ParameterEncoding {
/** /**
Creates a URL request by encoding parameters and applying them onto an existing request. Creates a URL request by encoding parameters and applying them onto an existing request.
- parameter URLRequest: The request to have parameters applied - parameter URLRequest: The request to have parameters applied.
- parameter parameters: The parameters to apply - parameter parameters: The parameters to apply.
- returns: A tuple containing the constructed request and the error that occurred during parameter encoding, - returns: A tuple containing the constructed request and the error that occurred during parameter encoding,
if any. if any.
@ -82,9 +84,7 @@ public enum ParameterEncoding {
{ {
var mutableURLRequest = URLRequest.URLRequest var mutableURLRequest = URLRequest.URLRequest
guard let parameters = parameters where !parameters.isEmpty else { guard let parameters = parameters else { return (mutableURLRequest, nil) }
return (mutableURLRequest, nil)
}
var encodingError: NSError? = nil var encodingError: NSError? = nil
@ -118,7 +118,10 @@ public enum ParameterEncoding {
} }
if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) { if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) {
if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) { if let
URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false)
where !parameters.isEmpty
{
let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
URLComponents.percentEncodedQuery = percentEncodedQuery URLComponents.percentEncodedQuery = percentEncodedQuery
mutableURLRequest.URL = URLComponents.URL mutableURLRequest.URL = URLComponents.URL
@ -141,7 +144,10 @@ public enum ParameterEncoding {
let options = NSJSONWritingOptions() let options = NSJSONWritingOptions()
let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options) let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options)
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
mutableURLRequest.HTTPBody = data mutableURLRequest.HTTPBody = data
} catch { } catch {
encodingError = error as NSError encodingError = error as NSError
@ -153,7 +159,11 @@ public enum ParameterEncoding {
format: format, format: format,
options: options options: options
) )
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
}
mutableURLRequest.HTTPBody = data mutableURLRequest.HTTPBody = data
} catch { } catch {
encodingError = error as NSError encodingError = error as NSError
@ -219,7 +229,7 @@ public enum ParameterEncoding {
//========================================================================================================== //==========================================================================================================
// //
// Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few
// hundred Chinense characters causes various malloc error crashes. To avoid this issue until iOS 8 is no // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no
// longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more
// info, please refer to: // info, please refer to:
// //
@ -236,7 +246,7 @@ public enum ParameterEncoding {
while index != string.endIndex { while index != string.endIndex {
let startIndex = index let startIndex = index
let endIndex = index.advancedBy(batchSize, limit: string.endIndex) let endIndex = index.advancedBy(batchSize, limit: string.endIndex)
let range = Range(start: startIndex, end: endIndex) let range = startIndex..<endIndex
let substring = string.substringWithRange(range) let substring = string.substringWithRange(range)

View File

@ -1,6 +1,7 @@
//
// Request.swift // Request.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -48,6 +50,9 @@ public class Request {
/// The progress of the request lifecycle. /// The progress of the request lifecycle.
public var progress: NSProgress { return delegate.progress } public var progress: NSProgress { return delegate.progress }
var startTime: CFAbsoluteTime?
var endTime: CFAbsoluteTime?
// MARK: - Lifecycle // MARK: - Lifecycle
init(session: NSURLSession, task: NSURLSessionTask) { init(session: NSURLSession, task: NSURLSessionTask) {
@ -55,14 +60,16 @@ public class Request {
switch task { switch task {
case is NSURLSessionUploadTask: case is NSURLSessionUploadTask:
self.delegate = UploadTaskDelegate(task: task) delegate = UploadTaskDelegate(task: task)
case is NSURLSessionDataTask: case is NSURLSessionDataTask:
self.delegate = DataTaskDelegate(task: task) delegate = DataTaskDelegate(task: task)
case is NSURLSessionDownloadTask: case is NSURLSessionDownloadTask:
self.delegate = DownloadTaskDelegate(task: task) delegate = DownloadTaskDelegate(task: task)
default: default:
self.delegate = TaskDelegate(task: task) delegate = TaskDelegate(task: task)
} }
delegate.queue.addOperationWithBlock { self.endTime = CFAbsoluteTimeGetCurrent() }
} }
// MARK: - Authentication // MARK: - Authentication
@ -100,6 +107,22 @@ public class Request {
return self return self
} }
/**
Returns a base64 encoded basic authentication credential as an authorization header dictionary.
- parameter user: The user.
- parameter password: The password.
- returns: A dictionary with Authorization key and credential value or empty dictionary if encoding fails.
*/
public static func authorizationHeader(user user: String, password: String) -> [String: String] {
guard let data = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding) else { return [:] }
let credential = data.base64EncodedStringWithOptions([])
return ["Authorization": "Basic \(credential)"]
}
// MARK: - Progress // MARK: - Progress
/** /**
@ -148,18 +171,22 @@ public class Request {
// MARK: - State // MARK: - State
/**
Resumes the request.
*/
public func resume() {
if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() }
task.resume()
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidResume, object: task)
}
/** /**
Suspends the request. Suspends the request.
*/ */
public func suspend() { public func suspend() {
task.suspend() task.suspend()
} NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidSuspend, object: task)
/**
Resumes the request.
*/
public func resume() {
task.resume()
} }
/** /**
@ -176,6 +203,8 @@ public class Request {
} else { } else {
task.cancel() task.cancel()
} }
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidCancel, object: task)
} }
// MARK: - TaskDelegate // MARK: - TaskDelegate
@ -195,6 +224,7 @@ public class Request {
var data: NSData? { return nil } var data: NSData? { return nil }
var error: NSError? var error: NSError?
var initialResponseTime: CFAbsoluteTime?
var credential: NSURLCredential? var credential: NSURLCredential?
init(task: NSURLSessionTask) { init(task: NSURLSessionTask) {
@ -272,7 +302,7 @@ public class Request {
} }
} else { } else {
if challenge.previousFailureCount > 0 { if challenge.previousFailureCount > 0 {
disposition = .CancelAuthenticationChallenge disposition = .RejectProtectionSpace
} else { } else {
credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace) credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)
@ -381,6 +411,8 @@ public class Request {
} }
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let dataTaskDidReceiveData = dataTaskDidReceiveData { if let dataTaskDidReceiveData = dataTaskDidReceiveData {
dataTaskDidReceiveData(session, dataTask, data) dataTaskDidReceiveData(session, dataTask, data)
} else { } else {
@ -470,7 +502,7 @@ extension Request: CustomDebugStringConvertible {
let protectionSpace = NSURLProtectionSpace( let protectionSpace = NSURLProtectionSpace(
host: host, host: host,
port: URL.port?.integerValue ?? 0, port: URL.port?.integerValue ?? 0,
`protocol`: URL.scheme, protocol: URL.scheme,
realm: host, realm: host,
authenticationMethod: NSURLAuthenticationMethodHTTPBasic authenticationMethod: NSURLAuthenticationMethodHTTPBasic
) )
@ -496,33 +528,31 @@ extension Request: CustomDebugStringConvertible {
} }
} }
if let headerFields = request.allHTTPHeaderFields { var headers: [NSObject: AnyObject] = [:]
for (field, value) in headerFields {
switch field { if let additionalHeaders = session.configuration.HTTPAdditionalHeaders {
case "Cookie": for (field, value) in additionalHeaders where field != "Cookie" {
continue headers[field] = value
default:
components.append("-H \"\(field): \(value)\"")
}
} }
} }
if let additionalHeaders = session.configuration.HTTPAdditionalHeaders { if let headerFields = request.allHTTPHeaderFields {
for (field, value) in additionalHeaders { for (field, value) in headerFields where field != "Cookie" {
switch field { headers[field] = value
case "Cookie": }
continue }
default:
for (field, value) in headers {
components.append("-H \"\(field): \(value)\"") components.append("-H \"\(field): \(value)\"")
} }
}
}
if let if let
HTTPBodyData = request.HTTPBody, HTTPBodyData = request.HTTPBody,
HTTPBody = String(data: HTTPBodyData, encoding: NSUTF8StringEncoding) HTTPBody = String(data: HTTPBodyData, encoding: NSUTF8StringEncoding)
{ {
let escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"") var escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\\\"", withString: "\\\\\"")
escapedBody = escapedBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
components.append("-d \"\(escapedBody)\"") components.append("-d \"\(escapedBody)\"")
} }

View File

@ -1,6 +1,7 @@
//
// Response.swift // Response.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -36,6 +38,9 @@ public struct Response<Value, Error: ErrorType> {
/// The result of response serialization. /// The result of response serialization.
public let result: Result<Value, Error> public let result: Result<Value, Error>
/// The timeline of the complete lifecycle of the `Request`.
public let timeline: Timeline
/** /**
Initializes the `Response` instance with the specified URL request, URL response, server data and response Initializes the `Response` instance with the specified URL request, URL response, server data and response
serialization result. serialization result.
@ -44,14 +49,22 @@ public struct Response<Value, Error: ErrorType> {
- parameter response: The server's response to the URL request. - parameter response: The server's response to the URL request.
- parameter data: The data returned by the server. - parameter data: The data returned by the server.
- parameter result: The result of response serialization. - parameter result: The result of response serialization.
- parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`.
- returns: the new `Response` instance. - returns: the new `Response` instance.
*/ */
public init(request: NSURLRequest?, response: NSHTTPURLResponse?, data: NSData?, result: Result<Value, Error>) { public init(
request: NSURLRequest?,
response: NSHTTPURLResponse?,
data: NSData?,
result: Result<Value, Error>,
timeline: Timeline = Timeline())
{
self.request = request self.request = request
self.response = response self.response = response
self.data = data self.data = data
self.result = result self.result = result
self.timeline = timeline
} }
} }
@ -77,6 +90,7 @@ extension Response: CustomDebugStringConvertible {
output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil")
output.append("[Data]: \(data?.length ?? 0) bytes") output.append("[Data]: \(data?.length ?? 0) bytes")
output.append("[Result]: \(result.debugDescription)") output.append("[Result]: \(result.debugDescription)")
output.append("[Timeline]: \(timeline.debugDescription)")
return output.joinWithSeparator("\n") return output.joinWithSeparator("\n")
} }

View File

@ -1,6 +1,7 @@
//
// ResponseSerialization.swift // ResponseSerialization.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -29,10 +31,10 @@ import Foundation
*/ */
public protocol ResponseSerializerType { public protocol ResponseSerializerType {
/// The type of serialized object to be created by this `ResponseSerializerType`. /// The type of serialized object to be created by this `ResponseSerializerType`.
typealias SerializedObject associatedtype SerializedObject
/// The type of error to be created by this `ResponseSerializer` if serialization fails. /// The type of error to be created by this `ResponseSerializer` if serialization fails.
typealias ErrorObject: ErrorType associatedtype ErrorObject: ErrorType
/** /**
A closure used by response handlers that takes a request, response, data and error and returns a result. A closure used by response handlers that takes a request, response, data and error and returns a result.
@ -119,16 +121,25 @@ extension Request {
self.delegate.error self.delegate.error
) )
dispatch_async(queue ?? dispatch_get_main_queue()) { let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent()
let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime
let timeline = Timeline(
requestStartTime: self.startTime ?? CFAbsoluteTimeGetCurrent(),
initialResponseTime: initialResponseTime,
requestCompletedTime: requestCompletedTime,
serializationCompletedTime: CFAbsoluteTimeGetCurrent()
)
let response = Response<T.SerializedObject, T.ErrorObject>( let response = Response<T.SerializedObject, T.ErrorObject>(
request: self.request, request: self.request,
response: self.response, response: self.response,
data: self.delegate.data, data: self.delegate.data,
result: result result: result,
timeline: timeline
) )
completionHandler(response) dispatch_async(queue ?? dispatch_get_main_queue()) { completionHandler(response) }
}
} }
return self return self
@ -152,7 +163,7 @@ extension Request {
guard let validData = data else { guard let validData = data else {
let failureReason = "Data could not be serialized. Input data was nil." let failureReason = "Data could not be serialized. Input data was nil."
let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason) let error = Error.error(code: .DataSerializationFailed, failureReason: failureReason)
return .Failure(error) return .Failure(error)
} }
@ -167,8 +178,12 @@ extension Request {
- returns: The request. - returns: The request.
*/ */
public func responseData(completionHandler: Response<NSData, NSError> -> Void) -> Self { public func responseData(
return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler) queue queue: dispatch_queue_t? = nil,
completionHandler: Response<NSData, NSError> -> Void)
-> Self
{
return response(queue: queue, responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
} }
} }
@ -186,7 +201,7 @@ extension Request {
- returns: A string response serializer. - returns: A string response serializer.
*/ */
public static func stringResponseSerializer( public static func stringResponseSerializer(
var encoding encoding: NSStringEncoding? = nil) encoding encoding: NSStringEncoding? = nil)
-> ResponseSerializer<String, NSError> -> ResponseSerializer<String, NSError>
{ {
return ResponseSerializer { _, response, data, error in return ResponseSerializer { _, response, data, error in
@ -196,23 +211,25 @@ extension Request {
guard let validData = data else { guard let validData = data else {
let failureReason = "String could not be serialized. Input data was nil." let failureReason = "String could not be serialized. Input data was nil."
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason) let error = Error.error(code: .StringSerializationFailed, failureReason: failureReason)
return .Failure(error) return .Failure(error)
} }
if let encodingName = response?.textEncodingName where encoding == nil { var convertedEncoding = encoding
encoding = CFStringConvertEncodingToNSStringEncoding(
if let encodingName = response?.textEncodingName where convertedEncoding == nil {
convertedEncoding = CFStringConvertEncodingToNSStringEncoding(
CFStringConvertIANACharSetNameToEncoding(encodingName) CFStringConvertIANACharSetNameToEncoding(encodingName)
) )
} }
let actualEncoding = encoding ?? NSISOLatin1StringEncoding let actualEncoding = convertedEncoding ?? NSISOLatin1StringEncoding
if let string = String(data: validData, encoding: actualEncoding) { if let string = String(data: validData, encoding: actualEncoding) {
return .Success(string) return .Success(string)
} else { } else {
let failureReason = "String could not be serialized with encoding: \(actualEncoding)" let failureReason = "String could not be serialized with encoding: \(actualEncoding)"
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason) let error = Error.error(code: .StringSerializationFailed, failureReason: failureReason)
return .Failure(error) return .Failure(error)
} }
} }
@ -229,11 +246,13 @@ extension Request {
- returns: The request. - returns: The request.
*/ */
public func responseString( public func responseString(
encoding encoding: NSStringEncoding? = nil, queue queue: dispatch_queue_t? = nil,
encoding: NSStringEncoding? = nil,
completionHandler: Response<String, NSError> -> Void) completionHandler: Response<String, NSError> -> Void)
-> Self -> Self
{ {
return response( return response(
queue: queue,
responseSerializer: Request.stringResponseSerializer(encoding: encoding), responseSerializer: Request.stringResponseSerializer(encoding: encoding),
completionHandler: completionHandler completionHandler: completionHandler
) )
@ -263,7 +282,7 @@ extension Request {
guard let validData = data where validData.length > 0 else { guard let validData = data where validData.length > 0 else {
let failureReason = "JSON could not be serialized. Input data was nil or zero length." let failureReason = "JSON could not be serialized. Input data was nil or zero length."
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason) let error = Error.error(code: .JSONSerializationFailed, failureReason: failureReason)
return .Failure(error) return .Failure(error)
} }
@ -285,11 +304,13 @@ extension Request {
- returns: The request. - returns: The request.
*/ */
public func responseJSON( public func responseJSON(
options options: NSJSONReadingOptions = .AllowFragments, queue queue: dispatch_queue_t? = nil,
options: NSJSONReadingOptions = .AllowFragments,
completionHandler: Response<AnyObject, NSError> -> Void) completionHandler: Response<AnyObject, NSError> -> Void)
-> Self -> Self
{ {
return response( return response(
queue: queue,
responseSerializer: Request.JSONResponseSerializer(options: options), responseSerializer: Request.JSONResponseSerializer(options: options),
completionHandler: completionHandler completionHandler: completionHandler
) )
@ -319,7 +340,7 @@ extension Request {
guard let validData = data where validData.length > 0 else { guard let validData = data where validData.length > 0 else {
let failureReason = "Property list could not be serialized. Input data was nil or zero length." let failureReason = "Property list could not be serialized. Input data was nil or zero length."
let error = Error.errorWithCode(.PropertyListSerializationFailed, failureReason: failureReason) let error = Error.error(code: .PropertyListSerializationFailed, failureReason: failureReason)
return .Failure(error) return .Failure(error)
} }
@ -343,11 +364,13 @@ extension Request {
- returns: The request. - returns: The request.
*/ */
public func responsePropertyList( public func responsePropertyList(
options options: NSPropertyListReadOptions = NSPropertyListReadOptions(), queue queue: dispatch_queue_t? = nil,
options: NSPropertyListReadOptions = NSPropertyListReadOptions(),
completionHandler: Response<AnyObject, NSError> -> Void) completionHandler: Response<AnyObject, NSError> -> Void)
-> Self -> Self
{ {
return response( return response(
queue: queue,
responseSerializer: Request.propertyListResponseSerializer(options: options), responseSerializer: Request.propertyListResponseSerializer(options: options),
completionHandler: completionHandler completionHandler: completionHandler
) )

View File

@ -1,6 +1,7 @@
//
// Result.swift // Result.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation

View File

@ -1,6 +1,7 @@
//
// ServerTrustPolicy.swift // ServerTrustPolicy.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation

View File

@ -1,6 +1,7 @@
//
// Stream.swift // Stream.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,12 +20,13 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
#if !os(watchOS) #if !os(watchOS)
@available(iOS 9.0, OSX 10.11, *) @available(iOS 9.0, OSX 10.11, tvOS 9.0, *)
extension Manager { extension Manager {
private enum Streamable { private enum Streamable {
case Stream(String, Int) case Stream(String, Int)
@ -82,7 +84,7 @@ extension Manager {
// MARK: - // MARK: -
@available(iOS 9.0, OSX 10.11, *) @available(iOS 9.0, OSX 10.11, tvOS 9.0, *)
extension Manager.SessionDelegate: NSURLSessionStreamDelegate { extension Manager.SessionDelegate: NSURLSessionStreamDelegate {
// MARK: Override Closures // MARK: Override Closures

View File

@ -0,0 +1,138 @@
//
// Timeline.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// Responsible for computing the timing metrics for the complete lifecycle of a `Request`.
public struct Timeline {
/// The time the request was initialized.
public let requestStartTime: CFAbsoluteTime
/// The time the first bytes were received from or sent to the server.
public let initialResponseTime: CFAbsoluteTime
/// The time when the request was completed.
public let requestCompletedTime: CFAbsoluteTime
/// The time when the response serialization was completed.
public let serializationCompletedTime: CFAbsoluteTime
/// The time interval in seconds from the time the request started to the initial response from the server.
public let latency: NSTimeInterval
/// The time interval in seconds from the time the request started to the time the request completed.
public let requestDuration: NSTimeInterval
/// The time interval in seconds from the time the request completed to the time response serialization completed.
public let serializationDuration: NSTimeInterval
/// The time interval in seconds from the time the request started to the time response serialization completed.
public let totalDuration: NSTimeInterval
/**
Creates a new `Timeline` instance with the specified request times.
- parameter requestStartTime: The time the request was initialized. Defaults to `0.0`.
- parameter initialResponseTime: The time the first bytes were received from or sent to the server.
Defaults to `0.0`.
- parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`.
- parameter serializationCompletedTime: The time when the response serialization was completed. Defaults
to `0.0`.
- returns: The new `Timeline` instance.
*/
public init(
requestStartTime: CFAbsoluteTime = 0.0,
initialResponseTime: CFAbsoluteTime = 0.0,
requestCompletedTime: CFAbsoluteTime = 0.0,
serializationCompletedTime: CFAbsoluteTime = 0.0)
{
self.requestStartTime = requestStartTime
self.initialResponseTime = initialResponseTime
self.requestCompletedTime = requestCompletedTime
self.serializationCompletedTime = serializationCompletedTime
self.latency = initialResponseTime - requestStartTime
self.requestDuration = requestCompletedTime - requestStartTime
self.serializationDuration = serializationCompletedTime - requestCompletedTime
self.totalDuration = serializationCompletedTime - requestStartTime
}
}
// MARK: - CustomStringConvertible
extension Timeline: CustomStringConvertible {
/// The textual representation used when written to an output stream, which includes the latency, the request
/// duration and the total duration.
public var description: String {
let latency = String(format: "%.3f", self.latency)
let requestDuration = String(format: "%.3f", self.requestDuration)
let serializationDuration = String(format: "%.3f", self.serializationDuration)
let totalDuration = String(format: "%.3f", self.totalDuration)
// NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is
// fixed, we should move back to string interpolation by reverting commit 7d4a43b1.
let timings = [
"\"Latency\": " + latency + " secs",
"\"Request Duration\": " + requestDuration + " secs",
"\"Serialization Duration\": " + serializationDuration + " secs",
"\"Total Duration\": " + totalDuration + " secs"
]
return "Timeline: { " + timings.joinWithSeparator(", ") + " }"
}
}
// MARK: - CustomDebugStringConvertible
extension Timeline: CustomDebugStringConvertible {
/// The textual representation used when written to an output stream, which includes the request start time, the
/// initial response time, the request completed time, the serialization completed time, the latency, the request
/// duration and the total duration.
public var debugDescription: String {
let requestStartTime = String(format: "%.3f", self.requestStartTime)
let initialResponseTime = String(format: "%.3f", self.initialResponseTime)
let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime)
let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime)
let latency = String(format: "%.3f", self.latency)
let requestDuration = String(format: "%.3f", self.requestDuration)
let serializationDuration = String(format: "%.3f", self.serializationDuration)
let totalDuration = String(format: "%.3f", self.totalDuration)
// NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is
// fixed, we should move back to string interpolation by reverting commit 7d4a43b1.
let timings = [
"\"Request Start Time\": " + requestStartTime,
"\"Initial Response Time\": " + initialResponseTime,
"\"Request Completed Time\": " + requestCompletedTime,
"\"Serialization Completed Time\": " + serializationCompletedTime,
"\"Latency\": " + latency + " secs",
"\"Request Duration\": " + requestDuration + " secs",
"\"Serialization Duration\": " + serializationDuration + " secs",
"\"Total Duration\": " + totalDuration + " secs"
]
return "Timeline: { " + timings.joinWithSeparator(", ") + " }"
}
}

View File

@ -1,6 +1,7 @@
//
// Upload.swift // Upload.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -359,6 +361,8 @@ extension Request {
totalBytesSent: Int64, totalBytesSent: Int64,
totalBytesExpectedToSend: Int64) totalBytesExpectedToSend: Int64)
{ {
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let taskDidSendBodyData = taskDidSendBodyData { if let taskDidSendBodyData = taskDidSendBodyData {
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
} else { } else {

View File

@ -1,6 +1,7 @@
//
// Validation.swift // Validation.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -80,7 +82,17 @@ extension Request {
return .Success return .Success
} else { } else {
let failureReason = "Response status code was unacceptable: \(response.statusCode)" let failureReason = "Response status code was unacceptable: \(response.statusCode)"
return .Failure(Error.errorWithCode(.StatusCodeValidationFailed, failureReason: failureReason))
let error = NSError(
domain: Error.Domain,
code: Error.Code.StatusCodeValidationFailed.rawValue,
userInfo: [
NSLocalizedFailureReasonErrorKey: failureReason,
Error.UserInfoKeys.StatusCode: response.statusCode
]
)
return .Failure(error)
} }
} }
} }
@ -149,18 +161,31 @@ extension Request {
} }
} }
let contentType: String
let failureReason: String let failureReason: String
if let responseContentType = response.MIMEType { if let responseContentType = response.MIMEType {
contentType = responseContentType
failureReason = ( failureReason = (
"Response content type \"\(responseContentType)\" does not match any acceptable " + "Response content type \"\(responseContentType)\" does not match any acceptable " +
"content types: \(acceptableContentTypes)" "content types: \(acceptableContentTypes)"
) )
} else { } else {
contentType = ""
failureReason = "Response content type was missing and acceptable content type does not match \"*/*\"" failureReason = "Response content type was missing and acceptable content type does not match \"*/*\""
} }
return .Failure(Error.errorWithCode(.ContentTypeValidationFailed, failureReason: failureReason)) let error = NSError(
domain: Error.Domain,
code: Error.Code.ContentTypeValidationFailed.rawValue,
userInfo: [
NSLocalizedFailureReasonErrorKey: failureReason,
Error.UserInfoKeys.ContentType: contentType
]
)
return .Failure(error)
} }
} }

View File

@ -16,7 +16,7 @@
"source_files": "PetstoreClient/Classes/Swaggers/**/*.swift", "source_files": "PetstoreClient/Classes/Swaggers/**/*.swift",
"dependencies": { "dependencies": {
"Alamofire": [ "Alamofire": [
"~> 3.1.5" "~> 3.4.1"
] ]
} }
} }

View File

@ -1,18 +1,18 @@
PODS: PODS:
- Alamofire (3.1.5) - Alamofire (3.4.1)
- PetstoreClient (0.0.1): - PetstoreClient (0.0.1):
- Alamofire (~> 3.1.5) - Alamofire (~> 3.4.1)
DEPENDENCIES: DEPENDENCIES:
- PetstoreClient (from `../`) - PetstoreClient (from `../`)
EXTERNAL SOURCES: EXTERNAL SOURCES:
PetstoreClient: PetstoreClient:
:path: ../ :path: "../"
SPEC CHECKSUMS: SPEC CHECKSUMS:
Alamofire: 5f730ba29fd113b7ddd71c1e65d0c630acf5d7b0 Alamofire: 01a82e2f6c0f860ade35534c8dd88be61bdef40c
PetstoreClient: 575f4a5776e6a693e70f9d14bae0aabd8c467111 PetstoreClient: 7489b461499be1b2c4e0ed6624ca76c8db506297
PODFILE CHECKSUM: 84472aca2a88b7f7ed9fcd63e9f5fdb5ad4aab94 PODFILE CHECKSUM: 84472aca2a88b7f7ed9fcd63e9f5fdb5ad4aab94

View File

@ -7,46 +7,49 @@
objects = { objects = {
/* Begin PBXBuildFile section */ /* Begin PBXBuildFile section */
03F494989CC1A8857B68A317D5D6860F /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8AE82608C8C2A46981A07D7E422BEB45 /* Response.swift */; }; 095406039B4D371E48D08B38A2975AC8 /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D1F9022AC9979CD59E8F83962DAF51D /* Error.swift */; };
0681ADC8BAE2C3185F13487BAAB4D9DD /* Upload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 948996616B0A38BD6FE8C4CB309CC964 /* Upload.swift */; };
0BD8B4E55E72312366130E97A1204CD8 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 41EA265E42E2F53F87DD98BDA6BDEFD5 /* Foundation.framework */; };
121BA006C3D23D9290D868AA19E4BFBA /* Category.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4DF0604EDC1460935E6E445A47023A4 /* Category.swift */; }; 121BA006C3D23D9290D868AA19E4BFBA /* Category.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4DF0604EDC1460935E6E445A47023A4 /* Category.swift */; };
16102E4E35FAA0FC4161282FECE56469 /* Timeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0DBA7F3642776C1964512C9A38829081 /* Timeline.swift */; };
1ED3811BA132299733D3A71543A4339C /* Models.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F0266C5AE0B23A436291F6647902086 /* Models.swift */; }; 1ED3811BA132299733D3A71543A4339C /* Models.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F0266C5AE0B23A436291F6647902086 /* Models.swift */; };
2737DA3907C231E7CCCBF6075FCE4AB3 /* UserAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 552D15E0340BF58CC1922B82E864AEC9 /* UserAPI.swift */; }; 2737DA3907C231E7CCCBF6075FCE4AB3 /* UserAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 552D15E0340BF58CC1922B82E864AEC9 /* UserAPI.swift */; };
2C5450AC69398958CF6F7539EF7D99E5 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 4FC4583A4BD15196E6859EA5E990AD3F /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; 2D3405986FC586FA6C0A5E0B6BA7E64E /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 658CBED44D4009D80F990A188D7A8B3F /* Validation.swift */; };
34CCDCA848A701466256BC2927DA8856 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = F9278DA00F41E390EE68B6F3C8161C54 /* NetworkReachabilityManager.swift */; };
37D0F7B54F7677AEB499F204040C6DA1 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 41EA265E42E2F53F87DD98BDA6BDEFD5 /* Foundation.framework */; }; 37D0F7B54F7677AEB499F204040C6DA1 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 41EA265E42E2F53F87DD98BDA6BDEFD5 /* Foundation.framework */; };
388FE86EB5084CB37EC19ED82DE8242C /* AlamofireImplementations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 92734297B64DFE0EB0EDE1EA821163DB /* AlamofireImplementations.swift */; }; 388FE86EB5084CB37EC19ED82DE8242C /* AlamofireImplementations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 92734297B64DFE0EB0EDE1EA821163DB /* AlamofireImplementations.swift */; };
39EBC7781F42F6F790D3E54F3E8D8ED1 /* Tag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 211F73A46D90346F7FC6D0D29640EE4F /* Tag.swift */; }; 39EBC7781F42F6F790D3E54F3E8D8ED1 /* Tag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 211F73A46D90346F7FC6D0D29640EE4F /* Tag.swift */; };
3CA0C61EB5AA01268C12B7E61FF59C56 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 41EA265E42E2F53F87DD98BDA6BDEFD5 /* Foundation.framework */; }; 3CA0C61EB5AA01268C12B7E61FF59C56 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 41EA265E42E2F53F87DD98BDA6BDEFD5 /* Foundation.framework */; };
3EA8F215C9C1432D74E5CCA4834AA8C0 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2959D264574F227296E36F7CDF2E4F4F /* ResponseSerialization.swift */; };
4081EA628AF0B73AC51FFB9D7AB3B89E /* Manager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 101C763FD5409006D69EDB82815E4A61 /* Manager.swift */; };
40AED0FDEFFB776F649058C34D72BB95 /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 706C7AFFE37BA158C3553250F4B5FAED /* Alamofire.framework */; }; 40AED0FDEFFB776F649058C34D72BB95 /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 706C7AFFE37BA158C3553250F4B5FAED /* Alamofire.framework */; };
45961D28C6B8E4BAB87690F714B8727B /* PetstoreClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */; }; 45961D28C6B8E4BAB87690F714B8727B /* PetstoreClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */; };
4DE5FCC41D100B113B6645EA64410F16 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5465E2051CE332BA7D4E0595F9B44718 /* ParameterEncoding.swift */; };
562F951C949B9293B74C2E5D86BEF1BC /* StoreAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A3E5E3CD673B025FD8AC260E67AB47E /* StoreAPI.swift */; }; 562F951C949B9293B74C2E5D86BEF1BC /* StoreAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A3E5E3CD673B025FD8AC260E67AB47E /* StoreAPI.swift */; };
59C731A013A3F62794AABFB1C1025B4F /* APIs.swift in Sources */ = {isa = PBXBuildFile; fileRef = D8072E1108951F272C003553FC8926C7 /* APIs.swift */; }; 59C731A013A3F62794AABFB1C1025B4F /* APIs.swift in Sources */ = {isa = PBXBuildFile; fileRef = D8072E1108951F272C003553FC8926C7 /* APIs.swift */; };
5BC19E6E0F199276003F0AF96838BCE5 /* Upload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 09DC3EB7B14F56C5823591E484CC06DC /* Upload.swift */; };
5CB05FBCB32D21E194B5ECF680CB6AE0 /* Download.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50BCAC7849E43619A0E6BA6D3291D195 /* Download.swift */; };
62E8346F03C03E7F4D631361F325689E /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = DDC2C7A48545D8C54D52554343225FB8 /* Response.swift */; };
7B48852C4D848FA2DA416A98F6425869 /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E07E98001DB6C163294A39CAB05963D /* ServerTrustPolicy.swift */; };
7D0C7E08FEC92B9C59B3EAFB8D15026D /* APIHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = D2BAD338E56EF3CAA6E54490FE0C5DF9 /* APIHelper.swift */; }; 7D0C7E08FEC92B9C59B3EAFB8D15026D /* APIHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = D2BAD338E56EF3CAA6E54490FE0C5DF9 /* APIHelper.swift */; };
80F496237530D382A045A29654D8C11C /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 52836A3E223CCB5C120D4BE7D37AC1BF /* ServerTrustPolicy.swift */; };
816BE1BBC1F4E434D7BD3F793F38B347 /* Pods-SwaggerClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; 816BE1BBC1F4E434D7BD3F793F38B347 /* Pods-SwaggerClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; };
82971968CBDAB224212EEB4607C9FB8D /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7835749D1C4FA403E4BB17A0C787EDCA /* Result.swift */; };
8399DBEE3E2D98EB1F466132E476F4D9 /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10653C142FFDF1986227894BF0317944 /* MultipartFormData.swift */; };
897283A0B7F5299913327CC8FD6CC997 /* Pods-SwaggerClientTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; 897283A0B7F5299913327CC8FD6CC997 /* Pods-SwaggerClientTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; };
8EB11202167FCDDF1257AAAB1D1FB244 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7ED443D528393D61A04FBD88603DE5F3 /* Alamofire.swift */; };
909E1A21FF97D3DFD0E2707B0E078686 /* PetAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 261F03A3C73374FD19333EEA59CCD59F /* PetAPI.swift */; }; 909E1A21FF97D3DFD0E2707B0E078686 /* PetAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 261F03A3C73374FD19333EEA59CCD59F /* PetAPI.swift */; };
91C09AC2A52ED69A27C8D923139A006F /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 41EA265E42E2F53F87DD98BDA6BDEFD5 /* Foundation.framework */; };
93A9E4EBCD41B6C350DB55CB545D797E /* User.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B248364ABF60ACD7DB31A17DCFDFD0C /* User.swift */; }; 93A9E4EBCD41B6C350DB55CB545D797E /* User.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B248364ABF60ACD7DB31A17DCFDFD0C /* User.swift */; };
A2C172FE407C0BC3478ADCA91A6C9CEC /* Manager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5241F56B5C8C48BD734958D586267D1A /* Manager.swift */; }; 9469DF81ECB494E84675969B5E13374C /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = AE6827D6CBD3F8B59B79641ABF6ED159 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; };
A3505FA2FB3067D53847AD288AC04F03 /* Download.swift in Sources */ = {isa = PBXBuildFile; fileRef = ADA14379DE2012C9EFB2B9C3A3A39AB4 /* Download.swift */; };
A871DC508D9A11F280135D7B56266E97 /* PetstoreClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; A871DC508D9A11F280135D7B56266E97 /* PetstoreClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; };
B0FB4B01682814B9E3D32F9DC4A5E762 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 23D4D8DBF3D77B1F970DB9DF6C963A84 /* Alamofire.swift */; }; AA314156AC500125F4078EE968DB14C6 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E393CF47FE31F265B29AA2D9B67C656 /* Result.swift */; };
B6D2DC3E3DA44CD382B9B425F40E11C1 /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 8D1C843C58F0C2DFE4522F24897D8CCE /* Alamofire-dummy.m */; }; ADF19C953CE2A7D0B72EC93A81FCCC26 /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 9FD74E0A1B7122513F9BCD2B66B65219 /* Alamofire-dummy.m */; };
AE4CF87C02C042DF13ED5B21C4FDC1E0 /* Stream.swift in Sources */ = {isa = PBXBuildFile; fileRef = F9039D48B1E893EF8AD87645A4FF820F /* Stream.swift */; };
BE41196F6A3903E59C3306FE3F8B43FE /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79E32C97D15B18BFEB591B4A8B5C8477 /* Notifications.swift */; };
C0DB70AB368765DC64BFB5FEA75E0696 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB714D2EF499EE0EF3E1957151533A5D /* ParameterEncoding.swift */; };
C546890220177F840E8AFC829D0E3FEB /* Pods-SwaggerClientTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */; }; C546890220177F840E8AFC829D0E3FEB /* Pods-SwaggerClientTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */; };
C75519F0450166A6F28126ECC7664E9C /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 779B19103BE8402A434ED95F67573911 /* Validation.swift */; }; C7B6DD7C0456C50289A2C381DFE9FA3F /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B09F376C277F027BDCD54137D76C547 /* MultipartFormData.swift */; };
C8592AD030234E841A61CA09ED02059A /* Pods-SwaggerClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */; }; C8592AD030234E841A61CA09ED02059A /* Pods-SwaggerClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */; };
CA8020EE393C1F6085F284A7CAE3B9E3 /* Pet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 284B3DE9B793FCC633E971DB1798AFAF /* Pet.swift */; }; CA8020EE393C1F6085F284A7CAE3B9E3 /* Pet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 284B3DE9B793FCC633E971DB1798AFAF /* Pet.swift */; };
D21B7325B3642887BFBE977E021F2D26 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5EBB70A7BA5F9037CD2DA409E148A73 /* ResponseSerialization.swift */; };
D228AFA3B6BFAE551ADA6A57A57F8DF9 /* Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5412898DEB10F1983487A10453C6B9CB /* Extensions.swift */; }; D228AFA3B6BFAE551ADA6A57A57F8DF9 /* Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5412898DEB10F1983487A10453C6B9CB /* Extensions.swift */; };
D75CA395D510E08C404E55F5BDAE55CE /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83957AB2EE778B52399CC4C903539BD0 /* Error.swift */; };
DAF614ED4A24537ACAF1F517EF31668E /* Order.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A545673F09F49CDD60A13B4B0AF1020 /* Order.swift */; }; DAF614ED4A24537ACAF1F517EF31668E /* Order.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A545673F09F49CDD60A13B4B0AF1020 /* Order.swift */; };
EFE92E8D3813DD26E78E93EEAF6D7E7E /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1E2A29BA50E80B66E36C94B60FAD8863 /* Request.swift */; };
F206C370F63155D3468E0C188498C5DC /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 41EA265E42E2F53F87DD98BDA6BDEFD5 /* Foundation.framework */; }; F206C370F63155D3468E0C188498C5DC /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 41EA265E42E2F53F87DD98BDA6BDEFD5 /* Foundation.framework */; };
FC14480CECE872865A9C6E584F886DA3 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA23887509C9FF173ECBE0A470EDD527 /* Request.swift */; };
FEF0D7653948988B804226129471C1EC /* Stream.swift in Sources */ = {isa = PBXBuildFile; fileRef = C89117FC38D94C9DF36CA21E3C96EEB7 /* Stream.swift */; };
/* End PBXBuildFile section */ /* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */ /* Begin PBXContainerItemProxy section */
@ -61,14 +64,14 @@
isa = PBXContainerItemProxy; isa = PBXContainerItemProxy;
containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */;
proxyType = 1; proxyType = 1;
remoteGlobalIDString = 432ECC54282C84882B482CCB4CF227FC; remoteGlobalIDString = 79C040AFDDCE1BCBF6D8B5EB0B85887F;
remoteInfo = Alamofire; remoteInfo = Alamofire;
}; };
9587C29FFB2EF204C279D7FF29DA45C2 /* PBXContainerItemProxy */ = { 9587C29FFB2EF204C279D7FF29DA45C2 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy; isa = PBXContainerItemProxy;
containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */;
proxyType = 1; proxyType = 1;
remoteGlobalIDString = 432ECC54282C84882B482CCB4CF227FC; remoteGlobalIDString = 79C040AFDDCE1BCBF6D8B5EB0B85887F;
remoteInfo = Alamofire; remoteInfo = Alamofire;
}; };
/* End PBXContainerItemProxy section */ /* End PBXContainerItemProxy section */
@ -76,15 +79,17 @@
/* Begin PBXFileReference section */ /* Begin PBXFileReference section */
00ACB4396DD1B4E4539E4E81C1D7A14E /* Pods-SwaggerClientTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = "Pods-SwaggerClientTests.modulemap"; sourceTree = "<group>"; }; 00ACB4396DD1B4E4539E4E81C1D7A14E /* Pods-SwaggerClientTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = "Pods-SwaggerClientTests.modulemap"; sourceTree = "<group>"; };
02F28E719AA874BE9213D6CF8CE7E36B /* Pods-SwaggerClientTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClientTests-acknowledgements.plist"; sourceTree = "<group>"; }; 02F28E719AA874BE9213D6CF8CE7E36B /* Pods-SwaggerClientTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClientTests-acknowledgements.plist"; sourceTree = "<group>"; };
09DC3EB7B14F56C5823591E484CC06DC /* Upload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Upload.swift; path = Source/Upload.swift; sourceTree = "<group>"; };
0A545673F09F49CDD60A13B4B0AF1020 /* Order.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Order.swift; sourceTree = "<group>"; }; 0A545673F09F49CDD60A13B4B0AF1020 /* Order.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Order.swift; sourceTree = "<group>"; };
10653C142FFDF1986227894BF0317944 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = "<group>"; }; 0DBA7F3642776C1964512C9A38829081 /* Timeline.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeline.swift; path = Source/Timeline.swift; sourceTree = "<group>"; };
101C763FD5409006D69EDB82815E4A61 /* Manager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Manager.swift; path = Source/Manager.swift; sourceTree = "<group>"; };
1A3E5E3CD673B025FD8AC260E67AB47E /* StoreAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = StoreAPI.swift; sourceTree = "<group>"; }; 1A3E5E3CD673B025FD8AC260E67AB47E /* StoreAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = StoreAPI.swift; sourceTree = "<group>"; };
1E2A29BA50E80B66E36C94B60FAD8863 /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = "<group>"; };
211F73A46D90346F7FC6D0D29640EE4F /* Tag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Tag.swift; sourceTree = "<group>"; }; 211F73A46D90346F7FC6D0D29640EE4F /* Tag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Tag.swift; sourceTree = "<group>"; };
21FA4AD1EF77337F9C8F2AD871ED371D /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Alamofire.modulemap; sourceTree = "<group>"; };
23D4D8DBF3D77B1F970DB9DF6C963A84 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = "<group>"; };
261F03A3C73374FD19333EEA59CCD59F /* PetAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PetAPI.swift; sourceTree = "<group>"; }; 261F03A3C73374FD19333EEA59CCD59F /* PetAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PetAPI.swift; sourceTree = "<group>"; };
284B3DE9B793FCC633E971DB1798AFAF /* Pet.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Pet.swift; sourceTree = "<group>"; }; 284B3DE9B793FCC633E971DB1798AFAF /* Pet.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Pet.swift; sourceTree = "<group>"; };
291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClient-dummy.m"; sourceTree = "<group>"; }; 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClient-dummy.m"; sourceTree = "<group>"; };
2959D264574F227296E36F7CDF2E4F4F /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = "<group>"; };
2FF17440CCD2E1A69791A4AA23325AD5 /* Pods-SwaggerClient-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClient-acknowledgements.markdown"; sourceTree = "<group>"; }; 2FF17440CCD2E1A69791A4AA23325AD5 /* Pods-SwaggerClient-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClient-acknowledgements.markdown"; sourceTree = "<group>"; };
3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClient-umbrella.h"; sourceTree = "<group>"; }; 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClient-umbrella.h"; sourceTree = "<group>"; };
3F16B43ABD2C8CD4A311AA1AB3B6C02F /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; }; 3F16B43ABD2C8CD4A311AA1AB3B6C02F /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
@ -92,53 +97,54 @@
43FC49AA70D3E2A84CAED9C37BE9C4B5 /* Pods-SwaggerClientTests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-frameworks.sh"; sourceTree = "<group>"; }; 43FC49AA70D3E2A84CAED9C37BE9C4B5 /* Pods-SwaggerClientTests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-frameworks.sh"; sourceTree = "<group>"; };
46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PetstoreClient-dummy.m"; sourceTree = "<group>"; }; 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PetstoreClient-dummy.m"; sourceTree = "<group>"; };
49A9B3BBFEA1CFFC48229E438EA64F9E /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 49A9B3BBFEA1CFFC48229E438EA64F9E /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; };
4FC4583A4BD15196E6859EA5E990AD3F /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = "<group>"; }; 4E07E98001DB6C163294A39CAB05963D /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = "<group>"; };
5241F56B5C8C48BD734958D586267D1A /* Manager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Manager.swift; path = Source/Manager.swift; sourceTree = "<group>"; }; 4E393CF47FE31F265B29AA2D9B67C656 /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = "<group>"; };
52836A3E223CCB5C120D4BE7D37AC1BF /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = "<group>"; }; 50BCAC7849E43619A0E6BA6D3291D195 /* Download.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Download.swift; path = Source/Download.swift; sourceTree = "<group>"; };
5175E677ADC3F810A4FB10B104C4332B /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
5412898DEB10F1983487A10453C6B9CB /* Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Extensions.swift; sourceTree = "<group>"; }; 5412898DEB10F1983487A10453C6B9CB /* Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Extensions.swift; sourceTree = "<group>"; };
5465E2051CE332BA7D4E0595F9B44718 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = "<group>"; };
549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.debug.xcconfig"; sourceTree = "<group>"; }; 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.debug.xcconfig"; sourceTree = "<group>"; };
552D15E0340BF58CC1922B82E864AEC9 /* UserAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = UserAPI.swift; sourceTree = "<group>"; }; 552D15E0340BF58CC1922B82E864AEC9 /* UserAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = UserAPI.swift; sourceTree = "<group>"; };
5B09F376C277F027BDCD54137D76C547 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = "<group>"; };
5B248364ABF60ACD7DB31A17DCFDFD0C /* User.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = User.swift; sourceTree = "<group>"; }; 5B248364ABF60ACD7DB31A17DCFDFD0C /* User.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = User.swift; sourceTree = "<group>"; };
5E53BF5A61CAF6972C5CDD2C3EE6C003 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; }; 5C5763A83A1E028B6C4A073221CB764F /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Alamofire.modulemap; sourceTree = "<group>"; };
658CBED44D4009D80F990A188D7A8B3F /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = "<group>"; };
687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClientTests-dummy.m"; sourceTree = "<group>"; }; 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClientTests-dummy.m"; sourceTree = "<group>"; };
6C0ACB269F0C836F1865A56C4AF7A07E /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 6C0ACB269F0C836F1865A56C4AF7A07E /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; };
6D1F9022AC9979CD59E8F83962DAF51D /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Source/Error.swift; sourceTree = "<group>"; };
706C7AFFE37BA158C3553250F4B5FAED /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 706C7AFFE37BA158C3553250F4B5FAED /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; };
779B19103BE8402A434ED95F67573911 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = "<group>"; }; 79E32C97D15B18BFEB591B4A8B5C8477 /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = "<group>"; };
7835749D1C4FA403E4BB17A0C787EDCA /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = "<group>"; };
7C8E63660D346FD8ED2A97242E74EA09 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; }; 7C8E63660D346FD8ED2A97242E74EA09 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
7D7AAA0E85E40ED735D6BCBF7A243C46 /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = "<group>"; }; 7ED443D528393D61A04FBD88603DE5F3 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = "<group>"; };
83957AB2EE778B52399CC4C903539BD0 /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Source/Error.swift; sourceTree = "<group>"; };
849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.release.xcconfig"; sourceTree = "<group>"; }; 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.release.xcconfig"; sourceTree = "<group>"; };
86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.release.xcconfig"; sourceTree = "<group>"; }; 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.release.xcconfig"; sourceTree = "<group>"; };
897F0C201C5E0C66A1F1E359AECF4C9C /* PetstoreClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PetstoreClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 897F0C201C5E0C66A1F1E359AECF4C9C /* PetstoreClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PetstoreClient.framework; sourceTree = BUILT_PRODUCTS_DIR; };
8AE82608C8C2A46981A07D7E422BEB45 /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = "<group>"; };
8D1C843C58F0C2DFE4522F24897D8CCE /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = "<group>"; };
8F0266C5AE0B23A436291F6647902086 /* Models.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Models.swift; sourceTree = "<group>"; }; 8F0266C5AE0B23A436291F6647902086 /* Models.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Models.swift; sourceTree = "<group>"; };
8FFF564423DBE209836D47626963E9D4 /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = "<group>"; };
92734297B64DFE0EB0EDE1EA821163DB /* AlamofireImplementations.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AlamofireImplementations.swift; sourceTree = "<group>"; }; 92734297B64DFE0EB0EDE1EA821163DB /* AlamofireImplementations.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AlamofireImplementations.swift; sourceTree = "<group>"; };
93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; };
948996616B0A38BD6FE8C4CB309CC964 /* Upload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Upload.swift; path = Source/Upload.swift; sourceTree = "<group>"; };
969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = "<group>"; }; 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = "<group>"; };
9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-umbrella.h"; sourceTree = "<group>"; }; 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-umbrella.h"; sourceTree = "<group>"; };
ADA14379DE2012C9EFB2B9C3A3A39AB4 /* Download.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Download.swift; path = Source/Download.swift; sourceTree = "<group>"; }; 9FD74E0A1B7122513F9BCD2B66B65219 /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = "<group>"; };
A149BF2819128352A98494A4402603EE /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = "<group>"; };
AB714D2EF499EE0EF3E1957151533A5D /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = "<group>"; };
AE6827D6CBD3F8B59B79641ABF6ED159 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = "<group>"; };
B3A144887C8B13FD888B76AB096B0CA1 /* PetstoreClient-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-prefix.pch"; sourceTree = "<group>"; }; B3A144887C8B13FD888B76AB096B0CA1 /* PetstoreClient-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-prefix.pch"; sourceTree = "<group>"; };
BCF2D4DFF08D2A18E8C8FE4C4B4633FB /* Pods-SwaggerClient-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-frameworks.sh"; sourceTree = "<group>"; }; BCF2D4DFF08D2A18E8C8FE4C4B4633FB /* Pods-SwaggerClient-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-frameworks.sh"; sourceTree = "<group>"; };
C89117FC38D94C9DF36CA21E3C96EEB7 /* Stream.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Stream.swift; path = Source/Stream.swift; sourceTree = "<group>"; };
D2841E5E2183846280B97F6E660DA26C /* Pods-SwaggerClient-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-resources.sh"; sourceTree = "<group>"; }; D2841E5E2183846280B97F6E660DA26C /* Pods-SwaggerClient-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-resources.sh"; sourceTree = "<group>"; };
D2BAD338E56EF3CAA6E54490FE0C5DF9 /* APIHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIHelper.swift; sourceTree = "<group>"; }; D2BAD338E56EF3CAA6E54490FE0C5DF9 /* APIHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIHelper.swift; sourceTree = "<group>"; };
D4DF0604EDC1460935E6E445A47023A4 /* Category.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Category.swift; sourceTree = "<group>"; }; D4DF0604EDC1460935E6E445A47023A4 /* Category.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Category.swift; sourceTree = "<group>"; };
D8072E1108951F272C003553FC8926C7 /* APIs.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIs.swift; sourceTree = "<group>"; }; D8072E1108951F272C003553FC8926C7 /* APIs.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIs.swift; sourceTree = "<group>"; };
DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PetstoreClient.xcconfig; sourceTree = "<group>"; }; DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PetstoreClient.xcconfig; sourceTree = "<group>"; };
DDC2C7A48545D8C54D52554343225FB8 /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = "<group>"; };
DE164497A94DD3215ED4D1AE0D4703B1 /* Pods-SwaggerClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = "Pods-SwaggerClient.modulemap"; sourceTree = "<group>"; }; DE164497A94DD3215ED4D1AE0D4703B1 /* Pods-SwaggerClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = "Pods-SwaggerClient.modulemap"; sourceTree = "<group>"; };
E1E4BCB344D3C100253B24B79421F00A /* Pods-SwaggerClient-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClient-acknowledgements.plist"; sourceTree = "<group>"; }; E1E4BCB344D3C100253B24B79421F00A /* Pods-SwaggerClient-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClient-acknowledgements.plist"; sourceTree = "<group>"; };
E3D1141B63DF38660CD6F3AC588A782B /* PetstoreClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = PetstoreClient.modulemap; sourceTree = "<group>"; }; E3D1141B63DF38660CD6F3AC588A782B /* PetstoreClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = PetstoreClient.modulemap; sourceTree = "<group>"; };
E4E6F4A58FE7868CA2177D3AC79AD2FA /* Pods-SwaggerClientTests-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-resources.sh"; sourceTree = "<group>"; }; E4E6F4A58FE7868CA2177D3AC79AD2FA /* Pods-SwaggerClientTests-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-resources.sh"; sourceTree = "<group>"; };
E6D51E88CF06503F74AC8F5ECD5A209B /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = "<group>"; };
EA3FFA48FB4D08FC02C47F71C0089CD9 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; EA3FFA48FB4D08FC02C47F71C0089CD9 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; };
F0D4E00A8974E74325E9E53D456F9AD4 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; }; F0D4E00A8974E74325E9E53D456F9AD4 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClientTests-umbrella.h"; sourceTree = "<group>"; }; F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClientTests-umbrella.h"; sourceTree = "<group>"; };
F5EBB70A7BA5F9037CD2DA409E148A73 /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = "<group>"; }; F9039D48B1E893EF8AD87645A4FF820F /* Stream.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Stream.swift; path = Source/Stream.swift; sourceTree = "<group>"; };
FA23887509C9FF173ECBE0A470EDD527 /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = "<group>"; }; F9278DA00F41E390EE68B6F3C8161C54 /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = "<group>"; };
FB170EFD14935F121CDE3211DB4C5CA3 /* Pods-SwaggerClientTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClientTests-acknowledgements.markdown"; sourceTree = "<group>"; }; FB170EFD14935F121CDE3211DB4C5CA3 /* Pods-SwaggerClientTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClientTests-acknowledgements.markdown"; sourceTree = "<group>"; };
/* End PBXFileReference section */ /* End PBXFileReference section */
@ -151,11 +157,11 @@
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
}; };
A5AE1D340C4A0691EC28EEA8241C9FCD /* Frameworks */ = { B1729F851F648EC60EE93CDB3C8BAEAD /* Frameworks */ = {
isa = PBXFrameworksBuildPhase; isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
0BD8B4E55E72312366130E97A1204CD8 /* Foundation.framework in Frameworks */, 91C09AC2A52ED69A27C8D923139A006F /* Foundation.framework in Frameworks */,
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
}; };
@ -179,28 +185,6 @@
/* End PBXFrameworksBuildPhase section */ /* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */ /* Begin PBXGroup section */
09192E6B9C45ACAB5568261F45FA3D88 /* Alamofire */ = {
isa = PBXGroup;
children = (
23D4D8DBF3D77B1F970DB9DF6C963A84 /* Alamofire.swift */,
ADA14379DE2012C9EFB2B9C3A3A39AB4 /* Download.swift */,
83957AB2EE778B52399CC4C903539BD0 /* Error.swift */,
5241F56B5C8C48BD734958D586267D1A /* Manager.swift */,
10653C142FFDF1986227894BF0317944 /* MultipartFormData.swift */,
5465E2051CE332BA7D4E0595F9B44718 /* ParameterEncoding.swift */,
FA23887509C9FF173ECBE0A470EDD527 /* Request.swift */,
8AE82608C8C2A46981A07D7E422BEB45 /* Response.swift */,
F5EBB70A7BA5F9037CD2DA409E148A73 /* ResponseSerialization.swift */,
7835749D1C4FA403E4BB17A0C787EDCA /* Result.swift */,
52836A3E223CCB5C120D4BE7D37AC1BF /* ServerTrustPolicy.swift */,
C89117FC38D94C9DF36CA21E3C96EEB7 /* Stream.swift */,
948996616B0A38BD6FE8C4CB309CC964 /* Upload.swift */,
779B19103BE8402A434ED95F67573911 /* Validation.swift */,
405A7C3030F6D3BDE3978D6D558FDF7F /* Support Files */,
);
path = Alamofire;
sourceTree = "<group>";
};
1322FED69118C64DAD026CAF7F4C38C6 /* Models */ = { 1322FED69118C64DAD026CAF7F4C38C6 /* Models */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
@ -213,14 +197,6 @@
path = Models; path = Models;
sourceTree = "<group>"; sourceTree = "<group>";
}; };
20C396BA1B90EEE39D4B19FE012C4F6D /* Pods */ = {
isa = PBXGroup;
children = (
09192E6B9C45ACAB5568261F45FA3D88 /* Alamofire */,
);
name = Pods;
sourceTree = "<group>";
};
22F52349E1BE90FC6E064DAAC9EA9612 /* Development Pods */ = { 22F52349E1BE90FC6E064DAAC9EA9612 /* Development Pods */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
@ -237,18 +213,12 @@
name = iOS; name = iOS;
sourceTree = "<group>"; sourceTree = "<group>";
}; };
405A7C3030F6D3BDE3978D6D558FDF7F /* Support Files */ = { 35F128EB69B6F7FB7DA93BBF6C130FAE /* Pods */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
21FA4AD1EF77337F9C8F2AD871ED371D /* Alamofire.modulemap */, 6E519FC8760483F5D136181B2EBCBDEB /* Alamofire */,
7D7AAA0E85E40ED735D6BCBF7A243C46 /* Alamofire.xcconfig */,
8D1C843C58F0C2DFE4522F24897D8CCE /* Alamofire-dummy.m */,
E6D51E88CF06503F74AC8F5ECD5A209B /* Alamofire-prefix.pch */,
4FC4583A4BD15196E6859EA5E990AD3F /* Alamofire-umbrella.h */,
5E53BF5A61CAF6972C5CDD2C3EE6C003 /* Info.plist */,
); );
name = "Support Files"; name = Pods;
path = "../Target Support Files/Alamofire";
sourceTree = "<group>"; sourceTree = "<group>";
}; };
59B91F212518421F271EBA85D5530651 /* Frameworks */ = { 59B91F212518421F271EBA85D5530651 /* Frameworks */ = {
@ -260,13 +230,52 @@
name = Frameworks; name = Frameworks;
sourceTree = "<group>"; sourceTree = "<group>";
}; };
68F6D4CBC8B6CDE1D634D9F379F37168 /* Support Files */ = {
isa = PBXGroup;
children = (
5C5763A83A1E028B6C4A073221CB764F /* Alamofire.modulemap */,
A149BF2819128352A98494A4402603EE /* Alamofire.xcconfig */,
9FD74E0A1B7122513F9BCD2B66B65219 /* Alamofire-dummy.m */,
8FFF564423DBE209836D47626963E9D4 /* Alamofire-prefix.pch */,
AE6827D6CBD3F8B59B79641ABF6ED159 /* Alamofire-umbrella.h */,
5175E677ADC3F810A4FB10B104C4332B /* Info.plist */,
);
name = "Support Files";
path = "../Target Support Files/Alamofire";
sourceTree = "<group>";
};
6E519FC8760483F5D136181B2EBCBDEB /* Alamofire */ = {
isa = PBXGroup;
children = (
7ED443D528393D61A04FBD88603DE5F3 /* Alamofire.swift */,
50BCAC7849E43619A0E6BA6D3291D195 /* Download.swift */,
6D1F9022AC9979CD59E8F83962DAF51D /* Error.swift */,
101C763FD5409006D69EDB82815E4A61 /* Manager.swift */,
5B09F376C277F027BDCD54137D76C547 /* MultipartFormData.swift */,
F9278DA00F41E390EE68B6F3C8161C54 /* NetworkReachabilityManager.swift */,
79E32C97D15B18BFEB591B4A8B5C8477 /* Notifications.swift */,
AB714D2EF499EE0EF3E1957151533A5D /* ParameterEncoding.swift */,
1E2A29BA50E80B66E36C94B60FAD8863 /* Request.swift */,
DDC2C7A48545D8C54D52554343225FB8 /* Response.swift */,
2959D264574F227296E36F7CDF2E4F4F /* ResponseSerialization.swift */,
4E393CF47FE31F265B29AA2D9B67C656 /* Result.swift */,
4E07E98001DB6C163294A39CAB05963D /* ServerTrustPolicy.swift */,
F9039D48B1E893EF8AD87645A4FF820F /* Stream.swift */,
0DBA7F3642776C1964512C9A38829081 /* Timeline.swift */,
09DC3EB7B14F56C5823591E484CC06DC /* Upload.swift */,
658CBED44D4009D80F990A188D7A8B3F /* Validation.swift */,
68F6D4CBC8B6CDE1D634D9F379F37168 /* Support Files */,
);
path = Alamofire;
sourceTree = "<group>";
};
7DB346D0F39D3F0E887471402A8071AB = { 7DB346D0F39D3F0E887471402A8071AB = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */,
22F52349E1BE90FC6E064DAAC9EA9612 /* Development Pods */, 22F52349E1BE90FC6E064DAAC9EA9612 /* Development Pods */,
59B91F212518421F271EBA85D5530651 /* Frameworks */, 59B91F212518421F271EBA85D5530651 /* Frameworks */,
20C396BA1B90EEE39D4B19FE012C4F6D /* Pods */, 35F128EB69B6F7FB7DA93BBF6C130FAE /* Pods */,
9BBD96A0F02B8F92DD3659B2DCDF1A8C /* Products */, 9BBD96A0F02B8F92DD3659B2DCDF1A8C /* Products */,
C1A60D10CED0E61146591438999C7502 /* Targets Support Files */, C1A60D10CED0E61146591438999C7502 /* Targets Support Files */,
); );
@ -395,14 +404,6 @@
/* End PBXGroup section */ /* End PBXGroup section */
/* Begin PBXHeadersBuildPhase section */ /* Begin PBXHeadersBuildPhase section */
5F7B61281F714E2A64A51E80A2C9C062 /* Headers */ = {
isa = PBXHeadersBuildPhase;
buildActionMask = 2147483647;
files = (
2C5450AC69398958CF6F7539EF7D99E5 /* Alamofire-umbrella.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
};
6C794A7763C2F85750D66CDD002E271F /* Headers */ = { 6C794A7763C2F85750D66CDD002E271F /* Headers */ = {
isa = PBXHeadersBuildPhase; isa = PBXHeadersBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
@ -419,6 +420,14 @@
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
}; };
EFDF3B631BBB965A372347705CA14854 /* Headers */ = {
isa = PBXHeadersBuildPhase;
buildActionMask = 2147483647;
files = (
9469DF81ECB494E84675969B5E13374C /* Alamofire-umbrella.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
};
FF84DA06E91FBBAA756A7832375803CE /* Headers */ = { FF84DA06E91FBBAA756A7832375803CE /* Headers */ = {
isa = PBXHeadersBuildPhase; isa = PBXHeadersBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
@ -449,23 +458,6 @@
productReference = 6C0ACB269F0C836F1865A56C4AF7A07E /* Pods_SwaggerClient.framework */; productReference = 6C0ACB269F0C836F1865A56C4AF7A07E /* Pods_SwaggerClient.framework */;
productType = "com.apple.product-type.framework"; productType = "com.apple.product-type.framework";
}; };
432ECC54282C84882B482CCB4CF227FC /* Alamofire */ = {
isa = PBXNativeTarget;
buildConfigurationList = 8B2B2DA2F7F80D41B1FDB5FACFA4B3DE /* Build configuration list for PBXNativeTarget "Alamofire" */;
buildPhases = (
EF659EFF40D426A3A32A82CDB98CC6EE /* Sources */,
A5AE1D340C4A0691EC28EEA8241C9FCD /* Frameworks */,
5F7B61281F714E2A64A51E80A2C9C062 /* Headers */,
);
buildRules = (
);
dependencies = (
);
name = Alamofire;
productName = Alamofire;
productReference = 49A9B3BBFEA1CFFC48229E438EA64F9E /* Alamofire.framework */;
productType = "com.apple.product-type.framework";
};
462B200BD111D7F438E47B7C42B6772F /* Pods-SwaggerClientTests */ = { 462B200BD111D7F438E47B7C42B6772F /* Pods-SwaggerClientTests */ = {
isa = PBXNativeTarget; isa = PBXNativeTarget;
buildConfigurationList = 245A935A321D16F418F4D34C5D17D2B6 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClientTests" */; buildConfigurationList = 245A935A321D16F418F4D34C5D17D2B6 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClientTests" */;
@ -501,6 +493,23 @@
productReference = 897F0C201C5E0C66A1F1E359AECF4C9C /* PetstoreClient.framework */; productReference = 897F0C201C5E0C66A1F1E359AECF4C9C /* PetstoreClient.framework */;
productType = "com.apple.product-type.framework"; productType = "com.apple.product-type.framework";
}; };
79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */ = {
isa = PBXNativeTarget;
buildConfigurationList = 3CFB42910790CF0BDBCCEBAACD6B9367 /* Build configuration list for PBXNativeTarget "Alamofire" */;
buildPhases = (
95CC2C7E06DC188A05DAAEE9CAA555A3 /* Sources */,
B1729F851F648EC60EE93CDB3C8BAEAD /* Frameworks */,
EFDF3B631BBB965A372347705CA14854 /* Headers */,
);
buildRules = (
);
dependencies = (
);
name = Alamofire;
productName = Alamofire;
productReference = 49A9B3BBFEA1CFFC48229E438EA64F9E /* Alamofire.framework */;
productType = "com.apple.product-type.framework";
};
/* End PBXNativeTarget section */ /* End PBXNativeTarget section */
/* Begin PBXProject section */ /* Begin PBXProject section */
@ -522,7 +531,7 @@
projectDirPath = ""; projectDirPath = "";
projectRoot = ""; projectRoot = "";
targets = ( targets = (
432ECC54282C84882B482CCB4CF227FC /* Alamofire */, 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */,
757F9BBABE83623770250F65EAEE4FD6 /* PetstoreClient */, 757F9BBABE83623770250F65EAEE4FD6 /* PetstoreClient */,
01C67FBB627BDC9D36B9F648C0BF5228 /* Pods-SwaggerClient */, 01C67FBB627BDC9D36B9F648C0BF5228 /* Pods-SwaggerClient */,
462B200BD111D7F438E47B7C42B6772F /* Pods-SwaggerClientTests */, 462B200BD111D7F438E47B7C42B6772F /* Pods-SwaggerClientTests */,
@ -560,6 +569,31 @@
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
}; };
95CC2C7E06DC188A05DAAEE9CAA555A3 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
ADF19C953CE2A7D0B72EC93A81FCCC26 /* Alamofire-dummy.m in Sources */,
8EB11202167FCDDF1257AAAB1D1FB244 /* Alamofire.swift in Sources */,
5CB05FBCB32D21E194B5ECF680CB6AE0 /* Download.swift in Sources */,
095406039B4D371E48D08B38A2975AC8 /* Error.swift in Sources */,
4081EA628AF0B73AC51FFB9D7AB3B89E /* Manager.swift in Sources */,
C7B6DD7C0456C50289A2C381DFE9FA3F /* MultipartFormData.swift in Sources */,
34CCDCA848A701466256BC2927DA8856 /* NetworkReachabilityManager.swift in Sources */,
BE41196F6A3903E59C3306FE3F8B43FE /* Notifications.swift in Sources */,
C0DB70AB368765DC64BFB5FEA75E0696 /* ParameterEncoding.swift in Sources */,
EFE92E8D3813DD26E78E93EEAF6D7E7E /* Request.swift in Sources */,
62E8346F03C03E7F4D631361F325689E /* Response.swift in Sources */,
3EA8F215C9C1432D74E5CCA4834AA8C0 /* ResponseSerialization.swift in Sources */,
AA314156AC500125F4078EE968DB14C6 /* Result.swift in Sources */,
7B48852C4D848FA2DA416A98F6425869 /* ServerTrustPolicy.swift in Sources */,
AE4CF87C02C042DF13ED5B21C4FDC1E0 /* Stream.swift in Sources */,
16102E4E35FAA0FC4161282FECE56469 /* Timeline.swift in Sources */,
5BC19E6E0F199276003F0AF96838BCE5 /* Upload.swift in Sources */,
2D3405986FC586FA6C0A5E0B6BA7E64E /* Validation.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
C2AD20E62D6A15C7CE3E20F8A811548F /* Sources */ = { C2AD20E62D6A15C7CE3E20F8A811548F /* Sources */ = {
isa = PBXSourcesBuildPhase; isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
@ -568,41 +602,19 @@
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
}; };
EF659EFF40D426A3A32A82CDB98CC6EE /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
B6D2DC3E3DA44CD382B9B425F40E11C1 /* Alamofire-dummy.m in Sources */,
B0FB4B01682814B9E3D32F9DC4A5E762 /* Alamofire.swift in Sources */,
A3505FA2FB3067D53847AD288AC04F03 /* Download.swift in Sources */,
D75CA395D510E08C404E55F5BDAE55CE /* Error.swift in Sources */,
A2C172FE407C0BC3478ADCA91A6C9CEC /* Manager.swift in Sources */,
8399DBEE3E2D98EB1F466132E476F4D9 /* MultipartFormData.swift in Sources */,
4DE5FCC41D100B113B6645EA64410F16 /* ParameterEncoding.swift in Sources */,
FC14480CECE872865A9C6E584F886DA3 /* Request.swift in Sources */,
03F494989CC1A8857B68A317D5D6860F /* Response.swift in Sources */,
D21B7325B3642887BFBE977E021F2D26 /* ResponseSerialization.swift in Sources */,
82971968CBDAB224212EEB4607C9FB8D /* Result.swift in Sources */,
80F496237530D382A045A29654D8C11C /* ServerTrustPolicy.swift in Sources */,
FEF0D7653948988B804226129471C1EC /* Stream.swift in Sources */,
0681ADC8BAE2C3185F13487BAAB4D9DD /* Upload.swift in Sources */,
C75519F0450166A6F28126ECC7664E9C /* Validation.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */ /* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */ /* Begin PBXTargetDependency section */
9D7C00D5DABDA9EE2ED06BE7F85DD5EA /* PBXTargetDependency */ = { 9D7C00D5DABDA9EE2ED06BE7F85DD5EA /* PBXTargetDependency */ = {
isa = PBXTargetDependency; isa = PBXTargetDependency;
name = Alamofire; name = Alamofire;
target = 432ECC54282C84882B482CCB4CF227FC /* Alamofire */; target = 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */;
targetProxy = 9587C29FFB2EF204C279D7FF29DA45C2 /* PBXContainerItemProxy */; targetProxy = 9587C29FFB2EF204C279D7FF29DA45C2 /* PBXContainerItemProxy */;
}; };
A2B064722D89556FD34AF0A4A3EC3847 /* PBXTargetDependency */ = { A2B064722D89556FD34AF0A4A3EC3847 /* PBXTargetDependency */ = {
isa = PBXTargetDependency; isa = PBXTargetDependency;
name = Alamofire; name = Alamofire;
target = 432ECC54282C84882B482CCB4CF227FC /* Alamofire */; target = 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */;
targetProxy = 815A2A76D6EC0B2933867EA1BA7E51D8 /* PBXContainerItemProxy */; targetProxy = 815A2A76D6EC0B2933867EA1BA7E51D8 /* PBXContainerItemProxy */;
}; };
A51999658423B0F25DD2B4FEECD542E3 /* PBXTargetDependency */ = { A51999658423B0F25DD2B4FEECD542E3 /* PBXTargetDependency */ = {
@ -614,6 +626,35 @@
/* End PBXTargetDependency section */ /* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */ /* Begin XCBuildConfiguration section */
32AD5F8918CA8B349E4671410FA624C9 /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = A149BF2819128352A98494A4402603EE /* Alamofire.xcconfig */;
buildSettings = {
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
CURRENT_PROJECT_VERSION = 1;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
DEFINES_MODULE = YES;
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_NO_COMMON_BLOCKS = YES;
GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch";
INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist";
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap";
MTL_ENABLE_DEBUG_INFO = NO;
PRODUCT_NAME = Alamofire;
SDKROOT = iphoneos;
SKIP_INSTALL = YES;
TARGETED_DEVICE_FAMILY = "1,2";
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
};
name = Release;
};
51E864C21FD4E8BF48B7DE196DE05017 /* Debug */ = { 51E864C21FD4E8BF48B7DE196DE05017 /* Debug */ = {
isa = XCBuildConfiguration; isa = XCBuildConfiguration;
baseConfigurationReference = 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */; baseConfigurationReference = 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */;
@ -648,6 +689,36 @@
}; };
name = Debug; name = Debug;
}; };
75218111E718FACE36F771E8ABECDB62 /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = A149BF2819128352A98494A4402603EE /* Alamofire.xcconfig */;
buildSettings = {
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
CURRENT_PROJECT_VERSION = 1;
DEBUG_INFORMATION_FORMAT = dwarf;
DEFINES_MODULE = YES;
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_NO_COMMON_BLOCKS = YES;
GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch";
INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist";
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap";
MTL_ENABLE_DEBUG_INFO = YES;
PRODUCT_NAME = Alamofire;
SDKROOT = iphoneos;
SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
TARGETED_DEVICE_FAMILY = "1,2";
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
};
name = Debug;
};
7C4A68800C97518F39692FF062F013EE /* Release */ = { 7C4A68800C97518F39692FF062F013EE /* Release */ = {
isa = XCBuildConfiguration; isa = XCBuildConfiguration;
baseConfigurationReference = 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */; baseConfigurationReference = 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */;
@ -785,35 +856,6 @@
}; };
name = Release; name = Release;
}; };
9B26D3A39011247999C097562A550399 /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 7D7AAA0E85E40ED735D6BCBF7A243C46 /* Alamofire.xcconfig */;
buildSettings = {
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
CURRENT_PROJECT_VERSION = 1;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
DEFINES_MODULE = YES;
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_NO_COMMON_BLOCKS = YES;
GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch";
INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist";
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap";
MTL_ENABLE_DEBUG_INFO = NO;
PRODUCT_NAME = Alamofire;
SDKROOT = iphoneos;
SKIP_INSTALL = YES;
TARGETED_DEVICE_FAMILY = "1,2";
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
};
name = Release;
};
B316166B7E92675830371A4D5A9C5B6B /* Debug */ = { B316166B7E92675830371A4D5A9C5B6B /* Debug */ = {
isa = XCBuildConfiguration; isa = XCBuildConfiguration;
baseConfigurationReference = DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */; baseConfigurationReference = DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */;
@ -844,36 +886,6 @@
}; };
name = Debug; name = Debug;
}; };
BE1BF3E5FC53BAFA505AB342C35E1F50 /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 7D7AAA0E85E40ED735D6BCBF7A243C46 /* Alamofire.xcconfig */;
buildSettings = {
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
CURRENT_PROJECT_VERSION = 1;
DEBUG_INFORMATION_FORMAT = dwarf;
DEFINES_MODULE = YES;
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_NO_COMMON_BLOCKS = YES;
GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch";
INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist";
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap";
MTL_ENABLE_DEBUG_INFO = YES;
PRODUCT_NAME = Alamofire;
SDKROOT = iphoneos;
SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
TARGETED_DEVICE_FAMILY = "1,2";
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
};
name = Debug;
};
F594C655D48020EC34B00AA63E001773 /* Release */ = { F594C655D48020EC34B00AA63E001773 /* Release */ = {
isa = XCBuildConfiguration; isa = XCBuildConfiguration;
buildSettings = { buildSettings = {
@ -966,6 +978,15 @@
defaultConfigurationIsVisible = 0; defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release; defaultConfigurationName = Release;
}; };
3CFB42910790CF0BDBCCEBAACD6B9367 /* Build configuration list for PBXNativeTarget "Alamofire" */ = {
isa = XCConfigurationList;
buildConfigurations = (
75218111E718FACE36F771E8ABECDB62 /* Debug */,
32AD5F8918CA8B349E4671410FA624C9 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
75D763A79F74FE2B1D1C066F125F118E /* Build configuration list for PBXNativeTarget "PetstoreClient" */ = { 75D763A79F74FE2B1D1C066F125F118E /* Build configuration list for PBXNativeTarget "PetstoreClient" */ = {
isa = XCConfigurationList; isa = XCConfigurationList;
buildConfigurations = ( buildConfigurations = (
@ -975,15 +996,6 @@
defaultConfigurationIsVisible = 0; defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release; defaultConfigurationName = Release;
}; };
8B2B2DA2F7F80D41B1FDB5FACFA4B3DE /* Build configuration list for PBXNativeTarget "Alamofire" */ = {
isa = XCConfigurationList;
buildConfigurations = (
BE1BF3E5FC53BAFA505AB342C35E1F50 /* Debug */,
9B26D3A39011247999C097562A550399 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
A255A180370C09C28653A0EC123D2678 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClient" */ = { A255A180370C09C28653A0EC123D2678 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClient" */ = {
isa = XCConfigurationList; isa = XCConfigurationList;
buildConfigurations = ( buildConfigurations = (

View File

@ -15,7 +15,7 @@
<key>CFBundlePackageType</key> <key>CFBundlePackageType</key>
<string>FMWK</string> <string>FMWK</string>
<key>CFBundleShortVersionString</key> <key>CFBundleShortVersionString</key>
<string>3.1.5</string> <string>3.4.1</string>
<key>CFBundleSignature</key> <key>CFBundleSignature</key>
<string>????</string> <string>????</string>
<key>CFBundleVersion</key> <key>CFBundleVersion</key>

View File

@ -3,7 +3,7 @@ This application makes use of the following third party libraries:
## Alamofire ## Alamofire
Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

View File

@ -14,7 +14,7 @@
</dict> </dict>
<dict> <dict>
<key>FooterText</key> <key>FooterText</key>
<string>Copyright (c) 2014&#8211;2016 Alamofire Software Foundation (http://alamofire.org/) <string>Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

View File

@ -4,11 +4,11 @@ Pod::Spec.new do |s|
s.osx.deployment_target = '10.9' s.osx.deployment_target = '10.9'
s.version = '0.0.1' s.version = '0.0.1'
s.source = { :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' } s.source = { :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' }
s.authors = s.authors = ''
s.license = 'Apache License, Version 2.0' s.license = 'Apache License, Version 2.0'
s.homepage = 'https://github.com/swagger-api/swagger-codegen' s.homepage = 'https://github.com/swagger-api/swagger-codegen'
s.summary = 'PetstoreClient' s.summary = 'PetstoreClient'
s.source_files = 'PetstoreClient/Classes/Swaggers/**/*.swift' s.source_files = 'PetstoreClient/Classes/Swaggers/**/*.swift'
s.dependency 'PromiseKit', '~> 3.1.1' s.dependency 'PromiseKit', '~> 3.1.1'
s.dependency 'Alamofire', '~> 3.1.5' s.dependency 'Alamofire', '~> 3.4.1'
end end

View File

@ -37,6 +37,9 @@ public class RequestBuilder<T> {
let method: String let method: String
let URLString: String let URLString: String
/// Optional block to obtain a reference to the request's progress instance when available.
public var onProgressReady: ((NSProgress) -> ())?
required public init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool) { required public init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool) {
self.method = method self.method = method
self.URLString = URLString self.URLString = URLString

View File

@ -57,15 +57,22 @@ class AlamofireRequestBuilder<T>: RequestBuilder<T> {
encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold, encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold,
encodingCompletion: { encodingResult in encodingCompletion: { encodingResult in
switch encodingResult { switch encodingResult {
case .Success(let upload, _, _): case .Success(let uploadRequest, _, _):
self.processRequest(upload, managerId, completion) if let onProgressReady = self.onProgressReady {
onProgressReady(uploadRequest.progress)
}
self.processRequest(uploadRequest, managerId, completion)
case .Failure(let encodingError): case .Failure(let encodingError):
completion(response: nil, error: encodingError) completion(response: nil, error: encodingError)
} }
} }
) )
} else { } else {
processRequest(manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding), managerId, completion) let request = manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding)
if let onProgressReady = self.onProgressReady {
onProgressReady(request.progress)
}
processRequest(request, managerId, completion)
} }
} }
@ -75,8 +82,36 @@ class AlamofireRequestBuilder<T>: RequestBuilder<T> {
request.authenticate(usingCredential: credential) request.authenticate(usingCredential: credential)
} }
request.validate().responseJSON(options: .AllowFragments) { response in let cleanupRequest = {
managerStore.removeValueForKey(managerId) managerStore.removeValueForKey(managerId)
}
let validatedRequest = request.validate()
switch T.self {
case is NSData.Type:
validatedRequest.responseData(completionHandler: { (dataResponse) in
cleanupRequest()
if (dataResponse.result.isFailure) {
completion(
response: nil,
error: dataResponse.result.error
)
return
}
completion(
response: Response(
response: dataResponse.response!,
body: dataResponse.data as! T
),
error: nil
)
})
default:
validatedRequest.responseJSON(options: .AllowFragments) { response in
cleanupRequest()
if response.result.isFailure { if response.result.isFailure {
completion(response: nil, error: response.result.error) completion(response: nil, error: response.result.error)
@ -101,6 +136,7 @@ class AlamofireRequestBuilder<T>: RequestBuilder<T> {
completion(response: nil, error: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) completion(response: nil, error: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"]))
} }
} }
}
private func buildHeaders() -> [String: AnyObject] { private func buildHeaders() -> [String: AnyObject] {
var httpHeaders = Manager.defaultHTTPHeaders var httpHeaders = Manager.defaultHTTPHeaders

View File

@ -59,6 +59,11 @@ extension Dictionary: JSONEncodable {
} }
} }
extension NSData: JSONEncodable {
func encodeToJSON() -> AnyObject {
return self.base64EncodedStringWithOptions(NSDataBase64EncodingOptions())
}
}
private let dateFormatter: NSDateFormatter = { private let dateFormatter: NSDateFormatter = {
let fmt = NSDateFormatter() let fmt = NSDateFormatter()
@ -73,6 +78,12 @@ extension NSDate: JSONEncodable {
} }
} }
extension NSUUID: JSONEncodable {
func encodeToJSON() -> AnyObject {
return self.UUIDString
}
}
extension RequestBuilder { extension RequestBuilder {
public func execute() -> Promise<Response<T>> { public func execute() -> Promise<Response<T>> {
let deferred = Promise<Response<T>>.pendingPromise() let deferred = Promise<Response<T>>.pendingPromise()

View File

@ -62,9 +62,15 @@ class Decoders {
if T.self is Int64.Type && source is NSNumber { if T.self is Int64.Type && source is NSNumber {
return source.longLongValue as! T; return source.longLongValue as! T;
} }
if T.self is NSUUID.Type && source is String {
return NSUUID(UUIDString: source as! String) as! T
}
if source is T { if source is T {
return source as! T return source as! T
} }
if T.self is NSData.Type && source is String {
return NSData(base64EncodedString: source as! String, options: NSDataBase64DecodingOptions()) as! T
}
let key = "\(T.self)" let key = "\(T.self)"
if let decoder = decoders[key] { if let decoder = decoders[key] {

View File

@ -1,4 +1,4 @@
Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

View File

@ -1,7 +1,7 @@
![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/assets/alamofire.png) ![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/assets/alamofire.png)
[![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg)](https://travis-ci.org/Alamofire/Alamofire) [![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg)](https://travis-ci.org/Alamofire/Alamofire)
[![Cocoapods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg) [![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg)
[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![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) [![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) [![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat)](http://twitter.com/AlamofireSF)
@ -22,10 +22,17 @@ Alamofire is an HTTP networking library written in Swift.
- [x] Comprehensive Unit Test Coverage - [x] Comprehensive Unit Test Coverage
- [x] [Complete Documentation](http://cocoadocs.org/docsets/Alamofire) - [x] [Complete Documentation](http://cocoadocs.org/docsets/Alamofire)
## 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.
* [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.
## Requirements ## Requirements
- iOS 8.0+ / Mac OS X 10.9+ / tvOS 9.0+ / watchOS 2.0+ - iOS 8.0+ / Mac OS X 10.9+ / tvOS 9.0+ / watchOS 2.0+
- Xcode 7.2+ - Xcode 7.3+
## Migration Guides ## Migration Guides
@ -60,10 +67,12 @@ To integrate Alamofire into your Xcode project using CocoaPods, specify it in yo
```ruby ```ruby
source 'https://github.com/CocoaPods/Specs.git' source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0' platform :ios, '9.0'
use_frameworks! use_frameworks!
pod 'Alamofire', '~> 3.0' target '<Your Target Name>' do
pod 'Alamofire', '~> 3.4'
end
``` ```
Then, run the following command: Then, run the following command:
@ -86,7 +95,7 @@ $ brew install carthage
To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`:
```ogdl ```ogdl
github "Alamofire/Alamofire" ~> 3.0 github "Alamofire/Alamofire" ~> 3.4
``` ```
Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project. Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project.
@ -161,6 +170,38 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
> 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. > 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.
### 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)
}
}
```
### Response Serialization ### Response Serialization
**Built-in Response Methods** **Built-in Response Methods**
@ -175,6 +216,7 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
```swift ```swift
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.validate()
.response { request, response, data, error in .response { request, response, data, error in
print(request) print(request)
print(response) print(response)
@ -183,12 +225,13 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
} }
``` ```
> 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 responser serializers taking advantage of `Response` and `Result` types. > 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.
#### Response Data Handler #### Response Data Handler
```swift ```swift
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.validate()
.responseData { response in .responseData { response in
print(response.request) print(response.request)
print(response.response) print(response.response)
@ -200,6 +243,7 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
```swift ```swift
Alamofire.request(.GET, "https://httpbin.org/get") Alamofire.request(.GET, "https://httpbin.org/get")
.validate()
.responseString { response in .responseString { response in
print("Success: \(response.result.isSuccess)") print("Success: \(response.result.isSuccess)")
print("Response String: \(response.result.value)") print("Response String: \(response.result.value)")
@ -210,6 +254,7 @@ Alamofire.request(.GET, "https://httpbin.org/get")
```swift ```swift
Alamofire.request(.GET, "https://httpbin.org/get") Alamofire.request(.GET, "https://httpbin.org/get")
.validate()
.responseJSON { response in .responseJSON { response in
debugPrint(response) debugPrint(response)
} }
@ -221,6 +266,7 @@ Response handlers can even be chained:
```swift ```swift
Alamofire.request(.GET, "https://httpbin.org/get") Alamofire.request(.GET, "https://httpbin.org/get")
.validate()
.responseString { response in .responseString { response in
print("Response String: \(response.result.value)") print("Response String: \(response.result.value)")
} }
@ -332,7 +378,7 @@ Adding a custom HTTP header to a `Request` is supported directly in the global `
```swift ```swift
let headers = [ let headers = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Content-Type": "application/x-www-form-urlencoded" "Accept": "application/json"
] ]
Alamofire.request(.GET, "https://httpbin.org/get", headers: headers) Alamofire.request(.GET, "https://httpbin.org/get", headers: headers)
@ -374,6 +420,7 @@ Alamofire.upload(.POST, "https://httpbin.org/post", file: fileURL)
print("Total bytes written on main queue: \(totalBytesWritten)") print("Total bytes written on main queue: \(totalBytesWritten)")
} }
} }
.validate()
.responseJSON { response in .responseJSON { response in
debugPrint(response) debugPrint(response)
} }
@ -540,38 +587,25 @@ Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)")
} }
``` ```
### Validation ### Timeline
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. Alamofire collects timings throughout the lifecycle of a `Request` and creates a `Timeline` object exposed as a property on a `Response`.
#### 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 ```swift
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.validate() .validate()
.responseJSON { response in .responseJSON { response in
switch response.result { print(response.timeline)
case .Success:
print("Validation Successful")
case .Failure(let error):
print(error)
}
} }
``` ```
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
### Printable ### Printable
```swift ```swift
@ -679,6 +713,20 @@ Requests can be suspended, resumed, and cancelled:
### Response Serialization ### Response Serialization
#### Handling Errors
Before implementing custom response serializers or object serialization methods, it's important to be prepared to handle any errors that may occur. 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
enum BackendError: ErrorType {
case Network(error: NSError)
case DataSerialization(reason: String)
case JSONSerialization(error: NSError)
case ObjectSerialization(reason: String)
case XMLSerialization(error: NSError)
}
```
#### Creating a Custom Response Serializer #### Creating a Custom Response Serializer
Alamofire provides built-in response serialization for strings, JSON, and property lists, but others can be added in extensions on `Alamofire.Request`. Alamofire provides built-in response serialization for strings, JSON, and property lists, but others can be added in extensions on `Alamofire.Request`.
@ -687,26 +735,24 @@ For example, here's how a response handler using [Ono](https://github.com/mattt/
```swift ```swift
extension Request { extension Request {
public static func XMLResponseSerializer() -> ResponseSerializer<ONOXMLDocument, NSError> { public static func XMLResponseSerializer() -> ResponseSerializer<ONOXMLDocument, BackendError> {
return ResponseSerializer { request, response, data, error in return ResponseSerializer { request, response, data, error in
guard error == nil else { return .Failure(error!) } guard error == nil else { return .Failure(.Network(error: error!)) }
guard let validData = data else { guard let validData = data else {
let failureReason = "Data could not be serialized. Input data was nil." return .Failure(.DataSerialization(reason: "Data could not be serialized. Input data was nil."))
let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
return .Failure(error)
} }
do { do {
let XML = try ONOXMLDocument(data: validData) let XML = try ONOXMLDocument(data: validData)
return .Success(XML) return .Success(XML)
} catch { } catch {
return .Failure(error as NSError) return .Failure(.XMLSerialization(error: error as NSError))
} }
} }
} }
public func responseXMLDocument(completionHandler: Response<ONOXMLDocument, NSError> -> Void) -> Self { public func responseXMLDocument(completionHandler: Response<ONOXMLDocument, BackendError> -> Void) -> Self {
return response(responseSerializer: Request.XMLResponseSerializer(), completionHandler: completionHandler) return response(responseSerializer: Request.XMLResponseSerializer(), completionHandler: completionHandler)
} }
} }
@ -722,9 +768,9 @@ public protocol ResponseObjectSerializable {
} }
extension Request { extension Request {
public func responseObject<T: ResponseObjectSerializable>(completionHandler: Response<T, NSError> -> Void) -> Self { public func responseObject<T: ResponseObjectSerializable>(completionHandler: Response<T, BackendError> -> Void) -> Self {
let responseSerializer = ResponseSerializer<T, NSError> { request, response, data, error in let responseSerializer = ResponseSerializer<T, BackendError> { request, response, data, error in
guard error == nil else { return .Failure(error!) } guard error == nil else { return .Failure(.Network(error: error!)) }
let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments) let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
let result = JSONResponseSerializer.serializeResponse(request, response, data, error) let result = JSONResponseSerializer.serializeResponse(request, response, data, error)
@ -737,12 +783,10 @@ extension Request {
{ {
return .Success(responseObject) return .Success(responseObject)
} else { } else {
let failureReason = "JSON could not be serialized into response object: \(value)" return .Failure(.ObjectSerialization(reason: "JSON could not be serialized into response object: \(value)"))
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
return .Failure(error)
} }
case .Failure(let error): case .Failure(let error):
return .Failure(error) return .Failure(.JSONSerialization(error: error))
} }
} }
@ -765,7 +809,7 @@ final class User: ResponseObjectSerializable {
```swift ```swift
Alamofire.request(.GET, "https://example.com/users/mattt") Alamofire.request(.GET, "https://example.com/users/mattt")
.responseObject { (response: Response<User, NSError>) in .responseObject { (response: Response<User, BackendError>) in
debugPrint(response) debugPrint(response)
} }
``` ```
@ -777,10 +821,26 @@ public protocol ResponseCollectionSerializable {
static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Self] static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Self]
} }
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
}
}
extension Alamofire.Request { extension Alamofire.Request {
public func responseCollection<T: ResponseCollectionSerializable>(completionHandler: Response<[T], NSError> -> Void) -> Self { public func responseCollection<T: ResponseCollectionSerializable>(completionHandler: Response<[T], BackendError> -> Void) -> Self {
let responseSerializer = ResponseSerializer<[T], NSError> { request, response, data, error in let responseSerializer = ResponseSerializer<[T], BackendError> { request, response, data, error in
guard error == nil else { return .Failure(error!) } guard error == nil else { return .Failure(.Network(error: error!)) }
let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments) let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
let result = JSONSerializer.serializeResponse(request, response, data, error) let result = JSONSerializer.serializeResponse(request, response, data, error)
@ -790,12 +850,10 @@ extension Alamofire.Request {
if let response = response { if let response = response {
return .Success(T.collection(response: response, representation: value)) return .Success(T.collection(response: response, representation: value))
} else { } else {
let failureReason = "Response collection could not be serialized due to nil response" return .Failure(. ObjectSerialization(reason: "Response collection could not be serialized due to nil response"))
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
return .Failure(error)
} }
case .Failure(let error): case .Failure(let error):
return .Failure(error) return .Failure(.JSONSerialization(error: error))
} }
} }
@ -813,26 +871,12 @@ final class User: ResponseObjectSerializable, ResponseCollectionSerializable {
self.username = response.URL!.lastPathComponent! self.username = response.URL!.lastPathComponent!
self.name = representation.valueForKeyPath("name") as! String self.name = representation.valueForKeyPath("name") as! String
} }
static func collection(response 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
}
} }
``` ```
```swift ```swift
Alamofire.request(.GET, "http://example.com/users") Alamofire.request(.GET, "http://example.com/users")
.responseCollection { (response: Response<[User], NSError>) in .responseCollection { (response: Response<[User], BackendError>) in
debugPrint(response) debugPrint(response)
} }
``` ```
@ -912,7 +956,7 @@ enum Router: URLRequestConvertible {
var URLRequest: NSMutableURLRequest { var URLRequest: NSMutableURLRequest {
let result: (path: String, parameters: [String: AnyObject]) = { let result: (path: String, parameters: [String: AnyObject]) = {
switch self { switch self {
case .Search(let query, let page) where page > 1: case .Search(let query, let page) where page > 0:
return ("/search", ["q": query, "offset": Router.perPage * page]) return ("/search", ["q": query, "offset": Router.perPage * page])
case .Search(let query, _): case .Search(let query, _):
return ("/search", ["q": query]) return ("/search", ["q": query])
@ -997,6 +1041,74 @@ enum Router: URLRequestConvertible {
Alamofire.request(Router.ReadUser("mattt")) // GET /users/mattt Alamofire.request(Router.ReadUser("mattt")) // GET /users/mattt
``` ```
### 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.
### Security ### 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`. 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`.
@ -1075,7 +1187,7 @@ The `.PerformDefaultEvaluation`, `.PinCertificates` and `.PinPublicKeys` server
#### Validating the Certificate Chain #### Validating the Certificate Chain
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 certficates or public keys. A value of `false` will skip the certificate chain validation, but will still perform the byte equality check. 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.
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. 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.
@ -1114,19 +1226,41 @@ Whether you need to set the `NSExceptionRequiresForwardSecrecy` to `NO` depends
> It is recommended to always use valid certificates in production environments. > It is recommended to always use valid certificates in production environments.
### 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()
```
> Make sure to remember to retain the `manager` in the above example, or no status changes will be reported.
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.
* 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."
> It is recommended to check out [WWDC 2012 Session 706, "Networking Best Practices"](https://developer.apple.com/videos/play/wwdc2012-706/) for more info.
--- ---
## 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.
## Open Rdars ## Open Rdars
The following rdars have some affect on the current implementation of Alamofire. The following rdars have some affect on the current implementation of Alamofire.
* [rdar://21349340](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case * [rdar://21349340](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case
* [rdar://26761490](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage
## FAQ ## FAQ
@ -1144,6 +1278,20 @@ Alamofire is owned and maintained by the [Alamofire Software Foundation](http://
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. 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.
## 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>
## License ## License
Alamofire is released under the MIT license. See LICENSE for details. Alamofire is released under the MIT license. See LICENSE for details.

View File

@ -1,6 +1,7 @@
//
// Alamofire.swift // Alamofire.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation

View File

@ -1,6 +1,7 @@
//
// Download.swift // Download.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -211,6 +213,8 @@ extension Request {
totalBytesWritten: Int64, totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64) totalBytesExpectedToWrite: Int64)
{ {
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let downloadTaskDidWriteData = downloadTaskDidWriteData { if let downloadTaskDidWriteData = downloadTaskDidWriteData {
downloadTaskDidWriteData( downloadTaskDidWriteData(
session, session,

View File

@ -1,6 +1,7 @@
//
// Error.swift // Error.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -39,6 +41,15 @@ public struct Error {
case PropertyListSerializationFailed = -6007 case PropertyListSerializationFailed = -6007
} }
/// Custom keys contained within certain NSError `userInfo` dictionaries generated by Alamofire.
public struct UserInfoKeys {
/// The content type user info key for a `.ContentTypeValidationFailed` error stored as a `String` value.
public static let ContentType = "ContentType"
/// The status code user info key for a `.StatusCodeValidationFailed` error stored as an `Int` value.
public static let StatusCode = "StatusCode"
}
/** /**
Creates an `NSError` with the given error code and failure reason. Creates an `NSError` with the given error code and failure reason.
@ -47,6 +58,7 @@ public struct Error {
- returns: An `NSError` with the given error code and failure reason. - returns: An `NSError` with the given error code and failure reason.
*/ */
@available(*, deprecated=3.4.0)
public static func errorWithCode(code: Code, failureReason: String) -> NSError { public static func errorWithCode(code: Code, failureReason: String) -> NSError {
return errorWithCode(code.rawValue, failureReason: failureReason) return errorWithCode(code.rawValue, failureReason: failureReason)
} }
@ -59,8 +71,18 @@ public struct Error {
- returns: An `NSError` with the given error code and failure reason. - returns: An `NSError` with the given error code and failure reason.
*/ */
@available(*, deprecated=3.4.0)
public static func errorWithCode(code: Int, failureReason: String) -> NSError { public static func errorWithCode(code: Int, failureReason: String) -> NSError {
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
return NSError(domain: Domain, code: code, userInfo: userInfo) return NSError(domain: Domain, code: code, userInfo: userInfo)
} }
static func error(domain domain: String = Error.Domain, code: Code, failureReason: String) -> NSError {
return error(domain: domain, code: code.rawValue, failureReason: failureReason)
}
static func error(domain domain: String = Error.Domain, code: Int, failureReason: String) -> NSError {
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
return NSError(domain: domain, code: code, userInfo: userInfo)
}
} }

View File

@ -1,6 +1,7 @@
//
// Manager.swift // Manager.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -56,17 +58,40 @@ public class Manager {
// User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3
let userAgent: String = { let userAgent: String = {
if let info = NSBundle.mainBundle().infoDictionary { if let info = NSBundle.mainBundle().infoDictionary {
let executable: AnyObject = info[kCFBundleExecutableKey as String] ?? "Unknown" let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown"
let bundle: AnyObject = info[kCFBundleIdentifierKey as String] ?? "Unknown" let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown"
let version: AnyObject = info[kCFBundleVersionKey as String] ?? "Unknown" let version = info[kCFBundleVersionKey as String] as? String ?? "Unknown"
let os: AnyObject = NSProcessInfo.processInfo().operatingSystemVersionString ?? "Unknown"
var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString let osNameVersion: String = {
let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString let versionString: String
if CFStringTransform(mutableUserAgent, UnsafeMutablePointer<CFRange>(nil), transform, false) { if #available(OSX 10.10, *) {
return mutableUserAgent as String let version = NSProcessInfo.processInfo().operatingSystemVersion
versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"
} else {
versionString = "10.9"
} }
let osName: String = {
#if os(iOS)
return "iOS"
#elseif os(watchOS)
return "watchOS"
#elseif os(tvOS)
return "tvOS"
#elseif os(OSX)
return "OS X"
#elseif os(Linux)
return "Linux"
#else
return "Unknown"
#endif
}()
return "\(osName) \(versionString)"
}()
return "\(executable)/\(bundle) (\(version); \(osNameVersion))"
} }
return "Alamofire" return "Alamofire"
@ -143,11 +168,11 @@ public class Manager {
delegate: SessionDelegate, delegate: SessionDelegate,
serverTrustPolicyManager: ServerTrustPolicyManager? = nil) serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{ {
guard delegate === session.delegate else { return nil }
self.delegate = delegate self.delegate = delegate
self.session = session self.session = session
guard delegate === session.delegate else { return nil }
commonInit(serverTrustPolicyManager: serverTrustPolicyManager) commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
} }
@ -218,18 +243,18 @@ public class Manager {
/** /**
Responsible for handling all delegate callbacks for the underlying session. Responsible for handling all delegate callbacks for the underlying session.
*/ */
public final class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate { public class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
private var subdelegates: [Int: Request.TaskDelegate] = [:] private var subdelegates: [Int: Request.TaskDelegate] = [:]
private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
subscript(task: NSURLSessionTask) -> Request.TaskDelegate? { /// Access the task delegate for the specified task in a thread-safe manner.
public subscript(task: NSURLSessionTask) -> Request.TaskDelegate? {
get { get {
var subdelegate: Request.TaskDelegate? var subdelegate: Request.TaskDelegate?
dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] } dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] }
return subdelegate return subdelegate
} }
set { set {
dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue } dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue }
} }
@ -254,6 +279,9 @@ public class Manager {
/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`. /// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`.
public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
/// Overrides all behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:` and requires the caller to call the `completionHandler`.
public var sessionDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`. /// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`.
public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)? public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)?
@ -281,6 +309,11 @@ public class Manager {
didReceiveChallenge challenge: NSURLAuthenticationChallenge, didReceiveChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void))
{ {
guard sessionDidReceiveChallengeWithCompletion == nil else {
sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler)
return
}
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
var credential: NSURLCredential? var credential: NSURLCredential?
@ -321,11 +354,23 @@ public class Manager {
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`. /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`.
public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)?
/// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:` and
/// requires the caller to call the `completionHandler`.
public var taskWillPerformHTTPRedirectionWithCompletion: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest, NSURLRequest? -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`. /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`.
public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
/// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:` and
/// requires the caller to call the `completionHandler`.
public var taskDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`. /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`.
public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream!)? public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)?
/// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:` and
/// requires the caller to call the `completionHandler`.
public var taskNeedNewBodyStreamWithCompletion: ((NSURLSession, NSURLSessionTask, NSInputStream? -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.
public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)? public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)?
@ -351,8 +396,13 @@ public class Manager {
task: NSURLSessionTask, task: NSURLSessionTask,
willPerformHTTPRedirection response: NSHTTPURLResponse, willPerformHTTPRedirection response: NSHTTPURLResponse,
newRequest request: NSURLRequest, newRequest request: NSURLRequest,
completionHandler: ((NSURLRequest?) -> Void)) completionHandler: NSURLRequest? -> Void)
{ {
guard taskWillPerformHTTPRedirectionWithCompletion == nil else {
taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler)
return
}
var redirectRequest: NSURLRequest? = request var redirectRequest: NSURLRequest? = request
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
@ -374,10 +424,16 @@ public class Manager {
session: NSURLSession, session: NSURLSession,
task: NSURLSessionTask, task: NSURLSessionTask,
didReceiveChallenge challenge: NSURLAuthenticationChallenge, didReceiveChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)
{ {
guard taskDidReceiveChallengeWithCompletion == nil else {
taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler)
return
}
if let taskDidReceiveChallenge = taskDidReceiveChallenge { if let taskDidReceiveChallenge = taskDidReceiveChallenge {
completionHandler(taskDidReceiveChallenge(session, task, challenge)) let result = taskDidReceiveChallenge(session, task, challenge)
completionHandler(result.0, result.1)
} else if let delegate = self[task] { } else if let delegate = self[task] {
delegate.URLSession( delegate.URLSession(
session, session,
@ -400,8 +456,13 @@ public class Manager {
public func URLSession( public func URLSession(
session: NSURLSession, session: NSURLSession,
task: NSURLSessionTask, task: NSURLSessionTask,
needNewBodyStream completionHandler: ((NSInputStream?) -> Void)) needNewBodyStream completionHandler: NSInputStream? -> Void)
{ {
guard taskNeedNewBodyStreamWithCompletion == nil else {
taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler)
return
}
if let taskNeedNewBodyStream = taskNeedNewBodyStream { if let taskNeedNewBodyStream = taskNeedNewBodyStream {
completionHandler(taskNeedNewBodyStream(session, task)) completionHandler(taskNeedNewBodyStream(session, task))
} else if let delegate = self[task] { } else if let delegate = self[task] {
@ -452,6 +513,8 @@ public class Manager {
delegate.URLSession(session, task: task, didCompleteWithError: error) delegate.URLSession(session, task: task, didCompleteWithError: error)
} }
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidComplete, object: task)
self[task] = nil self[task] = nil
} }
@ -462,6 +525,10 @@ public class Manager {
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`. /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`.
public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)? public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)?
/// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:` and
/// requires caller to call the `completionHandler`.
public var dataTaskDidReceiveResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSURLResponse, NSURLSessionResponseDisposition -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`. /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`.
public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)? public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)?
@ -469,7 +536,11 @@ public class Manager {
public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)? public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`. /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`.
public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse!)? public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)?
/// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:` and
/// requires caller to call the `completionHandler`.
public var dataTaskWillCacheResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse, NSCachedURLResponse? -> Void) -> Void)?
// MARK: Delegate Methods // MARK: Delegate Methods
@ -487,8 +558,13 @@ public class Manager {
session: NSURLSession, session: NSURLSession,
dataTask: NSURLSessionDataTask, dataTask: NSURLSessionDataTask,
didReceiveResponse response: NSURLResponse, didReceiveResponse response: NSURLResponse,
completionHandler: ((NSURLSessionResponseDisposition) -> Void)) completionHandler: NSURLSessionResponseDisposition -> Void)
{ {
guard dataTaskDidReceiveResponseWithCompletion == nil else {
dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler)
return
}
var disposition: NSURLSessionResponseDisposition = .Allow var disposition: NSURLSessionResponseDisposition = .Allow
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
@ -550,8 +626,13 @@ public class Manager {
session: NSURLSession, session: NSURLSession,
dataTask: NSURLSessionDataTask, dataTask: NSURLSessionDataTask,
willCacheResponse proposedResponse: NSCachedURLResponse, willCacheResponse proposedResponse: NSCachedURLResponse,
completionHandler: ((NSCachedURLResponse?) -> Void)) completionHandler: NSCachedURLResponse? -> Void)
{ {
guard dataTaskWillCacheResponseWithCompletion == nil else {
dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler)
return
}
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse))
} else if let delegate = self[dataTask] as? Request.DataTaskDelegate { } else if let delegate = self[dataTask] as? Request.DataTaskDelegate {
@ -674,17 +755,21 @@ public class Manager {
// MARK: - NSObject // MARK: - NSObject
public override func respondsToSelector(selector: Selector) -> Bool { public override func respondsToSelector(selector: Selector) -> Bool {
switch selector { #if !os(OSX)
case "URLSession:didBecomeInvalidWithError:": if selector == #selector(NSURLSessionDelegate.URLSessionDidFinishEventsForBackgroundURLSession(_:)) {
return sessionDidBecomeInvalidWithError != nil
case "URLSession:didReceiveChallenge:completionHandler:":
return sessionDidReceiveChallenge != nil
case "URLSessionDidFinishEventsForBackgroundURLSession:":
return sessionDidFinishEventsForBackgroundURLSession != nil return sessionDidFinishEventsForBackgroundURLSession != nil
case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:": }
return taskWillPerformHTTPRedirection != nil #endif
case "URLSession:dataTask:didReceiveResponse:completionHandler:":
return dataTaskDidReceiveResponse != nil switch selector {
case #selector(NSURLSessionDelegate.URLSession(_:didBecomeInvalidWithError:)):
return sessionDidBecomeInvalidWithError != nil
case #selector(NSURLSessionDelegate.URLSession(_:didReceiveChallenge:completionHandler:)):
return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil)
case #selector(NSURLSessionTaskDelegate.URLSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)):
return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil)
case #selector(NSURLSessionDataDelegate.URLSession(_:dataTask:didReceiveResponse:completionHandler:)):
return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil)
default: default:
return self.dynamicType.instancesRespondToSelector(selector) return self.dynamicType.instancesRespondToSelector(selector)
} }

View File

@ -1,6 +1,7 @@
//
// MultipartFormData.swift // MultipartFormData.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -217,7 +219,7 @@ public class MultipartFormData {
appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType) appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType)
} else { } else {
let failureReason = "Failed to extract the fileName of the provided URL: \(fileURL)" let failureReason = "Failed to extract the fileName of the provided URL: \(fileURL)"
setBodyPartError(Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)) setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
} }
} }
@ -245,8 +247,7 @@ public class MultipartFormData {
guard fileURL.fileURL else { guard fileURL.fileURL else {
let failureReason = "The file URL does not point to a file URL: \(fileURL)" let failureReason = "The file URL does not point to a file URL: \(fileURL)"
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
setBodyPartError(error)
return return
} }
@ -261,8 +262,7 @@ public class MultipartFormData {
} }
guard isReachable else { guard isReachable else {
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)") setBodyPartError(code: NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)")
setBodyPartError(error)
return return
} }
@ -277,8 +277,7 @@ public class MultipartFormData {
where NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) && !isDirectory else where NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) && !isDirectory else
{ {
let failureReason = "The file URL is a directory, not a file: \(fileURL)" let failureReason = "The file URL is a directory, not a file: \(fileURL)"
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
setBodyPartError(error)
return return
} }
@ -301,8 +300,7 @@ public class MultipartFormData {
guard let length = bodyContentLength else { guard let length = bodyContentLength else {
let failureReason = "Could not fetch attributes from the file URL: \(fileURL)" let failureReason = "Could not fetch attributes from the file URL: \(fileURL)"
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
setBodyPartError(error)
return return
} }
@ -312,8 +310,7 @@ public class MultipartFormData {
guard let stream = NSInputStream(URL: fileURL) else { guard let stream = NSInputStream(URL: fileURL) else {
let failureReason = "Failed to create an input stream from the file URL: \(fileURL)" let failureReason = "Failed to create an input stream from the file URL: \(fileURL)"
let error = Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason) setBodyPartError(code: NSURLErrorCannotOpenFile, failureReason: failureReason)
setBodyPartError(error)
return return
} }
@ -413,10 +410,10 @@ public class MultipartFormData {
if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) { if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) {
let failureReason = "A file already exists at the given file URL: \(fileURL)" let failureReason = "A file already exists at the given file URL: \(fileURL)"
throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason)
} else if !fileURL.fileURL { } else if !fileURL.fileURL {
let failureReason = "The URL does not point to a valid file: \(fileURL)" let failureReason = "The URL does not point to a valid file: \(fileURL)"
throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason)
} }
let outputStream: NSOutputStream let outputStream: NSOutputStream
@ -425,10 +422,9 @@ public class MultipartFormData {
outputStream = possibleOutputStream outputStream = possibleOutputStream
} else { } else {
let failureReason = "Failed to create an output stream with the given URL: \(fileURL)" let failureReason = "Failed to create an output stream with the given URL: \(fileURL)"
throw Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason) throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorCannotOpenFile, failureReason: failureReason)
} }
outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
outputStream.open() outputStream.open()
self.bodyParts.first?.hasInitialBoundary = true self.bodyParts.first?.hasInitialBoundary = true
@ -439,7 +435,6 @@ public class MultipartFormData {
} }
outputStream.close() outputStream.close()
outputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
} }
// MARK: - Private - Body Part Encoding // MARK: - Private - Body Part Encoding
@ -476,7 +471,6 @@ public class MultipartFormData {
private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) throws -> NSData { private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) throws -> NSData {
let inputStream = bodyPart.bodyStream let inputStream = bodyPart.bodyStream
inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
inputStream.open() inputStream.open()
var error: NSError? var error: NSError?
@ -495,7 +489,7 @@ public class MultipartFormData {
encoded.appendBytes(buffer, length: bytesRead) encoded.appendBytes(buffer, length: bytesRead)
} else if bytesRead < 0 { } else if bytesRead < 0 {
let failureReason = "Failed to read from input stream: \(inputStream)" let failureReason = "Failed to read from input stream: \(inputStream)"
error = Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason) error = Error.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason)
break break
} else { } else {
break break
@ -503,7 +497,6 @@ public class MultipartFormData {
} }
inputStream.close() inputStream.close()
inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
if let error = error { if let error = error {
throw error throw error
@ -537,7 +530,6 @@ public class MultipartFormData {
private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
let inputStream = bodyPart.bodyStream let inputStream = bodyPart.bodyStream
inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
inputStream.open() inputStream.open()
while inputStream.hasBytesAvailable { while inputStream.hasBytesAvailable {
@ -556,14 +548,13 @@ public class MultipartFormData {
try writeBuffer(&buffer, toOutputStream: outputStream) try writeBuffer(&buffer, toOutputStream: outputStream)
} else if bytesRead < 0 { } else if bytesRead < 0 {
let failureReason = "Failed to read from input stream: \(inputStream)" let failureReason = "Failed to read from input stream: \(inputStream)"
throw Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason) throw Error.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason)
} else { } else {
break break
} }
} }
inputStream.close() inputStream.close()
inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
} }
private func writeFinalBoundaryDataForBodyPart( private func writeFinalBoundaryDataForBodyPart(
@ -598,7 +589,7 @@ public class MultipartFormData {
if bytesWritten < 0 { if bytesWritten < 0 {
let failureReason = "Failed to write to output stream: \(outputStream)" let failureReason = "Failed to write to output stream: \(outputStream)"
throw Error.errorWithCode(.OutputStreamWriteFailed, failureReason: failureReason) throw Error.error(domain: NSURLErrorDomain, code: .OutputStreamWriteFailed, failureReason: failureReason)
} }
bytesToWrite -= bytesWritten bytesToWrite -= bytesWritten
@ -661,9 +652,8 @@ public class MultipartFormData {
// MARK: - Private - Errors // MARK: - Private - Errors
private func setBodyPartError(error: NSError) { private func setBodyPartError(code code: Int, failureReason: String) {
if bodyPartError == nil { guard bodyPartError == nil else { return }
bodyPartError = error bodyPartError = Error.error(domain: NSURLErrorDomain, code: code, failureReason: failureReason)
}
} }
} }

View File

@ -0,0 +1,244 @@
//
// NetworkReachabilityManager.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#if !os(watchOS)
import Foundation
import SystemConfiguration
/**
The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and
WiFi network interfaces.
Reachability can be used to determine background information about why a network operation failed, or to retry
network requests when a connection is established. It should not be used to prevent a user from initiating a network
request, as it's possible that an initial request may be required to establish reachability.
*/
public class NetworkReachabilityManager {
/**
Defines the various states of network reachability.
- Unknown: It is unknown whether the network is reachable.
- NotReachable: The network is not reachable.
- ReachableOnWWAN: The network is reachable over the WWAN connection.
- ReachableOnWiFi: The network is reachable over the WiFi connection.
*/
public enum NetworkReachabilityStatus {
case Unknown
case NotReachable
case Reachable(ConnectionType)
}
/**
Defines the various connection types detected by reachability flags.
- EthernetOrWiFi: The connection type is either over Ethernet or WiFi.
- WWAN: The connection type is a WWAN connection.
*/
public enum ConnectionType {
case EthernetOrWiFi
case WWAN
}
/// A closure executed when the network reachability status changes. The closure takes a single argument: the
/// network reachability status.
public typealias Listener = NetworkReachabilityStatus -> Void
// MARK: - Properties
/// Whether the network is currently reachable.
public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi }
/// Whether the network is currently reachable over the WWAN interface.
public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .Reachable(.WWAN) }
/// Whether the network is currently reachable over Ethernet or WiFi interface.
public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .Reachable(.EthernetOrWiFi) }
/// The current network reachability status.
public var networkReachabilityStatus: NetworkReachabilityStatus {
guard let flags = self.flags else { return .Unknown }
return networkReachabilityStatusForFlags(flags)
}
/// The dispatch queue to execute the `listener` closure on.
public var listenerQueue: dispatch_queue_t = dispatch_get_main_queue()
/// A closure executed when the network reachability status changes.
public var listener: Listener?
private var flags: SCNetworkReachabilityFlags? {
var flags = SCNetworkReachabilityFlags()
if SCNetworkReachabilityGetFlags(reachability, &flags) {
return flags
}
return nil
}
private let reachability: SCNetworkReachability
private var previousFlags: SCNetworkReachabilityFlags
// MARK: - Initialization
/**
Creates a `NetworkReachabilityManager` instance with the specified host.
- parameter host: The host used to evaluate network reachability.
- returns: The new `NetworkReachabilityManager` instance.
*/
public convenience init?(host: String) {
guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil }
self.init(reachability: reachability)
}
/**
Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0.
Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing
status of the device, both IPv4 and IPv6.
- returns: The new `NetworkReachabilityManager` instance.
*/
public convenience init?() {
var address = sockaddr_in()
address.sin_len = UInt8(sizeofValue(address))
address.sin_family = sa_family_t(AF_INET)
guard let reachability = withUnsafePointer(&address, {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}) else { return nil }
self.init(reachability: reachability)
}
private init(reachability: SCNetworkReachability) {
self.reachability = reachability
self.previousFlags = SCNetworkReachabilityFlags()
}
deinit {
stopListening()
}
// MARK: - Listening
/**
Starts listening for changes in network reachability status.
- returns: `true` if listening was started successfully, `false` otherwise.
*/
public func startListening() -> Bool {
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
context.info = UnsafeMutablePointer(Unmanaged.passUnretained(self).toOpaque())
let callbackEnabled = SCNetworkReachabilitySetCallback(
reachability,
{ (_, flags, info) in
let reachability = Unmanaged<NetworkReachabilityManager>.fromOpaque(COpaquePointer(info)).takeUnretainedValue()
reachability.notifyListener(flags)
},
&context
)
let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue)
dispatch_async(listenerQueue) {
self.previousFlags = SCNetworkReachabilityFlags()
self.notifyListener(self.flags ?? SCNetworkReachabilityFlags())
}
return callbackEnabled && queueEnabled
}
/**
Stops listening for changes in network reachability status.
*/
public func stopListening() {
SCNetworkReachabilitySetCallback(reachability, nil, nil)
SCNetworkReachabilitySetDispatchQueue(reachability, nil)
}
// MARK: - Internal - Listener Notification
func notifyListener(flags: SCNetworkReachabilityFlags) {
guard previousFlags != flags else { return }
previousFlags = flags
listener?(networkReachabilityStatusForFlags(flags))
}
// MARK: - Internal - Network Reachability Status
func networkReachabilityStatusForFlags(flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus {
guard flags.contains(.Reachable) else { return .NotReachable }
var networkStatus: NetworkReachabilityStatus = .NotReachable
if !flags.contains(.ConnectionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) }
if flags.contains(.ConnectionOnDemand) || flags.contains(.ConnectionOnTraffic) {
if !flags.contains(.InterventionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) }
}
#if os(iOS)
if flags.contains(.IsWWAN) { networkStatus = .Reachable(.WWAN) }
#endif
return networkStatus
}
}
// MARK: -
extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {}
/**
Returns whether the two network reachability status values are equal.
- parameter lhs: The left-hand side value to compare.
- parameter rhs: The right-hand side value to compare.
- returns: `true` if the two values are equal, `false` otherwise.
*/
public func ==(
lhs: NetworkReachabilityManager.NetworkReachabilityStatus,
rhs: NetworkReachabilityManager.NetworkReachabilityStatus)
-> Bool
{
switch (lhs, rhs) {
case (.Unknown, .Unknown):
return true
case (.NotReachable, .NotReachable):
return true
case let (.Reachable(lhsConnectionType), .Reachable(rhsConnectionType)):
return lhsConnectionType == rhsConnectionType
default:
return false
}
}
#endif

View File

@ -0,0 +1,47 @@
//
// Notifications.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// Contains all the `NSNotification` names posted by Alamofire with descriptions of each notification's payload.
public struct Notifications {
/// Used as a namespace for all `NSURLSessionTask` related notifications.
public struct Task {
/// Notification posted when an `NSURLSessionTask` is resumed. The notification `object` contains the resumed
/// `NSURLSessionTask`.
public static let DidResume = "com.alamofire.notifications.task.didResume"
/// Notification posted when an `NSURLSessionTask` is suspended. The notification `object` contains the
/// suspended `NSURLSessionTask`.
public static let DidSuspend = "com.alamofire.notifications.task.didSuspend"
/// Notification posted when an `NSURLSessionTask` is cancelled. The notification `object` contains the
/// cancelled `NSURLSessionTask`.
public static let DidCancel = "com.alamofire.notifications.task.didCancel"
/// Notification posted when an `NSURLSessionTask` is completed. The notification `object` contains the
/// completed `NSURLSessionTask`.
public static let DidComplete = "com.alamofire.notifications.task.didComplete"
}
}

View File

@ -1,6 +1,7 @@
//
// ParameterEncoding.swift // ParameterEncoding.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -69,8 +71,8 @@ public enum ParameterEncoding {
/** /**
Creates a URL request by encoding parameters and applying them onto an existing request. Creates a URL request by encoding parameters and applying them onto an existing request.
- parameter URLRequest: The request to have parameters applied - parameter URLRequest: The request to have parameters applied.
- parameter parameters: The parameters to apply - parameter parameters: The parameters to apply.
- returns: A tuple containing the constructed request and the error that occurred during parameter encoding, - returns: A tuple containing the constructed request and the error that occurred during parameter encoding,
if any. if any.
@ -82,9 +84,7 @@ public enum ParameterEncoding {
{ {
var mutableURLRequest = URLRequest.URLRequest var mutableURLRequest = URLRequest.URLRequest
guard let parameters = parameters where !parameters.isEmpty else { guard let parameters = parameters else { return (mutableURLRequest, nil) }
return (mutableURLRequest, nil)
}
var encodingError: NSError? = nil var encodingError: NSError? = nil
@ -118,7 +118,10 @@ public enum ParameterEncoding {
} }
if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) { if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) {
if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) { if let
URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false)
where !parameters.isEmpty
{
let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
URLComponents.percentEncodedQuery = percentEncodedQuery URLComponents.percentEncodedQuery = percentEncodedQuery
mutableURLRequest.URL = URLComponents.URL mutableURLRequest.URL = URLComponents.URL
@ -141,7 +144,10 @@ public enum ParameterEncoding {
let options = NSJSONWritingOptions() let options = NSJSONWritingOptions()
let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options) let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options)
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
mutableURLRequest.HTTPBody = data mutableURLRequest.HTTPBody = data
} catch { } catch {
encodingError = error as NSError encodingError = error as NSError
@ -153,7 +159,11 @@ public enum ParameterEncoding {
format: format, format: format,
options: options options: options
) )
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
}
mutableURLRequest.HTTPBody = data mutableURLRequest.HTTPBody = data
} catch { } catch {
encodingError = error as NSError encodingError = error as NSError
@ -219,7 +229,7 @@ public enum ParameterEncoding {
//========================================================================================================== //==========================================================================================================
// //
// Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few
// hundred Chinense characters causes various malloc error crashes. To avoid this issue until iOS 8 is no // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no
// longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more
// info, please refer to: // info, please refer to:
// //
@ -236,7 +246,7 @@ public enum ParameterEncoding {
while index != string.endIndex { while index != string.endIndex {
let startIndex = index let startIndex = index
let endIndex = index.advancedBy(batchSize, limit: string.endIndex) let endIndex = index.advancedBy(batchSize, limit: string.endIndex)
let range = Range(start: startIndex, end: endIndex) let range = startIndex..<endIndex
let substring = string.substringWithRange(range) let substring = string.substringWithRange(range)

View File

@ -1,6 +1,7 @@
//
// Request.swift // Request.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -48,6 +50,9 @@ public class Request {
/// The progress of the request lifecycle. /// The progress of the request lifecycle.
public var progress: NSProgress { return delegate.progress } public var progress: NSProgress { return delegate.progress }
var startTime: CFAbsoluteTime?
var endTime: CFAbsoluteTime?
// MARK: - Lifecycle // MARK: - Lifecycle
init(session: NSURLSession, task: NSURLSessionTask) { init(session: NSURLSession, task: NSURLSessionTask) {
@ -55,14 +60,16 @@ public class Request {
switch task { switch task {
case is NSURLSessionUploadTask: case is NSURLSessionUploadTask:
self.delegate = UploadTaskDelegate(task: task) delegate = UploadTaskDelegate(task: task)
case is NSURLSessionDataTask: case is NSURLSessionDataTask:
self.delegate = DataTaskDelegate(task: task) delegate = DataTaskDelegate(task: task)
case is NSURLSessionDownloadTask: case is NSURLSessionDownloadTask:
self.delegate = DownloadTaskDelegate(task: task) delegate = DownloadTaskDelegate(task: task)
default: default:
self.delegate = TaskDelegate(task: task) delegate = TaskDelegate(task: task)
} }
delegate.queue.addOperationWithBlock { self.endTime = CFAbsoluteTimeGetCurrent() }
} }
// MARK: - Authentication // MARK: - Authentication
@ -100,6 +107,22 @@ public class Request {
return self return self
} }
/**
Returns a base64 encoded basic authentication credential as an authorization header dictionary.
- parameter user: The user.
- parameter password: The password.
- returns: A dictionary with Authorization key and credential value or empty dictionary if encoding fails.
*/
public static func authorizationHeader(user user: String, password: String) -> [String: String] {
guard let data = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding) else { return [:] }
let credential = data.base64EncodedStringWithOptions([])
return ["Authorization": "Basic \(credential)"]
}
// MARK: - Progress // MARK: - Progress
/** /**
@ -148,18 +171,22 @@ public class Request {
// MARK: - State // MARK: - State
/**
Resumes the request.
*/
public func resume() {
if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() }
task.resume()
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidResume, object: task)
}
/** /**
Suspends the request. Suspends the request.
*/ */
public func suspend() { public func suspend() {
task.suspend() task.suspend()
} NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidSuspend, object: task)
/**
Resumes the request.
*/
public func resume() {
task.resume()
} }
/** /**
@ -176,6 +203,8 @@ public class Request {
} else { } else {
task.cancel() task.cancel()
} }
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidCancel, object: task)
} }
// MARK: - TaskDelegate // MARK: - TaskDelegate
@ -195,6 +224,7 @@ public class Request {
var data: NSData? { return nil } var data: NSData? { return nil }
var error: NSError? var error: NSError?
var initialResponseTime: CFAbsoluteTime?
var credential: NSURLCredential? var credential: NSURLCredential?
init(task: NSURLSessionTask) { init(task: NSURLSessionTask) {
@ -272,7 +302,7 @@ public class Request {
} }
} else { } else {
if challenge.previousFailureCount > 0 { if challenge.previousFailureCount > 0 {
disposition = .CancelAuthenticationChallenge disposition = .RejectProtectionSpace
} else { } else {
credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace) credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)
@ -381,6 +411,8 @@ public class Request {
} }
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let dataTaskDidReceiveData = dataTaskDidReceiveData { if let dataTaskDidReceiveData = dataTaskDidReceiveData {
dataTaskDidReceiveData(session, dataTask, data) dataTaskDidReceiveData(session, dataTask, data)
} else { } else {
@ -470,7 +502,7 @@ extension Request: CustomDebugStringConvertible {
let protectionSpace = NSURLProtectionSpace( let protectionSpace = NSURLProtectionSpace(
host: host, host: host,
port: URL.port?.integerValue ?? 0, port: URL.port?.integerValue ?? 0,
`protocol`: URL.scheme, protocol: URL.scheme,
realm: host, realm: host,
authenticationMethod: NSURLAuthenticationMethodHTTPBasic authenticationMethod: NSURLAuthenticationMethodHTTPBasic
) )
@ -496,33 +528,31 @@ extension Request: CustomDebugStringConvertible {
} }
} }
if let headerFields = request.allHTTPHeaderFields { var headers: [NSObject: AnyObject] = [:]
for (field, value) in headerFields {
switch field { if let additionalHeaders = session.configuration.HTTPAdditionalHeaders {
case "Cookie": for (field, value) in additionalHeaders where field != "Cookie" {
continue headers[field] = value
default:
components.append("-H \"\(field): \(value)\"")
}
} }
} }
if let additionalHeaders = session.configuration.HTTPAdditionalHeaders { if let headerFields = request.allHTTPHeaderFields {
for (field, value) in additionalHeaders { for (field, value) in headerFields where field != "Cookie" {
switch field { headers[field] = value
case "Cookie": }
continue }
default:
for (field, value) in headers {
components.append("-H \"\(field): \(value)\"") components.append("-H \"\(field): \(value)\"")
} }
}
}
if let if let
HTTPBodyData = request.HTTPBody, HTTPBodyData = request.HTTPBody,
HTTPBody = String(data: HTTPBodyData, encoding: NSUTF8StringEncoding) HTTPBody = String(data: HTTPBodyData, encoding: NSUTF8StringEncoding)
{ {
let escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"") var escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\\\"", withString: "\\\\\"")
escapedBody = escapedBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
components.append("-d \"\(escapedBody)\"") components.append("-d \"\(escapedBody)\"")
} }

View File

@ -1,6 +1,7 @@
//
// Response.swift // Response.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -36,6 +38,9 @@ public struct Response<Value, Error: ErrorType> {
/// The result of response serialization. /// The result of response serialization.
public let result: Result<Value, Error> public let result: Result<Value, Error>
/// The timeline of the complete lifecycle of the `Request`.
public let timeline: Timeline
/** /**
Initializes the `Response` instance with the specified URL request, URL response, server data and response Initializes the `Response` instance with the specified URL request, URL response, server data and response
serialization result. serialization result.
@ -44,14 +49,22 @@ public struct Response<Value, Error: ErrorType> {
- parameter response: The server's response to the URL request. - parameter response: The server's response to the URL request.
- parameter data: The data returned by the server. - parameter data: The data returned by the server.
- parameter result: The result of response serialization. - parameter result: The result of response serialization.
- parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`.
- returns: the new `Response` instance. - returns: the new `Response` instance.
*/ */
public init(request: NSURLRequest?, response: NSHTTPURLResponse?, data: NSData?, result: Result<Value, Error>) { public init(
request: NSURLRequest?,
response: NSHTTPURLResponse?,
data: NSData?,
result: Result<Value, Error>,
timeline: Timeline = Timeline())
{
self.request = request self.request = request
self.response = response self.response = response
self.data = data self.data = data
self.result = result self.result = result
self.timeline = timeline
} }
} }
@ -77,6 +90,7 @@ extension Response: CustomDebugStringConvertible {
output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil")
output.append("[Data]: \(data?.length ?? 0) bytes") output.append("[Data]: \(data?.length ?? 0) bytes")
output.append("[Result]: \(result.debugDescription)") output.append("[Result]: \(result.debugDescription)")
output.append("[Timeline]: \(timeline.debugDescription)")
return output.joinWithSeparator("\n") return output.joinWithSeparator("\n")
} }

View File

@ -1,6 +1,7 @@
//
// ResponseSerialization.swift // ResponseSerialization.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -29,10 +31,10 @@ import Foundation
*/ */
public protocol ResponseSerializerType { public protocol ResponseSerializerType {
/// The type of serialized object to be created by this `ResponseSerializerType`. /// The type of serialized object to be created by this `ResponseSerializerType`.
typealias SerializedObject associatedtype SerializedObject
/// The type of error to be created by this `ResponseSerializer` if serialization fails. /// The type of error to be created by this `ResponseSerializer` if serialization fails.
typealias ErrorObject: ErrorType associatedtype ErrorObject: ErrorType
/** /**
A closure used by response handlers that takes a request, response, data and error and returns a result. A closure used by response handlers that takes a request, response, data and error and returns a result.
@ -119,16 +121,25 @@ extension Request {
self.delegate.error self.delegate.error
) )
dispatch_async(queue ?? dispatch_get_main_queue()) { let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent()
let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime
let timeline = Timeline(
requestStartTime: self.startTime ?? CFAbsoluteTimeGetCurrent(),
initialResponseTime: initialResponseTime,
requestCompletedTime: requestCompletedTime,
serializationCompletedTime: CFAbsoluteTimeGetCurrent()
)
let response = Response<T.SerializedObject, T.ErrorObject>( let response = Response<T.SerializedObject, T.ErrorObject>(
request: self.request, request: self.request,
response: self.response, response: self.response,
data: self.delegate.data, data: self.delegate.data,
result: result result: result,
timeline: timeline
) )
completionHandler(response) dispatch_async(queue ?? dispatch_get_main_queue()) { completionHandler(response) }
}
} }
return self return self
@ -152,7 +163,7 @@ extension Request {
guard let validData = data else { guard let validData = data else {
let failureReason = "Data could not be serialized. Input data was nil." let failureReason = "Data could not be serialized. Input data was nil."
let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason) let error = Error.error(code: .DataSerializationFailed, failureReason: failureReason)
return .Failure(error) return .Failure(error)
} }
@ -167,8 +178,12 @@ extension Request {
- returns: The request. - returns: The request.
*/ */
public func responseData(completionHandler: Response<NSData, NSError> -> Void) -> Self { public func responseData(
return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler) queue queue: dispatch_queue_t? = nil,
completionHandler: Response<NSData, NSError> -> Void)
-> Self
{
return response(queue: queue, responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
} }
} }
@ -186,7 +201,7 @@ extension Request {
- returns: A string response serializer. - returns: A string response serializer.
*/ */
public static func stringResponseSerializer( public static func stringResponseSerializer(
var encoding encoding: NSStringEncoding? = nil) encoding encoding: NSStringEncoding? = nil)
-> ResponseSerializer<String, NSError> -> ResponseSerializer<String, NSError>
{ {
return ResponseSerializer { _, response, data, error in return ResponseSerializer { _, response, data, error in
@ -196,23 +211,25 @@ extension Request {
guard let validData = data else { guard let validData = data else {
let failureReason = "String could not be serialized. Input data was nil." let failureReason = "String could not be serialized. Input data was nil."
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason) let error = Error.error(code: .StringSerializationFailed, failureReason: failureReason)
return .Failure(error) return .Failure(error)
} }
if let encodingName = response?.textEncodingName where encoding == nil { var convertedEncoding = encoding
encoding = CFStringConvertEncodingToNSStringEncoding(
if let encodingName = response?.textEncodingName where convertedEncoding == nil {
convertedEncoding = CFStringConvertEncodingToNSStringEncoding(
CFStringConvertIANACharSetNameToEncoding(encodingName) CFStringConvertIANACharSetNameToEncoding(encodingName)
) )
} }
let actualEncoding = encoding ?? NSISOLatin1StringEncoding let actualEncoding = convertedEncoding ?? NSISOLatin1StringEncoding
if let string = String(data: validData, encoding: actualEncoding) { if let string = String(data: validData, encoding: actualEncoding) {
return .Success(string) return .Success(string)
} else { } else {
let failureReason = "String could not be serialized with encoding: \(actualEncoding)" let failureReason = "String could not be serialized with encoding: \(actualEncoding)"
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason) let error = Error.error(code: .StringSerializationFailed, failureReason: failureReason)
return .Failure(error) return .Failure(error)
} }
} }
@ -229,11 +246,13 @@ extension Request {
- returns: The request. - returns: The request.
*/ */
public func responseString( public func responseString(
encoding encoding: NSStringEncoding? = nil, queue queue: dispatch_queue_t? = nil,
encoding: NSStringEncoding? = nil,
completionHandler: Response<String, NSError> -> Void) completionHandler: Response<String, NSError> -> Void)
-> Self -> Self
{ {
return response( return response(
queue: queue,
responseSerializer: Request.stringResponseSerializer(encoding: encoding), responseSerializer: Request.stringResponseSerializer(encoding: encoding),
completionHandler: completionHandler completionHandler: completionHandler
) )
@ -263,7 +282,7 @@ extension Request {
guard let validData = data where validData.length > 0 else { guard let validData = data where validData.length > 0 else {
let failureReason = "JSON could not be serialized. Input data was nil or zero length." let failureReason = "JSON could not be serialized. Input data was nil or zero length."
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason) let error = Error.error(code: .JSONSerializationFailed, failureReason: failureReason)
return .Failure(error) return .Failure(error)
} }
@ -285,11 +304,13 @@ extension Request {
- returns: The request. - returns: The request.
*/ */
public func responseJSON( public func responseJSON(
options options: NSJSONReadingOptions = .AllowFragments, queue queue: dispatch_queue_t? = nil,
options: NSJSONReadingOptions = .AllowFragments,
completionHandler: Response<AnyObject, NSError> -> Void) completionHandler: Response<AnyObject, NSError> -> Void)
-> Self -> Self
{ {
return response( return response(
queue: queue,
responseSerializer: Request.JSONResponseSerializer(options: options), responseSerializer: Request.JSONResponseSerializer(options: options),
completionHandler: completionHandler completionHandler: completionHandler
) )
@ -319,7 +340,7 @@ extension Request {
guard let validData = data where validData.length > 0 else { guard let validData = data where validData.length > 0 else {
let failureReason = "Property list could not be serialized. Input data was nil or zero length." let failureReason = "Property list could not be serialized. Input data was nil or zero length."
let error = Error.errorWithCode(.PropertyListSerializationFailed, failureReason: failureReason) let error = Error.error(code: .PropertyListSerializationFailed, failureReason: failureReason)
return .Failure(error) return .Failure(error)
} }
@ -343,11 +364,13 @@ extension Request {
- returns: The request. - returns: The request.
*/ */
public func responsePropertyList( public func responsePropertyList(
options options: NSPropertyListReadOptions = NSPropertyListReadOptions(), queue queue: dispatch_queue_t? = nil,
options: NSPropertyListReadOptions = NSPropertyListReadOptions(),
completionHandler: Response<AnyObject, NSError> -> Void) completionHandler: Response<AnyObject, NSError> -> Void)
-> Self -> Self
{ {
return response( return response(
queue: queue,
responseSerializer: Request.propertyListResponseSerializer(options: options), responseSerializer: Request.propertyListResponseSerializer(options: options),
completionHandler: completionHandler completionHandler: completionHandler
) )

View File

@ -1,6 +1,7 @@
//
// Result.swift // Result.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation

View File

@ -1,6 +1,7 @@
//
// ServerTrustPolicy.swift // ServerTrustPolicy.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation

View File

@ -1,6 +1,7 @@
//
// Stream.swift // Stream.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,12 +20,13 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
#if !os(watchOS) #if !os(watchOS)
@available(iOS 9.0, OSX 10.11, *) @available(iOS 9.0, OSX 10.11, tvOS 9.0, *)
extension Manager { extension Manager {
private enum Streamable { private enum Streamable {
case Stream(String, Int) case Stream(String, Int)
@ -82,7 +84,7 @@ extension Manager {
// MARK: - // MARK: -
@available(iOS 9.0, OSX 10.11, *) @available(iOS 9.0, OSX 10.11, tvOS 9.0, *)
extension Manager.SessionDelegate: NSURLSessionStreamDelegate { extension Manager.SessionDelegate: NSURLSessionStreamDelegate {
// MARK: Override Closures // MARK: Override Closures

View File

@ -0,0 +1,138 @@
//
// Timeline.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// Responsible for computing the timing metrics for the complete lifecycle of a `Request`.
public struct Timeline {
/// The time the request was initialized.
public let requestStartTime: CFAbsoluteTime
/// The time the first bytes were received from or sent to the server.
public let initialResponseTime: CFAbsoluteTime
/// The time when the request was completed.
public let requestCompletedTime: CFAbsoluteTime
/// The time when the response serialization was completed.
public let serializationCompletedTime: CFAbsoluteTime
/// The time interval in seconds from the time the request started to the initial response from the server.
public let latency: NSTimeInterval
/// The time interval in seconds from the time the request started to the time the request completed.
public let requestDuration: NSTimeInterval
/// The time interval in seconds from the time the request completed to the time response serialization completed.
public let serializationDuration: NSTimeInterval
/// The time interval in seconds from the time the request started to the time response serialization completed.
public let totalDuration: NSTimeInterval
/**
Creates a new `Timeline` instance with the specified request times.
- parameter requestStartTime: The time the request was initialized. Defaults to `0.0`.
- parameter initialResponseTime: The time the first bytes were received from or sent to the server.
Defaults to `0.0`.
- parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`.
- parameter serializationCompletedTime: The time when the response serialization was completed. Defaults
to `0.0`.
- returns: The new `Timeline` instance.
*/
public init(
requestStartTime: CFAbsoluteTime = 0.0,
initialResponseTime: CFAbsoluteTime = 0.0,
requestCompletedTime: CFAbsoluteTime = 0.0,
serializationCompletedTime: CFAbsoluteTime = 0.0)
{
self.requestStartTime = requestStartTime
self.initialResponseTime = initialResponseTime
self.requestCompletedTime = requestCompletedTime
self.serializationCompletedTime = serializationCompletedTime
self.latency = initialResponseTime - requestStartTime
self.requestDuration = requestCompletedTime - requestStartTime
self.serializationDuration = serializationCompletedTime - requestCompletedTime
self.totalDuration = serializationCompletedTime - requestStartTime
}
}
// MARK: - CustomStringConvertible
extension Timeline: CustomStringConvertible {
/// The textual representation used when written to an output stream, which includes the latency, the request
/// duration and the total duration.
public var description: String {
let latency = String(format: "%.3f", self.latency)
let requestDuration = String(format: "%.3f", self.requestDuration)
let serializationDuration = String(format: "%.3f", self.serializationDuration)
let totalDuration = String(format: "%.3f", self.totalDuration)
// NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is
// fixed, we should move back to string interpolation by reverting commit 7d4a43b1.
let timings = [
"\"Latency\": " + latency + " secs",
"\"Request Duration\": " + requestDuration + " secs",
"\"Serialization Duration\": " + serializationDuration + " secs",
"\"Total Duration\": " + totalDuration + " secs"
]
return "Timeline: { " + timings.joinWithSeparator(", ") + " }"
}
}
// MARK: - CustomDebugStringConvertible
extension Timeline: CustomDebugStringConvertible {
/// The textual representation used when written to an output stream, which includes the request start time, the
/// initial response time, the request completed time, the serialization completed time, the latency, the request
/// duration and the total duration.
public var debugDescription: String {
let requestStartTime = String(format: "%.3f", self.requestStartTime)
let initialResponseTime = String(format: "%.3f", self.initialResponseTime)
let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime)
let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime)
let latency = String(format: "%.3f", self.latency)
let requestDuration = String(format: "%.3f", self.requestDuration)
let serializationDuration = String(format: "%.3f", self.serializationDuration)
let totalDuration = String(format: "%.3f", self.totalDuration)
// NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is
// fixed, we should move back to string interpolation by reverting commit 7d4a43b1.
let timings = [
"\"Request Start Time\": " + requestStartTime,
"\"Initial Response Time\": " + initialResponseTime,
"\"Request Completed Time\": " + requestCompletedTime,
"\"Serialization Completed Time\": " + serializationCompletedTime,
"\"Latency\": " + latency + " secs",
"\"Request Duration\": " + requestDuration + " secs",
"\"Serialization Duration\": " + serializationDuration + " secs",
"\"Total Duration\": " + totalDuration + " secs"
]
return "Timeline: { " + timings.joinWithSeparator(", ") + " }"
}
}

View File

@ -1,6 +1,7 @@
//
// Upload.swift // Upload.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -359,6 +361,8 @@ extension Request {
totalBytesSent: Int64, totalBytesSent: Int64,
totalBytesExpectedToSend: Int64) totalBytesExpectedToSend: Int64)
{ {
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let taskDidSendBodyData = taskDidSendBodyData { if let taskDidSendBodyData = taskDidSendBodyData {
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
} else { } else {

View File

@ -1,6 +1,7 @@
//
// Validation.swift // Validation.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -80,7 +82,17 @@ extension Request {
return .Success return .Success
} else { } else {
let failureReason = "Response status code was unacceptable: \(response.statusCode)" let failureReason = "Response status code was unacceptable: \(response.statusCode)"
return .Failure(Error.errorWithCode(.StatusCodeValidationFailed, failureReason: failureReason))
let error = NSError(
domain: Error.Domain,
code: Error.Code.StatusCodeValidationFailed.rawValue,
userInfo: [
NSLocalizedFailureReasonErrorKey: failureReason,
Error.UserInfoKeys.StatusCode: response.statusCode
]
)
return .Failure(error)
} }
} }
} }
@ -149,18 +161,31 @@ extension Request {
} }
} }
let contentType: String
let failureReason: String let failureReason: String
if let responseContentType = response.MIMEType { if let responseContentType = response.MIMEType {
contentType = responseContentType
failureReason = ( failureReason = (
"Response content type \"\(responseContentType)\" does not match any acceptable " + "Response content type \"\(responseContentType)\" does not match any acceptable " +
"content types: \(acceptableContentTypes)" "content types: \(acceptableContentTypes)"
) )
} else { } else {
contentType = ""
failureReason = "Response content type was missing and acceptable content type does not match \"*/*\"" failureReason = "Response content type was missing and acceptable content type does not match \"*/*\""
} }
return .Failure(Error.errorWithCode(.ContentTypeValidationFailed, failureReason: failureReason)) let error = NSError(
domain: Error.Domain,
code: Error.Code.ContentTypeValidationFailed.rawValue,
userInfo: [
NSLocalizedFailureReasonErrorKey: failureReason,
Error.UserInfoKeys.ContentType: contentType
]
)
return .Failure(error)
} }
} }

View File

@ -9,8 +9,8 @@
"git": "git@github.com:swagger-api/swagger-mustache.git", "git": "git@github.com:swagger-api/swagger-mustache.git",
"tag": "v1.0.0" "tag": "v1.0.0"
}, },
"authors": "",
"license": "Apache License, Version 2.0", "license": "Apache License, Version 2.0",
"authors": "Apache License, Version 2.0",
"homepage": "https://github.com/swagger-api/swagger-codegen", "homepage": "https://github.com/swagger-api/swagger-codegen",
"summary": "PetstoreClient", "summary": "PetstoreClient",
"source_files": "PetstoreClient/Classes/Swaggers/**/*.swift", "source_files": "PetstoreClient/Classes/Swaggers/**/*.swift",
@ -19,7 +19,7 @@
"~> 3.1.1" "~> 3.1.1"
], ],
"Alamofire": [ "Alamofire": [
"~> 3.1.5" "~> 3.4.1"
] ]
} }
} }

View File

@ -1,14 +1,14 @@
PODS: PODS:
- Alamofire (3.1.5) - Alamofire (3.4.1)
- OMGHTTPURLRQ (3.1.1): - OMGHTTPURLRQ (3.1.3):
- OMGHTTPURLRQ/RQ (= 3.1.1) - OMGHTTPURLRQ/RQ (= 3.1.3)
- OMGHTTPURLRQ/FormURLEncode (3.1.1) - OMGHTTPURLRQ/FormURLEncode (3.1.3)
- OMGHTTPURLRQ/RQ (3.1.1): - OMGHTTPURLRQ/RQ (3.1.3):
- OMGHTTPURLRQ/FormURLEncode - OMGHTTPURLRQ/FormURLEncode
- OMGHTTPURLRQ/UserAgent - OMGHTTPURLRQ/UserAgent
- OMGHTTPURLRQ/UserAgent (3.1.1) - OMGHTTPURLRQ/UserAgent (3.1.3)
- PetstoreClient (0.0.1): - PetstoreClient (0.0.1):
- Alamofire (~> 3.1.5) - Alamofire (~> 3.4.1)
- PromiseKit (~> 3.1.1) - PromiseKit (~> 3.1.1)
- PromiseKit (3.1.1): - PromiseKit (3.1.1):
- PromiseKit/Foundation (= 3.1.1) - PromiseKit/Foundation (= 3.1.1)
@ -31,11 +31,11 @@ EXTERNAL SOURCES:
:path: "../" :path: "../"
SPEC CHECKSUMS: SPEC CHECKSUMS:
Alamofire: 5f730ba29fd113b7ddd71c1e65d0c630acf5d7b0 Alamofire: 01a82e2f6c0f860ade35534c8dd88be61bdef40c
OMGHTTPURLRQ: 633f98ee745aeda02345935a52eec1784cddb589 OMGHTTPURLRQ: a547be1b9721ddfbf9d08aab56ab72dc4c1cc417
PetstoreClient: efd495da2b7a6f3e798752702d59f96e306dbace PetstoreClient: 24135348a992f2cbd76bc324719173b52e864cdc
PromiseKit: 4e8127c22a9b29d1b44958ab2ec762ea6115cbfb PromiseKit: 4e8127c22a9b29d1b44958ab2ec762ea6115cbfb
PODFILE CHECKSUM: 84472aca2a88b7f7ed9fcd63e9f5fdb5ad4aab94 PODFILE CHECKSUM: 84472aca2a88b7f7ed9fcd63e9f5fdb5ad4aab94
COCOAPODS: 1.0.0 COCOAPODS: 1.0.1

View File

@ -39,7 +39,7 @@ NSData *data2 = UIImagePNGRepresentation(image2);
[multipartFormData addFile:data2 parameterName:@"file2" filename:@"myimage2.png" contentType:@"image/png"]; [multipartFormData addFile:data2 parameterName:@"file2" filename:@"myimage2.png" contentType:@"image/png"];
// SUPER Ideally you would not want to re-encode the JPEG as the process // SUPER Ideally you would not want to re-encode the JPEG as the process
// is lossy. If you image comes from the AssetLibrary you *CAN* get the // is lossy. If your image comes from the AssetLibrary you *CAN* get the
// original `NSData`. See stackoverflow.com. // original `NSData`. See stackoverflow.com.
UIImage *image3 = [UIImage imageNamed:@"image3"]; UIImage *image3 = [UIImage imageNamed:@"image3"];
NSData *data3 = UIImageJPEGRepresentation(image3); NSData *data3 = UIImageJPEGRepresentation(image3);

View File

@ -47,7 +47,6 @@ static inline NSMutableURLRequest *OMGMutableURLRequest() {
[body appendData:[ln1 dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[ln1 dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[ln2 dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[ln2 dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:payload]; [body appendData:payload];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
} }
- (void)addFile:(NSData *)payload parameterName:(NSString *)name filename:(NSString *)filename contentType:(NSString *)contentType - (void)addFile:(NSData *)payload parameterName:(NSString *)name filename:(NSString *)filename contentType:(NSString *)contentType
@ -71,8 +70,8 @@ static inline NSMutableURLRequest *OMGMutableURLRequest() {
@implementation OMGHTTPURLRQ @implementation OMGHTTPURLRQ
+ (NSMutableURLRequest *)GET:(NSString *)urlString :(NSDictionary *)params error:(NSError **)error { + (NSMutableURLRequest *)GET:(NSString *)urlString :(NSDictionary *)params error:(NSError **)error {
id queryString = OMGFormURLEncode(params); NSString *queryString = OMGFormURLEncode(params);
if (queryString) urlString = [urlString stringByAppendingFormat:@"?%@", queryString]; if (queryString.length) urlString = [urlString stringByAppendingFormat:@"?%@", queryString];
id url = [NSURL URLWithString:urlString]; id url = [NSURL URLWithString:urlString];
if (!url) { if (!url) {

View File

@ -15,7 +15,7 @@
<key>CFBundlePackageType</key> <key>CFBundlePackageType</key>
<string>FMWK</string> <string>FMWK</string>
<key>CFBundleShortVersionString</key> <key>CFBundleShortVersionString</key>
<string>3.1.5</string> <string>3.4.1</string>
<key>CFBundleSignature</key> <key>CFBundleSignature</key>
<string>????</string> <string>????</string>
<key>CFBundleVersion</key> <key>CFBundleVersion</key>

View File

@ -15,7 +15,7 @@
<key>CFBundlePackageType</key> <key>CFBundlePackageType</key>
<string>FMWK</string> <string>FMWK</string>
<key>CFBundleShortVersionString</key> <key>CFBundleShortVersionString</key>
<string>3.1.1</string> <string>3.1.3</string>
<key>CFBundleSignature</key> <key>CFBundleSignature</key>
<string>????</string> <string>????</string>
<key>CFBundleVersion</key> <key>CFBundleVersion</key>

View File

@ -3,7 +3,7 @@ This application makes use of the following third party libraries:
## Alamofire ## Alamofire
Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
@ -26,7 +26,7 @@ THE SOFTWARE.
## OMGHTTPURLRQ ## OMGHTTPURLRQ
See README.markdown for full license text. https://github.com/mxcl/OMGHTTPURLRQ/blob/master/README.markdown
## PetstoreClient ## PetstoreClient

View File

@ -14,7 +14,7 @@
</dict> </dict>
<dict> <dict>
<key>FooterText</key> <key>FooterText</key>
<string>Copyright (c) 2014&#8211;2016 Alamofire Software Foundation (http://alamofire.org/) <string>Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
@ -41,7 +41,7 @@ THE SOFTWARE.
</dict> </dict>
<dict> <dict>
<key>FooterText</key> <key>FooterText</key>
<string>See README.markdown for full license text.</string> <string>https://github.com/mxcl/OMGHTTPURLRQ/blob/master/README.markdown</string>
<key>Title</key> <key>Title</key>
<string>OMGHTTPURLRQ</string> <string>OMGHTTPURLRQ</string>
<key>Type</key> <key>Type</key>

View File

@ -48,8 +48,8 @@ EOM
ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS}
;; ;;
*.xib) *.xib)
echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT}" echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}"
ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS}
;; ;;
*.framework) *.framework)
echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"

View File

@ -48,8 +48,8 @@ EOM
ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS}
;; ;;
*.xib) *.xib)
echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT}" echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}"
ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS}
;; ;;
*.framework) *.framework)
echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"

View File

@ -143,12 +143,12 @@
isa = PBXNativeTarget; isa = PBXNativeTarget;
buildConfigurationList = 6D4EFBAE1C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClient" */; buildConfigurationList = 6D4EFBAE1C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClient" */;
buildPhases = ( buildPhases = (
1F03F780DC2D9727E5E64BA9 /* 📦 Check Pods Manifest.lock */, 1F03F780DC2D9727E5E64BA9 /* [CP] Check Pods Manifest.lock */,
6D4EFB8D1C692C6300B96B06 /* Sources */, 6D4EFB8D1C692C6300B96B06 /* Sources */,
6D4EFB8E1C692C6300B96B06 /* Frameworks */, 6D4EFB8E1C692C6300B96B06 /* Frameworks */,
6D4EFB8F1C692C6300B96B06 /* Resources */, 6D4EFB8F1C692C6300B96B06 /* Resources */,
4485A75250058E2D5BBDF63F /* 📦 Embed Pods Frameworks */, 4485A75250058E2D5BBDF63F /* [CP] Embed Pods Frameworks */,
808CE4A0CE801CAC5ABF5B08 /* 📦 Copy Pods Resources */, 808CE4A0CE801CAC5ABF5B08 /* [CP] Copy Pods Resources */,
); );
buildRules = ( buildRules = (
); );
@ -163,12 +163,12 @@
isa = PBXNativeTarget; isa = PBXNativeTarget;
buildConfigurationList = 6D4EFBB11C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */; buildConfigurationList = 6D4EFBB11C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */;
buildPhases = ( buildPhases = (
79FE27B09B2DD354C831BD49 /* 📦 Check Pods Manifest.lock */, 79FE27B09B2DD354C831BD49 /* [CP] Check Pods Manifest.lock */,
6D4EFBA11C692C6300B96B06 /* Sources */, 6D4EFBA11C692C6300B96B06 /* Sources */,
6D4EFBA21C692C6300B96B06 /* Frameworks */, 6D4EFBA21C692C6300B96B06 /* Frameworks */,
6D4EFBA31C692C6300B96B06 /* Resources */, 6D4EFBA31C692C6300B96B06 /* Resources */,
796EAD48F1BCCDAA291CD963 /* 📦 Embed Pods Frameworks */, 796EAD48F1BCCDAA291CD963 /* [CP] Embed Pods Frameworks */,
1652CB1A246A4689869E442D /* 📦 Copy Pods Resources */, 1652CB1A246A4689869E442D /* [CP] Copy Pods Resources */,
); );
buildRules = ( buildRules = (
); );
@ -239,14 +239,14 @@
/* End PBXResourcesBuildPhase section */ /* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */
1652CB1A246A4689869E442D /* 📦 Copy Pods Resources */ = { 1652CB1A246A4689869E442D /* [CP] Copy Pods Resources */ = {
isa = PBXShellScriptBuildPhase; isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
); );
inputPaths = ( inputPaths = (
); );
name = "📦 Copy Pods Resources"; name = "[CP] Copy Pods Resources";
outputPaths = ( outputPaths = (
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
@ -254,14 +254,14 @@
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh\"\n"; shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh\"\n";
showEnvVarsInLog = 0; showEnvVarsInLog = 0;
}; };
1F03F780DC2D9727E5E64BA9 /* 📦 Check Pods Manifest.lock */ = { 1F03F780DC2D9727E5E64BA9 /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase; isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
); );
inputPaths = ( inputPaths = (
); );
name = "📦 Check Pods Manifest.lock"; name = "[CP] Check Pods Manifest.lock";
outputPaths = ( outputPaths = (
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
@ -269,14 +269,14 @@
shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n";
showEnvVarsInLog = 0; showEnvVarsInLog = 0;
}; };
4485A75250058E2D5BBDF63F /* 📦 Embed Pods Frameworks */ = { 4485A75250058E2D5BBDF63F /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase; isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
); );
inputPaths = ( inputPaths = (
); );
name = "📦 Embed Pods Frameworks"; name = "[CP] Embed Pods Frameworks";
outputPaths = ( outputPaths = (
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
@ -284,14 +284,14 @@
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n"; shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n";
showEnvVarsInLog = 0; showEnvVarsInLog = 0;
}; };
796EAD48F1BCCDAA291CD963 /* 📦 Embed Pods Frameworks */ = { 796EAD48F1BCCDAA291CD963 /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase; isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
); );
inputPaths = ( inputPaths = (
); );
name = "📦 Embed Pods Frameworks"; name = "[CP] Embed Pods Frameworks";
outputPaths = ( outputPaths = (
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
@ -299,14 +299,14 @@
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh\"\n"; shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh\"\n";
showEnvVarsInLog = 0; showEnvVarsInLog = 0;
}; };
79FE27B09B2DD354C831BD49 /* 📦 Check Pods Manifest.lock */ = { 79FE27B09B2DD354C831BD49 /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase; isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
); );
inputPaths = ( inputPaths = (
); );
name = "📦 Check Pods Manifest.lock"; name = "[CP] Check Pods Manifest.lock";
outputPaths = ( outputPaths = (
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
@ -314,14 +314,14 @@
shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n";
showEnvVarsInLog = 0; showEnvVarsInLog = 0;
}; };
808CE4A0CE801CAC5ABF5B08 /* 📦 Copy Pods Resources */ = { 808CE4A0CE801CAC5ABF5B08 /* [CP] Copy Pods Resources */ = {
isa = PBXShellScriptBuildPhase; isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
); );
inputPaths = ( inputPaths = (
); );
name = "📦 Copy Pods Resources"; name = "[CP] Copy Pods Resources";
outputPaths = ( outputPaths = (
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;