mirror of
https://github.com/valitydev/openapi-generator.git
synced 2024-11-08 03:18:53 +00:00
Merge pull request #2931 from Edubits/swift-sample-without-promisekit
[Swift] Add sample/tests for Swift client without PromiseKit
This commit is contained in:
commit
52a928bb2e
7
bin/swift-petstore-promisekit.json
Normal file
7
bin/swift-petstore-promisekit.json
Normal file
@ -0,0 +1,7 @@
|
||||
{
|
||||
"podSummary": "PetstoreClient",
|
||||
"podHomepage": "https://github.com/swagger-api/swagger-codegen",
|
||||
"podAuthors": "",
|
||||
"projectName": "PetstoreClient",
|
||||
"responseAs": "PromiseKit"
|
||||
}
|
31
bin/swift-petstore-promisekit.sh
Executable file
31
bin/swift-petstore-promisekit.sh
Executable file
@ -0,0 +1,31 @@
|
||||
#!/bin/sh
|
||||
|
||||
SCRIPT="$0"
|
||||
|
||||
while [ -h "$SCRIPT" ] ; do
|
||||
ls=`ls -ld "$SCRIPT"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
SCRIPT="$link"
|
||||
else
|
||||
SCRIPT=`dirname "$SCRIPT"`/"$link"
|
||||
fi
|
||||
done
|
||||
|
||||
if [ ! -d "${APP_DIR}" ]; then
|
||||
APP_DIR=`dirname "$SCRIPT"`/..
|
||||
APP_DIR=`cd "${APP_DIR}"; pwd`
|
||||
fi
|
||||
|
||||
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
|
||||
|
||||
if [ ! -f "$executable" ]
|
||||
then
|
||||
mvn clean package
|
||||
fi
|
||||
|
||||
# if you've executed sbt assembly previously it will use that instead.
|
||||
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
|
||||
ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l swift -c ./bin/swift-petstore-promisekit.json -o samples/client/petstore/swift-promisekit"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
@ -2,6 +2,5 @@
|
||||
"podSummary": "PetstoreClient",
|
||||
"podHomepage": "https://github.com/swagger-api/swagger-codegen",
|
||||
"podAuthors": "",
|
||||
"projectName": "PetstoreClient",
|
||||
"responseAs": "PromiseKit"
|
||||
"projectName": "PetstoreClient"
|
||||
}
|
0
bin/swift-petstore.sh
Executable file → Normal file
0
bin/swift-petstore.sh
Executable file → Normal file
63
samples/client/petstore/swift-promisekit/.gitignore
vendored
Normal file
63
samples/client/petstore/swift-promisekit/.gitignore
vendored
Normal file
@ -0,0 +1,63 @@
|
||||
# Xcode
|
||||
#
|
||||
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
|
||||
|
||||
## Build generated
|
||||
build/
|
||||
DerivedData
|
||||
|
||||
## Various settings
|
||||
*.pbxuser
|
||||
!default.pbxuser
|
||||
*.mode1v3
|
||||
!default.mode1v3
|
||||
*.mode2v3
|
||||
!default.mode2v3
|
||||
*.perspectivev3
|
||||
!default.perspectivev3
|
||||
xcuserdata
|
||||
|
||||
## Other
|
||||
*.xccheckout
|
||||
*.moved-aside
|
||||
*.xcuserstate
|
||||
*.xcscmblueprint
|
||||
|
||||
## Obj-C/Swift specific
|
||||
*.hmap
|
||||
*.ipa
|
||||
|
||||
## Playgrounds
|
||||
timeline.xctimeline
|
||||
playground.xcworkspace
|
||||
|
||||
# Swift Package Manager
|
||||
#
|
||||
# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.
|
||||
# Packages/
|
||||
.build/
|
||||
|
||||
# CocoaPods
|
||||
#
|
||||
# We recommend against adding the Pods directory to your .gitignore. However
|
||||
# you should judge for yourself, the pros and cons are mentioned at:
|
||||
# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
|
||||
#
|
||||
# Pods/
|
||||
|
||||
# Carthage
|
||||
#
|
||||
# Add this line if you want to avoid checking in source code from Carthage dependencies.
|
||||
# Carthage/Checkouts
|
||||
|
||||
Carthage/Build
|
||||
|
||||
# fastlane
|
||||
#
|
||||
# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the
|
||||
# screenshots whenever they are needed.
|
||||
# For more information about the recommended setup visit:
|
||||
# https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md
|
||||
|
||||
fastlane/report.xml
|
||||
fastlane/screenshots
|
2
samples/client/petstore/swift-promisekit/Cartfile
Normal file
2
samples/client/petstore/swift-promisekit/Cartfile
Normal file
@ -0,0 +1,2 @@
|
||||
github "Alamofire/Alamofire" >= 3.1.0
|
||||
github "mxcl/PromiseKit" >=1.5.3
|
@ -0,0 +1,14 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'PetstoreClient'
|
||||
s.ios.deployment_target = '8.0'
|
||||
s.osx.deployment_target = '10.9'
|
||||
s.version = '0.0.1'
|
||||
s.source = { :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' }
|
||||
s.authors =
|
||||
s.license = 'Apache License, Version 2.0'
|
||||
s.homepage = 'https://github.com/swagger-api/swagger-codegen'
|
||||
s.summary = 'PetstoreClient'
|
||||
s.source_files = 'PetstoreClient/Classes/Swaggers/**/*.swift'
|
||||
s.dependency 'PromiseKit', '~> 3.1.1'
|
||||
s.dependency 'Alamofire', '~> 3.1.5'
|
||||
end
|
@ -0,0 +1,39 @@
|
||||
// APIHelper.swift
|
||||
//
|
||||
// Generated by swagger-codegen
|
||||
// https://github.com/swagger-api/swagger-codegen
|
||||
//
|
||||
|
||||
class APIHelper {
|
||||
static func rejectNil(source: [String:AnyObject?]) -> [String:AnyObject]? {
|
||||
var destination = [String:AnyObject]()
|
||||
for (key, nillableValue) in source {
|
||||
if let value: AnyObject = nillableValue {
|
||||
destination[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
if destination.isEmpty {
|
||||
return nil
|
||||
}
|
||||
return destination
|
||||
}
|
||||
|
||||
static func convertBoolToString(source: [String: AnyObject]?) -> [String:AnyObject] {
|
||||
var destination = [String:AnyObject]()
|
||||
let theTrue = NSNumber(bool: true)
|
||||
let theFalse = NSNumber(bool: false)
|
||||
if (source != nil) {
|
||||
for (key, value) in source! {
|
||||
switch value {
|
||||
case let x where x === theTrue || x === theFalse:
|
||||
destination[key] = "\(value as! Bool)"
|
||||
default:
|
||||
destination[key] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
return destination
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,73 @@
|
||||
// APIs.swift
|
||||
//
|
||||
// Generated by swagger-codegen
|
||||
// https://github.com/swagger-api/swagger-codegen
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
public class PetstoreClientAPI {
|
||||
public static var basePath = "http://petstore.swagger.io/v2"
|
||||
public static var credential: NSURLCredential?
|
||||
public static var customHeaders: [String:String] = [:]
|
||||
static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory()
|
||||
}
|
||||
|
||||
public class APIBase {
|
||||
func toParameters(encodable: JSONEncodable?) -> [String: AnyObject]? {
|
||||
let encoded: AnyObject? = encodable?.encodeToJSON()
|
||||
|
||||
if encoded! is [AnyObject] {
|
||||
var dictionary = [String:AnyObject]()
|
||||
for (index, item) in (encoded as! [AnyObject]).enumerate() {
|
||||
dictionary["\(index)"] = item
|
||||
}
|
||||
return dictionary
|
||||
} else {
|
||||
return encoded as? [String:AnyObject]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class RequestBuilder<T> {
|
||||
var credential: NSURLCredential?
|
||||
var headers: [String:String] = [:]
|
||||
let parameters: [String:AnyObject]?
|
||||
let isBody: Bool
|
||||
let method: String
|
||||
let URLString: String
|
||||
|
||||
required public init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool) {
|
||||
self.method = method
|
||||
self.URLString = URLString
|
||||
self.parameters = parameters
|
||||
self.isBody = isBody
|
||||
|
||||
addHeaders(PetstoreClientAPI.customHeaders)
|
||||
}
|
||||
|
||||
public func addHeaders(aHeaders:[String:String]) {
|
||||
for (header, value) in aHeaders {
|
||||
headers[header] = value
|
||||
}
|
||||
}
|
||||
|
||||
public func execute(completion: (response: Response<T>?, error: ErrorType?) -> Void) { }
|
||||
|
||||
public func addHeader(name name: String, value: String) -> Self {
|
||||
if !value.isEmpty {
|
||||
headers[name] = value
|
||||
}
|
||||
return self
|
||||
}
|
||||
|
||||
public func addCredential() -> Self {
|
||||
self.credential = PetstoreClientAPI.credential
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
protocol RequestBuilderFactory {
|
||||
func getBuilder<T>() -> RequestBuilder<T>.Type
|
||||
}
|
||||
|
@ -0,0 +1,592 @@
|
||||
//
|
||||
// PetAPI.swift
|
||||
//
|
||||
// Generated by swagger-codegen
|
||||
// https://github.com/swagger-api/swagger-codegen
|
||||
//
|
||||
|
||||
import Alamofire
|
||||
import PromiseKit
|
||||
|
||||
|
||||
|
||||
public class PetAPI: APIBase {
|
||||
/**
|
||||
Add a new pet to the store
|
||||
|
||||
- parameter body: (body) Pet object that needs to be added to the store (optional)
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func addPet(body body: Pet? = nil, completion: ((error: ErrorType?) -> Void)) {
|
||||
addPetWithRequestBuilder(body: body).execute { (response, error) -> Void in
|
||||
completion(error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Add a new pet to the store
|
||||
|
||||
- parameter body: (body) Pet object that needs to be added to the store (optional)
|
||||
- returns: Promise<Void>
|
||||
*/
|
||||
public class func addPet(body body: Pet? = nil) -> Promise<Void> {
|
||||
let deferred = Promise<Void>.pendingPromise()
|
||||
addPet(body: body) { error in
|
||||
if let error = error {
|
||||
deferred.reject(error)
|
||||
} else {
|
||||
deferred.fulfill()
|
||||
}
|
||||
}
|
||||
return deferred.promise
|
||||
}
|
||||
|
||||
/**
|
||||
Add a new pet to the store
|
||||
- POST /pet
|
||||
-
|
||||
- OAuth:
|
||||
- type: oauth2
|
||||
- name: petstore_auth
|
||||
|
||||
- parameter body: (body) Pet object that needs to be added to the store (optional)
|
||||
|
||||
- returns: RequestBuilder<Void>
|
||||
*/
|
||||
public class func addPetWithRequestBuilder(body body: Pet? = nil) -> RequestBuilder<Void> {
|
||||
let path = "/pet"
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
let parameters = body?.encodeToJSON() as? [String:AnyObject]
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Deletes a pet
|
||||
|
||||
- parameter petId: (path) Pet id to delete
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func deletePet(petId petId: Int64, completion: ((error: ErrorType?) -> Void)) {
|
||||
deletePetWithRequestBuilder(petId: petId).execute { (response, error) -> Void in
|
||||
completion(error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Deletes a pet
|
||||
|
||||
- parameter petId: (path) Pet id to delete
|
||||
- returns: Promise<Void>
|
||||
*/
|
||||
public class func deletePet(petId petId: Int64) -> Promise<Void> {
|
||||
let deferred = Promise<Void>.pendingPromise()
|
||||
deletePet(petId: petId) { error in
|
||||
if let error = error {
|
||||
deferred.reject(error)
|
||||
} else {
|
||||
deferred.fulfill()
|
||||
}
|
||||
}
|
||||
return deferred.promise
|
||||
}
|
||||
|
||||
/**
|
||||
Deletes a pet
|
||||
- DELETE /pet/{petId}
|
||||
-
|
||||
- OAuth:
|
||||
- type: oauth2
|
||||
- name: petstore_auth
|
||||
|
||||
- parameter petId: (path) Pet id to delete
|
||||
|
||||
- returns: RequestBuilder<Void>
|
||||
*/
|
||||
public class func deletePetWithRequestBuilder(petId petId: Int64) -> RequestBuilder<Void> {
|
||||
var path = "/pet/{petId}"
|
||||
path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil)
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
|
||||
let nillableParameters: [String:AnyObject?] = [:]
|
||||
|
||||
let parameters = APIHelper.rejectNil(nillableParameters)
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Finds Pets by status
|
||||
|
||||
- parameter status: (query) Status values that need to be considered for filter (optional, default to available)
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func findPetsByStatus(status status: [String]? = nil, completion: ((data: [Pet]?, error: ErrorType?) -> Void)) {
|
||||
findPetsByStatusWithRequestBuilder(status: status).execute { (response, error) -> Void in
|
||||
completion(data: response?.body, error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Finds Pets by status
|
||||
|
||||
- parameter status: (query) Status values that need to be considered for filter (optional, default to available)
|
||||
- returns: Promise<[Pet]>
|
||||
*/
|
||||
public class func findPetsByStatus(status status: [String]? = nil) -> Promise<[Pet]> {
|
||||
let deferred = Promise<[Pet]>.pendingPromise()
|
||||
findPetsByStatus(status: status) { data, error in
|
||||
if let error = error {
|
||||
deferred.reject(error)
|
||||
} else {
|
||||
deferred.fulfill(data!)
|
||||
}
|
||||
}
|
||||
return deferred.promise
|
||||
}
|
||||
|
||||
/**
|
||||
Finds Pets by status
|
||||
- GET /pet/findByStatus
|
||||
- Multiple status values can be provided with comma seperated strings
|
||||
- OAuth:
|
||||
- type: oauth2
|
||||
- name: petstore_auth
|
||||
- examples: [{contentType=application/json, example={
|
||||
"name" : "Puma",
|
||||
"type" : "Dog",
|
||||
"color" : "Black",
|
||||
"gender" : "Female",
|
||||
"breed" : "Mixed"
|
||||
}}]
|
||||
|
||||
- parameter status: (query) Status values that need to be considered for filter (optional, default to available)
|
||||
|
||||
- returns: RequestBuilder<[Pet]>
|
||||
*/
|
||||
public class func findPetsByStatusWithRequestBuilder(status status: [String]? = nil) -> RequestBuilder<[Pet]> {
|
||||
let path = "/pet/findByStatus"
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
|
||||
let nillableParameters: [String:AnyObject?] = [
|
||||
"status": status
|
||||
]
|
||||
|
||||
let parameters = APIHelper.rejectNil(nillableParameters)
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
|
||||
}
|
||||
|
||||
/**
|
||||
Finds Pets by tags
|
||||
|
||||
- parameter tags: (query) Tags to filter by (optional)
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func findPetsByTags(tags tags: [String]? = nil, completion: ((data: [Pet]?, error: ErrorType?) -> Void)) {
|
||||
findPetsByTagsWithRequestBuilder(tags: tags).execute { (response, error) -> Void in
|
||||
completion(data: response?.body, error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Finds Pets by tags
|
||||
|
||||
- parameter tags: (query) Tags to filter by (optional)
|
||||
- returns: Promise<[Pet]>
|
||||
*/
|
||||
public class func findPetsByTags(tags tags: [String]? = nil) -> Promise<[Pet]> {
|
||||
let deferred = Promise<[Pet]>.pendingPromise()
|
||||
findPetsByTags(tags: tags) { data, error in
|
||||
if let error = error {
|
||||
deferred.reject(error)
|
||||
} else {
|
||||
deferred.fulfill(data!)
|
||||
}
|
||||
}
|
||||
return deferred.promise
|
||||
}
|
||||
|
||||
/**
|
||||
Finds Pets by tags
|
||||
- GET /pet/findByTags
|
||||
- Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
|
||||
- OAuth:
|
||||
- type: oauth2
|
||||
- name: petstore_auth
|
||||
- examples: [{contentType=application/json, example=[ {
|
||||
"photoUrls" : [ "aeiou" ],
|
||||
"name" : "doggie",
|
||||
"id" : 123456789,
|
||||
"category" : {
|
||||
"name" : "aeiou",
|
||||
"id" : 123456789
|
||||
},
|
||||
"tags" : [ {
|
||||
"name" : "aeiou",
|
||||
"id" : 123456789
|
||||
} ],
|
||||
"status" : "aeiou"
|
||||
} ]}, {contentType=application/xml, example=<Pet>
|
||||
<id>123456</id>
|
||||
<name>doggie</name>
|
||||
<photoUrls>
|
||||
<photoUrls>string</photoUrls>
|
||||
</photoUrls>
|
||||
<tags>
|
||||
</tags>
|
||||
<status>string</status>
|
||||
</Pet>}]
|
||||
- examples: [{contentType=application/json, example=[ {
|
||||
"photoUrls" : [ "aeiou" ],
|
||||
"name" : "doggie",
|
||||
"id" : 123456789,
|
||||
"category" : {
|
||||
"name" : "aeiou",
|
||||
"id" : 123456789
|
||||
},
|
||||
"tags" : [ {
|
||||
"name" : "aeiou",
|
||||
"id" : 123456789
|
||||
} ],
|
||||
"status" : "aeiou"
|
||||
} ]}, {contentType=application/xml, example=<Pet>
|
||||
<id>123456</id>
|
||||
<name>doggie</name>
|
||||
<photoUrls>
|
||||
<photoUrls>string</photoUrls>
|
||||
</photoUrls>
|
||||
<tags>
|
||||
</tags>
|
||||
<status>string</status>
|
||||
</Pet>}]
|
||||
|
||||
- parameter tags: (query) Tags to filter by (optional)
|
||||
|
||||
- returns: RequestBuilder<[Pet]>
|
||||
*/
|
||||
public class func findPetsByTagsWithRequestBuilder(tags tags: [String]? = nil) -> RequestBuilder<[Pet]> {
|
||||
let path = "/pet/findByTags"
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
|
||||
let nillableParameters: [String:AnyObject?] = [
|
||||
"tags": tags
|
||||
]
|
||||
|
||||
let parameters = APIHelper.rejectNil(nillableParameters)
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
|
||||
}
|
||||
|
||||
/**
|
||||
Find pet by ID
|
||||
|
||||
- parameter petId: (path) ID of pet that needs to be fetched
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func getPetById(petId petId: Int64, completion: ((data: Pet?, error: ErrorType?) -> Void)) {
|
||||
getPetByIdWithRequestBuilder(petId: petId).execute { (response, error) -> Void in
|
||||
completion(data: response?.body, error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Find pet by ID
|
||||
|
||||
- parameter petId: (path) ID of pet that needs to be fetched
|
||||
- returns: Promise<Pet>
|
||||
*/
|
||||
public class func getPetById(petId petId: Int64) -> Promise<Pet> {
|
||||
let deferred = Promise<Pet>.pendingPromise()
|
||||
getPetById(petId: petId) { data, error in
|
||||
if let error = error {
|
||||
deferred.reject(error)
|
||||
} else {
|
||||
deferred.fulfill(data!)
|
||||
}
|
||||
}
|
||||
return deferred.promise
|
||||
}
|
||||
|
||||
/**
|
||||
Find pet by ID
|
||||
- GET /pet/{petId}
|
||||
- Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions
|
||||
- OAuth:
|
||||
- type: oauth2
|
||||
- name: petstore_auth
|
||||
- API Key:
|
||||
- type: apiKey api_key
|
||||
- name: api_key
|
||||
- examples: [{contentType=application/json, example={
|
||||
"photoUrls" : [ "aeiou" ],
|
||||
"name" : "doggie",
|
||||
"id" : 123456789,
|
||||
"category" : {
|
||||
"name" : "aeiou",
|
||||
"id" : 123456789
|
||||
},
|
||||
"tags" : [ {
|
||||
"name" : "aeiou",
|
||||
"id" : 123456789
|
||||
} ],
|
||||
"status" : "aeiou"
|
||||
}}, {contentType=application/xml, example=<Pet>
|
||||
<id>123456</id>
|
||||
<name>doggie</name>
|
||||
<photoUrls>
|
||||
<photoUrls>string</photoUrls>
|
||||
</photoUrls>
|
||||
<tags>
|
||||
</tags>
|
||||
<status>string</status>
|
||||
</Pet>}]
|
||||
- examples: [{contentType=application/json, example={
|
||||
"photoUrls" : [ "aeiou" ],
|
||||
"name" : "doggie",
|
||||
"id" : 123456789,
|
||||
"category" : {
|
||||
"name" : "aeiou",
|
||||
"id" : 123456789
|
||||
},
|
||||
"tags" : [ {
|
||||
"name" : "aeiou",
|
||||
"id" : 123456789
|
||||
} ],
|
||||
"status" : "aeiou"
|
||||
}}, {contentType=application/xml, example=<Pet>
|
||||
<id>123456</id>
|
||||
<name>doggie</name>
|
||||
<photoUrls>
|
||||
<photoUrls>string</photoUrls>
|
||||
</photoUrls>
|
||||
<tags>
|
||||
</tags>
|
||||
<status>string</status>
|
||||
</Pet>}]
|
||||
|
||||
- parameter petId: (path) ID of pet that needs to be fetched
|
||||
|
||||
- returns: RequestBuilder<Pet>
|
||||
*/
|
||||
public class func getPetByIdWithRequestBuilder(petId petId: Int64) -> RequestBuilder<Pet> {
|
||||
var path = "/pet/{petId}"
|
||||
path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil)
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
|
||||
let nillableParameters: [String:AnyObject?] = [:]
|
||||
|
||||
let parameters = APIHelper.rejectNil(nillableParameters)
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Pet>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Update an existing pet
|
||||
|
||||
- parameter body: (body) Pet object that needs to be added to the store (optional)
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func updatePet(body body: Pet? = nil, completion: ((error: ErrorType?) -> Void)) {
|
||||
updatePetWithRequestBuilder(body: body).execute { (response, error) -> Void in
|
||||
completion(error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Update an existing pet
|
||||
|
||||
- parameter body: (body) Pet object that needs to be added to the store (optional)
|
||||
- returns: Promise<Void>
|
||||
*/
|
||||
public class func updatePet(body body: Pet? = nil) -> Promise<Void> {
|
||||
let deferred = Promise<Void>.pendingPromise()
|
||||
updatePet(body: body) { error in
|
||||
if let error = error {
|
||||
deferred.reject(error)
|
||||
} else {
|
||||
deferred.fulfill()
|
||||
}
|
||||
}
|
||||
return deferred.promise
|
||||
}
|
||||
|
||||
/**
|
||||
Update an existing pet
|
||||
- PUT /pet
|
||||
-
|
||||
- OAuth:
|
||||
- type: oauth2
|
||||
- name: petstore_auth
|
||||
|
||||
- parameter body: (body) Pet object that needs to be added to the store (optional)
|
||||
|
||||
- returns: RequestBuilder<Void>
|
||||
*/
|
||||
public class func updatePetWithRequestBuilder(body body: Pet? = nil) -> RequestBuilder<Void> {
|
||||
let path = "/pet"
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
let parameters = body?.encodeToJSON() as? [String:AnyObject]
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Updates a pet in the store with form data
|
||||
|
||||
- parameter petId: (path) ID of pet that needs to be updated
|
||||
- parameter name: (form) Updated name of the pet (optional)
|
||||
- parameter status: (form) Updated status of the pet (optional)
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func updatePetWithForm(petId petId: String, name: String? = nil, status: String? = nil, completion: ((error: ErrorType?) -> Void)) {
|
||||
updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (response, error) -> Void in
|
||||
completion(error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Updates a pet in the store with form data
|
||||
|
||||
- parameter petId: (path) ID of pet that needs to be updated
|
||||
- parameter name: (form) Updated name of the pet (optional)
|
||||
- parameter status: (form) Updated status of the pet (optional)
|
||||
- returns: Promise<Void>
|
||||
*/
|
||||
public class func updatePetWithForm(petId petId: String, name: String? = nil, status: String? = nil) -> Promise<Void> {
|
||||
let deferred = Promise<Void>.pendingPromise()
|
||||
updatePetWithForm(petId: petId, name: name, status: status) { error in
|
||||
if let error = error {
|
||||
deferred.reject(error)
|
||||
} else {
|
||||
deferred.fulfill()
|
||||
}
|
||||
}
|
||||
return deferred.promise
|
||||
}
|
||||
|
||||
/**
|
||||
Updates a pet in the store with form data
|
||||
- POST /pet/{petId}
|
||||
-
|
||||
- OAuth:
|
||||
- type: oauth2
|
||||
- name: petstore_auth
|
||||
|
||||
- parameter petId: (path) ID of pet that needs to be updated
|
||||
- parameter name: (form) Updated name of the pet (optional)
|
||||
- parameter status: (form) Updated status of the pet (optional)
|
||||
|
||||
- returns: RequestBuilder<Void>
|
||||
*/
|
||||
public class func updatePetWithFormWithRequestBuilder(petId petId: String, name: String? = nil, status: String? = nil) -> RequestBuilder<Void> {
|
||||
var path = "/pet/{petId}"
|
||||
path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil)
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
|
||||
let nillableParameters: [String:AnyObject?] = [
|
||||
"name": name,
|
||||
"status": status
|
||||
]
|
||||
|
||||
let parameters = APIHelper.rejectNil(nillableParameters)
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false)
|
||||
}
|
||||
|
||||
/**
|
||||
uploads an image
|
||||
|
||||
- parameter petId: (path) ID of pet to update
|
||||
- parameter additionalMetadata: (form) Additional data to pass to server (optional)
|
||||
- parameter file: (form) file to upload (optional)
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func uploadFile(petId petId: Int64, additionalMetadata: String? = nil, file: NSURL? = nil, completion: ((error: ErrorType?) -> Void)) {
|
||||
uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute { (response, error) -> Void in
|
||||
completion(error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
uploads an image
|
||||
|
||||
- parameter petId: (path) ID of pet to update
|
||||
- parameter additionalMetadata: (form) Additional data to pass to server (optional)
|
||||
- parameter file: (form) file to upload (optional)
|
||||
- returns: Promise<Void>
|
||||
*/
|
||||
public class func uploadFile(petId petId: Int64, additionalMetadata: String? = nil, file: NSURL? = nil) -> Promise<Void> {
|
||||
let deferred = Promise<Void>.pendingPromise()
|
||||
uploadFile(petId: petId, additionalMetadata: additionalMetadata, file: file) { error in
|
||||
if let error = error {
|
||||
deferred.reject(error)
|
||||
} else {
|
||||
deferred.fulfill()
|
||||
}
|
||||
}
|
||||
return deferred.promise
|
||||
}
|
||||
|
||||
/**
|
||||
uploads an image
|
||||
- POST /pet/{petId}/uploadImage
|
||||
-
|
||||
- OAuth:
|
||||
- type: oauth2
|
||||
- name: petstore_auth
|
||||
|
||||
- parameter petId: (path) ID of pet to update
|
||||
- parameter additionalMetadata: (form) Additional data to pass to server (optional)
|
||||
- parameter file: (form) file to upload (optional)
|
||||
|
||||
- returns: RequestBuilder<Void>
|
||||
*/
|
||||
public class func uploadFileWithRequestBuilder(petId petId: Int64, additionalMetadata: String? = nil, file: NSURL? = nil) -> RequestBuilder<Void> {
|
||||
var path = "/pet/{petId}/uploadImage"
|
||||
path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil)
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
|
||||
let nillableParameters: [String:AnyObject?] = [
|
||||
"additionalMetadata": additionalMetadata,
|
||||
"file": file
|
||||
]
|
||||
|
||||
let parameters = APIHelper.rejectNil(nillableParameters)
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false)
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,294 @@
|
||||
//
|
||||
// StoreAPI.swift
|
||||
//
|
||||
// Generated by swagger-codegen
|
||||
// https://github.com/swagger-api/swagger-codegen
|
||||
//
|
||||
|
||||
import Alamofire
|
||||
import PromiseKit
|
||||
|
||||
|
||||
|
||||
public class StoreAPI: APIBase {
|
||||
/**
|
||||
Delete purchase order by ID
|
||||
|
||||
- parameter orderId: (path) ID of the order that needs to be deleted
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func deleteOrder(orderId orderId: String, completion: ((error: ErrorType?) -> Void)) {
|
||||
deleteOrderWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in
|
||||
completion(error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Delete purchase order by ID
|
||||
|
||||
- parameter orderId: (path) ID of the order that needs to be deleted
|
||||
- returns: Promise<Void>
|
||||
*/
|
||||
public class func deleteOrder(orderId orderId: String) -> Promise<Void> {
|
||||
let deferred = Promise<Void>.pendingPromise()
|
||||
deleteOrder(orderId: orderId) { error in
|
||||
if let error = error {
|
||||
deferred.reject(error)
|
||||
} else {
|
||||
deferred.fulfill()
|
||||
}
|
||||
}
|
||||
return deferred.promise
|
||||
}
|
||||
|
||||
/**
|
||||
Delete purchase order by ID
|
||||
- DELETE /store/order/{orderId}
|
||||
- For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
|
||||
|
||||
- parameter orderId: (path) ID of the order that needs to be deleted
|
||||
|
||||
- returns: RequestBuilder<Void>
|
||||
*/
|
||||
public class func deleteOrderWithRequestBuilder(orderId orderId: String) -> RequestBuilder<Void> {
|
||||
var path = "/store/order/{orderId}"
|
||||
path = path.stringByReplacingOccurrencesOfString("{orderId}", withString: "\(orderId)", options: .LiteralSearch, range: nil)
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
|
||||
let nillableParameters: [String:AnyObject?] = [:]
|
||||
|
||||
let parameters = APIHelper.rejectNil(nillableParameters)
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Returns pet inventories by status
|
||||
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func getInventory(completion: ((data: [String:Int32]?, error: ErrorType?) -> Void)) {
|
||||
getInventoryWithRequestBuilder().execute { (response, error) -> Void in
|
||||
completion(data: response?.body, error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Returns pet inventories by status
|
||||
|
||||
- returns: Promise<[String:Int32]>
|
||||
*/
|
||||
public class func getInventory() -> Promise<[String:Int32]> {
|
||||
let deferred = Promise<[String:Int32]>.pendingPromise()
|
||||
getInventory() { data, error in
|
||||
if let error = error {
|
||||
deferred.reject(error)
|
||||
} else {
|
||||
deferred.fulfill(data!)
|
||||
}
|
||||
}
|
||||
return deferred.promise
|
||||
}
|
||||
|
||||
/**
|
||||
Returns pet inventories by status
|
||||
- GET /store/inventory
|
||||
- Returns a map of status codes to quantities
|
||||
- API Key:
|
||||
- type: apiKey api_key
|
||||
- name: api_key
|
||||
- examples: [{contentType=application/json, example={
|
||||
"key" : 123
|
||||
}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}]
|
||||
- examples: [{contentType=application/json, example={
|
||||
"key" : 123
|
||||
}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}]
|
||||
|
||||
- returns: RequestBuilder<[String:Int32]>
|
||||
*/
|
||||
public class func getInventoryWithRequestBuilder() -> RequestBuilder<[String:Int32]> {
|
||||
let path = "/store/inventory"
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
|
||||
let nillableParameters: [String:AnyObject?] = [:]
|
||||
|
||||
let parameters = APIHelper.rejectNil(nillableParameters)
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<[String:Int32]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Find purchase order by ID
|
||||
|
||||
- parameter orderId: (path) ID of pet that needs to be fetched
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func getOrderById(orderId orderId: String, completion: ((data: Order?, error: ErrorType?) -> Void)) {
|
||||
getOrderByIdWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in
|
||||
completion(data: response?.body, error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Find purchase order by ID
|
||||
|
||||
- parameter orderId: (path) ID of pet that needs to be fetched
|
||||
- returns: Promise<Order>
|
||||
*/
|
||||
public class func getOrderById(orderId orderId: String) -> Promise<Order> {
|
||||
let deferred = Promise<Order>.pendingPromise()
|
||||
getOrderById(orderId: orderId) { data, error in
|
||||
if let error = error {
|
||||
deferred.reject(error)
|
||||
} else {
|
||||
deferred.fulfill(data!)
|
||||
}
|
||||
}
|
||||
return deferred.promise
|
||||
}
|
||||
|
||||
/**
|
||||
Find purchase order by ID
|
||||
- GET /store/order/{orderId}
|
||||
- For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
|
||||
- examples: [{contentType=application/json, example={
|
||||
"petId" : 123456789,
|
||||
"quantity" : 123,
|
||||
"id" : 123456789,
|
||||
"shipDate" : "2000-01-23T04:56:07.000+0000",
|
||||
"complete" : true,
|
||||
"status" : "aeiou"
|
||||
}}, {contentType=application/xml, example=<Order>
|
||||
<id>123456</id>
|
||||
<petId>123456</petId>
|
||||
<quantity>0</quantity>
|
||||
<shipDate>2000-01-23T04:56:07.000Z</shipDate>
|
||||
<status>string</status>
|
||||
<complete>true</complete>
|
||||
</Order>}]
|
||||
- examples: [{contentType=application/json, example={
|
||||
"petId" : 123456789,
|
||||
"quantity" : 123,
|
||||
"id" : 123456789,
|
||||
"shipDate" : "2000-01-23T04:56:07.000+0000",
|
||||
"complete" : true,
|
||||
"status" : "aeiou"
|
||||
}}, {contentType=application/xml, example=<Order>
|
||||
<id>123456</id>
|
||||
<petId>123456</petId>
|
||||
<quantity>0</quantity>
|
||||
<shipDate>2000-01-23T04:56:07.000Z</shipDate>
|
||||
<status>string</status>
|
||||
<complete>true</complete>
|
||||
</Order>}]
|
||||
|
||||
- parameter orderId: (path) ID of pet that needs to be fetched
|
||||
|
||||
- returns: RequestBuilder<Order>
|
||||
*/
|
||||
public class func getOrderByIdWithRequestBuilder(orderId orderId: String) -> RequestBuilder<Order> {
|
||||
var path = "/store/order/{orderId}"
|
||||
path = path.stringByReplacingOccurrencesOfString("{orderId}", withString: "\(orderId)", options: .LiteralSearch, range: nil)
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
|
||||
let nillableParameters: [String:AnyObject?] = [:]
|
||||
|
||||
let parameters = APIHelper.rejectNil(nillableParameters)
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Order>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Place an order for a pet
|
||||
|
||||
- parameter body: (body) order placed for purchasing the pet (optional)
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func placeOrder(body body: Order? = nil, completion: ((data: Order?, error: ErrorType?) -> Void)) {
|
||||
placeOrderWithRequestBuilder(body: body).execute { (response, error) -> Void in
|
||||
completion(data: response?.body, error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Place an order for a pet
|
||||
|
||||
- parameter body: (body) order placed for purchasing the pet (optional)
|
||||
- returns: Promise<Order>
|
||||
*/
|
||||
public class func placeOrder(body body: Order? = nil) -> Promise<Order> {
|
||||
let deferred = Promise<Order>.pendingPromise()
|
||||
placeOrder(body: body) { data, error in
|
||||
if let error = error {
|
||||
deferred.reject(error)
|
||||
} else {
|
||||
deferred.fulfill(data!)
|
||||
}
|
||||
}
|
||||
return deferred.promise
|
||||
}
|
||||
|
||||
/**
|
||||
Place an order for a pet
|
||||
- POST /store/order
|
||||
-
|
||||
- examples: [{contentType=application/json, example={
|
||||
"petId" : 123456789,
|
||||
"quantity" : 123,
|
||||
"id" : 123456789,
|
||||
"shipDate" : "2000-01-23T04:56:07.000+0000",
|
||||
"complete" : true,
|
||||
"status" : "aeiou"
|
||||
}}, {contentType=application/xml, example=<Order>
|
||||
<id>123456</id>
|
||||
<petId>123456</petId>
|
||||
<quantity>0</quantity>
|
||||
<shipDate>2000-01-23T04:56:07.000Z</shipDate>
|
||||
<status>string</status>
|
||||
<complete>true</complete>
|
||||
</Order>}]
|
||||
- examples: [{contentType=application/json, example={
|
||||
"petId" : 123456789,
|
||||
"quantity" : 123,
|
||||
"id" : 123456789,
|
||||
"shipDate" : "2000-01-23T04:56:07.000+0000",
|
||||
"complete" : true,
|
||||
"status" : "aeiou"
|
||||
}}, {contentType=application/xml, example=<Order>
|
||||
<id>123456</id>
|
||||
<petId>123456</petId>
|
||||
<quantity>0</quantity>
|
||||
<shipDate>2000-01-23T04:56:07.000Z</shipDate>
|
||||
<status>string</status>
|
||||
<complete>true</complete>
|
||||
</Order>}]
|
||||
|
||||
- parameter body: (body) order placed for purchasing the pet (optional)
|
||||
|
||||
- returns: RequestBuilder<Order>
|
||||
*/
|
||||
public class func placeOrderWithRequestBuilder(body body: Order? = nil) -> RequestBuilder<Order> {
|
||||
let path = "/store/order"
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
let parameters = body?.encodeToJSON() as? [String:AnyObject]
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Order>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,482 @@
|
||||
//
|
||||
// UserAPI.swift
|
||||
//
|
||||
// Generated by swagger-codegen
|
||||
// https://github.com/swagger-api/swagger-codegen
|
||||
//
|
||||
|
||||
import Alamofire
|
||||
import PromiseKit
|
||||
|
||||
|
||||
|
||||
public class UserAPI: APIBase {
|
||||
/**
|
||||
Create user
|
||||
|
||||
- parameter body: (body) Created user object (optional)
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func createUser(body body: User? = nil, completion: ((error: ErrorType?) -> Void)) {
|
||||
createUserWithRequestBuilder(body: body).execute { (response, error) -> Void in
|
||||
completion(error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Create user
|
||||
|
||||
- parameter body: (body) Created user object (optional)
|
||||
- returns: Promise<Void>
|
||||
*/
|
||||
public class func createUser(body body: User? = nil) -> Promise<Void> {
|
||||
let deferred = Promise<Void>.pendingPromise()
|
||||
createUser(body: body) { error in
|
||||
if let error = error {
|
||||
deferred.reject(error)
|
||||
} else {
|
||||
deferred.fulfill()
|
||||
}
|
||||
}
|
||||
return deferred.promise
|
||||
}
|
||||
|
||||
/**
|
||||
Create user
|
||||
- POST /user
|
||||
- This can only be done by the logged in user.
|
||||
|
||||
- parameter body: (body) Created user object (optional)
|
||||
|
||||
- returns: RequestBuilder<Void>
|
||||
*/
|
||||
public class func createUserWithRequestBuilder(body body: User? = nil) -> RequestBuilder<Void> {
|
||||
let path = "/user"
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
let parameters = body?.encodeToJSON() as? [String:AnyObject]
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates list of users with given input array
|
||||
|
||||
- parameter body: (body) List of user object (optional)
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func createUsersWithArrayInput(body body: [User]? = nil, completion: ((error: ErrorType?) -> Void)) {
|
||||
createUsersWithArrayInputWithRequestBuilder(body: body).execute { (response, error) -> Void in
|
||||
completion(error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Creates list of users with given input array
|
||||
|
||||
- parameter body: (body) List of user object (optional)
|
||||
- returns: Promise<Void>
|
||||
*/
|
||||
public class func createUsersWithArrayInput(body body: [User]? = nil) -> Promise<Void> {
|
||||
let deferred = Promise<Void>.pendingPromise()
|
||||
createUsersWithArrayInput(body: body) { error in
|
||||
if let error = error {
|
||||
deferred.reject(error)
|
||||
} else {
|
||||
deferred.fulfill()
|
||||
}
|
||||
}
|
||||
return deferred.promise
|
||||
}
|
||||
|
||||
/**
|
||||
Creates list of users with given input array
|
||||
- POST /user/createWithArray
|
||||
-
|
||||
|
||||
- parameter body: (body) List of user object (optional)
|
||||
|
||||
- returns: RequestBuilder<Void>
|
||||
*/
|
||||
public class func createUsersWithArrayInputWithRequestBuilder(body body: [User]? = nil) -> RequestBuilder<Void> {
|
||||
let path = "/user/createWithArray"
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
let parameters = body?.encodeToJSON() as? [String:AnyObject]
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates list of users with given input array
|
||||
|
||||
- parameter body: (body) List of user object (optional)
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func createUsersWithListInput(body body: [User]? = nil, completion: ((error: ErrorType?) -> Void)) {
|
||||
createUsersWithListInputWithRequestBuilder(body: body).execute { (response, error) -> Void in
|
||||
completion(error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Creates list of users with given input array
|
||||
|
||||
- parameter body: (body) List of user object (optional)
|
||||
- returns: Promise<Void>
|
||||
*/
|
||||
public class func createUsersWithListInput(body body: [User]? = nil) -> Promise<Void> {
|
||||
let deferred = Promise<Void>.pendingPromise()
|
||||
createUsersWithListInput(body: body) { error in
|
||||
if let error = error {
|
||||
deferred.reject(error)
|
||||
} else {
|
||||
deferred.fulfill()
|
||||
}
|
||||
}
|
||||
return deferred.promise
|
||||
}
|
||||
|
||||
/**
|
||||
Creates list of users with given input array
|
||||
- POST /user/createWithList
|
||||
-
|
||||
|
||||
- parameter body: (body) List of user object (optional)
|
||||
|
||||
- returns: RequestBuilder<Void>
|
||||
*/
|
||||
public class func createUsersWithListInputWithRequestBuilder(body body: [User]? = nil) -> RequestBuilder<Void> {
|
||||
let path = "/user/createWithList"
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
let parameters = body?.encodeToJSON() as? [String:AnyObject]
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Delete user
|
||||
|
||||
- parameter username: (path) The name that needs to be deleted
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func deleteUser(username username: String, completion: ((error: ErrorType?) -> Void)) {
|
||||
deleteUserWithRequestBuilder(username: username).execute { (response, error) -> Void in
|
||||
completion(error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Delete user
|
||||
|
||||
- parameter username: (path) The name that needs to be deleted
|
||||
- returns: Promise<Void>
|
||||
*/
|
||||
public class func deleteUser(username username: String) -> Promise<Void> {
|
||||
let deferred = Promise<Void>.pendingPromise()
|
||||
deleteUser(username: username) { error in
|
||||
if let error = error {
|
||||
deferred.reject(error)
|
||||
} else {
|
||||
deferred.fulfill()
|
||||
}
|
||||
}
|
||||
return deferred.promise
|
||||
}
|
||||
|
||||
/**
|
||||
Delete user
|
||||
- DELETE /user/{username}
|
||||
- This can only be done by the logged in user.
|
||||
|
||||
- parameter username: (path) The name that needs to be deleted
|
||||
|
||||
- returns: RequestBuilder<Void>
|
||||
*/
|
||||
public class func deleteUserWithRequestBuilder(username username: String) -> RequestBuilder<Void> {
|
||||
var path = "/user/{username}"
|
||||
path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil)
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
|
||||
let nillableParameters: [String:AnyObject?] = [:]
|
||||
|
||||
let parameters = APIHelper.rejectNil(nillableParameters)
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Get user by user name
|
||||
|
||||
- parameter username: (path) The name that needs to be fetched. Use user1 for testing.
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func getUserByName(username username: String, completion: ((data: User?, error: ErrorType?) -> Void)) {
|
||||
getUserByNameWithRequestBuilder(username: username).execute { (response, error) -> Void in
|
||||
completion(data: response?.body, error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Get user by user name
|
||||
|
||||
- parameter username: (path) The name that needs to be fetched. Use user1 for testing.
|
||||
- returns: Promise<User>
|
||||
*/
|
||||
public class func getUserByName(username username: String) -> Promise<User> {
|
||||
let deferred = Promise<User>.pendingPromise()
|
||||
getUserByName(username: username) { data, error in
|
||||
if let error = error {
|
||||
deferred.reject(error)
|
||||
} else {
|
||||
deferred.fulfill(data!)
|
||||
}
|
||||
}
|
||||
return deferred.promise
|
||||
}
|
||||
|
||||
/**
|
||||
Get user by user name
|
||||
- GET /user/{username}
|
||||
-
|
||||
- examples: [{contentType=application/json, example={
|
||||
"firstName" : "aeiou",
|
||||
"lastName" : "aeiou",
|
||||
"password" : "aeiou",
|
||||
"userStatus" : 123,
|
||||
"phone" : "aeiou",
|
||||
"id" : 123456789,
|
||||
"email" : "aeiou",
|
||||
"username" : "aeiou"
|
||||
}}, {contentType=application/xml, example=<User>
|
||||
<id>123456</id>
|
||||
<username>string</username>
|
||||
<firstName>string</firstName>
|
||||
<lastName>string</lastName>
|
||||
<email>string</email>
|
||||
<password>string</password>
|
||||
<phone>string</phone>
|
||||
<userStatus>0</userStatus>
|
||||
</User>}]
|
||||
- examples: [{contentType=application/json, example={
|
||||
"firstName" : "aeiou",
|
||||
"lastName" : "aeiou",
|
||||
"password" : "aeiou",
|
||||
"userStatus" : 123,
|
||||
"phone" : "aeiou",
|
||||
"id" : 123456789,
|
||||
"email" : "aeiou",
|
||||
"username" : "aeiou"
|
||||
}}, {contentType=application/xml, example=<User>
|
||||
<id>123456</id>
|
||||
<username>string</username>
|
||||
<firstName>string</firstName>
|
||||
<lastName>string</lastName>
|
||||
<email>string</email>
|
||||
<password>string</password>
|
||||
<phone>string</phone>
|
||||
<userStatus>0</userStatus>
|
||||
</User>}]
|
||||
|
||||
- parameter username: (path) The name that needs to be fetched. Use user1 for testing.
|
||||
|
||||
- returns: RequestBuilder<User>
|
||||
*/
|
||||
public class func getUserByNameWithRequestBuilder(username username: String) -> RequestBuilder<User> {
|
||||
var path = "/user/{username}"
|
||||
path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil)
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
|
||||
let nillableParameters: [String:AnyObject?] = [:]
|
||||
|
||||
let parameters = APIHelper.rejectNil(nillableParameters)
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<User>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Logs user into the system
|
||||
|
||||
- parameter username: (query) The user name for login (optional)
|
||||
- parameter password: (query) The password for login in clear text (optional)
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func loginUser(username username: String? = nil, password: String? = nil, completion: ((data: String?, error: ErrorType?) -> Void)) {
|
||||
loginUserWithRequestBuilder(username: username, password: password).execute { (response, error) -> Void in
|
||||
completion(data: response?.body, error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Logs user into the system
|
||||
|
||||
- parameter username: (query) The user name for login (optional)
|
||||
- parameter password: (query) The password for login in clear text (optional)
|
||||
- returns: Promise<String>
|
||||
*/
|
||||
public class func loginUser(username username: String? = nil, password: String? = nil) -> Promise<String> {
|
||||
let deferred = Promise<String>.pendingPromise()
|
||||
loginUser(username: username, password: password) { data, error in
|
||||
if let error = error {
|
||||
deferred.reject(error)
|
||||
} else {
|
||||
deferred.fulfill(data!)
|
||||
}
|
||||
}
|
||||
return deferred.promise
|
||||
}
|
||||
|
||||
/**
|
||||
Logs user into the system
|
||||
- GET /user/login
|
||||
-
|
||||
- examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}]
|
||||
- examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}]
|
||||
|
||||
- parameter username: (query) The user name for login (optional)
|
||||
- parameter password: (query) The password for login in clear text (optional)
|
||||
|
||||
- returns: RequestBuilder<String>
|
||||
*/
|
||||
public class func loginUserWithRequestBuilder(username username: String? = nil, password: String? = nil) -> RequestBuilder<String> {
|
||||
let path = "/user/login"
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
|
||||
let nillableParameters: [String:AnyObject?] = [
|
||||
"username": username,
|
||||
"password": password
|
||||
]
|
||||
|
||||
let parameters = APIHelper.rejectNil(nillableParameters)
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<String>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
|
||||
}
|
||||
|
||||
/**
|
||||
Logs out current logged in user session
|
||||
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func logoutUser(completion: ((error: ErrorType?) -> Void)) {
|
||||
logoutUserWithRequestBuilder().execute { (response, error) -> Void in
|
||||
completion(error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Logs out current logged in user session
|
||||
|
||||
- returns: Promise<Void>
|
||||
*/
|
||||
public class func logoutUser() -> Promise<Void> {
|
||||
let deferred = Promise<Void>.pendingPromise()
|
||||
logoutUser() { error in
|
||||
if let error = error {
|
||||
deferred.reject(error)
|
||||
} else {
|
||||
deferred.fulfill()
|
||||
}
|
||||
}
|
||||
return deferred.promise
|
||||
}
|
||||
|
||||
/**
|
||||
Logs out current logged in user session
|
||||
- GET /user/logout
|
||||
-
|
||||
|
||||
- returns: RequestBuilder<Void>
|
||||
*/
|
||||
public class func logoutUserWithRequestBuilder() -> RequestBuilder<Void> {
|
||||
let path = "/user/logout"
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
|
||||
let nillableParameters: [String:AnyObject?] = [:]
|
||||
|
||||
let parameters = APIHelper.rejectNil(nillableParameters)
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Updated user
|
||||
|
||||
- parameter username: (path) name that need to be deleted
|
||||
- parameter body: (body) Updated user object (optional)
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func updateUser(username username: String, body: User? = nil, completion: ((error: ErrorType?) -> Void)) {
|
||||
updateUserWithRequestBuilder(username: username, body: body).execute { (response, error) -> Void in
|
||||
completion(error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Updated user
|
||||
|
||||
- parameter username: (path) name that need to be deleted
|
||||
- parameter body: (body) Updated user object (optional)
|
||||
- returns: Promise<Void>
|
||||
*/
|
||||
public class func updateUser(username username: String, body: User? = nil) -> Promise<Void> {
|
||||
let deferred = Promise<Void>.pendingPromise()
|
||||
updateUser(username: username, body: body) { error in
|
||||
if let error = error {
|
||||
deferred.reject(error)
|
||||
} else {
|
||||
deferred.fulfill()
|
||||
}
|
||||
}
|
||||
return deferred.promise
|
||||
}
|
||||
|
||||
/**
|
||||
Updated user
|
||||
- PUT /user/{username}
|
||||
- This can only be done by the logged in user.
|
||||
|
||||
- parameter username: (path) name that need to be deleted
|
||||
- parameter body: (body) Updated user object (optional)
|
||||
|
||||
- returns: RequestBuilder<Void>
|
||||
*/
|
||||
public class func updateUserWithRequestBuilder(username username: String, body: User? = nil) -> RequestBuilder<Void> {
|
||||
var path = "/user/{username}"
|
||||
path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil)
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
let parameters = body?.encodeToJSON() as? [String:AnyObject]
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,112 @@
|
||||
// AlamofireImplementations.swift
|
||||
//
|
||||
// Generated by swagger-codegen
|
||||
// https://github.com/swagger-api/swagger-codegen
|
||||
//
|
||||
|
||||
import Alamofire
|
||||
|
||||
class AlamofireRequestBuilderFactory: RequestBuilderFactory {
|
||||
func getBuilder<T>() -> RequestBuilder<T>.Type {
|
||||
return AlamofireRequestBuilder<T>.self
|
||||
}
|
||||
}
|
||||
|
||||
// Store manager to retain its reference
|
||||
private var managerStore: [String: Alamofire.Manager] = [:]
|
||||
|
||||
class AlamofireRequestBuilder<T>: RequestBuilder<T> {
|
||||
required init(method: String, URLString: String, parameters: [String : AnyObject]?, isBody: Bool) {
|
||||
super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody)
|
||||
}
|
||||
|
||||
override func execute(completion: (response: Response<T>?, error: ErrorType?) -> Void) {
|
||||
let managerId = NSUUID().UUIDString
|
||||
// Create a new manager for each request to customize its request header
|
||||
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
|
||||
configuration.HTTPAdditionalHeaders = buildHeaders()
|
||||
let manager = Alamofire.Manager(configuration: configuration)
|
||||
managerStore[managerId] = manager
|
||||
|
||||
let encoding = isBody ? Alamofire.ParameterEncoding.JSON : Alamofire.ParameterEncoding.URL
|
||||
let xMethod = Alamofire.Method(rawValue: method)
|
||||
let fileKeys = parameters == nil ? [] : parameters!.filter { $1.isKindOfClass(NSURL) }
|
||||
.map { $0.0 }
|
||||
|
||||
if fileKeys.count > 0 {
|
||||
manager.upload(
|
||||
xMethod!, URLString, headers: nil,
|
||||
multipartFormData: { mpForm in
|
||||
for (k, v) in self.parameters! {
|
||||
switch v {
|
||||
case let fileURL as NSURL:
|
||||
mpForm.appendBodyPart(fileURL: fileURL, name: k)
|
||||
break
|
||||
case let string as NSString:
|
||||
mpForm.appendBodyPart(data: string.dataUsingEncoding(NSUTF8StringEncoding)!, name: k)
|
||||
break
|
||||
case let number as NSNumber:
|
||||
mpForm.appendBodyPart(data: number.stringValue.dataUsingEncoding(NSUTF8StringEncoding)!, name: k)
|
||||
break
|
||||
default:
|
||||
fatalError("Unprocessable value \(v) with key \(k)")
|
||||
break
|
||||
}
|
||||
}
|
||||
},
|
||||
encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold,
|
||||
encodingCompletion: { encodingResult in
|
||||
switch encodingResult {
|
||||
case .Success(let upload, _, _):
|
||||
self.processRequest(upload, managerId, completion)
|
||||
case .Failure(let encodingError):
|
||||
completion(response: nil, error: encodingError)
|
||||
}
|
||||
}
|
||||
)
|
||||
} else {
|
||||
processRequest(manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding), managerId, completion)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private func processRequest(request: Request, _ managerId: String, _ completion: (response: Response<T>?, error: ErrorType?) -> Void) {
|
||||
if let credential = self.credential {
|
||||
request.authenticate(usingCredential: credential)
|
||||
}
|
||||
|
||||
request.validate().responseJSON(options: .AllowFragments) { response in
|
||||
managerStore.removeValueForKey(managerId)
|
||||
|
||||
if response.result.isFailure {
|
||||
completion(response: nil, error: response.result.error)
|
||||
return
|
||||
}
|
||||
|
||||
if () is T {
|
||||
completion(response: Response(response: response.response!, body: () as! T), error: nil)
|
||||
return
|
||||
}
|
||||
if let json: AnyObject = response.result.value {
|
||||
let body = Decoders.decode(clazz: T.self, source: json)
|
||||
completion(response: Response(response: response.response!, body: body), error: nil)
|
||||
return
|
||||
} else if "" is T {
|
||||
// swagger-parser currently doesn't support void, which will be fixed in future swagger-parser release
|
||||
// https://github.com/swagger-api/swagger-parser/pull/34
|
||||
completion(response: Response(response: response.response!, body: "" as! T), error: nil)
|
||||
return
|
||||
}
|
||||
|
||||
completion(response: nil, error: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"]))
|
||||
}
|
||||
}
|
||||
|
||||
private func buildHeaders() -> [String: AnyObject] {
|
||||
var httpHeaders = Manager.defaultHTTPHeaders
|
||||
for (key, value) in self.headers {
|
||||
httpHeaders[key] = value
|
||||
}
|
||||
return httpHeaders
|
||||
}
|
||||
}
|
@ -0,0 +1,87 @@
|
||||
// Extensions.swift
|
||||
//
|
||||
// Generated by swagger-codegen
|
||||
// https://github.com/swagger-api/swagger-codegen
|
||||
//
|
||||
|
||||
import Alamofire
|
||||
import PromiseKit
|
||||
|
||||
extension Bool: JSONEncodable {
|
||||
func encodeToJSON() -> AnyObject { return self }
|
||||
}
|
||||
|
||||
extension Float: JSONEncodable {
|
||||
func encodeToJSON() -> AnyObject { return self }
|
||||
}
|
||||
|
||||
extension Int: JSONEncodable {
|
||||
func encodeToJSON() -> AnyObject { return self }
|
||||
}
|
||||
|
||||
extension Int32: JSONEncodable {
|
||||
func encodeToJSON() -> AnyObject { return NSNumber(int: self) }
|
||||
}
|
||||
|
||||
extension Int64: JSONEncodable {
|
||||
func encodeToJSON() -> AnyObject { return NSNumber(longLong: self) }
|
||||
}
|
||||
|
||||
extension Double: JSONEncodable {
|
||||
func encodeToJSON() -> AnyObject { return self }
|
||||
}
|
||||
|
||||
extension String: JSONEncodable {
|
||||
func encodeToJSON() -> AnyObject { return self }
|
||||
}
|
||||
|
||||
private func encodeIfPossible<T>(object: T) -> AnyObject {
|
||||
if object is JSONEncodable {
|
||||
return (object as! JSONEncodable).encodeToJSON()
|
||||
} else {
|
||||
return object as! AnyObject
|
||||
}
|
||||
}
|
||||
|
||||
extension Array: JSONEncodable {
|
||||
func encodeToJSON() -> AnyObject {
|
||||
return self.map(encodeIfPossible)
|
||||
}
|
||||
}
|
||||
|
||||
extension Dictionary: JSONEncodable {
|
||||
func encodeToJSON() -> AnyObject {
|
||||
var dictionary = [NSObject:AnyObject]()
|
||||
for (key, value) in self {
|
||||
dictionary[key as! NSObject] = encodeIfPossible(value)
|
||||
}
|
||||
return dictionary
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private let dateFormatter: NSDateFormatter = {
|
||||
let dateFormatter = NSDateFormatter()
|
||||
dateFormatter.dateFormat = "yyyy-MM-dd"
|
||||
return dateFormatter
|
||||
}()
|
||||
|
||||
extension NSDate: JSONEncodable {
|
||||
func encodeToJSON() -> AnyObject {
|
||||
return dateFormatter.stringFromDate(self)
|
||||
}
|
||||
}
|
||||
|
||||
extension RequestBuilder {
|
||||
public func execute() -> Promise<Response<T>> {
|
||||
let deferred = Promise<Response<T>>.pendingPromise()
|
||||
self.execute { (response: Response<T>?, error: ErrorType?) in
|
||||
if let response = response {
|
||||
deferred.fulfill(response)
|
||||
} else {
|
||||
deferred.reject(error!)
|
||||
}
|
||||
}
|
||||
return deferred.promise
|
||||
}
|
||||
}
|
@ -0,0 +1,217 @@
|
||||
// Models.swift
|
||||
//
|
||||
// Generated by swagger-codegen
|
||||
// https://github.com/swagger-api/swagger-codegen
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol JSONEncodable {
|
||||
func encodeToJSON() -> AnyObject
|
||||
}
|
||||
|
||||
public class Response<T> {
|
||||
public let statusCode: Int
|
||||
public let header: [String: String]
|
||||
public let body: T
|
||||
|
||||
public init(statusCode: Int, header: [String: String], body: T) {
|
||||
self.statusCode = statusCode
|
||||
self.header = header
|
||||
self.body = body
|
||||
}
|
||||
|
||||
public convenience init(response: NSHTTPURLResponse, body: T) {
|
||||
let rawHeader = response.allHeaderFields
|
||||
var header = [String:String]()
|
||||
for (key, value) in rawHeader {
|
||||
header[key as! String] = value as? String
|
||||
}
|
||||
self.init(statusCode: response.statusCode, header: header, body: body)
|
||||
}
|
||||
}
|
||||
|
||||
private var once = dispatch_once_t()
|
||||
class Decoders {
|
||||
static private var decoders = Dictionary<String, ((AnyObject) -> AnyObject)>()
|
||||
|
||||
static func addDecoder<T>(clazz clazz: T.Type, decoder: ((AnyObject) -> T)) {
|
||||
let key = "\(T.self)"
|
||||
decoders[key] = { decoder($0) as! AnyObject }
|
||||
}
|
||||
|
||||
static func decode<T>(clazz clazz: [T].Type, source: AnyObject) -> [T] {
|
||||
let array = source as! [AnyObject]
|
||||
return array.map { Decoders.decode(clazz: T.self, source: $0) }
|
||||
}
|
||||
|
||||
static func decode<T, Key: Hashable>(clazz clazz: [Key:T].Type, source: AnyObject) -> [Key:T] {
|
||||
let sourceDictionary = source as! [Key: AnyObject]
|
||||
var dictionary = [Key:T]()
|
||||
for (key, value) in sourceDictionary {
|
||||
dictionary[key] = Decoders.decode(clazz: T.self, source: value)
|
||||
}
|
||||
return dictionary
|
||||
}
|
||||
|
||||
static func decode<T>(clazz clazz: T.Type, source: AnyObject) -> T {
|
||||
initialize()
|
||||
if T.self is Int32.Type && source is NSNumber {
|
||||
return source.intValue as! T;
|
||||
}
|
||||
if T.self is Int64.Type && source is NSNumber {
|
||||
return source.longLongValue as! T;
|
||||
}
|
||||
if source is T {
|
||||
return source as! T
|
||||
}
|
||||
|
||||
let key = "\(T.self)"
|
||||
if let decoder = decoders[key] {
|
||||
return decoder(source) as! T
|
||||
} else {
|
||||
fatalError("Source \(source) is not convertible to type \(clazz): Maybe swagger file is insufficient")
|
||||
}
|
||||
}
|
||||
|
||||
static func decodeOptional<T>(clazz clazz: T.Type, source: AnyObject?) -> T? {
|
||||
if source is NSNull {
|
||||
return nil
|
||||
}
|
||||
return source.map { (source: AnyObject) -> T in
|
||||
Decoders.decode(clazz: clazz, source: source)
|
||||
}
|
||||
}
|
||||
|
||||
static func decodeOptional<T>(clazz clazz: [T].Type, source: AnyObject?) -> [T]? {
|
||||
if source is NSNull {
|
||||
return nil
|
||||
}
|
||||
return source.map { (someSource: AnyObject) -> [T] in
|
||||
Decoders.decode(clazz: clazz, source: someSource)
|
||||
}
|
||||
}
|
||||
|
||||
static func decodeOptional<T, Key: Hashable>(clazz clazz: [Key:T].Type, source: AnyObject?) -> [Key:T]? {
|
||||
if source is NSNull {
|
||||
return nil
|
||||
}
|
||||
return source.map { (someSource: AnyObject) -> [Key:T] in
|
||||
Decoders.decode(clazz: clazz, source: someSource)
|
||||
}
|
||||
}
|
||||
|
||||
static private func initialize() {
|
||||
dispatch_once(&once) {
|
||||
let formatters = [
|
||||
"yyyy-MM-dd",
|
||||
"yyyy-MM-dd'T'HH:mm:ssZZZZZ",
|
||||
"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ",
|
||||
"yyyy-MM-dd'T'HH:mm:ss'Z'"
|
||||
].map { (format: String) -> NSDateFormatter in
|
||||
let formatter = NSDateFormatter()
|
||||
formatter.dateFormat = format
|
||||
return formatter
|
||||
}
|
||||
// Decoder for NSDate
|
||||
Decoders.addDecoder(clazz: NSDate.self) { (source: AnyObject) -> NSDate in
|
||||
if let sourceString = source as? String {
|
||||
for formatter in formatters {
|
||||
if let date = formatter.dateFromString(sourceString) {
|
||||
return date
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
if let sourceInt = source as? Int {
|
||||
// treat as a java date
|
||||
return NSDate(timeIntervalSince1970: Double(sourceInt / 1000) )
|
||||
}
|
||||
fatalError("formatter failed to parse \(source)")
|
||||
}
|
||||
|
||||
// Decoder for [Category]
|
||||
Decoders.addDecoder(clazz: [Category].self) { (source: AnyObject) -> [Category] in
|
||||
return Decoders.decode(clazz: [Category].self, source: source)
|
||||
}
|
||||
// Decoder for Category
|
||||
Decoders.addDecoder(clazz: Category.self) { (source: AnyObject) -> Category in
|
||||
let sourceDictionary = source as! [NSObject:AnyObject]
|
||||
let instance = Category()
|
||||
instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"])
|
||||
instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"])
|
||||
return instance
|
||||
}
|
||||
|
||||
|
||||
// Decoder for [Order]
|
||||
Decoders.addDecoder(clazz: [Order].self) { (source: AnyObject) -> [Order] in
|
||||
return Decoders.decode(clazz: [Order].self, source: source)
|
||||
}
|
||||
// Decoder for Order
|
||||
Decoders.addDecoder(clazz: Order.self) { (source: AnyObject) -> Order in
|
||||
let sourceDictionary = source as! [NSObject:AnyObject]
|
||||
let instance = Order()
|
||||
instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"])
|
||||
instance.petId = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["petId"])
|
||||
instance.quantity = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["quantity"])
|
||||
instance.shipDate = Decoders.decodeOptional(clazz: NSDate.self, source: sourceDictionary["shipDate"])
|
||||
instance.status = Order.Status(rawValue: (sourceDictionary["status"] as? String) ?? "")
|
||||
instance.complete = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["complete"])
|
||||
return instance
|
||||
}
|
||||
|
||||
|
||||
// Decoder for [Pet]
|
||||
Decoders.addDecoder(clazz: [Pet].self) { (source: AnyObject) -> [Pet] in
|
||||
return Decoders.decode(clazz: [Pet].self, source: source)
|
||||
}
|
||||
// Decoder for Pet
|
||||
Decoders.addDecoder(clazz: Pet.self) { (source: AnyObject) -> Pet in
|
||||
let sourceDictionary = source as! [NSObject:AnyObject]
|
||||
let instance = Pet()
|
||||
instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"])
|
||||
instance.category = Decoders.decodeOptional(clazz: Category.self, source: sourceDictionary["category"])
|
||||
instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"])
|
||||
instance.photoUrls = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["photoUrls"])
|
||||
instance.tags = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["tags"])
|
||||
instance.status = Pet.Status(rawValue: (sourceDictionary["status"] as? String) ?? "")
|
||||
return instance
|
||||
}
|
||||
|
||||
|
||||
// Decoder for [Tag]
|
||||
Decoders.addDecoder(clazz: [Tag].self) { (source: AnyObject) -> [Tag] in
|
||||
return Decoders.decode(clazz: [Tag].self, source: source)
|
||||
}
|
||||
// Decoder for Tag
|
||||
Decoders.addDecoder(clazz: Tag.self) { (source: AnyObject) -> Tag in
|
||||
let sourceDictionary = source as! [NSObject:AnyObject]
|
||||
let instance = Tag()
|
||||
instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"])
|
||||
instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"])
|
||||
return instance
|
||||
}
|
||||
|
||||
|
||||
// Decoder for [User]
|
||||
Decoders.addDecoder(clazz: [User].self) { (source: AnyObject) -> [User] in
|
||||
return Decoders.decode(clazz: [User].self, source: source)
|
||||
}
|
||||
// Decoder for User
|
||||
Decoders.addDecoder(clazz: User.self) { (source: AnyObject) -> User in
|
||||
let sourceDictionary = source as! [NSObject:AnyObject]
|
||||
let instance = User()
|
||||
instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"])
|
||||
instance.username = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["username"])
|
||||
instance.firstName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["firstName"])
|
||||
instance.lastName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["lastName"])
|
||||
instance.email = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["email"])
|
||||
instance.password = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["password"])
|
||||
instance.phone = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["phone"])
|
||||
instance.userStatus = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["userStatus"])
|
||||
return instance
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
//
|
||||
// Category.swift
|
||||
//
|
||||
// Generated by swagger-codegen
|
||||
// https://github.com/swagger-api/swagger-codegen
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
|
||||
public class Category: JSONEncodable {
|
||||
public var id: Int64?
|
||||
public var name: String?
|
||||
|
||||
public init() {}
|
||||
|
||||
// MARK: JSONEncodable
|
||||
func encodeToJSON() -> AnyObject {
|
||||
var nillableDictionary = [String:AnyObject?]()
|
||||
nillableDictionary["id"] = self.id?.encodeToJSON()
|
||||
nillableDictionary["name"] = self.name
|
||||
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
|
||||
return dictionary
|
||||
}
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
//
|
||||
// Order.swift
|
||||
//
|
||||
// Generated by swagger-codegen
|
||||
// https://github.com/swagger-api/swagger-codegen
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
|
||||
public class Order: JSONEncodable {
|
||||
public enum Status: String {
|
||||
case Placed = "placed"
|
||||
case Approved = "approved"
|
||||
case Delivered = "delivered"
|
||||
}
|
||||
public var id: Int64?
|
||||
public var petId: Int64?
|
||||
public var quantity: Int32?
|
||||
public var shipDate: NSDate?
|
||||
/** Order Status */
|
||||
public var status: Status?
|
||||
public var complete: Bool?
|
||||
|
||||
public init() {}
|
||||
|
||||
// MARK: JSONEncodable
|
||||
func encodeToJSON() -> AnyObject {
|
||||
var nillableDictionary = [String:AnyObject?]()
|
||||
nillableDictionary["id"] = self.id?.encodeToJSON()
|
||||
nillableDictionary["petId"] = self.petId?.encodeToJSON()
|
||||
nillableDictionary["quantity"] = self.quantity?.encodeToJSON()
|
||||
nillableDictionary["shipDate"] = self.shipDate?.encodeToJSON()
|
||||
nillableDictionary["status"] = self.status?.rawValue
|
||||
nillableDictionary["complete"] = self.complete
|
||||
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
|
||||
return dictionary
|
||||
}
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
//
|
||||
// Pet.swift
|
||||
//
|
||||
// Generated by swagger-codegen
|
||||
// https://github.com/swagger-api/swagger-codegen
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
|
||||
public class Pet: JSONEncodable {
|
||||
public enum Status: String {
|
||||
case Available = "available"
|
||||
case Pending = "pending"
|
||||
case Sold = "sold"
|
||||
}
|
||||
public var id: Int64?
|
||||
public var category: Category?
|
||||
public var name: String?
|
||||
public var photoUrls: [String]?
|
||||
public var tags: [Tag]?
|
||||
/** pet status in the store */
|
||||
public var status: Status?
|
||||
|
||||
public init() {}
|
||||
|
||||
// MARK: JSONEncodable
|
||||
func encodeToJSON() -> AnyObject {
|
||||
var nillableDictionary = [String:AnyObject?]()
|
||||
nillableDictionary["id"] = self.id?.encodeToJSON()
|
||||
nillableDictionary["category"] = self.category?.encodeToJSON()
|
||||
nillableDictionary["name"] = self.name
|
||||
nillableDictionary["photoUrls"] = self.photoUrls?.encodeToJSON()
|
||||
nillableDictionary["tags"] = self.tags?.encodeToJSON()
|
||||
nillableDictionary["status"] = self.status?.rawValue
|
||||
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
|
||||
return dictionary
|
||||
}
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
//
|
||||
// Tag.swift
|
||||
//
|
||||
// Generated by swagger-codegen
|
||||
// https://github.com/swagger-api/swagger-codegen
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
|
||||
public class Tag: JSONEncodable {
|
||||
public var id: Int64?
|
||||
public var name: String?
|
||||
|
||||
public init() {}
|
||||
|
||||
// MARK: JSONEncodable
|
||||
func encodeToJSON() -> AnyObject {
|
||||
var nillableDictionary = [String:AnyObject?]()
|
||||
nillableDictionary["id"] = self.id?.encodeToJSON()
|
||||
nillableDictionary["name"] = self.name
|
||||
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
|
||||
return dictionary
|
||||
}
|
||||
}
|
@ -0,0 +1,38 @@
|
||||
//
|
||||
// User.swift
|
||||
//
|
||||
// Generated by swagger-codegen
|
||||
// https://github.com/swagger-api/swagger-codegen
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
|
||||
public class User: JSONEncodable {
|
||||
public var id: Int64?
|
||||
public var username: String?
|
||||
public var firstName: String?
|
||||
public var lastName: String?
|
||||
public var email: String?
|
||||
public var password: String?
|
||||
public var phone: String?
|
||||
/** User Status */
|
||||
public var userStatus: Int32?
|
||||
|
||||
public init() {}
|
||||
|
||||
// MARK: JSONEncodable
|
||||
func encodeToJSON() -> AnyObject {
|
||||
var nillableDictionary = [String:AnyObject?]()
|
||||
nillableDictionary["id"] = self.id?.encodeToJSON()
|
||||
nillableDictionary["username"] = self.username
|
||||
nillableDictionary["firstName"] = self.firstName
|
||||
nillableDictionary["lastName"] = self.lastName
|
||||
nillableDictionary["email"] = self.email
|
||||
nillableDictionary["password"] = self.password
|
||||
nillableDictionary["phone"] = self.phone
|
||||
nillableDictionary["userStatus"] = self.userStatus?.encodeToJSON()
|
||||
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
|
||||
return dictionary
|
||||
}
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
use_frameworks!
|
||||
source 'https://github.com/CocoaPods/Specs.git'
|
||||
|
||||
target 'SwaggerClient' do
|
||||
pod "PetstoreClient", :path => "../"
|
||||
|
||||
target 'SwaggerClientTests' do
|
||||
inherit! :search_paths
|
||||
end
|
||||
end
|
||||
|
@ -0,0 +1,41 @@
|
||||
PODS:
|
||||
- Alamofire (3.1.5)
|
||||
- OMGHTTPURLRQ (3.1.1):
|
||||
- OMGHTTPURLRQ/RQ (= 3.1.1)
|
||||
- OMGHTTPURLRQ/FormURLEncode (3.1.1)
|
||||
- OMGHTTPURLRQ/RQ (3.1.1):
|
||||
- OMGHTTPURLRQ/FormURLEncode
|
||||
- OMGHTTPURLRQ/UserAgent
|
||||
- OMGHTTPURLRQ/UserAgent (3.1.1)
|
||||
- PetstoreClient (0.0.1):
|
||||
- Alamofire (~> 3.1.5)
|
||||
- PromiseKit (~> 3.1.1)
|
||||
- PromiseKit (3.1.1):
|
||||
- PromiseKit/Foundation (= 3.1.1)
|
||||
- PromiseKit/QuartzCore (= 3.1.1)
|
||||
- PromiseKit/UIKit (= 3.1.1)
|
||||
- PromiseKit/CorePromise (3.1.1)
|
||||
- PromiseKit/Foundation (3.1.1):
|
||||
- OMGHTTPURLRQ (~> 3.1.0)
|
||||
- PromiseKit/CorePromise
|
||||
- PromiseKit/QuartzCore (3.1.1):
|
||||
- PromiseKit/CorePromise
|
||||
- PromiseKit/UIKit (3.1.1):
|
||||
- PromiseKit/CorePromise
|
||||
|
||||
DEPENDENCIES:
|
||||
- PetstoreClient (from `../`)
|
||||
|
||||
EXTERNAL SOURCES:
|
||||
PetstoreClient:
|
||||
:path: ../
|
||||
|
||||
SPEC CHECKSUMS:
|
||||
Alamofire: 5f730ba29fd113b7ddd71c1e65d0c630acf5d7b0
|
||||
OMGHTTPURLRQ: 633f98ee745aeda02345935a52eec1784cddb589
|
||||
PetstoreClient: efd495da2b7a6f3e798752702d59f96e306dbace
|
||||
PromiseKit: 4e8127c22a9b29d1b44958ab2ec762ea6115cbfb
|
||||
|
||||
PODFILE CHECKSUM: 84472aca2a88b7f7ed9fcd63e9f5fdb5ad4aab94
|
||||
|
||||
COCOAPODS: 1.0.0
|
19
samples/client/petstore/swift-promisekit/SwaggerClientTests/Pods/Alamofire/LICENSE
generated
Normal file
19
samples/client/petstore/swift-promisekit/SwaggerClientTests/Pods/Alamofire/LICENSE
generated
Normal file
@ -0,0 +1,19 @@
|
||||
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.
|
1149
samples/client/petstore/swift-promisekit/SwaggerClientTests/Pods/Alamofire/README.md
generated
Normal file
1149
samples/client/petstore/swift-promisekit/SwaggerClientTests/Pods/Alamofire/README.md
generated
Normal file
File diff suppressed because it is too large
Load Diff
368
samples/client/petstore/swift-promisekit/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift
generated
Normal file
368
samples/client/petstore/swift-promisekit/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift
generated
Normal file
@ -0,0 +1,368 @@
|
||||
// Alamofire.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
|
||||
|
||||
// MARK: - URLStringConvertible
|
||||
|
||||
/**
|
||||
Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to
|
||||
construct URL requests.
|
||||
*/
|
||||
public protocol URLStringConvertible {
|
||||
/**
|
||||
A URL that conforms to RFC 2396.
|
||||
|
||||
Methods accepting a `URLStringConvertible` type parameter parse it according to RFCs 1738 and 1808.
|
||||
|
||||
See https://tools.ietf.org/html/rfc2396
|
||||
See https://tools.ietf.org/html/rfc1738
|
||||
See https://tools.ietf.org/html/rfc1808
|
||||
*/
|
||||
var URLString: String { get }
|
||||
}
|
||||
|
||||
extension String: URLStringConvertible {
|
||||
public var URLString: String {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
extension NSURL: URLStringConvertible {
|
||||
public var URLString: String {
|
||||
return absoluteString
|
||||
}
|
||||
}
|
||||
|
||||
extension NSURLComponents: URLStringConvertible {
|
||||
public var URLString: String {
|
||||
return URL!.URLString
|
||||
}
|
||||
}
|
||||
|
||||
extension NSURLRequest: URLStringConvertible {
|
||||
public var URLString: String {
|
||||
return URL!.URLString
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - URLRequestConvertible
|
||||
|
||||
/**
|
||||
Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests.
|
||||
*/
|
||||
public protocol URLRequestConvertible {
|
||||
/// The URL request.
|
||||
var URLRequest: NSMutableURLRequest { get }
|
||||
}
|
||||
|
||||
extension NSURLRequest: URLRequestConvertible {
|
||||
public var URLRequest: NSMutableURLRequest {
|
||||
return self.mutableCopy() as! NSMutableURLRequest
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Convenience
|
||||
|
||||
func URLRequest(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
headers: [String: String]? = nil)
|
||||
-> NSMutableURLRequest
|
||||
{
|
||||
let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString)!)
|
||||
mutableURLRequest.HTTPMethod = method.rawValue
|
||||
|
||||
if let headers = headers {
|
||||
for (headerField, headerValue) in headers {
|
||||
mutableURLRequest.setValue(headerValue, forHTTPHeaderField: headerField)
|
||||
}
|
||||
}
|
||||
|
||||
return mutableURLRequest
|
||||
}
|
||||
|
||||
// MARK: - Request Methods
|
||||
|
||||
/**
|
||||
Creates a request using the shared manager instance for the specified method, URL string, parameters, and
|
||||
parameter encoding.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter parameters: The parameters. `nil` by default.
|
||||
- parameter encoding: The parameter encoding. `.URL` by default.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
|
||||
- returns: The created request.
|
||||
*/
|
||||
public func request(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
parameters: [String: AnyObject]? = nil,
|
||||
encoding: ParameterEncoding = .URL,
|
||||
headers: [String: String]? = nil)
|
||||
-> Request
|
||||
{
|
||||
return Manager.sharedInstance.request(
|
||||
method,
|
||||
URLString,
|
||||
parameters: parameters,
|
||||
encoding: encoding,
|
||||
headers: headers
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a request using the shared manager instance for the specified URL request.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter URLRequest: The URL request
|
||||
|
||||
- returns: The created request.
|
||||
*/
|
||||
public func request(URLRequest: URLRequestConvertible) -> Request {
|
||||
return Manager.sharedInstance.request(URLRequest.URLRequest)
|
||||
}
|
||||
|
||||
// MARK: - Upload Methods
|
||||
|
||||
// MARK: File
|
||||
|
||||
/**
|
||||
Creates an upload request using the shared manager instance for the specified method, URL string, and file.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter file: The file to upload.
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
headers: [String: String]? = nil,
|
||||
file: NSURL)
|
||||
-> Request
|
||||
{
|
||||
return Manager.sharedInstance.upload(method, URLString, headers: headers, file: file)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates an upload request using the shared manager instance for the specified URL request and file.
|
||||
|
||||
- parameter URLRequest: The URL request.
|
||||
- parameter file: The file to upload.
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request {
|
||||
return Manager.sharedInstance.upload(URLRequest, file: file)
|
||||
}
|
||||
|
||||
// MARK: Data
|
||||
|
||||
/**
|
||||
Creates an upload request using the shared manager instance for the specified method, URL string, and data.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter data: The data to upload.
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
headers: [String: String]? = nil,
|
||||
data: NSData)
|
||||
-> Request
|
||||
{
|
||||
return Manager.sharedInstance.upload(method, URLString, headers: headers, data: data)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates an upload request using the shared manager instance for the specified URL request and data.
|
||||
|
||||
- parameter URLRequest: The URL request.
|
||||
- parameter data: The data to upload.
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request {
|
||||
return Manager.sharedInstance.upload(URLRequest, data: data)
|
||||
}
|
||||
|
||||
// MARK: Stream
|
||||
|
||||
/**
|
||||
Creates an upload request using the shared manager instance for the specified method, URL string, and stream.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter stream: The stream to upload.
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
headers: [String: String]? = nil,
|
||||
stream: NSInputStream)
|
||||
-> Request
|
||||
{
|
||||
return Manager.sharedInstance.upload(method, URLString, headers: headers, stream: stream)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates an upload request using the shared manager instance for the specified URL request and stream.
|
||||
|
||||
- parameter URLRequest: The URL request.
|
||||
- parameter stream: The stream to upload.
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request {
|
||||
return Manager.sharedInstance.upload(URLRequest, stream: stream)
|
||||
}
|
||||
|
||||
// MARK: MultipartFormData
|
||||
|
||||
/**
|
||||
Creates an upload request using the shared manager instance for the specified method and URL string.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
|
||||
- parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
|
||||
`MultipartFormDataEncodingMemoryThreshold` by default.
|
||||
- parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
|
||||
*/
|
||||
public func upload(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
headers: [String: String]? = nil,
|
||||
multipartFormData: MultipartFormData -> Void,
|
||||
encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold,
|
||||
encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?)
|
||||
{
|
||||
return Manager.sharedInstance.upload(
|
||||
method,
|
||||
URLString,
|
||||
headers: headers,
|
||||
multipartFormData: multipartFormData,
|
||||
encodingMemoryThreshold: encodingMemoryThreshold,
|
||||
encodingCompletion: encodingCompletion
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates an upload request using the shared manager instance for the specified method and URL string.
|
||||
|
||||
- parameter URLRequest: The URL request.
|
||||
- parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
|
||||
- parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
|
||||
`MultipartFormDataEncodingMemoryThreshold` by default.
|
||||
- parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
|
||||
*/
|
||||
public func upload(
|
||||
URLRequest: URLRequestConvertible,
|
||||
multipartFormData: MultipartFormData -> Void,
|
||||
encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold,
|
||||
encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?)
|
||||
{
|
||||
return Manager.sharedInstance.upload(
|
||||
URLRequest,
|
||||
multipartFormData: multipartFormData,
|
||||
encodingMemoryThreshold: encodingMemoryThreshold,
|
||||
encodingCompletion: encodingCompletion
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Download Methods
|
||||
|
||||
// MARK: URL Request
|
||||
|
||||
/**
|
||||
Creates a download request using the shared manager instance for the specified method and URL string.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter parameters: The parameters. `nil` by default.
|
||||
- parameter encoding: The parameter encoding. `.URL` by default.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter destination: The closure used to determine the destination of the downloaded file.
|
||||
|
||||
- returns: The created download request.
|
||||
*/
|
||||
public func download(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
parameters: [String: AnyObject]? = nil,
|
||||
encoding: ParameterEncoding = .URL,
|
||||
headers: [String: String]? = nil,
|
||||
destination: Request.DownloadFileDestination)
|
||||
-> Request
|
||||
{
|
||||
return Manager.sharedInstance.download(
|
||||
method,
|
||||
URLString,
|
||||
parameters: parameters,
|
||||
encoding: encoding,
|
||||
headers: headers,
|
||||
destination: destination
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a download request using the shared manager instance for the specified URL request.
|
||||
|
||||
- parameter URLRequest: The URL request.
|
||||
- parameter destination: The closure used to determine the destination of the downloaded file.
|
||||
|
||||
- returns: The created download request.
|
||||
*/
|
||||
public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request {
|
||||
return Manager.sharedInstance.download(URLRequest, destination: destination)
|
||||
}
|
||||
|
||||
// MARK: Resume Data
|
||||
|
||||
/**
|
||||
Creates a request using the shared manager instance for downloading from the resume data produced from a
|
||||
previous request cancellation.
|
||||
|
||||
- parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask`
|
||||
when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional
|
||||
information.
|
||||
- parameter destination: The closure used to determine the destination of the downloaded file.
|
||||
|
||||
- returns: The created download request.
|
||||
*/
|
||||
public func download(resumeData data: NSData, destination: Request.DownloadFileDestination) -> Request {
|
||||
return Manager.sharedInstance.download(data, destination: destination)
|
||||
}
|
244
samples/client/petstore/swift-promisekit/SwaggerClientTests/Pods/Alamofire/Source/Download.swift
generated
Normal file
244
samples/client/petstore/swift-promisekit/SwaggerClientTests/Pods/Alamofire/Source/Download.swift
generated
Normal file
@ -0,0 +1,244 @@
|
||||
// Download.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
|
||||
|
||||
extension Manager {
|
||||
private enum Downloadable {
|
||||
case Request(NSURLRequest)
|
||||
case ResumeData(NSData)
|
||||
}
|
||||
|
||||
private func download(downloadable: Downloadable, destination: Request.DownloadFileDestination) -> Request {
|
||||
var downloadTask: NSURLSessionDownloadTask!
|
||||
|
||||
switch downloadable {
|
||||
case .Request(let request):
|
||||
dispatch_sync(queue) {
|
||||
downloadTask = self.session.downloadTaskWithRequest(request)
|
||||
}
|
||||
case .ResumeData(let resumeData):
|
||||
dispatch_sync(queue) {
|
||||
downloadTask = self.session.downloadTaskWithResumeData(resumeData)
|
||||
}
|
||||
}
|
||||
|
||||
let request = Request(session: session, task: downloadTask)
|
||||
|
||||
if let downloadDelegate = request.delegate as? Request.DownloadTaskDelegate {
|
||||
downloadDelegate.downloadTaskDidFinishDownloadingToURL = { session, downloadTask, URL in
|
||||
return destination(URL, downloadTask.response as! NSHTTPURLResponse)
|
||||
}
|
||||
}
|
||||
|
||||
delegate[request.delegate.task] = request.delegate
|
||||
|
||||
if startRequestsImmediately {
|
||||
request.resume()
|
||||
}
|
||||
|
||||
return request
|
||||
}
|
||||
|
||||
// MARK: Request
|
||||
|
||||
/**
|
||||
Creates a download request for the specified method, URL string, parameters, parameter encoding, headers
|
||||
and destination.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter parameters: The parameters. `nil` by default.
|
||||
- parameter encoding: The parameter encoding. `.URL` by default.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter destination: The closure used to determine the destination of the downloaded file.
|
||||
|
||||
- returns: The created download request.
|
||||
*/
|
||||
public func download(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
parameters: [String: AnyObject]? = nil,
|
||||
encoding: ParameterEncoding = .URL,
|
||||
headers: [String: String]? = nil,
|
||||
destination: Request.DownloadFileDestination)
|
||||
-> Request
|
||||
{
|
||||
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
|
||||
let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0
|
||||
|
||||
return download(encodedURLRequest, destination: destination)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a request for downloading from the specified URL request.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter URLRequest: The URL request
|
||||
- parameter destination: The closure used to determine the destination of the downloaded file.
|
||||
|
||||
- returns: The created download request.
|
||||
*/
|
||||
public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request {
|
||||
return download(.Request(URLRequest.URLRequest), destination: destination)
|
||||
}
|
||||
|
||||
// MARK: Resume Data
|
||||
|
||||
/**
|
||||
Creates a request for downloading from the resume data produced from a previous request cancellation.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask`
|
||||
when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for
|
||||
additional information.
|
||||
- parameter destination: The closure used to determine the destination of the downloaded file.
|
||||
|
||||
- returns: The created download request.
|
||||
*/
|
||||
public func download(resumeData: NSData, destination: Request.DownloadFileDestination) -> Request {
|
||||
return download(.ResumeData(resumeData), destination: destination)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
extension Request {
|
||||
/**
|
||||
A closure executed once a request has successfully completed in order to determine where to move the temporary
|
||||
file written to during the download process. The closure takes two arguments: the temporary file URL and the URL
|
||||
response, and returns a single argument: the file URL where the temporary file should be moved.
|
||||
*/
|
||||
public typealias DownloadFileDestination = (NSURL, NSHTTPURLResponse) -> NSURL
|
||||
|
||||
/**
|
||||
Creates a download file destination closure which uses the default file manager to move the temporary file to a
|
||||
file URL in the first available directory with the specified search path directory and search path domain mask.
|
||||
|
||||
- parameter directory: The search path directory. `.DocumentDirectory` by default.
|
||||
- parameter domain: The search path domain mask. `.UserDomainMask` by default.
|
||||
|
||||
- returns: A download file destination closure.
|
||||
*/
|
||||
public class func suggestedDownloadDestination(
|
||||
directory directory: NSSearchPathDirectory = .DocumentDirectory,
|
||||
domain: NSSearchPathDomainMask = .UserDomainMask)
|
||||
-> DownloadFileDestination
|
||||
{
|
||||
return { temporaryURL, response -> NSURL in
|
||||
let directoryURLs = NSFileManager.defaultManager().URLsForDirectory(directory, inDomains: domain)
|
||||
|
||||
if !directoryURLs.isEmpty {
|
||||
return directoryURLs[0].URLByAppendingPathComponent(response.suggestedFilename!)
|
||||
}
|
||||
|
||||
return temporaryURL
|
||||
}
|
||||
}
|
||||
|
||||
/// The resume data of the underlying download task if available after a failure.
|
||||
public var resumeData: NSData? {
|
||||
var data: NSData?
|
||||
|
||||
if let delegate = delegate as? DownloadTaskDelegate {
|
||||
data = delegate.resumeData
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
// MARK: - DownloadTaskDelegate
|
||||
|
||||
class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate {
|
||||
var downloadTask: NSURLSessionDownloadTask? { return task as? NSURLSessionDownloadTask }
|
||||
var downloadProgress: ((Int64, Int64, Int64) -> Void)?
|
||||
|
||||
var resumeData: NSData?
|
||||
override var data: NSData? { return resumeData }
|
||||
|
||||
// MARK: - NSURLSessionDownloadDelegate
|
||||
|
||||
// MARK: Override Closures
|
||||
|
||||
var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> NSURL)?
|
||||
var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
|
||||
var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)?
|
||||
|
||||
// MARK: Delegate Methods
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
downloadTask: NSURLSessionDownloadTask,
|
||||
didFinishDownloadingToURL location: NSURL)
|
||||
{
|
||||
if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL {
|
||||
do {
|
||||
let destination = downloadTaskDidFinishDownloadingToURL(session, downloadTask, location)
|
||||
try NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination)
|
||||
} catch {
|
||||
self.error = error as NSError
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
downloadTask: NSURLSessionDownloadTask,
|
||||
didWriteData bytesWritten: Int64,
|
||||
totalBytesWritten: Int64,
|
||||
totalBytesExpectedToWrite: Int64)
|
||||
{
|
||||
if let downloadTaskDidWriteData = downloadTaskDidWriteData {
|
||||
downloadTaskDidWriteData(
|
||||
session,
|
||||
downloadTask,
|
||||
bytesWritten,
|
||||
totalBytesWritten,
|
||||
totalBytesExpectedToWrite
|
||||
)
|
||||
} else {
|
||||
progress.totalUnitCount = totalBytesExpectedToWrite
|
||||
progress.completedUnitCount = totalBytesWritten
|
||||
|
||||
downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
|
||||
}
|
||||
}
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
downloadTask: NSURLSessionDownloadTask,
|
||||
didResumeAtOffset fileOffset: Int64,
|
||||
expectedTotalBytes: Int64)
|
||||
{
|
||||
if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
|
||||
downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
|
||||
} else {
|
||||
progress.totalUnitCount = expectedTotalBytes
|
||||
progress.completedUnitCount = fileOffset
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
66
samples/client/petstore/swift-promisekit/SwaggerClientTests/Pods/Alamofire/Source/Error.swift
generated
Normal file
66
samples/client/petstore/swift-promisekit/SwaggerClientTests/Pods/Alamofire/Source/Error.swift
generated
Normal file
@ -0,0 +1,66 @@
|
||||
// Error.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
|
||||
|
||||
/// The `Error` struct provides a convenience for creating custom Alamofire NSErrors.
|
||||
public struct Error {
|
||||
/// The domain used for creating all Alamofire errors.
|
||||
public static let Domain = "com.alamofire.error"
|
||||
|
||||
/// The custom error codes generated by Alamofire.
|
||||
public enum Code: Int {
|
||||
case InputStreamReadFailed = -6000
|
||||
case OutputStreamWriteFailed = -6001
|
||||
case ContentTypeValidationFailed = -6002
|
||||
case StatusCodeValidationFailed = -6003
|
||||
case DataSerializationFailed = -6004
|
||||
case StringSerializationFailed = -6005
|
||||
case JSONSerializationFailed = -6006
|
||||
case PropertyListSerializationFailed = -6007
|
||||
}
|
||||
|
||||
/**
|
||||
Creates an `NSError` with the given error code and failure reason.
|
||||
|
||||
- parameter code: The error code.
|
||||
- parameter failureReason: The failure reason.
|
||||
|
||||
- returns: An `NSError` with the given error code and failure reason.
|
||||
*/
|
||||
public static func errorWithCode(code: Code, failureReason: String) -> NSError {
|
||||
return errorWithCode(code.rawValue, failureReason: failureReason)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates an `NSError` with the given error code and failure reason.
|
||||
|
||||
- parameter code: The error code.
|
||||
- parameter failureReason: The failure reason.
|
||||
|
||||
- returns: An `NSError` with the given error code and failure reason.
|
||||
*/
|
||||
public static func errorWithCode(code: Int, failureReason: String) -> NSError {
|
||||
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
|
||||
return NSError(domain: Domain, code: code, userInfo: userInfo)
|
||||
}
|
||||
}
|
693
samples/client/petstore/swift-promisekit/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift
generated
Normal file
693
samples/client/petstore/swift-promisekit/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift
generated
Normal file
@ -0,0 +1,693 @@
|
||||
// Manager.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 creating and managing `Request` objects, as well as their underlying `NSURLSession`.
|
||||
*/
|
||||
public class Manager {
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
/**
|
||||
A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly
|
||||
for any ad hoc requests.
|
||||
*/
|
||||
public static let sharedInstance: Manager = {
|
||||
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
|
||||
configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders
|
||||
|
||||
return Manager(configuration: configuration)
|
||||
}()
|
||||
|
||||
/**
|
||||
Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers.
|
||||
*/
|
||||
public static let defaultHTTPHeaders: [String: String] = {
|
||||
// Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3
|
||||
let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5"
|
||||
|
||||
// Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5
|
||||
let acceptLanguage = NSLocale.preferredLanguages().prefix(6).enumerate().map { index, languageCode in
|
||||
let quality = 1.0 - (Double(index) * 0.1)
|
||||
return "\(languageCode);q=\(quality)"
|
||||
}.joinWithSeparator(", ")
|
||||
|
||||
// User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3
|
||||
let userAgent: String = {
|
||||
if let info = NSBundle.mainBundle().infoDictionary {
|
||||
let executable: AnyObject = info[kCFBundleExecutableKey as String] ?? "Unknown"
|
||||
let bundle: AnyObject = info[kCFBundleIdentifierKey as String] ?? "Unknown"
|
||||
let version: AnyObject = info[kCFBundleVersionKey as String] ?? "Unknown"
|
||||
let os: AnyObject = NSProcessInfo.processInfo().operatingSystemVersionString ?? "Unknown"
|
||||
|
||||
var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString
|
||||
let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString
|
||||
|
||||
if CFStringTransform(mutableUserAgent, UnsafeMutablePointer<CFRange>(nil), transform, false) {
|
||||
return mutableUserAgent as String
|
||||
}
|
||||
}
|
||||
|
||||
return "Alamofire"
|
||||
}()
|
||||
|
||||
return [
|
||||
"Accept-Encoding": acceptEncoding,
|
||||
"Accept-Language": acceptLanguage,
|
||||
"User-Agent": userAgent
|
||||
]
|
||||
}()
|
||||
|
||||
let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL)
|
||||
|
||||
/// The underlying session.
|
||||
public let session: NSURLSession
|
||||
|
||||
/// The session delegate handling all the task and session delegate callbacks.
|
||||
public let delegate: SessionDelegate
|
||||
|
||||
/// Whether to start requests immediately after being constructed. `true` by default.
|
||||
public var startRequestsImmediately: Bool = true
|
||||
|
||||
/**
|
||||
The background completion handler closure provided by the UIApplicationDelegate
|
||||
`application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background
|
||||
completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation
|
||||
will automatically call the handler.
|
||||
|
||||
If you need to handle your own events before the handler is called, then you need to override the
|
||||
SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished.
|
||||
|
||||
`nil` by default.
|
||||
*/
|
||||
public var backgroundCompletionHandler: (() -> Void)?
|
||||
|
||||
// MARK: - Lifecycle
|
||||
|
||||
/**
|
||||
Initializes the `Manager` instance with the specified configuration, delegate and server trust policy.
|
||||
|
||||
- parameter configuration: The configuration used to construct the managed session.
|
||||
`NSURLSessionConfiguration.defaultSessionConfiguration()` by default.
|
||||
- parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by
|
||||
default.
|
||||
- parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
|
||||
challenges. `nil` by default.
|
||||
|
||||
- returns: The new `Manager` instance.
|
||||
*/
|
||||
public init(
|
||||
configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration(),
|
||||
delegate: SessionDelegate = SessionDelegate(),
|
||||
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
|
||||
{
|
||||
self.delegate = delegate
|
||||
self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
|
||||
|
||||
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
|
||||
}
|
||||
|
||||
/**
|
||||
Initializes the `Manager` instance with the specified session, delegate and server trust policy.
|
||||
|
||||
- parameter session: The URL session.
|
||||
- parameter delegate: The delegate of the URL session. Must equal the URL session's delegate.
|
||||
- parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
|
||||
challenges. `nil` by default.
|
||||
|
||||
- returns: The new `Manager` instance if the URL session's delegate matches the delegate parameter.
|
||||
*/
|
||||
public init?(
|
||||
session: NSURLSession,
|
||||
delegate: SessionDelegate,
|
||||
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
|
||||
{
|
||||
self.delegate = delegate
|
||||
self.session = session
|
||||
|
||||
guard delegate === session.delegate else { return nil }
|
||||
|
||||
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
|
||||
}
|
||||
|
||||
private func commonInit(serverTrustPolicyManager serverTrustPolicyManager: ServerTrustPolicyManager?) {
|
||||
session.serverTrustPolicyManager = serverTrustPolicyManager
|
||||
|
||||
delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in
|
||||
guard let strongSelf = self else { return }
|
||||
dispatch_async(dispatch_get_main_queue()) { strongSelf.backgroundCompletionHandler?() }
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
session.invalidateAndCancel()
|
||||
}
|
||||
|
||||
// MARK: - Request
|
||||
|
||||
/**
|
||||
Creates a request for the specified method, URL string, parameters, parameter encoding and headers.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter parameters: The parameters. `nil` by default.
|
||||
- parameter encoding: The parameter encoding. `.URL` by default.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
|
||||
- returns: The created request.
|
||||
*/
|
||||
public func request(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
parameters: [String: AnyObject]? = nil,
|
||||
encoding: ParameterEncoding = .URL,
|
||||
headers: [String: String]? = nil)
|
||||
-> Request
|
||||
{
|
||||
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
|
||||
let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0
|
||||
return request(encodedURLRequest)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a request for the specified URL request.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter URLRequest: The URL request
|
||||
|
||||
- returns: The created request.
|
||||
*/
|
||||
public func request(URLRequest: URLRequestConvertible) -> Request {
|
||||
var dataTask: NSURLSessionDataTask!
|
||||
dispatch_sync(queue) { dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest) }
|
||||
|
||||
let request = Request(session: session, task: dataTask)
|
||||
delegate[request.delegate.task] = request.delegate
|
||||
|
||||
if startRequestsImmediately {
|
||||
request.resume()
|
||||
}
|
||||
|
||||
return request
|
||||
}
|
||||
|
||||
// MARK: - SessionDelegate
|
||||
|
||||
/**
|
||||
Responsible for handling all delegate callbacks for the underlying session.
|
||||
*/
|
||||
public final class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
|
||||
private var subdelegates: [Int: Request.TaskDelegate] = [:]
|
||||
private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
|
||||
|
||||
subscript(task: NSURLSessionTask) -> Request.TaskDelegate? {
|
||||
get {
|
||||
var subdelegate: Request.TaskDelegate?
|
||||
dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] }
|
||||
|
||||
return subdelegate
|
||||
}
|
||||
|
||||
set {
|
||||
dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Initializes the `SessionDelegate` instance.
|
||||
|
||||
- returns: The new `SessionDelegate` instance.
|
||||
*/
|
||||
public override init() {
|
||||
super.init()
|
||||
}
|
||||
|
||||
// MARK: - NSURLSessionDelegate
|
||||
|
||||
// MARK: Override Closures
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didBecomeInvalidWithError:`.
|
||||
public var sessionDidBecomeInvalidWithError: ((NSURLSession, NSError?) -> Void)?
|
||||
|
||||
/// 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)?
|
||||
|
||||
// MARK: Delegate Methods
|
||||
|
||||
/**
|
||||
Tells the delegate that the session has been invalidated.
|
||||
|
||||
- parameter session: The session object that was invalidated.
|
||||
- parameter error: The error that caused invalidation, or nil if the invalidation was explicit.
|
||||
*/
|
||||
public func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) {
|
||||
sessionDidBecomeInvalidWithError?(session, error)
|
||||
}
|
||||
|
||||
/**
|
||||
Requests credentials from the delegate in response to a session-level authentication request from the remote server.
|
||||
|
||||
- parameter session: The session containing the task that requested authentication.
|
||||
- parameter challenge: An object that contains the request for authentication.
|
||||
- parameter completionHandler: A handler that your delegate method must call providing the disposition and credential.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
|
||||
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void))
|
||||
{
|
||||
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
|
||||
var credential: NSURLCredential?
|
||||
|
||||
if let sessionDidReceiveChallenge = sessionDidReceiveChallenge {
|
||||
(disposition, credential) = sessionDidReceiveChallenge(session, challenge)
|
||||
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
|
||||
let host = challenge.protectionSpace.host
|
||||
|
||||
if let
|
||||
serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host),
|
||||
serverTrust = challenge.protectionSpace.serverTrust
|
||||
{
|
||||
if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) {
|
||||
disposition = .UseCredential
|
||||
credential = NSURLCredential(forTrust: serverTrust)
|
||||
} else {
|
||||
disposition = .CancelAuthenticationChallenge
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
completionHandler(disposition, credential)
|
||||
}
|
||||
|
||||
/**
|
||||
Tells the delegate that all messages enqueued for a session have been delivered.
|
||||
|
||||
- parameter session: The session that no longer has any outstanding requests.
|
||||
*/
|
||||
public func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) {
|
||||
sessionDidFinishEventsForBackgroundURLSession?(session)
|
||||
}
|
||||
|
||||
// MARK: - NSURLSessionTaskDelegate
|
||||
|
||||
// MARK: Override Closures
|
||||
|
||||
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`.
|
||||
public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`.
|
||||
public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`.
|
||||
public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream!)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.
|
||||
public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didCompleteWithError:`.
|
||||
public var taskDidComplete: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)?
|
||||
|
||||
// MARK: Delegate Methods
|
||||
|
||||
/**
|
||||
Tells the delegate that the remote server requested an HTTP redirect.
|
||||
|
||||
- parameter session: The session containing the task whose request resulted in a redirect.
|
||||
- parameter task: The task whose request resulted in a redirect.
|
||||
- parameter response: An object containing the server’s response to the original request.
|
||||
- parameter request: A URL request object filled out with the new location.
|
||||
- parameter completionHandler: A closure that your handler should call with either the value of the request
|
||||
parameter, a modified URL request object, or NULL to refuse the redirect and
|
||||
return the body of the redirect response.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
task: NSURLSessionTask,
|
||||
willPerformHTTPRedirection response: NSHTTPURLResponse,
|
||||
newRequest request: NSURLRequest,
|
||||
completionHandler: ((NSURLRequest?) -> Void))
|
||||
{
|
||||
var redirectRequest: NSURLRequest? = request
|
||||
|
||||
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
|
||||
redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
|
||||
}
|
||||
|
||||
completionHandler(redirectRequest)
|
||||
}
|
||||
|
||||
/**
|
||||
Requests credentials from the delegate in response to an authentication request from the remote server.
|
||||
|
||||
- parameter session: The session containing the task whose request requires authentication.
|
||||
- parameter task: The task whose request requires authentication.
|
||||
- parameter challenge: An object that contains the request for authentication.
|
||||
- parameter completionHandler: A handler that your delegate method must call providing the disposition and credential.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
task: NSURLSessionTask,
|
||||
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
|
||||
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void))
|
||||
{
|
||||
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
|
||||
completionHandler(taskDidReceiveChallenge(session, task, challenge))
|
||||
} else if let delegate = self[task] {
|
||||
delegate.URLSession(
|
||||
session,
|
||||
task: task,
|
||||
didReceiveChallenge: challenge,
|
||||
completionHandler: completionHandler
|
||||
)
|
||||
} else {
|
||||
URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Tells the delegate when a task requires a new request body stream to send to the remote server.
|
||||
|
||||
- parameter session: The session containing the task that needs a new body stream.
|
||||
- parameter task: The task that needs a new body stream.
|
||||
- parameter completionHandler: A completion handler that your delegate method should call with the new body stream.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
task: NSURLSessionTask,
|
||||
needNewBodyStream completionHandler: ((NSInputStream?) -> Void))
|
||||
{
|
||||
if let taskNeedNewBodyStream = taskNeedNewBodyStream {
|
||||
completionHandler(taskNeedNewBodyStream(session, task))
|
||||
} else if let delegate = self[task] {
|
||||
delegate.URLSession(session, task: task, needNewBodyStream: completionHandler)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Periodically informs the delegate of the progress of sending body content to the server.
|
||||
|
||||
- parameter session: The session containing the data task.
|
||||
- parameter task: The data task.
|
||||
- parameter bytesSent: The number of bytes sent since the last time this delegate method was called.
|
||||
- parameter totalBytesSent: The total number of bytes sent so far.
|
||||
- parameter totalBytesExpectedToSend: The expected length of the body data.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
task: NSURLSessionTask,
|
||||
didSendBodyData bytesSent: Int64,
|
||||
totalBytesSent: Int64,
|
||||
totalBytesExpectedToSend: Int64)
|
||||
{
|
||||
if let taskDidSendBodyData = taskDidSendBodyData {
|
||||
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
|
||||
} else if let delegate = self[task] as? Request.UploadTaskDelegate {
|
||||
delegate.URLSession(
|
||||
session,
|
||||
task: task,
|
||||
didSendBodyData: bytesSent,
|
||||
totalBytesSent: totalBytesSent,
|
||||
totalBytesExpectedToSend: totalBytesExpectedToSend
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Tells the delegate that the task finished transferring data.
|
||||
|
||||
- parameter session: The session containing the task whose request finished transferring data.
|
||||
- parameter task: The task whose request finished transferring data.
|
||||
- parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil.
|
||||
*/
|
||||
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
|
||||
if let taskDidComplete = taskDidComplete {
|
||||
taskDidComplete(session, task, error)
|
||||
} else if let delegate = self[task] {
|
||||
delegate.URLSession(session, task: task, didCompleteWithError: error)
|
||||
}
|
||||
|
||||
self[task] = nil
|
||||
}
|
||||
|
||||
// MARK: - NSURLSessionDataDelegate
|
||||
|
||||
// MARK: Override Closures
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`.
|
||||
public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`.
|
||||
public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveData:`.
|
||||
public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`.
|
||||
public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse!)?
|
||||
|
||||
// MARK: Delegate Methods
|
||||
|
||||
/**
|
||||
Tells the delegate that the data task received the initial reply (headers) from the server.
|
||||
|
||||
- parameter session: The session containing the data task that received an initial reply.
|
||||
- parameter dataTask: The data task that received an initial reply.
|
||||
- parameter response: A URL response object populated with headers.
|
||||
- parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a
|
||||
constant to indicate whether the transfer should continue as a data task or
|
||||
should become a download task.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
dataTask: NSURLSessionDataTask,
|
||||
didReceiveResponse response: NSURLResponse,
|
||||
completionHandler: ((NSURLSessionResponseDisposition) -> Void))
|
||||
{
|
||||
var disposition: NSURLSessionResponseDisposition = .Allow
|
||||
|
||||
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
|
||||
disposition = dataTaskDidReceiveResponse(session, dataTask, response)
|
||||
}
|
||||
|
||||
completionHandler(disposition)
|
||||
}
|
||||
|
||||
/**
|
||||
Tells the delegate that the data task was changed to a download task.
|
||||
|
||||
- parameter session: The session containing the task that was replaced by a download task.
|
||||
- parameter dataTask: The data task that was replaced by a download task.
|
||||
- parameter downloadTask: The new download task that replaced the data task.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
dataTask: NSURLSessionDataTask,
|
||||
didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask)
|
||||
{
|
||||
if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask {
|
||||
dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask)
|
||||
} else {
|
||||
let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask)
|
||||
self[downloadTask] = downloadDelegate
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Tells the delegate that the data task has received some of the expected data.
|
||||
|
||||
- parameter session: The session containing the data task that provided data.
|
||||
- parameter dataTask: The data task that provided data.
|
||||
- parameter data: A data object containing the transferred data.
|
||||
*/
|
||||
public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
|
||||
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
|
||||
dataTaskDidReceiveData(session, dataTask, data)
|
||||
} else if let delegate = self[dataTask] as? Request.DataTaskDelegate {
|
||||
delegate.URLSession(session, dataTask: dataTask, didReceiveData: data)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Asks the delegate whether the data (or upload) task should store the response in the cache.
|
||||
|
||||
- parameter session: The session containing the data (or upload) task.
|
||||
- parameter dataTask: The data (or upload) task.
|
||||
- parameter proposedResponse: The default caching behavior. This behavior is determined based on the current
|
||||
caching policy and the values of certain received headers, such as the Pragma
|
||||
and Cache-Control headers.
|
||||
- parameter completionHandler: A block that your handler must call, providing either the original proposed
|
||||
response, a modified version of that response, or NULL to prevent caching the
|
||||
response. If your delegate implements this method, it must call this completion
|
||||
handler; otherwise, your app leaks memory.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
dataTask: NSURLSessionDataTask,
|
||||
willCacheResponse proposedResponse: NSCachedURLResponse,
|
||||
completionHandler: ((NSCachedURLResponse?) -> Void))
|
||||
{
|
||||
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
|
||||
completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse))
|
||||
} else if let delegate = self[dataTask] as? Request.DataTaskDelegate {
|
||||
delegate.URLSession(
|
||||
session,
|
||||
dataTask: dataTask,
|
||||
willCacheResponse: proposedResponse,
|
||||
completionHandler: completionHandler
|
||||
)
|
||||
} else {
|
||||
completionHandler(proposedResponse)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - NSURLSessionDownloadDelegate
|
||||
|
||||
// MARK: Override Closures
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didFinishDownloadingToURL:`.
|
||||
public var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> Void)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`.
|
||||
public var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`.
|
||||
public var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)?
|
||||
|
||||
// MARK: Delegate Methods
|
||||
|
||||
/**
|
||||
Tells the delegate that a download task has finished downloading.
|
||||
|
||||
- parameter session: The session containing the download task that finished.
|
||||
- parameter downloadTask: The download task that finished.
|
||||
- parameter location: A file URL for the temporary file. Because the file is temporary, you must either
|
||||
open the file for reading or move it to a permanent location in your app’s sandbox
|
||||
container directory before returning from this delegate method.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
downloadTask: NSURLSessionDownloadTask,
|
||||
didFinishDownloadingToURL location: NSURL)
|
||||
{
|
||||
if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL {
|
||||
downloadTaskDidFinishDownloadingToURL(session, downloadTask, location)
|
||||
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
|
||||
delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Periodically informs the delegate about the download’s progress.
|
||||
|
||||
- parameter session: The session containing the download task.
|
||||
- parameter downloadTask: The download task.
|
||||
- parameter bytesWritten: The number of bytes transferred since the last time this delegate
|
||||
method was called.
|
||||
- parameter totalBytesWritten: The total number of bytes transferred so far.
|
||||
- parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length
|
||||
header. If this header was not provided, the value is
|
||||
`NSURLSessionTransferSizeUnknown`.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
downloadTask: NSURLSessionDownloadTask,
|
||||
didWriteData bytesWritten: Int64,
|
||||
totalBytesWritten: Int64,
|
||||
totalBytesExpectedToWrite: Int64)
|
||||
{
|
||||
if let downloadTaskDidWriteData = downloadTaskDidWriteData {
|
||||
downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
|
||||
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
|
||||
delegate.URLSession(
|
||||
session,
|
||||
downloadTask: downloadTask,
|
||||
didWriteData: bytesWritten,
|
||||
totalBytesWritten: totalBytesWritten,
|
||||
totalBytesExpectedToWrite: totalBytesExpectedToWrite
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Tells the delegate that the download task has resumed downloading.
|
||||
|
||||
- parameter session: The session containing the download task that finished.
|
||||
- parameter downloadTask: The download task that resumed. See explanation in the discussion.
|
||||
- parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the
|
||||
existing content, then this value is zero. Otherwise, this value is an
|
||||
integer representing the number of bytes on disk that do not need to be
|
||||
retrieved again.
|
||||
- parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header.
|
||||
If this header was not provided, the value is NSURLSessionTransferSizeUnknown.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
downloadTask: NSURLSessionDownloadTask,
|
||||
didResumeAtOffset fileOffset: Int64,
|
||||
expectedTotalBytes: Int64)
|
||||
{
|
||||
if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
|
||||
downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
|
||||
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
|
||||
delegate.URLSession(
|
||||
session,
|
||||
downloadTask: downloadTask,
|
||||
didResumeAtOffset: fileOffset,
|
||||
expectedTotalBytes: expectedTotalBytes
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - NSURLSessionStreamDelegate
|
||||
|
||||
var _streamTaskReadClosed: Any?
|
||||
var _streamTaskWriteClosed: Any?
|
||||
var _streamTaskBetterRouteDiscovered: Any?
|
||||
var _streamTaskDidBecomeInputStream: Any?
|
||||
|
||||
// MARK: - NSObject
|
||||
|
||||
public override func respondsToSelector(selector: Selector) -> Bool {
|
||||
switch selector {
|
||||
case "URLSession:didBecomeInvalidWithError:":
|
||||
return sessionDidBecomeInvalidWithError != nil
|
||||
case "URLSession:didReceiveChallenge:completionHandler:":
|
||||
return sessionDidReceiveChallenge != nil
|
||||
case "URLSessionDidFinishEventsForBackgroundURLSession:":
|
||||
return sessionDidFinishEventsForBackgroundURLSession != nil
|
||||
case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:":
|
||||
return taskWillPerformHTTPRedirection != nil
|
||||
case "URLSession:dataTask:didReceiveResponse:completionHandler:":
|
||||
return dataTaskDidReceiveResponse != nil
|
||||
default:
|
||||
return self.dynamicType.instancesRespondToSelector(selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,669 @@
|
||||
// MultipartFormData.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
|
||||
|
||||
#if os(iOS) || os(watchOS) || os(tvOS)
|
||||
import MobileCoreServices
|
||||
#elseif os(OSX)
|
||||
import CoreServices
|
||||
#endif
|
||||
|
||||
/**
|
||||
Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode
|
||||
multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead
|
||||
to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the
|
||||
data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for
|
||||
larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset.
|
||||
|
||||
For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well
|
||||
and the w3 form documentation.
|
||||
|
||||
- https://www.ietf.org/rfc/rfc2388.txt
|
||||
- https://www.ietf.org/rfc/rfc2045.txt
|
||||
- https://www.w3.org/TR/html401/interact/forms.html#h-17.13
|
||||
*/
|
||||
public class MultipartFormData {
|
||||
|
||||
// MARK: - Helper Types
|
||||
|
||||
struct EncodingCharacters {
|
||||
static let CRLF = "\r\n"
|
||||
}
|
||||
|
||||
struct BoundaryGenerator {
|
||||
enum BoundaryType {
|
||||
case Initial, Encapsulated, Final
|
||||
}
|
||||
|
||||
static func randomBoundary() -> String {
|
||||
return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random())
|
||||
}
|
||||
|
||||
static func boundaryData(boundaryType boundaryType: BoundaryType, boundary: String) -> NSData {
|
||||
let boundaryText: String
|
||||
|
||||
switch boundaryType {
|
||||
case .Initial:
|
||||
boundaryText = "--\(boundary)\(EncodingCharacters.CRLF)"
|
||||
case .Encapsulated:
|
||||
boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)\(EncodingCharacters.CRLF)"
|
||||
case .Final:
|
||||
boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)--\(EncodingCharacters.CRLF)"
|
||||
}
|
||||
|
||||
return boundaryText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
|
||||
}
|
||||
}
|
||||
|
||||
class BodyPart {
|
||||
let headers: [String: String]
|
||||
let bodyStream: NSInputStream
|
||||
let bodyContentLength: UInt64
|
||||
var hasInitialBoundary = false
|
||||
var hasFinalBoundary = false
|
||||
|
||||
init(headers: [String: String], bodyStream: NSInputStream, bodyContentLength: UInt64) {
|
||||
self.headers = headers
|
||||
self.bodyStream = bodyStream
|
||||
self.bodyContentLength = bodyContentLength
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
/// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`.
|
||||
public var contentType: String { return "multipart/form-data; boundary=\(boundary)" }
|
||||
|
||||
/// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries.
|
||||
public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } }
|
||||
|
||||
/// The boundary used to separate the body parts in the encoded form data.
|
||||
public let boundary: String
|
||||
|
||||
private var bodyParts: [BodyPart]
|
||||
private var bodyPartError: NSError?
|
||||
private let streamBufferSize: Int
|
||||
|
||||
// MARK: - Lifecycle
|
||||
|
||||
/**
|
||||
Creates a multipart form data object.
|
||||
|
||||
- returns: The multipart form data object.
|
||||
*/
|
||||
public init() {
|
||||
self.boundary = BoundaryGenerator.randomBoundary()
|
||||
self.bodyParts = []
|
||||
|
||||
/**
|
||||
* The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more
|
||||
* information, please refer to the following article:
|
||||
* - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html
|
||||
*/
|
||||
|
||||
self.streamBufferSize = 1024
|
||||
}
|
||||
|
||||
// MARK: - Body Parts
|
||||
|
||||
/**
|
||||
Creates a body part from the data and appends it to the multipart form data object.
|
||||
|
||||
The body part data will be encoded using the following format:
|
||||
|
||||
- `Content-Disposition: form-data; name=#{name}` (HTTP Header)
|
||||
- Encoded data
|
||||
- Multipart form boundary
|
||||
|
||||
- parameter data: The data to encode into the multipart form data.
|
||||
- parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
|
||||
*/
|
||||
public func appendBodyPart(data data: NSData, name: String) {
|
||||
let headers = contentHeaders(name: name)
|
||||
let stream = NSInputStream(data: data)
|
||||
let length = UInt64(data.length)
|
||||
|
||||
appendBodyPart(stream: stream, length: length, headers: headers)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a body part from the data and appends it to the multipart form data object.
|
||||
|
||||
The body part data will be encoded using the following format:
|
||||
|
||||
- `Content-Disposition: form-data; name=#{name}` (HTTP Header)
|
||||
- `Content-Type: #{generated mimeType}` (HTTP Header)
|
||||
- Encoded data
|
||||
- Multipart form boundary
|
||||
|
||||
- parameter data: The data to encode into the multipart form data.
|
||||
- parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
|
||||
- parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header.
|
||||
*/
|
||||
public func appendBodyPart(data data: NSData, name: String, mimeType: String) {
|
||||
let headers = contentHeaders(name: name, mimeType: mimeType)
|
||||
let stream = NSInputStream(data: data)
|
||||
let length = UInt64(data.length)
|
||||
|
||||
appendBodyPart(stream: stream, length: length, headers: headers)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a body part from the data and appends it to the multipart form data object.
|
||||
|
||||
The body part data will be encoded using the following format:
|
||||
|
||||
- `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
|
||||
- `Content-Type: #{mimeType}` (HTTP Header)
|
||||
- Encoded file data
|
||||
- Multipart form boundary
|
||||
|
||||
- parameter data: The data to encode into the multipart form data.
|
||||
- parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
|
||||
- parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header.
|
||||
- parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header.
|
||||
*/
|
||||
public func appendBodyPart(data data: NSData, name: String, fileName: String, mimeType: String) {
|
||||
let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
|
||||
let stream = NSInputStream(data: data)
|
||||
let length = UInt64(data.length)
|
||||
|
||||
appendBodyPart(stream: stream, length: length, headers: headers)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a body part from the file and appends it to the multipart form data object.
|
||||
|
||||
The body part data will be encoded using the following format:
|
||||
|
||||
- `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header)
|
||||
- `Content-Type: #{generated mimeType}` (HTTP Header)
|
||||
- Encoded file data
|
||||
- Multipart form boundary
|
||||
|
||||
The filename in the `Content-Disposition` HTTP header is generated from the last path component of the
|
||||
`fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the
|
||||
system associated MIME type.
|
||||
|
||||
- parameter fileURL: The URL of the file whose content will be encoded into the multipart form data.
|
||||
- parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header.
|
||||
*/
|
||||
public func appendBodyPart(fileURL fileURL: NSURL, name: String) {
|
||||
if let
|
||||
fileName = fileURL.lastPathComponent,
|
||||
pathExtension = fileURL.pathExtension
|
||||
{
|
||||
let mimeType = mimeTypeForPathExtension(pathExtension)
|
||||
appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType)
|
||||
} else {
|
||||
let failureReason = "Failed to extract the fileName of the provided URL: \(fileURL)"
|
||||
setBodyPartError(Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a body part from the file and appends it to the multipart form data object.
|
||||
|
||||
The body part data will be encoded using the following format:
|
||||
|
||||
- Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header)
|
||||
- Content-Type: #{mimeType} (HTTP Header)
|
||||
- Encoded file data
|
||||
- Multipart form boundary
|
||||
|
||||
- parameter fileURL: The URL of the file whose content will be encoded into the multipart form data.
|
||||
- parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header.
|
||||
- parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header.
|
||||
- parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header.
|
||||
*/
|
||||
public func appendBodyPart(fileURL fileURL: NSURL, name: String, fileName: String, mimeType: String) {
|
||||
let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
|
||||
|
||||
//============================================================
|
||||
// Check 1 - is file URL?
|
||||
//============================================================
|
||||
|
||||
guard fileURL.fileURL else {
|
||||
let failureReason = "The file URL does not point to a file URL: \(fileURL)"
|
||||
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
|
||||
setBodyPartError(error)
|
||||
return
|
||||
}
|
||||
|
||||
//============================================================
|
||||
// Check 2 - is file URL reachable?
|
||||
//============================================================
|
||||
|
||||
var isReachable = true
|
||||
|
||||
if #available(OSX 10.10, *) {
|
||||
isReachable = fileURL.checkPromisedItemIsReachableAndReturnError(nil)
|
||||
}
|
||||
|
||||
guard isReachable else {
|
||||
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)")
|
||||
setBodyPartError(error)
|
||||
return
|
||||
}
|
||||
|
||||
//============================================================
|
||||
// Check 3 - is file URL a directory?
|
||||
//============================================================
|
||||
|
||||
var isDirectory: ObjCBool = false
|
||||
|
||||
guard let
|
||||
path = fileURL.path
|
||||
where NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) && !isDirectory else
|
||||
{
|
||||
let failureReason = "The file URL is a directory, not a file: \(fileURL)"
|
||||
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
|
||||
setBodyPartError(error)
|
||||
return
|
||||
}
|
||||
|
||||
//============================================================
|
||||
// Check 4 - can the file size be extracted?
|
||||
//============================================================
|
||||
|
||||
var bodyContentLength: UInt64?
|
||||
|
||||
do {
|
||||
if let
|
||||
path = fileURL.path,
|
||||
fileSize = try NSFileManager.defaultManager().attributesOfItemAtPath(path)[NSFileSize] as? NSNumber
|
||||
{
|
||||
bodyContentLength = fileSize.unsignedLongLongValue
|
||||
}
|
||||
} catch {
|
||||
// No-op
|
||||
}
|
||||
|
||||
guard let length = bodyContentLength else {
|
||||
let failureReason = "Could not fetch attributes from the file URL: \(fileURL)"
|
||||
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
|
||||
setBodyPartError(error)
|
||||
return
|
||||
}
|
||||
|
||||
//============================================================
|
||||
// Check 5 - can a stream be created from file URL?
|
||||
//============================================================
|
||||
|
||||
guard let stream = NSInputStream(URL: fileURL) else {
|
||||
let failureReason = "Failed to create an input stream from the file URL: \(fileURL)"
|
||||
let error = Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason)
|
||||
setBodyPartError(error)
|
||||
return
|
||||
}
|
||||
|
||||
appendBodyPart(stream: stream, length: length, headers: headers)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a body part from the stream and appends it to the multipart form data object.
|
||||
|
||||
The body part data will be encoded using the following format:
|
||||
|
||||
- `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
|
||||
- `Content-Type: #{mimeType}` (HTTP Header)
|
||||
- Encoded stream data
|
||||
- Multipart form boundary
|
||||
|
||||
- parameter stream: The input stream to encode in the multipart form data.
|
||||
- parameter length: The content length of the stream.
|
||||
- parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header.
|
||||
- parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header.
|
||||
- parameter mimeType: The MIME type to associate with the stream content in the `Content-Type` HTTP header.
|
||||
*/
|
||||
public func appendBodyPart(
|
||||
stream stream: NSInputStream,
|
||||
length: UInt64,
|
||||
name: String,
|
||||
fileName: String,
|
||||
mimeType: String)
|
||||
{
|
||||
let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
|
||||
appendBodyPart(stream: stream, length: length, headers: headers)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a body part with the headers, stream and length and appends it to the multipart form data object.
|
||||
|
||||
The body part data will be encoded using the following format:
|
||||
|
||||
- HTTP headers
|
||||
- Encoded stream data
|
||||
- Multipart form boundary
|
||||
|
||||
- parameter stream: The input stream to encode in the multipart form data.
|
||||
- parameter length: The content length of the stream.
|
||||
- parameter headers: The HTTP headers for the body part.
|
||||
*/
|
||||
public func appendBodyPart(stream stream: NSInputStream, length: UInt64, headers: [String: String]) {
|
||||
let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length)
|
||||
bodyParts.append(bodyPart)
|
||||
}
|
||||
|
||||
// MARK: - Data Encoding
|
||||
|
||||
/**
|
||||
Encodes all the appended body parts into a single `NSData` object.
|
||||
|
||||
It is important to note that this method will load all the appended body parts into memory all at the same
|
||||
time. This method should only be used when the encoded data will have a small memory footprint. For large data
|
||||
cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method.
|
||||
|
||||
- throws: An `NSError` if encoding encounters an error.
|
||||
|
||||
- returns: The encoded `NSData` if encoding is successful.
|
||||
*/
|
||||
public func encode() throws -> NSData {
|
||||
if let bodyPartError = bodyPartError {
|
||||
throw bodyPartError
|
||||
}
|
||||
|
||||
let encoded = NSMutableData()
|
||||
|
||||
bodyParts.first?.hasInitialBoundary = true
|
||||
bodyParts.last?.hasFinalBoundary = true
|
||||
|
||||
for bodyPart in bodyParts {
|
||||
let encodedData = try encodeBodyPart(bodyPart)
|
||||
encoded.appendData(encodedData)
|
||||
}
|
||||
|
||||
return encoded
|
||||
}
|
||||
|
||||
/**
|
||||
Writes the appended body parts into the given file URL.
|
||||
|
||||
This process is facilitated by reading and writing with input and output streams, respectively. Thus,
|
||||
this approach is very memory efficient and should be used for large body part data.
|
||||
|
||||
- parameter fileURL: The file URL to write the multipart form data into.
|
||||
|
||||
- throws: An `NSError` if encoding encounters an error.
|
||||
*/
|
||||
public func writeEncodedDataToDisk(fileURL: NSURL) throws {
|
||||
if let bodyPartError = bodyPartError {
|
||||
throw bodyPartError
|
||||
}
|
||||
|
||||
if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) {
|
||||
let failureReason = "A file already exists at the given file URL: \(fileURL)"
|
||||
throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
|
||||
} else if !fileURL.fileURL {
|
||||
let failureReason = "The URL does not point to a valid file: \(fileURL)"
|
||||
throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
|
||||
}
|
||||
|
||||
let outputStream: NSOutputStream
|
||||
|
||||
if let possibleOutputStream = NSOutputStream(URL: fileURL, append: false) {
|
||||
outputStream = possibleOutputStream
|
||||
} else {
|
||||
let failureReason = "Failed to create an output stream with the given URL: \(fileURL)"
|
||||
throw Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason)
|
||||
}
|
||||
|
||||
outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
outputStream.open()
|
||||
|
||||
self.bodyParts.first?.hasInitialBoundary = true
|
||||
self.bodyParts.last?.hasFinalBoundary = true
|
||||
|
||||
for bodyPart in self.bodyParts {
|
||||
try writeBodyPart(bodyPart, toOutputStream: outputStream)
|
||||
}
|
||||
|
||||
outputStream.close()
|
||||
outputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
}
|
||||
|
||||
// MARK: - Private - Body Part Encoding
|
||||
|
||||
private func encodeBodyPart(bodyPart: BodyPart) throws -> NSData {
|
||||
let encoded = NSMutableData()
|
||||
|
||||
let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
|
||||
encoded.appendData(initialData)
|
||||
|
||||
let headerData = encodeHeaderDataForBodyPart(bodyPart)
|
||||
encoded.appendData(headerData)
|
||||
|
||||
let bodyStreamData = try encodeBodyStreamDataForBodyPart(bodyPart)
|
||||
encoded.appendData(bodyStreamData)
|
||||
|
||||
if bodyPart.hasFinalBoundary {
|
||||
encoded.appendData(finalBoundaryData())
|
||||
}
|
||||
|
||||
return encoded
|
||||
}
|
||||
|
||||
private func encodeHeaderDataForBodyPart(bodyPart: BodyPart) -> NSData {
|
||||
var headerText = ""
|
||||
|
||||
for (key, value) in bodyPart.headers {
|
||||
headerText += "\(key): \(value)\(EncodingCharacters.CRLF)"
|
||||
}
|
||||
headerText += EncodingCharacters.CRLF
|
||||
|
||||
return headerText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
|
||||
}
|
||||
|
||||
private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) throws -> NSData {
|
||||
let inputStream = bodyPart.bodyStream
|
||||
inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
inputStream.open()
|
||||
|
||||
var error: NSError?
|
||||
let encoded = NSMutableData()
|
||||
|
||||
while inputStream.hasBytesAvailable {
|
||||
var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0)
|
||||
let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
|
||||
|
||||
if inputStream.streamError != nil {
|
||||
error = inputStream.streamError
|
||||
break
|
||||
}
|
||||
|
||||
if bytesRead > 0 {
|
||||
encoded.appendBytes(buffer, length: bytesRead)
|
||||
} else if bytesRead < 0 {
|
||||
let failureReason = "Failed to read from input stream: \(inputStream)"
|
||||
error = Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason)
|
||||
break
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
inputStream.close()
|
||||
inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
|
||||
if let error = error {
|
||||
throw error
|
||||
}
|
||||
|
||||
return encoded
|
||||
}
|
||||
|
||||
// MARK: - Private - Writing Body Part to Output Stream
|
||||
|
||||
private func writeBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
|
||||
try writeInitialBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream)
|
||||
try writeHeaderDataForBodyPart(bodyPart, toOutputStream: outputStream)
|
||||
try writeBodyStreamForBodyPart(bodyPart, toOutputStream: outputStream)
|
||||
try writeFinalBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream)
|
||||
}
|
||||
|
||||
private func writeInitialBoundaryDataForBodyPart(
|
||||
bodyPart: BodyPart,
|
||||
toOutputStream outputStream: NSOutputStream)
|
||||
throws
|
||||
{
|
||||
let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
|
||||
return try writeData(initialData, toOutputStream: outputStream)
|
||||
}
|
||||
|
||||
private func writeHeaderDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
|
||||
let headerData = encodeHeaderDataForBodyPart(bodyPart)
|
||||
return try writeData(headerData, toOutputStream: outputStream)
|
||||
}
|
||||
|
||||
private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
|
||||
let inputStream = bodyPart.bodyStream
|
||||
inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
inputStream.open()
|
||||
|
||||
while inputStream.hasBytesAvailable {
|
||||
var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0)
|
||||
let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
|
||||
|
||||
if let streamError = inputStream.streamError {
|
||||
throw streamError
|
||||
}
|
||||
|
||||
if bytesRead > 0 {
|
||||
if buffer.count != bytesRead {
|
||||
buffer = Array(buffer[0..<bytesRead])
|
||||
}
|
||||
|
||||
try writeBuffer(&buffer, toOutputStream: outputStream)
|
||||
} else if bytesRead < 0 {
|
||||
let failureReason = "Failed to read from input stream: \(inputStream)"
|
||||
throw Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason)
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
inputStream.close()
|
||||
inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
}
|
||||
|
||||
private func writeFinalBoundaryDataForBodyPart(
|
||||
bodyPart: BodyPart,
|
||||
toOutputStream outputStream: NSOutputStream)
|
||||
throws
|
||||
{
|
||||
if bodyPart.hasFinalBoundary {
|
||||
return try writeData(finalBoundaryData(), toOutputStream: outputStream)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Private - Writing Buffered Data to Output Stream
|
||||
|
||||
private func writeData(data: NSData, toOutputStream outputStream: NSOutputStream) throws {
|
||||
var buffer = [UInt8](count: data.length, repeatedValue: 0)
|
||||
data.getBytes(&buffer, length: data.length)
|
||||
|
||||
return try writeBuffer(&buffer, toOutputStream: outputStream)
|
||||
}
|
||||
|
||||
private func writeBuffer(inout buffer: [UInt8], toOutputStream outputStream: NSOutputStream) throws {
|
||||
var bytesToWrite = buffer.count
|
||||
|
||||
while bytesToWrite > 0 {
|
||||
if outputStream.hasSpaceAvailable {
|
||||
let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite)
|
||||
|
||||
if let streamError = outputStream.streamError {
|
||||
throw streamError
|
||||
}
|
||||
|
||||
if bytesWritten < 0 {
|
||||
let failureReason = "Failed to write to output stream: \(outputStream)"
|
||||
throw Error.errorWithCode(.OutputStreamWriteFailed, failureReason: failureReason)
|
||||
}
|
||||
|
||||
bytesToWrite -= bytesWritten
|
||||
|
||||
if bytesToWrite > 0 {
|
||||
buffer = Array(buffer[bytesWritten..<buffer.count])
|
||||
}
|
||||
} else if let streamError = outputStream.streamError {
|
||||
throw streamError
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Private - Mime Type
|
||||
|
||||
private func mimeTypeForPathExtension(pathExtension: String) -> String {
|
||||
if let
|
||||
id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil)?.takeRetainedValue(),
|
||||
contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue()
|
||||
{
|
||||
return contentType as String
|
||||
}
|
||||
|
||||
return "application/octet-stream"
|
||||
}
|
||||
|
||||
// MARK: - Private - Content Headers
|
||||
|
||||
private func contentHeaders(name name: String) -> [String: String] {
|
||||
return ["Content-Disposition": "form-data; name=\"\(name)\""]
|
||||
}
|
||||
|
||||
private func contentHeaders(name name: String, mimeType: String) -> [String: String] {
|
||||
return [
|
||||
"Content-Disposition": "form-data; name=\"\(name)\"",
|
||||
"Content-Type": "\(mimeType)"
|
||||
]
|
||||
}
|
||||
|
||||
private func contentHeaders(name name: String, fileName: String, mimeType: String) -> [String: String] {
|
||||
return [
|
||||
"Content-Disposition": "form-data; name=\"\(name)\"; filename=\"\(fileName)\"",
|
||||
"Content-Type": "\(mimeType)"
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Private - Boundary Encoding
|
||||
|
||||
private func initialBoundaryData() -> NSData {
|
||||
return BoundaryGenerator.boundaryData(boundaryType: .Initial, boundary: boundary)
|
||||
}
|
||||
|
||||
private func encapsulatedBoundaryData() -> NSData {
|
||||
return BoundaryGenerator.boundaryData(boundaryType: .Encapsulated, boundary: boundary)
|
||||
}
|
||||
|
||||
private func finalBoundaryData() -> NSData {
|
||||
return BoundaryGenerator.boundaryData(boundaryType: .Final, boundary: boundary)
|
||||
}
|
||||
|
||||
// MARK: - Private - Errors
|
||||
|
||||
private func setBodyPartError(error: NSError) {
|
||||
if bodyPartError == nil {
|
||||
bodyPartError = error
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,251 @@
|
||||
// ParameterEncoding.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
|
||||
|
||||
/**
|
||||
HTTP method definitions.
|
||||
|
||||
See https://tools.ietf.org/html/rfc7231#section-4.3
|
||||
*/
|
||||
public enum Method: String {
|
||||
case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT
|
||||
}
|
||||
|
||||
// MARK: ParameterEncoding
|
||||
|
||||
/**
|
||||
Used to specify the way in which a set of parameters are applied to a URL request.
|
||||
|
||||
- `URL`: Creates a query string to be set as or appended to any existing URL query for `GET`, `HEAD`,
|
||||
and `DELETE` requests, or set as the body for requests with any other HTTP method. The
|
||||
`Content-Type` HTTP header field of an encoded request with HTTP body is set to
|
||||
`application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification
|
||||
for how to encode collection types, the convention of appending `[]` to the key for array
|
||||
values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested
|
||||
dictionary values (`foo[bar]=baz`).
|
||||
|
||||
- `URLEncodedInURL`: Creates query string to be set as or appended to any existing URL query. Uses the same
|
||||
implementation as the `.URL` case, but always applies the encoded result to the URL.
|
||||
|
||||
- `JSON`: Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is
|
||||
set as the body of the request. The `Content-Type` HTTP header field of an encoded request is
|
||||
set to `application/json`.
|
||||
|
||||
- `PropertyList`: Uses `NSPropertyListSerialization` to create a plist representation of the parameters object,
|
||||
according to the associated format and write options values, which is set as the body of the
|
||||
request. The `Content-Type` HTTP header field of an encoded request is set to
|
||||
`application/x-plist`.
|
||||
|
||||
- `Custom`: Uses the associated closure value to construct a new request given an existing request and
|
||||
parameters.
|
||||
*/
|
||||
public enum ParameterEncoding {
|
||||
case URL
|
||||
case URLEncodedInURL
|
||||
case JSON
|
||||
case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
|
||||
case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?))
|
||||
|
||||
/**
|
||||
Creates a URL request by encoding parameters and applying them onto an existing request.
|
||||
|
||||
- parameter URLRequest: The request to have parameters applied
|
||||
- parameter parameters: The parameters to apply
|
||||
|
||||
- returns: A tuple containing the constructed request and the error that occurred during parameter encoding,
|
||||
if any.
|
||||
*/
|
||||
public func encode(
|
||||
URLRequest: URLRequestConvertible,
|
||||
parameters: [String: AnyObject]?)
|
||||
-> (NSMutableURLRequest, NSError?)
|
||||
{
|
||||
var mutableURLRequest = URLRequest.URLRequest
|
||||
|
||||
guard let parameters = parameters where !parameters.isEmpty else {
|
||||
return (mutableURLRequest, nil)
|
||||
}
|
||||
|
||||
var encodingError: NSError? = nil
|
||||
|
||||
switch self {
|
||||
case .URL, .URLEncodedInURL:
|
||||
func query(parameters: [String: AnyObject]) -> String {
|
||||
var components: [(String, String)] = []
|
||||
|
||||
for key in parameters.keys.sort(<) {
|
||||
let value = parameters[key]!
|
||||
components += queryComponents(key, value)
|
||||
}
|
||||
|
||||
return (components.map { "\($0)=\($1)" } as [String]).joinWithSeparator("&")
|
||||
}
|
||||
|
||||
func encodesParametersInURL(method: Method) -> Bool {
|
||||
switch self {
|
||||
case .URLEncodedInURL:
|
||||
return true
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
switch method {
|
||||
case .GET, .HEAD, .DELETE:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) {
|
||||
if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) {
|
||||
let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
|
||||
URLComponents.percentEncodedQuery = percentEncodedQuery
|
||||
mutableURLRequest.URL = URLComponents.URL
|
||||
}
|
||||
} else {
|
||||
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
|
||||
mutableURLRequest.setValue(
|
||||
"application/x-www-form-urlencoded; charset=utf-8",
|
||||
forHTTPHeaderField: "Content-Type"
|
||||
)
|
||||
}
|
||||
|
||||
mutableURLRequest.HTTPBody = query(parameters).dataUsingEncoding(
|
||||
NSUTF8StringEncoding,
|
||||
allowLossyConversion: false
|
||||
)
|
||||
}
|
||||
case .JSON:
|
||||
do {
|
||||
let options = NSJSONWritingOptions()
|
||||
let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options)
|
||||
|
||||
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
mutableURLRequest.HTTPBody = data
|
||||
} catch {
|
||||
encodingError = error as NSError
|
||||
}
|
||||
case .PropertyList(let format, let options):
|
||||
do {
|
||||
let data = try NSPropertyListSerialization.dataWithPropertyList(
|
||||
parameters,
|
||||
format: format,
|
||||
options: options
|
||||
)
|
||||
mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
|
||||
mutableURLRequest.HTTPBody = data
|
||||
} catch {
|
||||
encodingError = error as NSError
|
||||
}
|
||||
case .Custom(let closure):
|
||||
(mutableURLRequest, encodingError) = closure(mutableURLRequest, parameters)
|
||||
}
|
||||
|
||||
return (mutableURLRequest, encodingError)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion.
|
||||
|
||||
- parameter key: The key of the query component.
|
||||
- parameter value: The value of the query component.
|
||||
|
||||
- returns: The percent-escaped, URL encoded query string components.
|
||||
*/
|
||||
public func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
|
||||
var components: [(String, String)] = []
|
||||
|
||||
if let dictionary = value as? [String: AnyObject] {
|
||||
for (nestedKey, value) in dictionary {
|
||||
components += queryComponents("\(key)[\(nestedKey)]", value)
|
||||
}
|
||||
} else if let array = value as? [AnyObject] {
|
||||
for value in array {
|
||||
components += queryComponents("\(key)[]", value)
|
||||
}
|
||||
} else {
|
||||
components.append((escape(key), escape("\(value)")))
|
||||
}
|
||||
|
||||
return components
|
||||
}
|
||||
|
||||
/**
|
||||
Returns a percent-escaped string following RFC 3986 for a query string key or value.
|
||||
|
||||
RFC 3986 states that the following characters are "reserved" characters.
|
||||
|
||||
- General Delimiters: ":", "#", "[", "]", "@", "?", "/"
|
||||
- Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
|
||||
|
||||
In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
|
||||
query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
|
||||
should be percent-escaped in the query string.
|
||||
|
||||
- parameter string: The string to be percent-escaped.
|
||||
|
||||
- returns: The percent-escaped string.
|
||||
*/
|
||||
public func escape(string: String) -> String {
|
||||
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
|
||||
let subDelimitersToEncode = "!$&'()*+,;="
|
||||
|
||||
let allowedCharacterSet = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet
|
||||
allowedCharacterSet.removeCharactersInString(generalDelimitersToEncode + subDelimitersToEncode)
|
||||
|
||||
var escaped = ""
|
||||
|
||||
//==========================================================================================================
|
||||
//
|
||||
// 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
|
||||
// longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more
|
||||
// info, please refer to:
|
||||
//
|
||||
// - https://github.com/Alamofire/Alamofire/issues/206
|
||||
//
|
||||
//==========================================================================================================
|
||||
|
||||
if #available(iOS 8.3, OSX 10.10, *) {
|
||||
escaped = string.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? string
|
||||
} else {
|
||||
let batchSize = 50
|
||||
var index = string.startIndex
|
||||
|
||||
while index != string.endIndex {
|
||||
let startIndex = index
|
||||
let endIndex = index.advancedBy(batchSize, limit: string.endIndex)
|
||||
let range = Range(start: startIndex, end: endIndex)
|
||||
|
||||
let substring = string.substringWithRange(range)
|
||||
|
||||
escaped += substring.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? substring
|
||||
|
||||
index = endIndex
|
||||
}
|
||||
}
|
||||
|
||||
return escaped
|
||||
}
|
||||
}
|
538
samples/client/petstore/swift-promisekit/SwaggerClientTests/Pods/Alamofire/Source/Request.swift
generated
Normal file
538
samples/client/petstore/swift-promisekit/SwaggerClientTests/Pods/Alamofire/Source/Request.swift
generated
Normal file
@ -0,0 +1,538 @@
|
||||
// Request.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 sending a request and receiving the response and associated data from the server, as well as
|
||||
managing its underlying `NSURLSessionTask`.
|
||||
*/
|
||||
public class Request {
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
/// The delegate for the underlying task.
|
||||
public let delegate: TaskDelegate
|
||||
|
||||
/// The underlying task.
|
||||
public var task: NSURLSessionTask { return delegate.task }
|
||||
|
||||
/// The session belonging to the underlying task.
|
||||
public let session: NSURLSession
|
||||
|
||||
/// The request sent or to be sent to the server.
|
||||
public var request: NSURLRequest? { return task.originalRequest }
|
||||
|
||||
/// The response received from the server, if any.
|
||||
public var response: NSHTTPURLResponse? { return task.response as? NSHTTPURLResponse }
|
||||
|
||||
/// The progress of the request lifecycle.
|
||||
public var progress: NSProgress { return delegate.progress }
|
||||
|
||||
// MARK: - Lifecycle
|
||||
|
||||
init(session: NSURLSession, task: NSURLSessionTask) {
|
||||
self.session = session
|
||||
|
||||
switch task {
|
||||
case is NSURLSessionUploadTask:
|
||||
self.delegate = UploadTaskDelegate(task: task)
|
||||
case is NSURLSessionDataTask:
|
||||
self.delegate = DataTaskDelegate(task: task)
|
||||
case is NSURLSessionDownloadTask:
|
||||
self.delegate = DownloadTaskDelegate(task: task)
|
||||
default:
|
||||
self.delegate = TaskDelegate(task: task)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Authentication
|
||||
|
||||
/**
|
||||
Associates an HTTP Basic credential with the request.
|
||||
|
||||
- parameter user: The user.
|
||||
- parameter password: The password.
|
||||
- parameter persistence: The URL credential persistence. `.ForSession` by default.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func authenticate(
|
||||
user user: String,
|
||||
password: String,
|
||||
persistence: NSURLCredentialPersistence = .ForSession)
|
||||
-> Self
|
||||
{
|
||||
let credential = NSURLCredential(user: user, password: password, persistence: persistence)
|
||||
|
||||
return authenticate(usingCredential: credential)
|
||||
}
|
||||
|
||||
/**
|
||||
Associates a specified credential with the request.
|
||||
|
||||
- parameter credential: The credential.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func authenticate(usingCredential credential: NSURLCredential) -> Self {
|
||||
delegate.credential = credential
|
||||
|
||||
return self
|
||||
}
|
||||
|
||||
// MARK: - Progress
|
||||
|
||||
/**
|
||||
Sets a closure to be called periodically during the lifecycle of the request as data is written to or read
|
||||
from the server.
|
||||
|
||||
- For uploads, the progress closure returns the bytes written, total bytes written, and total bytes expected
|
||||
to write.
|
||||
- For downloads and data tasks, the progress closure returns the bytes read, total bytes read, and total bytes
|
||||
expected to read.
|
||||
|
||||
- parameter closure: The code to be executed periodically during the lifecycle of the request.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self {
|
||||
if let uploadDelegate = delegate as? UploadTaskDelegate {
|
||||
uploadDelegate.uploadProgress = closure
|
||||
} else if let dataDelegate = delegate as? DataTaskDelegate {
|
||||
dataDelegate.dataProgress = closure
|
||||
} else if let downloadDelegate = delegate as? DownloadTaskDelegate {
|
||||
downloadDelegate.downloadProgress = closure
|
||||
}
|
||||
|
||||
return self
|
||||
}
|
||||
|
||||
/**
|
||||
Sets a closure to be called periodically during the lifecycle of the request as data is read from the server.
|
||||
|
||||
This closure returns the bytes most recently received from the server, not including data from previous calls.
|
||||
If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is
|
||||
also important to note that the `response` closure will be called with nil `responseData`.
|
||||
|
||||
- parameter closure: The code to be executed periodically during the lifecycle of the request.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func stream(closure: (NSData -> Void)? = nil) -> Self {
|
||||
if let dataDelegate = delegate as? DataTaskDelegate {
|
||||
dataDelegate.dataStream = closure
|
||||
}
|
||||
|
||||
return self
|
||||
}
|
||||
|
||||
// MARK: - State
|
||||
|
||||
/**
|
||||
Suspends the request.
|
||||
*/
|
||||
public func suspend() {
|
||||
task.suspend()
|
||||
}
|
||||
|
||||
/**
|
||||
Resumes the request.
|
||||
*/
|
||||
public func resume() {
|
||||
task.resume()
|
||||
}
|
||||
|
||||
/**
|
||||
Cancels the request.
|
||||
*/
|
||||
public func cancel() {
|
||||
if let
|
||||
downloadDelegate = delegate as? DownloadTaskDelegate,
|
||||
downloadTask = downloadDelegate.downloadTask
|
||||
{
|
||||
downloadTask.cancelByProducingResumeData { data in
|
||||
downloadDelegate.resumeData = data
|
||||
}
|
||||
} else {
|
||||
task.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - TaskDelegate
|
||||
|
||||
/**
|
||||
The task delegate is responsible for handling all delegate callbacks for the underlying task as well as
|
||||
executing all operations attached to the serial operation queue upon task completion.
|
||||
*/
|
||||
public class TaskDelegate: NSObject {
|
||||
|
||||
/// The serial operation queue used to execute all operations after the task completes.
|
||||
public let queue: NSOperationQueue
|
||||
|
||||
let task: NSURLSessionTask
|
||||
let progress: NSProgress
|
||||
|
||||
var data: NSData? { return nil }
|
||||
var error: NSError?
|
||||
|
||||
var credential: NSURLCredential?
|
||||
|
||||
init(task: NSURLSessionTask) {
|
||||
self.task = task
|
||||
self.progress = NSProgress(totalUnitCount: 0)
|
||||
self.queue = {
|
||||
let operationQueue = NSOperationQueue()
|
||||
operationQueue.maxConcurrentOperationCount = 1
|
||||
operationQueue.suspended = true
|
||||
|
||||
if #available(OSX 10.10, *) {
|
||||
operationQueue.qualityOfService = NSQualityOfService.Utility
|
||||
}
|
||||
|
||||
return operationQueue
|
||||
}()
|
||||
}
|
||||
|
||||
deinit {
|
||||
queue.cancelAllOperations()
|
||||
queue.suspended = false
|
||||
}
|
||||
|
||||
// MARK: - NSURLSessionTaskDelegate
|
||||
|
||||
// MARK: Override Closures
|
||||
|
||||
var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)?
|
||||
var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
|
||||
var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)?
|
||||
var taskDidCompleteWithError: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)?
|
||||
|
||||
// MARK: Delegate Methods
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
task: NSURLSessionTask,
|
||||
willPerformHTTPRedirection response: NSHTTPURLResponse,
|
||||
newRequest request: NSURLRequest,
|
||||
completionHandler: ((NSURLRequest?) -> Void))
|
||||
{
|
||||
var redirectRequest: NSURLRequest? = request
|
||||
|
||||
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
|
||||
redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
|
||||
}
|
||||
|
||||
completionHandler(redirectRequest)
|
||||
}
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
task: NSURLSessionTask,
|
||||
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
|
||||
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void))
|
||||
{
|
||||
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
|
||||
var credential: NSURLCredential?
|
||||
|
||||
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
|
||||
(disposition, credential) = taskDidReceiveChallenge(session, task, challenge)
|
||||
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
|
||||
let host = challenge.protectionSpace.host
|
||||
|
||||
if let
|
||||
serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host),
|
||||
serverTrust = challenge.protectionSpace.serverTrust
|
||||
{
|
||||
if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) {
|
||||
disposition = .UseCredential
|
||||
credential = NSURLCredential(forTrust: serverTrust)
|
||||
} else {
|
||||
disposition = .CancelAuthenticationChallenge
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if challenge.previousFailureCount > 0 {
|
||||
disposition = .CancelAuthenticationChallenge
|
||||
} else {
|
||||
credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)
|
||||
|
||||
if credential != nil {
|
||||
disposition = .UseCredential
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
completionHandler(disposition, credential)
|
||||
}
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
task: NSURLSessionTask,
|
||||
needNewBodyStream completionHandler: ((NSInputStream?) -> Void))
|
||||
{
|
||||
var bodyStream: NSInputStream?
|
||||
|
||||
if let taskNeedNewBodyStream = taskNeedNewBodyStream {
|
||||
bodyStream = taskNeedNewBodyStream(session, task)
|
||||
}
|
||||
|
||||
completionHandler(bodyStream)
|
||||
}
|
||||
|
||||
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
|
||||
if let taskDidCompleteWithError = taskDidCompleteWithError {
|
||||
taskDidCompleteWithError(session, task, error)
|
||||
} else {
|
||||
if let error = error {
|
||||
self.error = error
|
||||
|
||||
if let
|
||||
downloadDelegate = self as? DownloadTaskDelegate,
|
||||
userInfo = error.userInfo as? [String: AnyObject],
|
||||
resumeData = userInfo[NSURLSessionDownloadTaskResumeData] as? NSData
|
||||
{
|
||||
downloadDelegate.resumeData = resumeData
|
||||
}
|
||||
}
|
||||
|
||||
queue.suspended = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - DataTaskDelegate
|
||||
|
||||
class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate {
|
||||
var dataTask: NSURLSessionDataTask? { return task as? NSURLSessionDataTask }
|
||||
|
||||
private var totalBytesReceived: Int64 = 0
|
||||
private var mutableData: NSMutableData
|
||||
override var data: NSData? {
|
||||
if dataStream != nil {
|
||||
return nil
|
||||
} else {
|
||||
return mutableData
|
||||
}
|
||||
}
|
||||
|
||||
private var expectedContentLength: Int64?
|
||||
private var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)?
|
||||
private var dataStream: ((data: NSData) -> Void)?
|
||||
|
||||
override init(task: NSURLSessionTask) {
|
||||
mutableData = NSMutableData()
|
||||
super.init(task: task)
|
||||
}
|
||||
|
||||
// MARK: - NSURLSessionDataDelegate
|
||||
|
||||
// MARK: Override Closures
|
||||
|
||||
var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)?
|
||||
var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)?
|
||||
var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)?
|
||||
var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)?
|
||||
|
||||
// MARK: Delegate Methods
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
dataTask: NSURLSessionDataTask,
|
||||
didReceiveResponse response: NSURLResponse,
|
||||
completionHandler: (NSURLSessionResponseDisposition -> Void))
|
||||
{
|
||||
var disposition: NSURLSessionResponseDisposition = .Allow
|
||||
|
||||
expectedContentLength = response.expectedContentLength
|
||||
|
||||
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
|
||||
disposition = dataTaskDidReceiveResponse(session, dataTask, response)
|
||||
}
|
||||
|
||||
completionHandler(disposition)
|
||||
}
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
dataTask: NSURLSessionDataTask,
|
||||
didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask)
|
||||
{
|
||||
dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask)
|
||||
}
|
||||
|
||||
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
|
||||
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
|
||||
dataTaskDidReceiveData(session, dataTask, data)
|
||||
} else {
|
||||
if let dataStream = dataStream {
|
||||
dataStream(data: data)
|
||||
} else {
|
||||
mutableData.appendData(data)
|
||||
}
|
||||
|
||||
totalBytesReceived += data.length
|
||||
let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
|
||||
|
||||
progress.totalUnitCount = totalBytesExpected
|
||||
progress.completedUnitCount = totalBytesReceived
|
||||
|
||||
dataProgress?(
|
||||
bytesReceived: Int64(data.length),
|
||||
totalBytesReceived: totalBytesReceived,
|
||||
totalBytesExpectedToReceive: totalBytesExpected
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
dataTask: NSURLSessionDataTask,
|
||||
willCacheResponse proposedResponse: NSCachedURLResponse,
|
||||
completionHandler: ((NSCachedURLResponse?) -> Void))
|
||||
{
|
||||
var cachedResponse: NSCachedURLResponse? = proposedResponse
|
||||
|
||||
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
|
||||
cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse)
|
||||
}
|
||||
|
||||
completionHandler(cachedResponse)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
extension Request: CustomStringConvertible {
|
||||
|
||||
/**
|
||||
The textual representation used when written to an output stream, which includes the HTTP method and URL, as
|
||||
well as the response status code if a response has been received.
|
||||
*/
|
||||
public var description: String {
|
||||
var components: [String] = []
|
||||
|
||||
if let HTTPMethod = request?.HTTPMethod {
|
||||
components.append(HTTPMethod)
|
||||
}
|
||||
|
||||
if let URLString = request?.URL?.absoluteString {
|
||||
components.append(URLString)
|
||||
}
|
||||
|
||||
if let response = response {
|
||||
components.append("(\(response.statusCode))")
|
||||
}
|
||||
|
||||
return components.joinWithSeparator(" ")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomDebugStringConvertible
|
||||
|
||||
extension Request: CustomDebugStringConvertible {
|
||||
func cURLRepresentation() -> String {
|
||||
var components = ["$ curl -i"]
|
||||
|
||||
guard let
|
||||
request = self.request,
|
||||
URL = request.URL,
|
||||
host = URL.host
|
||||
else {
|
||||
return "$ curl command could not be created"
|
||||
}
|
||||
|
||||
if let HTTPMethod = request.HTTPMethod where HTTPMethod != "GET" {
|
||||
components.append("-X \(HTTPMethod)")
|
||||
}
|
||||
|
||||
if let credentialStorage = self.session.configuration.URLCredentialStorage {
|
||||
let protectionSpace = NSURLProtectionSpace(
|
||||
host: host,
|
||||
port: URL.port?.integerValue ?? 0,
|
||||
`protocol`: URL.scheme,
|
||||
realm: host,
|
||||
authenticationMethod: NSURLAuthenticationMethodHTTPBasic
|
||||
)
|
||||
|
||||
if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values {
|
||||
for credential in credentials {
|
||||
components.append("-u \(credential.user!):\(credential.password!)")
|
||||
}
|
||||
} else {
|
||||
if let credential = delegate.credential {
|
||||
components.append("-u \(credential.user!):\(credential.password!)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if session.configuration.HTTPShouldSetCookies {
|
||||
if let
|
||||
cookieStorage = session.configuration.HTTPCookieStorage,
|
||||
cookies = cookieStorage.cookiesForURL(URL) where !cookies.isEmpty
|
||||
{
|
||||
let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value ?? String());" }
|
||||
components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"")
|
||||
}
|
||||
}
|
||||
|
||||
if let headerFields = request.allHTTPHeaderFields {
|
||||
for (field, value) in headerFields {
|
||||
switch field {
|
||||
case "Cookie":
|
||||
continue
|
||||
default:
|
||||
components.append("-H \"\(field): \(value)\"")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let additionalHeaders = session.configuration.HTTPAdditionalHeaders {
|
||||
for (field, value) in additionalHeaders {
|
||||
switch field {
|
||||
case "Cookie":
|
||||
continue
|
||||
default:
|
||||
components.append("-H \"\(field): \(value)\"")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let
|
||||
HTTPBodyData = request.HTTPBody,
|
||||
HTTPBody = String(data: HTTPBodyData, encoding: NSUTF8StringEncoding)
|
||||
{
|
||||
let escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
|
||||
components.append("-d \"\(escapedBody)\"")
|
||||
}
|
||||
|
||||
components.append("\"\(URL.absoluteString)\"")
|
||||
|
||||
return components.joinWithSeparator(" \\\n\t")
|
||||
}
|
||||
|
||||
/// The textual representation used when written to an output stream, in the form of a cURL command.
|
||||
public var debugDescription: String {
|
||||
return cURLRepresentation()
|
||||
}
|
||||
}
|
83
samples/client/petstore/swift-promisekit/SwaggerClientTests/Pods/Alamofire/Source/Response.swift
generated
Normal file
83
samples/client/petstore/swift-promisekit/SwaggerClientTests/Pods/Alamofire/Source/Response.swift
generated
Normal file
@ -0,0 +1,83 @@
|
||||
// Response.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
|
||||
|
||||
/// Used to store all response data returned from a completed `Request`.
|
||||
public struct Response<Value, Error: ErrorType> {
|
||||
/// The URL request sent to the server.
|
||||
public let request: NSURLRequest?
|
||||
|
||||
/// The server's response to the URL request.
|
||||
public let response: NSHTTPURLResponse?
|
||||
|
||||
/// The data returned by the server.
|
||||
public let data: NSData?
|
||||
|
||||
/// The result of response serialization.
|
||||
public let result: Result<Value, Error>
|
||||
|
||||
/**
|
||||
Initializes the `Response` instance with the specified URL request, URL response, server data and response
|
||||
serialization result.
|
||||
|
||||
- parameter request: The URL request sent to the server.
|
||||
- parameter response: The server's response to the URL request.
|
||||
- parameter data: The data returned by the server.
|
||||
- parameter result: The result of response serialization.
|
||||
|
||||
- returns: the new `Response` instance.
|
||||
*/
|
||||
public init(request: NSURLRequest?, response: NSHTTPURLResponse?, data: NSData?, result: Result<Value, Error>) {
|
||||
self.request = request
|
||||
self.response = response
|
||||
self.data = data
|
||||
self.result = result
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
extension Response: CustomStringConvertible {
|
||||
/// The textual representation used when written to an output stream, which includes whether the result was a
|
||||
/// success or failure.
|
||||
public var description: String {
|
||||
return result.debugDescription
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomDebugStringConvertible
|
||||
|
||||
extension Response: CustomDebugStringConvertible {
|
||||
/// The debug textual representation used when written to an output stream, which includes the URL request, the URL
|
||||
/// response, the server data and the response serialization result.
|
||||
public var debugDescription: String {
|
||||
var output: [String] = []
|
||||
|
||||
output.append(request != nil ? "[Request]: \(request!)" : "[Request]: nil")
|
||||
output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil")
|
||||
output.append("[Data]: \(data?.length ?? 0) bytes")
|
||||
output.append("[Result]: \(result.debugDescription)")
|
||||
|
||||
return output.joinWithSeparator("\n")
|
||||
}
|
||||
}
|
@ -0,0 +1,355 @@
|
||||
// ResponseSerialization.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
|
||||
|
||||
// MARK: ResponseSerializer
|
||||
|
||||
/**
|
||||
The type in which all response serializers must conform to in order to serialize a response.
|
||||
*/
|
||||
public protocol ResponseSerializerType {
|
||||
/// The type of serialized object to be created by this `ResponseSerializerType`.
|
||||
typealias SerializedObject
|
||||
|
||||
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
|
||||
typealias ErrorObject: ErrorType
|
||||
|
||||
/**
|
||||
A closure used by response handlers that takes a request, response, data and error and returns a result.
|
||||
*/
|
||||
var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<SerializedObject, ErrorObject> { get }
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
/**
|
||||
A generic `ResponseSerializerType` used to serialize a request, response, and data into a serialized object.
|
||||
*/
|
||||
public struct ResponseSerializer<Value, Error: ErrorType>: ResponseSerializerType {
|
||||
/// The type of serialized object to be created by this `ResponseSerializer`.
|
||||
public typealias SerializedObject = Value
|
||||
|
||||
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
|
||||
public typealias ErrorObject = Error
|
||||
|
||||
/**
|
||||
A closure used by response handlers that takes a request, response, data and error and returns a result.
|
||||
*/
|
||||
public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>
|
||||
|
||||
/**
|
||||
Initializes the `ResponseSerializer` instance with the given serialize response closure.
|
||||
|
||||
- parameter serializeResponse: The closure used to serialize the response.
|
||||
|
||||
- returns: The new generic response serializer instance.
|
||||
*/
|
||||
public init(serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>) {
|
||||
self.serializeResponse = serializeResponse
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Default
|
||||
|
||||
extension Request {
|
||||
|
||||
/**
|
||||
Adds a handler to be called once the request has finished.
|
||||
|
||||
- parameter queue: The queue on which the completion handler is dispatched.
|
||||
- parameter completionHandler: The code to be executed once the request has finished.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func response(
|
||||
queue queue: dispatch_queue_t? = nil,
|
||||
completionHandler: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Void)
|
||||
-> Self
|
||||
{
|
||||
delegate.queue.addOperationWithBlock {
|
||||
dispatch_async(queue ?? dispatch_get_main_queue()) {
|
||||
completionHandler(self.request, self.response, self.delegate.data, self.delegate.error)
|
||||
}
|
||||
}
|
||||
|
||||
return self
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler to be called once the request has finished.
|
||||
|
||||
- parameter queue: The queue on which the completion handler is dispatched.
|
||||
- parameter responseSerializer: The response serializer responsible for serializing the request, response,
|
||||
and data.
|
||||
- parameter completionHandler: The code to be executed once the request has finished.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func response<T: ResponseSerializerType>(
|
||||
queue queue: dispatch_queue_t? = nil,
|
||||
responseSerializer: T,
|
||||
completionHandler: Response<T.SerializedObject, T.ErrorObject> -> Void)
|
||||
-> Self
|
||||
{
|
||||
delegate.queue.addOperationWithBlock {
|
||||
let result = responseSerializer.serializeResponse(
|
||||
self.request,
|
||||
self.response,
|
||||
self.delegate.data,
|
||||
self.delegate.error
|
||||
)
|
||||
|
||||
dispatch_async(queue ?? dispatch_get_main_queue()) {
|
||||
let response = Response<T.SerializedObject, T.ErrorObject>(
|
||||
request: self.request,
|
||||
response: self.response,
|
||||
data: self.delegate.data,
|
||||
result: result
|
||||
)
|
||||
|
||||
completionHandler(response)
|
||||
}
|
||||
}
|
||||
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Data
|
||||
|
||||
extension Request {
|
||||
|
||||
/**
|
||||
Creates a response serializer that returns the associated data as-is.
|
||||
|
||||
- returns: A data response serializer.
|
||||
*/
|
||||
public static func dataResponseSerializer() -> ResponseSerializer<NSData, NSError> {
|
||||
return ResponseSerializer { _, response, data, error in
|
||||
guard error == nil else { return .Failure(error!) }
|
||||
|
||||
if let response = response where response.statusCode == 204 { return .Success(NSData()) }
|
||||
|
||||
guard let validData = data else {
|
||||
let failureReason = "Data could not be serialized. Input data was nil."
|
||||
let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
|
||||
return .Failure(error)
|
||||
}
|
||||
|
||||
return .Success(validData)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler to be called once the request has finished.
|
||||
|
||||
- parameter completionHandler: The code to be executed once the request has finished.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func responseData(completionHandler: Response<NSData, NSError> -> Void) -> Self {
|
||||
return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - String
|
||||
|
||||
extension Request {
|
||||
|
||||
/**
|
||||
Creates a response serializer that returns a string initialized from the response data with the specified
|
||||
string encoding.
|
||||
|
||||
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
|
||||
response, falling back to the default HTTP default character set, ISO-8859-1.
|
||||
|
||||
- returns: A string response serializer.
|
||||
*/
|
||||
public static func stringResponseSerializer(
|
||||
var encoding encoding: NSStringEncoding? = nil)
|
||||
-> ResponseSerializer<String, NSError>
|
||||
{
|
||||
return ResponseSerializer { _, response, data, error in
|
||||
guard error == nil else { return .Failure(error!) }
|
||||
|
||||
if let response = response where response.statusCode == 204 { return .Success("") }
|
||||
|
||||
guard let validData = data else {
|
||||
let failureReason = "String could not be serialized. Input data was nil."
|
||||
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
|
||||
return .Failure(error)
|
||||
}
|
||||
|
||||
if let encodingName = response?.textEncodingName where encoding == nil {
|
||||
encoding = CFStringConvertEncodingToNSStringEncoding(
|
||||
CFStringConvertIANACharSetNameToEncoding(encodingName)
|
||||
)
|
||||
}
|
||||
|
||||
let actualEncoding = encoding ?? NSISOLatin1StringEncoding
|
||||
|
||||
if let string = String(data: validData, encoding: actualEncoding) {
|
||||
return .Success(string)
|
||||
} else {
|
||||
let failureReason = "String could not be serialized with encoding: \(actualEncoding)"
|
||||
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
|
||||
return .Failure(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler to be called once the request has finished.
|
||||
|
||||
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
|
||||
server response, falling back to the default HTTP default character set,
|
||||
ISO-8859-1.
|
||||
- parameter completionHandler: A closure to be executed once the request has finished.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func responseString(
|
||||
encoding encoding: NSStringEncoding? = nil,
|
||||
completionHandler: Response<String, NSError> -> Void)
|
||||
-> Self
|
||||
{
|
||||
return response(
|
||||
responseSerializer: Request.stringResponseSerializer(encoding: encoding),
|
||||
completionHandler: completionHandler
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - JSON
|
||||
|
||||
extension Request {
|
||||
|
||||
/**
|
||||
Creates a response serializer that returns a JSON object constructed from the response data using
|
||||
`NSJSONSerialization` with the specified reading options.
|
||||
|
||||
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
|
||||
|
||||
- returns: A JSON object response serializer.
|
||||
*/
|
||||
public static func JSONResponseSerializer(
|
||||
options options: NSJSONReadingOptions = .AllowFragments)
|
||||
-> ResponseSerializer<AnyObject, NSError>
|
||||
{
|
||||
return ResponseSerializer { _, response, data, error in
|
||||
guard error == nil else { return .Failure(error!) }
|
||||
|
||||
if let response = response where response.statusCode == 204 { return .Success(NSNull()) }
|
||||
|
||||
guard let validData = data where validData.length > 0 else {
|
||||
let failureReason = "JSON could not be serialized. Input data was nil or zero length."
|
||||
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
|
||||
return .Failure(error)
|
||||
}
|
||||
|
||||
do {
|
||||
let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: options)
|
||||
return .Success(JSON)
|
||||
} catch {
|
||||
return .Failure(error as NSError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler to be called once the request has finished.
|
||||
|
||||
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
|
||||
- parameter completionHandler: A closure to be executed once the request has finished.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func responseJSON(
|
||||
options options: NSJSONReadingOptions = .AllowFragments,
|
||||
completionHandler: Response<AnyObject, NSError> -> Void)
|
||||
-> Self
|
||||
{
|
||||
return response(
|
||||
responseSerializer: Request.JSONResponseSerializer(options: options),
|
||||
completionHandler: completionHandler
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Property List
|
||||
|
||||
extension Request {
|
||||
|
||||
/**
|
||||
Creates a response serializer that returns an object constructed from the response data using
|
||||
`NSPropertyListSerialization` with the specified reading options.
|
||||
|
||||
- parameter options: The property list reading options. `NSPropertyListReadOptions()` by default.
|
||||
|
||||
- returns: A property list object response serializer.
|
||||
*/
|
||||
public static func propertyListResponseSerializer(
|
||||
options options: NSPropertyListReadOptions = NSPropertyListReadOptions())
|
||||
-> ResponseSerializer<AnyObject, NSError>
|
||||
{
|
||||
return ResponseSerializer { _, response, data, error in
|
||||
guard error == nil else { return .Failure(error!) }
|
||||
|
||||
if let response = response where response.statusCode == 204 { return .Success(NSNull()) }
|
||||
|
||||
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 error = Error.errorWithCode(.PropertyListSerializationFailed, failureReason: failureReason)
|
||||
return .Failure(error)
|
||||
}
|
||||
|
||||
do {
|
||||
let plist = try NSPropertyListSerialization.propertyListWithData(validData, options: options, format: nil)
|
||||
return .Success(plist)
|
||||
} catch {
|
||||
return .Failure(error as NSError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler to be called once the request has finished.
|
||||
|
||||
- parameter options: The property list reading options. `0` by default.
|
||||
- parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3
|
||||
arguments: the URL request, the URL response, the server data and the result
|
||||
produced while creating the property list.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func responsePropertyList(
|
||||
options options: NSPropertyListReadOptions = NSPropertyListReadOptions(),
|
||||
completionHandler: Response<AnyObject, NSError> -> Void)
|
||||
-> Self
|
||||
{
|
||||
return response(
|
||||
responseSerializer: Request.propertyListResponseSerializer(options: options),
|
||||
completionHandler: completionHandler
|
||||
)
|
||||
}
|
||||
}
|
101
samples/client/petstore/swift-promisekit/SwaggerClientTests/Pods/Alamofire/Source/Result.swift
generated
Normal file
101
samples/client/petstore/swift-promisekit/SwaggerClientTests/Pods/Alamofire/Source/Result.swift
generated
Normal file
@ -0,0 +1,101 @@
|
||||
// Result.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
|
||||
|
||||
/**
|
||||
Used to represent whether a request was successful or encountered an error.
|
||||
|
||||
- Success: The request and all post processing operations were successful resulting in the serialization of the
|
||||
provided associated value.
|
||||
- Failure: The request encountered an error resulting in a failure. The associated values are the original data
|
||||
provided by the server as well as the error that caused the failure.
|
||||
*/
|
||||
public enum Result<Value, Error: ErrorType> {
|
||||
case Success(Value)
|
||||
case Failure(Error)
|
||||
|
||||
/// Returns `true` if the result is a success, `false` otherwise.
|
||||
public var isSuccess: Bool {
|
||||
switch self {
|
||||
case .Success:
|
||||
return true
|
||||
case .Failure:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `true` if the result is a failure, `false` otherwise.
|
||||
public var isFailure: Bool {
|
||||
return !isSuccess
|
||||
}
|
||||
|
||||
/// Returns the associated value if the result is a success, `nil` otherwise.
|
||||
public var value: Value? {
|
||||
switch self {
|
||||
case .Success(let value):
|
||||
return value
|
||||
case .Failure:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the associated error value if the result is a failure, `nil` otherwise.
|
||||
public var error: Error? {
|
||||
switch self {
|
||||
case .Success:
|
||||
return nil
|
||||
case .Failure(let error):
|
||||
return error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
extension Result: CustomStringConvertible {
|
||||
/// The textual representation used when written to an output stream, which includes whether the result was a
|
||||
/// success or failure.
|
||||
public var description: String {
|
||||
switch self {
|
||||
case .Success:
|
||||
return "SUCCESS"
|
||||
case .Failure:
|
||||
return "FAILURE"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomDebugStringConvertible
|
||||
|
||||
extension Result: CustomDebugStringConvertible {
|
||||
/// The debug textual representation used when written to an output stream, which includes whether the result was a
|
||||
/// success or failure in addition to the value or error.
|
||||
public var debugDescription: String {
|
||||
switch self {
|
||||
case .Success(let value):
|
||||
return "SUCCESS: \(value)"
|
||||
case .Failure(let error):
|
||||
return "FAILURE: \(error)"
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,302 @@
|
||||
// ServerTrustPolicy.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 managing the mapping of `ServerTrustPolicy` objects to a given host.
|
||||
public class ServerTrustPolicyManager {
|
||||
/// The dictionary of policies mapped to a particular host.
|
||||
public let policies: [String: ServerTrustPolicy]
|
||||
|
||||
/**
|
||||
Initializes the `ServerTrustPolicyManager` instance with the given policies.
|
||||
|
||||
Since different servers and web services can have different leaf certificates, intermediate and even root
|
||||
certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This
|
||||
allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key
|
||||
pinning for host3 and disabling evaluation for host4.
|
||||
|
||||
- parameter policies: A dictionary of all policies mapped to a particular host.
|
||||
|
||||
- returns: The new `ServerTrustPolicyManager` instance.
|
||||
*/
|
||||
public init(policies: [String: ServerTrustPolicy]) {
|
||||
self.policies = policies
|
||||
}
|
||||
|
||||
/**
|
||||
Returns the `ServerTrustPolicy` for the given host if applicable.
|
||||
|
||||
By default, this method will return the policy that perfectly matches the given host. Subclasses could override
|
||||
this method and implement more complex mapping implementations such as wildcards.
|
||||
|
||||
- parameter host: The host to use when searching for a matching policy.
|
||||
|
||||
- returns: The server trust policy for the given host if found.
|
||||
*/
|
||||
public func serverTrustPolicyForHost(host: String) -> ServerTrustPolicy? {
|
||||
return policies[host]
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
extension NSURLSession {
|
||||
private struct AssociatedKeys {
|
||||
static var ManagerKey = "NSURLSession.ServerTrustPolicyManager"
|
||||
}
|
||||
|
||||
var serverTrustPolicyManager: ServerTrustPolicyManager? {
|
||||
get {
|
||||
return objc_getAssociatedObject(self, &AssociatedKeys.ManagerKey) as? ServerTrustPolicyManager
|
||||
}
|
||||
set (manager) {
|
||||
objc_setAssociatedObject(self, &AssociatedKeys.ManagerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ServerTrustPolicy
|
||||
|
||||
/**
|
||||
The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when
|
||||
connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust
|
||||
with a given set of criteria to determine whether the server trust is valid and the connection should be made.
|
||||
|
||||
Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other
|
||||
vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged
|
||||
to route all communication over an HTTPS connection with pinning enabled.
|
||||
|
||||
- PerformDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to
|
||||
validate the host provided by the challenge. Applications are encouraged to always
|
||||
validate the host in production environments to guarantee the validity of the server's
|
||||
certificate chain.
|
||||
|
||||
- PinCertificates: Uses the pinned certificates to validate the server trust. The server trust is
|
||||
considered valid if one of the pinned certificates match one of the server certificates.
|
||||
By validating both the certificate chain and host, certificate pinning provides a very
|
||||
secure form of server trust validation mitigating most, if not all, MITM attacks.
|
||||
Applications are encouraged to always validate the host and require a valid certificate
|
||||
chain in production environments.
|
||||
|
||||
- PinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered
|
||||
valid if one of the pinned public keys match one of the server certificate public keys.
|
||||
By validating both the certificate chain and host, public key pinning provides a very
|
||||
secure form of server trust validation mitigating most, if not all, MITM attacks.
|
||||
Applications are encouraged to always validate the host and require a valid certificate
|
||||
chain in production environments.
|
||||
|
||||
- DisableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid.
|
||||
|
||||
- CustomEvaluation: Uses the associated closure to evaluate the validity of the server trust.
|
||||
*/
|
||||
public enum ServerTrustPolicy {
|
||||
case PerformDefaultEvaluation(validateHost: Bool)
|
||||
case PinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool)
|
||||
case PinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool)
|
||||
case DisableEvaluation
|
||||
case CustomEvaluation((serverTrust: SecTrust, host: String) -> Bool)
|
||||
|
||||
// MARK: - Bundle Location
|
||||
|
||||
/**
|
||||
Returns all certificates within the given bundle with a `.cer` file extension.
|
||||
|
||||
- parameter bundle: The bundle to search for all `.cer` files.
|
||||
|
||||
- returns: All certificates within the given bundle.
|
||||
*/
|
||||
public static func certificatesInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecCertificate] {
|
||||
var certificates: [SecCertificate] = []
|
||||
|
||||
let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in
|
||||
bundle.pathsForResourcesOfType(fileExtension, inDirectory: nil)
|
||||
}.flatten())
|
||||
|
||||
for path in paths {
|
||||
if let
|
||||
certificateData = NSData(contentsOfFile: path),
|
||||
certificate = SecCertificateCreateWithData(nil, certificateData)
|
||||
{
|
||||
certificates.append(certificate)
|
||||
}
|
||||
}
|
||||
|
||||
return certificates
|
||||
}
|
||||
|
||||
/**
|
||||
Returns all public keys within the given bundle with a `.cer` file extension.
|
||||
|
||||
- parameter bundle: The bundle to search for all `*.cer` files.
|
||||
|
||||
- returns: All public keys within the given bundle.
|
||||
*/
|
||||
public static func publicKeysInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecKey] {
|
||||
var publicKeys: [SecKey] = []
|
||||
|
||||
for certificate in certificatesInBundle(bundle) {
|
||||
if let publicKey = publicKeyForCertificate(certificate) {
|
||||
publicKeys.append(publicKey)
|
||||
}
|
||||
}
|
||||
|
||||
return publicKeys
|
||||
}
|
||||
|
||||
// MARK: - Evaluation
|
||||
|
||||
/**
|
||||
Evaluates whether the server trust is valid for the given host.
|
||||
|
||||
- parameter serverTrust: The server trust to evaluate.
|
||||
- parameter host: The host of the challenge protection space.
|
||||
|
||||
- returns: Whether the server trust is valid.
|
||||
*/
|
||||
public func evaluateServerTrust(serverTrust: SecTrust, isValidForHost host: String) -> Bool {
|
||||
var serverTrustIsValid = false
|
||||
|
||||
switch self {
|
||||
case let .PerformDefaultEvaluation(validateHost):
|
||||
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
|
||||
SecTrustSetPolicies(serverTrust, [policy])
|
||||
|
||||
serverTrustIsValid = trustIsValid(serverTrust)
|
||||
case let .PinCertificates(pinnedCertificates, validateCertificateChain, validateHost):
|
||||
if validateCertificateChain {
|
||||
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
|
||||
SecTrustSetPolicies(serverTrust, [policy])
|
||||
|
||||
SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates)
|
||||
SecTrustSetAnchorCertificatesOnly(serverTrust, true)
|
||||
|
||||
serverTrustIsValid = trustIsValid(serverTrust)
|
||||
} else {
|
||||
let serverCertificatesDataArray = certificateDataForTrust(serverTrust)
|
||||
let pinnedCertificatesDataArray = certificateDataForCertificates(pinnedCertificates)
|
||||
|
||||
outerLoop: for serverCertificateData in serverCertificatesDataArray {
|
||||
for pinnedCertificateData in pinnedCertificatesDataArray {
|
||||
if serverCertificateData.isEqualToData(pinnedCertificateData) {
|
||||
serverTrustIsValid = true
|
||||
break outerLoop
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
case let .PinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost):
|
||||
var certificateChainEvaluationPassed = true
|
||||
|
||||
if validateCertificateChain {
|
||||
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
|
||||
SecTrustSetPolicies(serverTrust, [policy])
|
||||
|
||||
certificateChainEvaluationPassed = trustIsValid(serverTrust)
|
||||
}
|
||||
|
||||
if certificateChainEvaluationPassed {
|
||||
outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeysForTrust(serverTrust) as [AnyObject] {
|
||||
for pinnedPublicKey in pinnedPublicKeys as [AnyObject] {
|
||||
if serverPublicKey.isEqual(pinnedPublicKey) {
|
||||
serverTrustIsValid = true
|
||||
break outerLoop
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
case .DisableEvaluation:
|
||||
serverTrustIsValid = true
|
||||
case let .CustomEvaluation(closure):
|
||||
serverTrustIsValid = closure(serverTrust: serverTrust, host: host)
|
||||
}
|
||||
|
||||
return serverTrustIsValid
|
||||
}
|
||||
|
||||
// MARK: - Private - Trust Validation
|
||||
|
||||
private func trustIsValid(trust: SecTrust) -> Bool {
|
||||
var isValid = false
|
||||
|
||||
var result = SecTrustResultType(kSecTrustResultInvalid)
|
||||
let status = SecTrustEvaluate(trust, &result)
|
||||
|
||||
if status == errSecSuccess {
|
||||
let unspecified = SecTrustResultType(kSecTrustResultUnspecified)
|
||||
let proceed = SecTrustResultType(kSecTrustResultProceed)
|
||||
|
||||
isValid = result == unspecified || result == proceed
|
||||
}
|
||||
|
||||
return isValid
|
||||
}
|
||||
|
||||
// MARK: - Private - Certificate Data
|
||||
|
||||
private func certificateDataForTrust(trust: SecTrust) -> [NSData] {
|
||||
var certificates: [SecCertificate] = []
|
||||
|
||||
for index in 0..<SecTrustGetCertificateCount(trust) {
|
||||
if let certificate = SecTrustGetCertificateAtIndex(trust, index) {
|
||||
certificates.append(certificate)
|
||||
}
|
||||
}
|
||||
|
||||
return certificateDataForCertificates(certificates)
|
||||
}
|
||||
|
||||
private func certificateDataForCertificates(certificates: [SecCertificate]) -> [NSData] {
|
||||
return certificates.map { SecCertificateCopyData($0) as NSData }
|
||||
}
|
||||
|
||||
// MARK: - Private - Public Key Extraction
|
||||
|
||||
private static func publicKeysForTrust(trust: SecTrust) -> [SecKey] {
|
||||
var publicKeys: [SecKey] = []
|
||||
|
||||
for index in 0..<SecTrustGetCertificateCount(trust) {
|
||||
if let
|
||||
certificate = SecTrustGetCertificateAtIndex(trust, index),
|
||||
publicKey = publicKeyForCertificate(certificate)
|
||||
{
|
||||
publicKeys.append(publicKey)
|
||||
}
|
||||
}
|
||||
|
||||
return publicKeys
|
||||
}
|
||||
|
||||
private static func publicKeyForCertificate(certificate: SecCertificate) -> SecKey? {
|
||||
var publicKey: SecKey?
|
||||
|
||||
let policy = SecPolicyCreateBasicX509()
|
||||
var trust: SecTrust?
|
||||
let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust)
|
||||
|
||||
if let trust = trust where trustCreationStatus == errSecSuccess {
|
||||
publicKey = SecTrustCopyPublicKey(trust)
|
||||
}
|
||||
|
||||
return publicKey
|
||||
}
|
||||
}
|
180
samples/client/petstore/swift-promisekit/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift
generated
Normal file
180
samples/client/petstore/swift-promisekit/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift
generated
Normal file
@ -0,0 +1,180 @@
|
||||
// Stream.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
|
||||
|
||||
#if !os(watchOS)
|
||||
|
||||
@available(iOS 9.0, OSX 10.11, *)
|
||||
extension Manager {
|
||||
private enum Streamable {
|
||||
case Stream(String, Int)
|
||||
case NetService(NSNetService)
|
||||
}
|
||||
|
||||
private func stream(streamable: Streamable) -> Request {
|
||||
var streamTask: NSURLSessionStreamTask!
|
||||
|
||||
switch streamable {
|
||||
case .Stream(let hostName, let port):
|
||||
dispatch_sync(queue) {
|
||||
streamTask = self.session.streamTaskWithHostName(hostName, port: port)
|
||||
}
|
||||
case .NetService(let netService):
|
||||
dispatch_sync(queue) {
|
||||
streamTask = self.session.streamTaskWithNetService(netService)
|
||||
}
|
||||
}
|
||||
|
||||
let request = Request(session: session, task: streamTask)
|
||||
|
||||
delegate[request.delegate.task] = request.delegate
|
||||
|
||||
if startRequestsImmediately {
|
||||
request.resume()
|
||||
}
|
||||
|
||||
return request
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a request for bidirectional streaming with the given hostname and port.
|
||||
|
||||
- parameter hostName: The hostname of the server to connect to.
|
||||
- parameter port: The port of the server to connect to.
|
||||
|
||||
:returns: The created stream request.
|
||||
*/
|
||||
public func stream(hostName hostName: String, port: Int) -> Request {
|
||||
return stream(.Stream(hostName, port))
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a request for bidirectional streaming with the given `NSNetService`.
|
||||
|
||||
- parameter netService: The net service used to identify the endpoint.
|
||||
|
||||
- returns: The created stream request.
|
||||
*/
|
||||
public func stream(netService netService: NSNetService) -> Request {
|
||||
return stream(.NetService(netService))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
@available(iOS 9.0, OSX 10.11, *)
|
||||
extension Manager.SessionDelegate: NSURLSessionStreamDelegate {
|
||||
|
||||
// MARK: Override Closures
|
||||
|
||||
/// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:readClosedForStreamTask:`.
|
||||
public var streamTaskReadClosed: ((NSURLSession, NSURLSessionStreamTask) -> Void)? {
|
||||
get {
|
||||
return _streamTaskReadClosed as? (NSURLSession, NSURLSessionStreamTask) -> Void
|
||||
}
|
||||
set {
|
||||
_streamTaskReadClosed = newValue
|
||||
}
|
||||
}
|
||||
|
||||
/// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:writeClosedForStreamTask:`.
|
||||
public var streamTaskWriteClosed: ((NSURLSession, NSURLSessionStreamTask) -> Void)? {
|
||||
get {
|
||||
return _streamTaskWriteClosed as? (NSURLSession, NSURLSessionStreamTask) -> Void
|
||||
}
|
||||
set {
|
||||
_streamTaskWriteClosed = newValue
|
||||
}
|
||||
}
|
||||
|
||||
/// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:betterRouteDiscoveredForStreamTask:`.
|
||||
public var streamTaskBetterRouteDiscovered: ((NSURLSession, NSURLSessionStreamTask) -> Void)? {
|
||||
get {
|
||||
return _streamTaskBetterRouteDiscovered as? (NSURLSession, NSURLSessionStreamTask) -> Void
|
||||
}
|
||||
set {
|
||||
_streamTaskBetterRouteDiscovered = newValue
|
||||
}
|
||||
}
|
||||
|
||||
/// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:streamTask:didBecomeInputStream:outputStream:`.
|
||||
public var streamTaskDidBecomeInputStream: ((NSURLSession, NSURLSessionStreamTask, NSInputStream, NSOutputStream) -> Void)? {
|
||||
get {
|
||||
return _streamTaskDidBecomeInputStream as? (NSURLSession, NSURLSessionStreamTask, NSInputStream, NSOutputStream) -> Void
|
||||
}
|
||||
set {
|
||||
_streamTaskDidBecomeInputStream = newValue
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Delegate Methods
|
||||
|
||||
/**
|
||||
Tells the delegate that the read side of the connection has been closed.
|
||||
|
||||
- parameter session: The session.
|
||||
- parameter streamTask: The stream task.
|
||||
*/
|
||||
public func URLSession(session: NSURLSession, readClosedForStreamTask streamTask: NSURLSessionStreamTask) {
|
||||
streamTaskReadClosed?(session, streamTask)
|
||||
}
|
||||
|
||||
/**
|
||||
Tells the delegate that the write side of the connection has been closed.
|
||||
|
||||
- parameter session: The session.
|
||||
- parameter streamTask: The stream task.
|
||||
*/
|
||||
public func URLSession(session: NSURLSession, writeClosedForStreamTask streamTask: NSURLSessionStreamTask) {
|
||||
streamTaskWriteClosed?(session, streamTask)
|
||||
}
|
||||
|
||||
/**
|
||||
Tells the delegate that the system has determined that a better route to the host is available.
|
||||
|
||||
- parameter session: The session.
|
||||
- parameter streamTask: The stream task.
|
||||
*/
|
||||
public func URLSession(session: NSURLSession, betterRouteDiscoveredForStreamTask streamTask: NSURLSessionStreamTask) {
|
||||
streamTaskBetterRouteDiscovered?(session, streamTask)
|
||||
}
|
||||
|
||||
/**
|
||||
Tells the delegate that the stream task has been completed and provides the unopened stream objects.
|
||||
|
||||
- parameter session: The session.
|
||||
- parameter streamTask: The stream task.
|
||||
- parameter inputStream: The new input stream.
|
||||
- parameter outputStream: The new output stream.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
streamTask: NSURLSessionStreamTask,
|
||||
didBecomeInputStream inputStream: NSInputStream,
|
||||
outputStream: NSOutputStream)
|
||||
{
|
||||
streamTaskDidBecomeInputStream?(session, streamTask, inputStream, outputStream)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
372
samples/client/petstore/swift-promisekit/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift
generated
Normal file
372
samples/client/petstore/swift-promisekit/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift
generated
Normal file
@ -0,0 +1,372 @@
|
||||
// Upload.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
|
||||
|
||||
extension Manager {
|
||||
private enum Uploadable {
|
||||
case Data(NSURLRequest, NSData)
|
||||
case File(NSURLRequest, NSURL)
|
||||
case Stream(NSURLRequest, NSInputStream)
|
||||
}
|
||||
|
||||
private func upload(uploadable: Uploadable) -> Request {
|
||||
var uploadTask: NSURLSessionUploadTask!
|
||||
var HTTPBodyStream: NSInputStream?
|
||||
|
||||
switch uploadable {
|
||||
case .Data(let request, let data):
|
||||
dispatch_sync(queue) {
|
||||
uploadTask = self.session.uploadTaskWithRequest(request, fromData: data)
|
||||
}
|
||||
case .File(let request, let fileURL):
|
||||
dispatch_sync(queue) {
|
||||
uploadTask = self.session.uploadTaskWithRequest(request, fromFile: fileURL)
|
||||
}
|
||||
case .Stream(let request, let stream):
|
||||
dispatch_sync(queue) {
|
||||
uploadTask = self.session.uploadTaskWithStreamedRequest(request)
|
||||
}
|
||||
|
||||
HTTPBodyStream = stream
|
||||
}
|
||||
|
||||
let request = Request(session: session, task: uploadTask)
|
||||
|
||||
if HTTPBodyStream != nil {
|
||||
request.delegate.taskNeedNewBodyStream = { _, _ in
|
||||
return HTTPBodyStream
|
||||
}
|
||||
}
|
||||
|
||||
delegate[request.delegate.task] = request.delegate
|
||||
|
||||
if startRequestsImmediately {
|
||||
request.resume()
|
||||
}
|
||||
|
||||
return request
|
||||
}
|
||||
|
||||
// MARK: File
|
||||
|
||||
/**
|
||||
Creates a request for uploading a file to the specified URL request.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter URLRequest: The URL request
|
||||
- parameter file: The file to upload
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request {
|
||||
return upload(.File(URLRequest.URLRequest, file))
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a request for uploading a file to the specified URL request.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter file: The file to upload
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
headers: [String: String]? = nil,
|
||||
file: NSURL)
|
||||
-> Request
|
||||
{
|
||||
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
|
||||
return upload(mutableURLRequest, file: file)
|
||||
}
|
||||
|
||||
// MARK: Data
|
||||
|
||||
/**
|
||||
Creates a request for uploading data to the specified URL request.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter URLRequest: The URL request.
|
||||
- parameter data: The data to upload.
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request {
|
||||
return upload(.Data(URLRequest.URLRequest, data))
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a request for uploading data to the specified URL request.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter data: The data to upload
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
headers: [String: String]? = nil,
|
||||
data: NSData)
|
||||
-> Request
|
||||
{
|
||||
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
|
||||
|
||||
return upload(mutableURLRequest, data: data)
|
||||
}
|
||||
|
||||
// MARK: Stream
|
||||
|
||||
/**
|
||||
Creates a request for uploading a stream to the specified URL request.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter URLRequest: The URL request.
|
||||
- parameter stream: The stream to upload.
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request {
|
||||
return upload(.Stream(URLRequest.URLRequest, stream))
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a request for uploading a stream to the specified URL request.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter stream: The stream to upload.
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
headers: [String: String]? = nil,
|
||||
stream: NSInputStream)
|
||||
-> Request
|
||||
{
|
||||
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
|
||||
|
||||
return upload(mutableURLRequest, stream: stream)
|
||||
}
|
||||
|
||||
// MARK: MultipartFormData
|
||||
|
||||
/// Default memory threshold used when encoding `MultipartFormData`.
|
||||
public static let MultipartFormDataEncodingMemoryThreshold: UInt64 = 10 * 1024 * 1024
|
||||
|
||||
/**
|
||||
Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as
|
||||
associated values.
|
||||
|
||||
- Success: Represents a successful `MultipartFormData` encoding and contains the new `Request` along with
|
||||
streaming information.
|
||||
- Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding
|
||||
error.
|
||||
*/
|
||||
public enum MultipartFormDataEncodingResult {
|
||||
case Success(request: Request, streamingFromDisk: Bool, streamFileURL: NSURL?)
|
||||
case Failure(ErrorType)
|
||||
}
|
||||
|
||||
/**
|
||||
Encodes the `MultipartFormData` and creates a request to upload the result to the specified URL request.
|
||||
|
||||
It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
|
||||
payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
|
||||
efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
|
||||
be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
|
||||
footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
|
||||
used for larger payloads such as video content.
|
||||
|
||||
The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
|
||||
or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
|
||||
encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
|
||||
during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
|
||||
technique was used.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
|
||||
- parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
|
||||
`MultipartFormDataEncodingMemoryThreshold` by default.
|
||||
- parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
|
||||
*/
|
||||
public func upload(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
headers: [String: String]? = nil,
|
||||
multipartFormData: MultipartFormData -> Void,
|
||||
encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold,
|
||||
encodingCompletion: (MultipartFormDataEncodingResult -> Void)?)
|
||||
{
|
||||
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
|
||||
|
||||
return upload(
|
||||
mutableURLRequest,
|
||||
multipartFormData: multipartFormData,
|
||||
encodingMemoryThreshold: encodingMemoryThreshold,
|
||||
encodingCompletion: encodingCompletion
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
Encodes the `MultipartFormData` and creates a request to upload the result to the specified URL request.
|
||||
|
||||
It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
|
||||
payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
|
||||
efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
|
||||
be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
|
||||
footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
|
||||
used for larger payloads such as video content.
|
||||
|
||||
The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
|
||||
or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
|
||||
encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
|
||||
during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
|
||||
technique was used.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter URLRequest: The URL request.
|
||||
- parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
|
||||
- parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
|
||||
`MultipartFormDataEncodingMemoryThreshold` by default.
|
||||
- parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
|
||||
*/
|
||||
public func upload(
|
||||
URLRequest: URLRequestConvertible,
|
||||
multipartFormData: MultipartFormData -> Void,
|
||||
encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold,
|
||||
encodingCompletion: (MultipartFormDataEncodingResult -> Void)?)
|
||||
{
|
||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
|
||||
let formData = MultipartFormData()
|
||||
multipartFormData(formData)
|
||||
|
||||
let URLRequestWithContentType = URLRequest.URLRequest
|
||||
URLRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type")
|
||||
|
||||
let isBackgroundSession = self.session.configuration.identifier != nil
|
||||
|
||||
if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession {
|
||||
do {
|
||||
let data = try formData.encode()
|
||||
let encodingResult = MultipartFormDataEncodingResult.Success(
|
||||
request: self.upload(URLRequestWithContentType, data: data),
|
||||
streamingFromDisk: false,
|
||||
streamFileURL: nil
|
||||
)
|
||||
|
||||
dispatch_async(dispatch_get_main_queue()) {
|
||||
encodingCompletion?(encodingResult)
|
||||
}
|
||||
} catch {
|
||||
dispatch_async(dispatch_get_main_queue()) {
|
||||
encodingCompletion?(.Failure(error as NSError))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let fileManager = NSFileManager.defaultManager()
|
||||
let tempDirectoryURL = NSURL(fileURLWithPath: NSTemporaryDirectory())
|
||||
let directoryURL = tempDirectoryURL.URLByAppendingPathComponent("com.alamofire.manager/multipart.form.data")
|
||||
let fileName = NSUUID().UUIDString
|
||||
let fileURL = directoryURL.URLByAppendingPathComponent(fileName)
|
||||
|
||||
do {
|
||||
try fileManager.createDirectoryAtURL(directoryURL, withIntermediateDirectories: true, attributes: nil)
|
||||
try formData.writeEncodedDataToDisk(fileURL)
|
||||
|
||||
dispatch_async(dispatch_get_main_queue()) {
|
||||
let encodingResult = MultipartFormDataEncodingResult.Success(
|
||||
request: self.upload(URLRequestWithContentType, file: fileURL),
|
||||
streamingFromDisk: true,
|
||||
streamFileURL: fileURL
|
||||
)
|
||||
encodingCompletion?(encodingResult)
|
||||
}
|
||||
} catch {
|
||||
dispatch_async(dispatch_get_main_queue()) {
|
||||
encodingCompletion?(.Failure(error as NSError))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
extension Request {
|
||||
|
||||
// MARK: - UploadTaskDelegate
|
||||
|
||||
class UploadTaskDelegate: DataTaskDelegate {
|
||||
var uploadTask: NSURLSessionUploadTask? { return task as? NSURLSessionUploadTask }
|
||||
var uploadProgress: ((Int64, Int64, Int64) -> Void)!
|
||||
|
||||
// MARK: - NSURLSessionTaskDelegate
|
||||
|
||||
// MARK: Override Closures
|
||||
|
||||
var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)?
|
||||
|
||||
// MARK: Delegate Methods
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
task: NSURLSessionTask,
|
||||
didSendBodyData bytesSent: Int64,
|
||||
totalBytesSent: Int64,
|
||||
totalBytesExpectedToSend: Int64)
|
||||
{
|
||||
if let taskDidSendBodyData = taskDidSendBodyData {
|
||||
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
|
||||
} else {
|
||||
progress.totalUnitCount = totalBytesExpectedToSend
|
||||
progress.completedUnitCount = totalBytesSent
|
||||
|
||||
uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
189
samples/client/petstore/swift-promisekit/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift
generated
Normal file
189
samples/client/petstore/swift-promisekit/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift
generated
Normal file
@ -0,0 +1,189 @@
|
||||
// Validation.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
|
||||
|
||||
extension Request {
|
||||
|
||||
/**
|
||||
Used to represent whether validation was successful or encountered an error resulting in a failure.
|
||||
|
||||
- Success: The validation was successful.
|
||||
- Failure: The validation failed encountering the provided error.
|
||||
*/
|
||||
public enum ValidationResult {
|
||||
case Success
|
||||
case Failure(NSError)
|
||||
}
|
||||
|
||||
/**
|
||||
A closure used to validate a request that takes a URL request and URL response, and returns whether the
|
||||
request was valid.
|
||||
*/
|
||||
public typealias Validation = (NSURLRequest?, NSHTTPURLResponse) -> ValidationResult
|
||||
|
||||
/**
|
||||
Validates the request, using the specified closure.
|
||||
|
||||
If validation fails, subsequent calls to response handlers will have an associated error.
|
||||
|
||||
- parameter validation: A closure to validate the request.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func validate(validation: Validation) -> Self {
|
||||
delegate.queue.addOperationWithBlock {
|
||||
if let
|
||||
response = self.response where self.delegate.error == nil,
|
||||
case let .Failure(error) = validation(self.request, response)
|
||||
{
|
||||
self.delegate.error = error
|
||||
}
|
||||
}
|
||||
|
||||
return self
|
||||
}
|
||||
|
||||
// MARK: - Status Code
|
||||
|
||||
/**
|
||||
Validates that the response has a status code in the specified range.
|
||||
|
||||
If validation fails, subsequent calls to response handlers will have an associated error.
|
||||
|
||||
- parameter range: The range of acceptable status codes.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func validate<S: SequenceType where S.Generator.Element == Int>(statusCode acceptableStatusCode: S) -> Self {
|
||||
return validate { _, response in
|
||||
if acceptableStatusCode.contains(response.statusCode) {
|
||||
return .Success
|
||||
} else {
|
||||
let failureReason = "Response status code was unacceptable: \(response.statusCode)"
|
||||
return .Failure(Error.errorWithCode(.StatusCodeValidationFailed, failureReason: failureReason))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Content-Type
|
||||
|
||||
private struct MIMEType {
|
||||
let type: String
|
||||
let subtype: String
|
||||
|
||||
init?(_ string: String) {
|
||||
let components: [String] = {
|
||||
let stripped = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
|
||||
let split = stripped.substringToIndex(stripped.rangeOfString(";")?.startIndex ?? stripped.endIndex)
|
||||
return split.componentsSeparatedByString("/")
|
||||
}()
|
||||
|
||||
if let
|
||||
type = components.first,
|
||||
subtype = components.last
|
||||
{
|
||||
self.type = type
|
||||
self.subtype = subtype
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func matches(MIME: MIMEType) -> Bool {
|
||||
switch (type, subtype) {
|
||||
case (MIME.type, MIME.subtype), (MIME.type, "*"), ("*", MIME.subtype), ("*", "*"):
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Validates that the response has a content type in the specified array.
|
||||
|
||||
If validation fails, subsequent calls to response handlers will have an associated error.
|
||||
|
||||
- parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func validate<S : SequenceType where S.Generator.Element == String>(contentType acceptableContentTypes: S) -> Self {
|
||||
return validate { _, response in
|
||||
guard let validData = self.delegate.data where validData.length > 0 else { return .Success }
|
||||
|
||||
if let
|
||||
responseContentType = response.MIMEType,
|
||||
responseMIMEType = MIMEType(responseContentType)
|
||||
{
|
||||
for contentType in acceptableContentTypes {
|
||||
if let acceptableMIMEType = MIMEType(contentType) where acceptableMIMEType.matches(responseMIMEType) {
|
||||
return .Success
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for contentType in acceptableContentTypes {
|
||||
if let MIMEType = MIMEType(contentType) where MIMEType.type == "*" && MIMEType.subtype == "*" {
|
||||
return .Success
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let failureReason: String
|
||||
|
||||
if let responseContentType = response.MIMEType {
|
||||
failureReason = (
|
||||
"Response content type \"\(responseContentType)\" does not match any acceptable " +
|
||||
"content types: \(acceptableContentTypes)"
|
||||
)
|
||||
} else {
|
||||
failureReason = "Response content type was missing and acceptable content type does not match \"*/*\""
|
||||
}
|
||||
|
||||
return .Failure(Error.errorWithCode(.ContentTypeValidationFailed, failureReason: failureReason))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Automatic
|
||||
|
||||
/**
|
||||
Validates that the response has a status code in the default acceptable range of 200...299, and that the content
|
||||
type matches any specified in the Accept HTTP header field.
|
||||
|
||||
If validation fails, subsequent calls to response handlers will have an associated error.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func validate() -> Self {
|
||||
let acceptableStatusCodes: Range<Int> = 200..<300
|
||||
let acceptableContentTypes: [String] = {
|
||||
if let accept = request?.valueForHTTPHeaderField("Accept") {
|
||||
return accept.componentsSeparatedByString(",")
|
||||
}
|
||||
|
||||
return ["*/*"]
|
||||
}()
|
||||
|
||||
return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes)
|
||||
}
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
{
|
||||
"name": "PetstoreClient",
|
||||
"platforms": {
|
||||
"ios": "8.0",
|
||||
"osx": "10.9"
|
||||
},
|
||||
"version": "0.0.1",
|
||||
"source": {
|
||||
"git": "git@github.com:swagger-api/swagger-mustache.git",
|
||||
"tag": "v1.0.0"
|
||||
},
|
||||
"license": "Apache License, Version 2.0",
|
||||
"authors": "Apache License, Version 2.0",
|
||||
"homepage": "https://github.com/swagger-api/swagger-codegen",
|
||||
"summary": "PetstoreClient",
|
||||
"source_files": "PetstoreClient/Classes/Swaggers/**/*.swift",
|
||||
"dependencies": {
|
||||
"PromiseKit": [
|
||||
"~> 3.1.1"
|
||||
],
|
||||
"Alamofire": [
|
||||
"~> 3.1.5"
|
||||
]
|
||||
}
|
||||
}
|
41
samples/client/petstore/swift-promisekit/SwaggerClientTests/Pods/Manifest.lock
generated
Normal file
41
samples/client/petstore/swift-promisekit/SwaggerClientTests/Pods/Manifest.lock
generated
Normal file
@ -0,0 +1,41 @@
|
||||
PODS:
|
||||
- Alamofire (3.1.5)
|
||||
- OMGHTTPURLRQ (3.1.1):
|
||||
- OMGHTTPURLRQ/RQ (= 3.1.1)
|
||||
- OMGHTTPURLRQ/FormURLEncode (3.1.1)
|
||||
- OMGHTTPURLRQ/RQ (3.1.1):
|
||||
- OMGHTTPURLRQ/FormURLEncode
|
||||
- OMGHTTPURLRQ/UserAgent
|
||||
- OMGHTTPURLRQ/UserAgent (3.1.1)
|
||||
- PetstoreClient (0.0.1):
|
||||
- Alamofire (~> 3.1.5)
|
||||
- PromiseKit (~> 3.1.1)
|
||||
- PromiseKit (3.1.1):
|
||||
- PromiseKit/Foundation (= 3.1.1)
|
||||
- PromiseKit/QuartzCore (= 3.1.1)
|
||||
- PromiseKit/UIKit (= 3.1.1)
|
||||
- PromiseKit/CorePromise (3.1.1)
|
||||
- PromiseKit/Foundation (3.1.1):
|
||||
- OMGHTTPURLRQ (~> 3.1.0)
|
||||
- PromiseKit/CorePromise
|
||||
- PromiseKit/QuartzCore (3.1.1):
|
||||
- PromiseKit/CorePromise
|
||||
- PromiseKit/UIKit (3.1.1):
|
||||
- PromiseKit/CorePromise
|
||||
|
||||
DEPENDENCIES:
|
||||
- PetstoreClient (from `../`)
|
||||
|
||||
EXTERNAL SOURCES:
|
||||
PetstoreClient:
|
||||
:path: ../
|
||||
|
||||
SPEC CHECKSUMS:
|
||||
Alamofire: 5f730ba29fd113b7ddd71c1e65d0c630acf5d7b0
|
||||
OMGHTTPURLRQ: 633f98ee745aeda02345935a52eec1784cddb589
|
||||
PetstoreClient: efd495da2b7a6f3e798752702d59f96e306dbace
|
||||
PromiseKit: 4e8127c22a9b29d1b44958ab2ec762ea6115cbfb
|
||||
|
||||
PODFILE CHECKSUM: 84472aca2a88b7f7ed9fcd63e9f5fdb5ad4aab94
|
||||
|
||||
COCOAPODS: 1.0.0
|
1614
samples/client/petstore/swift-promisekit/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj
generated
Normal file
1614
samples/client/petstore/swift-promisekit/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj
generated
Normal file
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,5 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
@interface PodsDummy_Alamofire : NSObject
|
||||
@end
|
||||
@implementation PodsDummy_Alamofire
|
||||
@end
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user