forked from loafle/openapi-generator-original
Enable Travis CI tests for Swift, ObjC clients and move some tests to CircleCI (#5687)
* enable travis CI tests for swift, objc, move some tests to circleci
* fix comment in xml file
* use xcode8.3
* use ruby 2.2.5
* fix objc core data pom.xml
* use cocoapods 1.2.1
* use xcpretty for clearer test results
* fix pom with relative path to script
* comment out objc test
* fix xcpretty exit code
* add && exit ${PIPESTATUS[0]} for swift3 xcodebuild script
* use xcode 8.2
* update promisekit version for swift 2x, 3x
* add pod repo update
* remove Pods directory
* update swift dependencies to the latest version
* update podfile.lock
* rollback Alamofire to 4.0 for swift3
* fix swift3 rxswift api cliiet
* fix testDeletePet test in Swift3 rxswift petstore
* update clojure petstore
* comment out clojure test in travis (already covered in circleci)
* run pestore server locally
* use wing328/swagger-samples to run petstore
* run petstore server in the background
* test ruby petstore client
* add /Users/travis/.cocoapods/repos/master to cache
* add back ruby test, use public pestore server
* add back bash client test
* add npm config set registry to avoid time out
* use docker branch in swagger samples
* remove bash test
* show go version, reorder
* debug go petstore client
* reinstall go
* comment out pod repo update
* uncomment pod repo update
* test go in circleci
* remove go from travis test
* brew install sbt
This commit is contained in:
16
.gitignore
vendored
16
.gitignore
vendored
@@ -101,11 +101,19 @@ samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient.xcworksp
|
||||
samples/client/petstore/objc/core-data/SwaggerClientTests/Podfile.lock
|
||||
|
||||
# Swift
|
||||
samples/client/petstore/swift/SwaggerClientTests/SwaggerClient.xcodeproj/xcuserdata
|
||||
samples/client/petstore/swift/SwaggerClientTests/SwaggerClient.xcworkspace/xcuserdata
|
||||
samples/client/petstore/swift/SwaggerClientTests/Pods/Pods.xcodeproj/xcuserdata
|
||||
samples/client/petstore/swift/SwaggerClientTests/Pods/Pods.xcodeproj/xcshareddata/xcschemes
|
||||
samples/client/petstore/swift/**/SwaggerClientTests/SwaggerClient.xcodeproj/xcuserdata
|
||||
samples/client/petstore/swift/**/SwaggerClientTests/SwaggerClient.xcworkspace/xcuserdata
|
||||
samples/client/petstore/swift/**/SwaggerClientTests/Pods/
|
||||
#samples/client/petstore/swift/**/SwaggerClientTests/Pods/Pods.xcodeproj/xcuserdata
|
||||
#samples/client/petstore/swift/**/SwaggerClientTests/Pods/Pods.xcodeproj/xcshareddata/xcschemes
|
||||
samples/client/petstore/swift/**/SwaggerClientTests/Podfile.lock
|
||||
# Swift3
|
||||
samples/client/petstore/swift3/**/SwaggerClientTests/SwaggerClient.xcodeproj/xcuserdata
|
||||
samples/client/petstore/swift3/**/SwaggerClientTests/SwaggerClient.xcworkspace/xcuserdata
|
||||
samples/client/petstore/swift3/**/SwaggerClientTests/Pods/
|
||||
#samples/client/petstore/swift3/**/SwaggerClientTests/Pods/Pods.xcodeproj/xcuserdata
|
||||
#samples/client/petstore/swift3/**/SwaggerClientTests/Pods/Pods.xcodeproj/xcshareddata/xcschemes
|
||||
samples/client/petstore/swift3/**/SwaggerClientTests/Podfile.lock
|
||||
|
||||
# C#
|
||||
*.csproj.user
|
||||
|
||||
59
.travis.yml
59
.travis.yml
@@ -1,9 +1,6 @@
|
||||
sudo: required
|
||||
language: java
|
||||
jdk:
|
||||
- oraclejdk7
|
||||
- oraclejdk8
|
||||
|
||||
language: objective-c
|
||||
osx_image: xcode8.2
|
||||
cache:
|
||||
directories:
|
||||
- $HOME/.m2
|
||||
@@ -25,39 +22,59 @@ cache:
|
||||
- $HOME/samples/client/petstore/typescript-fetch/npm/with-npm-version/typings
|
||||
- $HOME/samples/client/petstore/typescript-angular/node_modules
|
||||
- $HOME/samples/client/petstore/typescript-angular/typings
|
||||
- /Users/travis/.cocoapods/repos/master
|
||||
# note: docker is not yet supported in iOS build
|
||||
#services:
|
||||
# - docker
|
||||
|
||||
services:
|
||||
- docker
|
||||
|
||||
# comment out the host table change to use the public petstore server
|
||||
addons:
|
||||
hosts:
|
||||
- petstore.swagger.io
|
||||
|
||||
before_install:
|
||||
# required when sudo: required for the Ruby petstore tests
|
||||
- gem install bundler
|
||||
- export SW=`pwd`
|
||||
- rvm list
|
||||
- rvm use 2.2.5
|
||||
- gem environment
|
||||
- gem install bundler -N --no-ri --no-rdoc
|
||||
- gem install cocoapods -v 1.2.1 -N --no-ri --no-rdoc
|
||||
- gem install xcpretty -N --no-ri --no-rdoc
|
||||
- pod --version
|
||||
- pod repo update
|
||||
- pod setup --silent > /dev/null
|
||||
- npm install -g typescript
|
||||
- npm config set registry http://registry.npmjs.org/
|
||||
- sudo pip install virtualenv
|
||||
- brew install sbt
|
||||
- brew install leiningen
|
||||
- brew install bats
|
||||
- brew install curl
|
||||
- brew install python3
|
||||
- pip install virtualenv
|
||||
# start local petstore server
|
||||
- git clone -b docker --single-branch https://github.com/wing328/swagger-samples
|
||||
- cd swagger-samples/java/java-jersey-jaxrs
|
||||
- sudo mvn jetty:run &
|
||||
- cd $SW
|
||||
# NOTE: iOS build not support docker at the moment
|
||||
# to run petstore server locally via docker
|
||||
- docker pull swaggerapi/petstore
|
||||
- docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore
|
||||
- docker ps -a
|
||||
# Add bats test framework and cURL for Bash script integration tests
|
||||
- sudo add-apt-repository ppa:duggan/bats --yes
|
||||
- sudo apt-get update -qq
|
||||
- sudo apt-get install -qq bats
|
||||
- sudo apt-get install -qq curl
|
||||
#- docker pull swaggerapi/petstore
|
||||
#- docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore
|
||||
#- docker ps -a
|
||||
# Add rebar3 build tool and recent Erlang/OTP for Erlang petstore server tests.
|
||||
# - Travis CI does not support rebar3 [yet](https://github.com/travis-ci/travis-ci/issues/6506#issuecomment-275189490).
|
||||
# - Rely on `kerl` for [pre-compiled versions available](https://docs.travis-ci.com/user/languages/erlang#Choosing-OTP-releases-to-test-against). Rely on installation path chosen by [`travis-erlang-builder`](https://github.com/travis-ci/travis-erlang-builder/blob/e6d016b1a91ca7ecac5a5a46395bde917ea13d36/bin/compile#L18).
|
||||
- . ~/otp/18.2.1/activate && erl -version
|
||||
- curl -f -L -o ./rebar3 https://s3.amazonaws.com/rebar3/rebar3 && chmod +x ./rebar3 && ./rebar3 version && export PATH="${TRAVIS_BUILD_DIR}:$PATH"
|
||||
|
||||
# show host table to confirm petstore.swagger.io is mapped to localhost
|
||||
- cat /etc/hosts
|
||||
# show java version
|
||||
- java -version
|
||||
# show brew version
|
||||
- brew --version
|
||||
# show xcpretty version
|
||||
- xcpretty -v
|
||||
# show go version
|
||||
- go version
|
||||
|
||||
install:
|
||||
# Add Godeps dependencies to GOPATH and PATH
|
||||
|
||||
@@ -14,6 +14,10 @@ dependencies:
|
||||
- "~/.sbt"
|
||||
|
||||
pre:
|
||||
- sudo add-apt-repository ppa:duggan/bats --yes
|
||||
- sudo apt-get update -qq
|
||||
- sudo apt-get install -qq bats
|
||||
- sudo apt-get install -qq curl
|
||||
# to run petstore server locally via docker
|
||||
- docker pull swaggerapi/petstore
|
||||
- docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore
|
||||
|
||||
@@ -27,10 +27,10 @@ Pod::Spec.new do |s|
|
||||
{{/podDocumentationURL}}
|
||||
s.source_files = '{{projectName}}/Classes/Swaggers/**/*.swift'
|
||||
{{#usePromiseKit}}
|
||||
s.dependency 'PromiseKit', '~> 3.1.1'
|
||||
s.dependency 'PromiseKit', '~> 3.5.3'
|
||||
{{/usePromiseKit}}
|
||||
{{#useRxSwift}}
|
||||
s.dependency 'RxSwift', '~> 2.0'
|
||||
s.dependency 'RxSwift', '~> 2.6.1'
|
||||
{{/useRxSwift}}
|
||||
s.dependency 'Alamofire', '~> 3.4.1'
|
||||
s.dependency 'Alamofire', '~> 3.5.1'
|
||||
end
|
||||
|
||||
@@ -15,7 +15,7 @@ Pod::Spec.new do |s|
|
||||
s.screenshots = {{& podScreenshots}}{{/podScreenshots}}{{#podDocumentationURL}}
|
||||
s.documentation_url = '{{podDocumentationURL}}'{{/podDocumentationURL}}
|
||||
s.source_files = '{{projectName}}/Classes/Swaggers/**/*.swift'{{#usePromiseKit}}
|
||||
s.dependency 'PromiseKit', '~> 4.0'{{/usePromiseKit}}{{#useRxSwift}}
|
||||
s.dependency 'RxSwift', '~> 3.0.0-beta.1'{{/useRxSwift}}
|
||||
s.dependency 'PromiseKit', '~> 4.2.2'{{/usePromiseKit}}{{#useRxSwift}}
|
||||
s.dependency 'RxSwift', '~> 3.4.1'{{/useRxSwift}}
|
||||
s.dependency 'Alamofire', '~> 4.0'
|
||||
end
|
||||
|
||||
@@ -80,7 +80,7 @@ open class {{classname}}: APIBase {
|
||||
}
|
||||
observer.on(.completed)
|
||||
}
|
||||
return NopDisposable.instance
|
||||
return Disposables.create()
|
||||
}
|
||||
}
|
||||
{{/useRxSwift}}
|
||||
|
||||
44
pom.xml
44
pom.xml
@@ -792,22 +792,18 @@
|
||||
</activation>
|
||||
<modules>
|
||||
<!-- clients -->
|
||||
<module>samples/client/petstore/clojure</module>
|
||||
<module>samples/client/petstore/java/feign</module>
|
||||
<module>samples/client/petstore/java/jersey1</module>
|
||||
<module>samples/client/petstore/java/jersey2</module>
|
||||
<module>samples/client/petstore/java/okhttp-gson</module>
|
||||
<module>samples/client/petstore/java/retrofit</module>
|
||||
<module>samples/client/petstore/java/retrofit2</module>
|
||||
<module>samples/client/petstore/java/retrofit2rx</module>
|
||||
<module>samples/client/petstore/jaxrs-cxf-client</module>
|
||||
<module>samples/client/petstore/java/resttemplate</module>
|
||||
<module>samples/client/petstore/ruby</module>
|
||||
<module>samples/client/petstore/swift3/default/SwaggerClientTests</module>
|
||||
<module>samples/client/petstore/swift3/promisekit/SwaggerClientTests</module>
|
||||
<module>samples/client/petstore/swift3/rxswift/SwaggerClientTests</module>
|
||||
<module>samples/client/petstore/swift/default/SwaggerClientTests</module>
|
||||
<module>samples/client/petstore/swift/promisekit/SwaggerClientTests</module>
|
||||
<module>samples/client/petstore/swift/rxswift/SwaggerClientTests</module>
|
||||
<!--<module>samples/client/petstore/objc/default/SwaggerClientTests</module>
|
||||
<module>samples/client/petstore/objc/core-data/SwaggerClientTests</module>
|
||||
<module>samples/client/petstore/bash</module>-->
|
||||
<module>samples/client/petstore/scala</module>
|
||||
<module>samples/client/petstore/akka-scala</module>
|
||||
<module>samples/client/petstore/ruby</module>
|
||||
<module>samples/client/petstore/android/volley</module>
|
||||
<module>samples/client/petstore/bash</module>
|
||||
<module>samples/client/petstore/go</module>
|
||||
<module>samples/client/petstore/javascript</module>
|
||||
<module>samples/client/petstore/python</module>
|
||||
<module>samples/client/petstore/typescript-fetch/builds/default</module>
|
||||
@@ -817,28 +813,8 @@
|
||||
<module>samples/client/petstore/typescript-angular</module>
|
||||
<module>samples/client/petstore/typescript-node/npm</module>
|
||||
<module>samples/client/petstore/typescript-jquery/npm</module>
|
||||
<!--module>samples/client/petstore/objc/SwaggerClientTests</module-->
|
||||
<!--module>samples/client/petstore/swift/SwaggerClientTests</module-->
|
||||
<!-- servers -->
|
||||
<module>samples/server/petstore/java-inflector</module>
|
||||
<module>samples/server/petstore/java-play-framework</module>
|
||||
<module>samples/server/petstore/undertow</module>
|
||||
<module>samples/server/petstore/jaxrs/jersey1</module>
|
||||
<module>samples/server/petstore/jaxrs/jersey2</module>
|
||||
<module>samples/server/petstore/jaxrs-resteasy/default</module>
|
||||
<module>samples/server/petstore/jaxrs-resteasy/eap</module>
|
||||
<module>samples/server/petstore/jaxrs-resteasy/eap-joda</module>
|
||||
<module>samples/server/petstore/jaxrs-resteasy/joda</module>
|
||||
<module>samples/server/petstore/scalatra</module>
|
||||
<module>samples/server/petstore/spring-mvc</module>
|
||||
<module>samples/client/petstore/spring-cloud</module>
|
||||
<module>samples/server/petstore/springboot</module>
|
||||
<module>samples/server/petstore/springboot-beanvalidation</module>
|
||||
<module>samples/server/petstore/jaxrs-cxf</module>
|
||||
<module>samples/server/petstore/jaxrs-cxf-annotated-base-path</module>
|
||||
<module>samples/server/petstore/jaxrs-cxf-cdi</module>
|
||||
<module>samples/server/petstore/jaxrs-cxf-non-spring-app</module>
|
||||
<!--<module>samples/server/petstore/java-msf4j</module> note: JDK8 only -->
|
||||
<!-- <module>samples/server/petstore/erlang-server</module> note: make sample compilation work -->
|
||||
</modules>
|
||||
</profile>
|
||||
|
||||
@@ -792,6 +792,8 @@
|
||||
</activation>
|
||||
<modules>
|
||||
<!-- clients -->
|
||||
<module>samples/client/petstore/go</module>
|
||||
<!-- test java-related projects -->
|
||||
<module>samples/client/petstore/clojure</module>
|
||||
<module>samples/client/petstore/java/feign</module>
|
||||
<module>samples/client/petstore/java/jersey1</module>
|
||||
@@ -802,25 +804,9 @@
|
||||
<module>samples/client/petstore/java/retrofit2rx</module>
|
||||
<module>samples/client/petstore/jaxrs-cxf-client</module>
|
||||
<module>samples/client/petstore/java/resttemplate</module>
|
||||
<!-- only test java-related projects
|
||||
<module>samples/client/petstore/scala</module>
|
||||
<module>samples/client/petstore/akka-scala</module>
|
||||
<module>samples/client/petstore/ruby</module>
|
||||
<module>samples/client/petstore/android/volley</module>
|
||||
<module>samples/client/petstore/bash</module>
|
||||
<module>samples/client/petstore/go</module>
|
||||
<module>samples/client/petstore/javascript</module>
|
||||
<module>samples/client/petstore/python</module>
|
||||
<module>samples/client/petstore/typescript-fetch/builds/default</module>
|
||||
<module>samples/client/petstore/typescript-fetch/builds/es6-target</module>
|
||||
<module>samples/client/petstore/typescript-fetch/builds/with-npm-version</module>
|
||||
<module>samples/client/petstore/typescript-fetch/tests/default</module>
|
||||
<module>samples/client/petstore/typescript-angular</module>
|
||||
<module>samples/client/petstore/typescript-node/npm</module>
|
||||
<module>samples/client/petstore/typescript-jquery/npm</module>
|
||||
-->
|
||||
<!--module>samples/client/petstore/objc/SwaggerClientTests</module-->
|
||||
<!--module>samples/client/petstore/swift/SwaggerClientTests</module-->
|
||||
<!-- comment out bash as it's failing after switching to CircleCI
|
||||
<module>samples/client/petstore/bash</module> -->
|
||||
<!-- servers -->
|
||||
<module>samples/server/petstore/java-inflector</module>
|
||||
<module>samples/server/petstore/java-play-framework</module>
|
||||
@@ -831,17 +817,15 @@
|
||||
<module>samples/server/petstore/jaxrs-resteasy/eap</module>
|
||||
<module>samples/server/petstore/jaxrs-resteasy/eap-joda</module>
|
||||
<module>samples/server/petstore/jaxrs-resteasy/joda</module>
|
||||
<!--<module>samples/server/petstore/scalatra</module>-->
|
||||
<module>samples/server/petstore/spring-mvc</module>
|
||||
<!-- comment out due to change in method signature
|
||||
<module>samples/client/petstore/spring-cloud</module> -->
|
||||
<module>samples/client/petstore/spring-cloud</module>
|
||||
<module>samples/server/petstore/springboot</module>
|
||||
<module>samples/server/petstore/springboot-beanvalidation</module>
|
||||
<module>samples/server/petstore/jaxrs-cxf</module>
|
||||
<module>samples/server/petstore/jaxrs-cxf-annotated-base-path</module>
|
||||
<module>samples/server/petstore/jaxrs-cxf-cdi</module>
|
||||
<module>samples/server/petstore/jaxrs-cxf-non-spring-app</module>
|
||||
<!--<module>samples/server/petstore/java-msf4j</module> note: JDK8 only -->
|
||||
<module>samples/server/petstore/java-msf4j</module>
|
||||
</modules>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
<project>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>io.swagger</groupId>
|
||||
<artifactId>ObjcPetstoreClientTests</artifactId>
|
||||
<artifactId>ObjcCoreDataPetstoreClientTests</artifactId>
|
||||
<packaging>pom</packaging>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>Objective-C Swagger Petstore Client</name>
|
||||
<name>Objective-C Core Data Swagger Petstore Client</name>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
||||
@@ -9,5 +9,5 @@ Pod::Spec.new do |s|
|
||||
s.homepage = 'https://github.com/swagger-api/swagger-codegen'
|
||||
s.summary = 'PetstoreClient'
|
||||
s.source_files = 'PetstoreClient/Classes/Swaggers/**/*.swift'
|
||||
s.dependency 'Alamofire', '~> 3.4.1'
|
||||
s.dependency 'Alamofire', '~> 3.5.1'
|
||||
end
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,369 +0,0 @@
|
||||
//
|
||||
// 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
|
||||
|
||||
if let request = URLString as? NSMutableURLRequest {
|
||||
mutableURLRequest = request
|
||||
} else if let request = URLString as? NSURLRequest {
|
||||
mutableURLRequest = request.URLRequest
|
||||
} else {
|
||||
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)
|
||||
}
|
||||
@@ -1,248 +0,0 @@
|
||||
//
|
||||
// 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 initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
//
|
||||
// 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
|
||||
}
|
||||
|
||||
/// Custom keys contained within certain NSError `userInfo` dictionaries generated by Alamofire.
|
||||
public struct UserInfoKeys {
|
||||
/// The content type user info key for a `.ContentTypeValidationFailed` error stored as a `String` value.
|
||||
public static let ContentType = "ContentType"
|
||||
|
||||
/// The status code user info key for a `.StatusCodeValidationFailed` error stored as an `Int` value.
|
||||
public static let StatusCode = "StatusCode"
|
||||
}
|
||||
|
||||
/**
|
||||
Creates an `NSError` with the given error code and failure reason.
|
||||
|
||||
- parameter code: The error code.
|
||||
- parameter failureReason: The failure reason.
|
||||
|
||||
- returns: An `NSError` with the given error code and failure reason.
|
||||
*/
|
||||
@available(*, deprecated=3.4.0)
|
||||
public static func errorWithCode(code: Code, failureReason: String) -> NSError {
|
||||
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.
|
||||
*/
|
||||
@available(*, deprecated=3.4.0)
|
||||
public static func errorWithCode(code: Int, failureReason: String) -> NSError {
|
||||
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
|
||||
return NSError(domain: Domain, code: code, userInfo: userInfo)
|
||||
}
|
||||
|
||||
static func error(domain domain: String = Error.Domain, code: Code, failureReason: String) -> NSError {
|
||||
return error(domain: domain, code: code.rawValue, failureReason: failureReason)
|
||||
}
|
||||
|
||||
static func error(domain domain: String = Error.Domain, code: Int, failureReason: String) -> NSError {
|
||||
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
|
||||
return NSError(domain: domain, code: code, userInfo: userInfo)
|
||||
}
|
||||
}
|
||||
@@ -1,779 +0,0 @@
|
||||
//
|
||||
// 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 = info[kCFBundleExecutableKey as String] as? String ?? "Unknown"
|
||||
let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown"
|
||||
let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown"
|
||||
let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown"
|
||||
|
||||
let osNameVersion: String = {
|
||||
let versionString: String
|
||||
|
||||
if #available(OSX 10.10, *) {
|
||||
let version = NSProcessInfo.processInfo().operatingSystemVersion
|
||||
versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"
|
||||
} else {
|
||||
versionString = "10.9"
|
||||
}
|
||||
|
||||
let osName: String = {
|
||||
#if os(iOS)
|
||||
return "iOS"
|
||||
#elseif os(watchOS)
|
||||
return "watchOS"
|
||||
#elseif os(tvOS)
|
||||
return "tvOS"
|
||||
#elseif os(OSX)
|
||||
return "OS X"
|
||||
#elseif os(Linux)
|
||||
return "Linux"
|
||||
#else
|
||||
return "Unknown"
|
||||
#endif
|
||||
}()
|
||||
|
||||
return "\(osName) \(versionString)"
|
||||
}()
|
||||
|
||||
return "\(executable)/\(bundle) (\(appVersion)/\(appBuild)); \(osNameVersion))"
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
guard delegate === session.delegate else { return nil }
|
||||
|
||||
self.delegate = delegate
|
||||
self.session = session
|
||||
|
||||
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 class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
|
||||
private var subdelegates: [Int: Request.TaskDelegate] = [:]
|
||||
private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
|
||||
|
||||
/// Access the task delegate for the specified task in a thread-safe manner.
|
||||
public 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 all behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:` and requires the caller to call the `completionHandler`.
|
||||
public var sessionDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`.
|
||||
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))
|
||||
{
|
||||
guard sessionDidReceiveChallengeWithCompletion == nil else {
|
||||
sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler)
|
||||
return
|
||||
}
|
||||
|
||||
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 all behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:` and
|
||||
/// requires the caller to call the `completionHandler`.
|
||||
public var taskWillPerformHTTPRedirectionWithCompletion: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest, NSURLRequest? -> Void) -> Void)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`.
|
||||
public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
|
||||
|
||||
/// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:` and
|
||||
/// requires the caller to call the `completionHandler`.
|
||||
public var taskDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`.
|
||||
public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)?
|
||||
|
||||
/// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:` and
|
||||
/// requires the caller to call the `completionHandler`.
|
||||
public var taskNeedNewBodyStreamWithCompletion: ((NSURLSession, NSURLSessionTask, NSInputStream? -> Void) -> Void)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.
|
||||
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)
|
||||
{
|
||||
guard taskWillPerformHTTPRedirectionWithCompletion == nil else {
|
||||
taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler)
|
||||
return
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
guard taskDidReceiveChallengeWithCompletion == nil else {
|
||||
taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler)
|
||||
return
|
||||
}
|
||||
|
||||
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
|
||||
let result = taskDidReceiveChallenge(session, task, challenge)
|
||||
completionHandler(result.0, result.1)
|
||||
} 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)
|
||||
{
|
||||
guard taskNeedNewBodyStreamWithCompletion == nil else {
|
||||
taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler)
|
||||
return
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidComplete, object: task)
|
||||
|
||||
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 all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:` and
|
||||
/// requires caller to call the `completionHandler`.
|
||||
public var dataTaskDidReceiveResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSURLResponse, NSURLSessionResponseDisposition -> Void) -> Void)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`.
|
||||
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?)?
|
||||
|
||||
/// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:` and
|
||||
/// requires caller to call the `completionHandler`.
|
||||
public var dataTaskWillCacheResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse, NSCachedURLResponse? -> Void) -> Void)?
|
||||
|
||||
// MARK: Delegate Methods
|
||||
|
||||
/**
|
||||
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)
|
||||
{
|
||||
guard dataTaskDidReceiveResponseWithCompletion == nil else {
|
||||
dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler)
|
||||
return
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
guard dataTaskWillCacheResponseWithCompletion == nil else {
|
||||
dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler)
|
||||
return
|
||||
}
|
||||
|
||||
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 {
|
||||
#if !os(OSX)
|
||||
if selector == #selector(NSURLSessionDelegate.URLSessionDidFinishEventsForBackgroundURLSession(_:)) {
|
||||
return sessionDidFinishEventsForBackgroundURLSession != nil
|
||||
}
|
||||
#endif
|
||||
|
||||
switch selector {
|
||||
case #selector(NSURLSessionDelegate.URLSession(_:didBecomeInvalidWithError:)):
|
||||
return sessionDidBecomeInvalidWithError != nil
|
||||
case #selector(NSURLSessionDelegate.URLSession(_:didReceiveChallenge:completionHandler:)):
|
||||
return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil)
|
||||
case #selector(NSURLSessionTaskDelegate.URLSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)):
|
||||
return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil)
|
||||
case #selector(NSURLSessionDataDelegate.URLSession(_:dataTask:didReceiveResponse:completionHandler:)):
|
||||
return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil)
|
||||
default:
|
||||
return self.dynamicType.instancesRespondToSelector(selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,659 +0,0 @@
|
||||
//
|
||||
// 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(code: 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)"
|
||||
setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
|
||||
return
|
||||
}
|
||||
|
||||
//============================================================
|
||||
// Check 2 - is file URL reachable?
|
||||
//============================================================
|
||||
|
||||
var isReachable = true
|
||||
|
||||
if #available(OSX 10.10, *) {
|
||||
isReachable = fileURL.checkPromisedItemIsReachableAndReturnError(nil)
|
||||
}
|
||||
|
||||
guard isReachable else {
|
||||
setBodyPartError(code: NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)")
|
||||
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)"
|
||||
setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
|
||||
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)"
|
||||
setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
|
||||
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)"
|
||||
setBodyPartError(code: NSURLErrorCannotOpenFile, failureReason: failureReason)
|
||||
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.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason)
|
||||
} else if !fileURL.fileURL {
|
||||
let failureReason = "The URL does not point to a valid file: \(fileURL)"
|
||||
throw Error.error(domain: NSURLErrorDomain, code: 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.error(domain: NSURLErrorDomain, code: NSURLErrorCannotOpenFile, failureReason: failureReason)
|
||||
}
|
||||
|
||||
outputStream.open()
|
||||
|
||||
self.bodyParts.first?.hasInitialBoundary = true
|
||||
self.bodyParts.last?.hasFinalBoundary = true
|
||||
|
||||
for bodyPart in self.bodyParts {
|
||||
try writeBodyPart(bodyPart, toOutputStream: outputStream)
|
||||
}
|
||||
|
||||
outputStream.close()
|
||||
}
|
||||
|
||||
// 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.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.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason)
|
||||
break
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
inputStream.close()
|
||||
|
||||
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.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.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason)
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
inputStream.close()
|
||||
}
|
||||
|
||||
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.error(domain: NSURLErrorDomain, code: .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(code code: Int, failureReason: String) {
|
||||
guard bodyPartError == nil else { return }
|
||||
bodyPartError = Error.error(domain: NSURLErrorDomain, code: code, failureReason: failureReason)
|
||||
}
|
||||
}
|
||||
@@ -1,244 +0,0 @@
|
||||
//
|
||||
// NetworkReachabilityManager.swift
|
||||
//
|
||||
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
//
|
||||
|
||||
#if !os(watchOS)
|
||||
|
||||
import Foundation
|
||||
import SystemConfiguration
|
||||
|
||||
/**
|
||||
The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and
|
||||
WiFi network interfaces.
|
||||
|
||||
Reachability can be used to determine background information about why a network operation failed, or to retry
|
||||
network requests when a connection is established. It should not be used to prevent a user from initiating a network
|
||||
request, as it's possible that an initial request may be required to establish reachability.
|
||||
*/
|
||||
public class NetworkReachabilityManager {
|
||||
/**
|
||||
Defines the various states of network reachability.
|
||||
|
||||
- Unknown: It is unknown whether the network is reachable.
|
||||
- NotReachable: The network is not reachable.
|
||||
- ReachableOnWWAN: The network is reachable over the WWAN connection.
|
||||
- ReachableOnWiFi: The network is reachable over the WiFi connection.
|
||||
*/
|
||||
public enum NetworkReachabilityStatus {
|
||||
case Unknown
|
||||
case NotReachable
|
||||
case Reachable(ConnectionType)
|
||||
}
|
||||
|
||||
/**
|
||||
Defines the various connection types detected by reachability flags.
|
||||
|
||||
- EthernetOrWiFi: The connection type is either over Ethernet or WiFi.
|
||||
- WWAN: The connection type is a WWAN connection.
|
||||
*/
|
||||
public enum ConnectionType {
|
||||
case EthernetOrWiFi
|
||||
case WWAN
|
||||
}
|
||||
|
||||
/// A closure executed when the network reachability status changes. The closure takes a single argument: the
|
||||
/// network reachability status.
|
||||
public typealias Listener = NetworkReachabilityStatus -> Void
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
/// Whether the network is currently reachable.
|
||||
public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi }
|
||||
|
||||
/// Whether the network is currently reachable over the WWAN interface.
|
||||
public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .Reachable(.WWAN) }
|
||||
|
||||
/// Whether the network is currently reachable over Ethernet or WiFi interface.
|
||||
public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .Reachable(.EthernetOrWiFi) }
|
||||
|
||||
/// The current network reachability status.
|
||||
public var networkReachabilityStatus: NetworkReachabilityStatus {
|
||||
guard let flags = self.flags else { return .Unknown }
|
||||
return networkReachabilityStatusForFlags(flags)
|
||||
}
|
||||
|
||||
/// The dispatch queue to execute the `listener` closure on.
|
||||
public var listenerQueue: dispatch_queue_t = dispatch_get_main_queue()
|
||||
|
||||
/// A closure executed when the network reachability status changes.
|
||||
public var listener: Listener?
|
||||
|
||||
private var flags: SCNetworkReachabilityFlags? {
|
||||
var flags = SCNetworkReachabilityFlags()
|
||||
|
||||
if SCNetworkReachabilityGetFlags(reachability, &flags) {
|
||||
return flags
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
private let reachability: SCNetworkReachability
|
||||
private var previousFlags: SCNetworkReachabilityFlags
|
||||
|
||||
// MARK: - Initialization
|
||||
|
||||
/**
|
||||
Creates a `NetworkReachabilityManager` instance with the specified host.
|
||||
|
||||
- parameter host: The host used to evaluate network reachability.
|
||||
|
||||
- returns: The new `NetworkReachabilityManager` instance.
|
||||
*/
|
||||
public convenience init?(host: String) {
|
||||
guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil }
|
||||
self.init(reachability: reachability)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0.
|
||||
|
||||
Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing
|
||||
status of the device, both IPv4 and IPv6.
|
||||
|
||||
- returns: The new `NetworkReachabilityManager` instance.
|
||||
*/
|
||||
public convenience init?() {
|
||||
var address = sockaddr_in()
|
||||
address.sin_len = UInt8(sizeofValue(address))
|
||||
address.sin_family = sa_family_t(AF_INET)
|
||||
|
||||
guard let reachability = withUnsafePointer(&address, {
|
||||
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
|
||||
}) else { return nil }
|
||||
|
||||
self.init(reachability: reachability)
|
||||
}
|
||||
|
||||
private init(reachability: SCNetworkReachability) {
|
||||
self.reachability = reachability
|
||||
self.previousFlags = SCNetworkReachabilityFlags()
|
||||
}
|
||||
|
||||
deinit {
|
||||
stopListening()
|
||||
}
|
||||
|
||||
// MARK: - Listening
|
||||
|
||||
/**
|
||||
Starts listening for changes in network reachability status.
|
||||
|
||||
- returns: `true` if listening was started successfully, `false` otherwise.
|
||||
*/
|
||||
public func startListening() -> Bool {
|
||||
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
|
||||
context.info = UnsafeMutablePointer(Unmanaged.passUnretained(self).toOpaque())
|
||||
|
||||
let callbackEnabled = SCNetworkReachabilitySetCallback(
|
||||
reachability,
|
||||
{ (_, flags, info) in
|
||||
let reachability = Unmanaged<NetworkReachabilityManager>.fromOpaque(COpaquePointer(info)).takeUnretainedValue()
|
||||
reachability.notifyListener(flags)
|
||||
},
|
||||
&context
|
||||
)
|
||||
|
||||
let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue)
|
||||
|
||||
dispatch_async(listenerQueue) {
|
||||
self.previousFlags = SCNetworkReachabilityFlags()
|
||||
self.notifyListener(self.flags ?? SCNetworkReachabilityFlags())
|
||||
}
|
||||
|
||||
return callbackEnabled && queueEnabled
|
||||
}
|
||||
|
||||
/**
|
||||
Stops listening for changes in network reachability status.
|
||||
*/
|
||||
public func stopListening() {
|
||||
SCNetworkReachabilitySetCallback(reachability, nil, nil)
|
||||
SCNetworkReachabilitySetDispatchQueue(reachability, nil)
|
||||
}
|
||||
|
||||
// MARK: - Internal - Listener Notification
|
||||
|
||||
func notifyListener(flags: SCNetworkReachabilityFlags) {
|
||||
guard previousFlags != flags else { return }
|
||||
previousFlags = flags
|
||||
|
||||
listener?(networkReachabilityStatusForFlags(flags))
|
||||
}
|
||||
|
||||
// MARK: - Internal - Network Reachability Status
|
||||
|
||||
func networkReachabilityStatusForFlags(flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus {
|
||||
guard flags.contains(.Reachable) else { return .NotReachable }
|
||||
|
||||
var networkStatus: NetworkReachabilityStatus = .NotReachable
|
||||
|
||||
if !flags.contains(.ConnectionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) }
|
||||
|
||||
if flags.contains(.ConnectionOnDemand) || flags.contains(.ConnectionOnTraffic) {
|
||||
if !flags.contains(.InterventionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) }
|
||||
}
|
||||
|
||||
#if os(iOS)
|
||||
if flags.contains(.IsWWAN) { networkStatus = .Reachable(.WWAN) }
|
||||
#endif
|
||||
|
||||
return networkStatus
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {}
|
||||
|
||||
/**
|
||||
Returns whether the two network reachability status values are equal.
|
||||
|
||||
- parameter lhs: The left-hand side value to compare.
|
||||
- parameter rhs: The right-hand side value to compare.
|
||||
|
||||
- returns: `true` if the two values are equal, `false` otherwise.
|
||||
*/
|
||||
public func ==(
|
||||
lhs: NetworkReachabilityManager.NetworkReachabilityStatus,
|
||||
rhs: NetworkReachabilityManager.NetworkReachabilityStatus)
|
||||
-> Bool
|
||||
{
|
||||
switch (lhs, rhs) {
|
||||
case (.Unknown, .Unknown):
|
||||
return true
|
||||
case (.NotReachable, .NotReachable):
|
||||
return true
|
||||
case let (.Reachable(lhsConnectionType), .Reachable(rhsConnectionType)):
|
||||
return lhsConnectionType == rhsConnectionType
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,47 +0,0 @@
|
||||
//
|
||||
// Notifications.swift
|
||||
//
|
||||
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Contains all the `NSNotification` names posted by Alamofire with descriptions of each notification's payload.
|
||||
public struct Notifications {
|
||||
/// Used as a namespace for all `NSURLSessionTask` related notifications.
|
||||
public struct Task {
|
||||
/// Notification posted when an `NSURLSessionTask` is resumed. The notification `object` contains the resumed
|
||||
/// `NSURLSessionTask`.
|
||||
public static let DidResume = "com.alamofire.notifications.task.didResume"
|
||||
|
||||
/// Notification posted when an `NSURLSessionTask` is suspended. The notification `object` contains the
|
||||
/// suspended `NSURLSessionTask`.
|
||||
public static let DidSuspend = "com.alamofire.notifications.task.didSuspend"
|
||||
|
||||
/// Notification posted when an `NSURLSessionTask` is cancelled. The notification `object` contains the
|
||||
/// cancelled `NSURLSessionTask`.
|
||||
public static let DidCancel = "com.alamofire.notifications.task.didCancel"
|
||||
|
||||
/// Notification posted when an `NSURLSessionTask` is completed. The notification `object` contains the
|
||||
/// completed `NSURLSessionTask`.
|
||||
public static let DidComplete = "com.alamofire.notifications.task.didComplete"
|
||||
}
|
||||
}
|
||||
@@ -1,261 +0,0 @@
|
||||
//
|
||||
// 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 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)
|
||||
where !parameters.isEmpty
|
||||
{
|
||||
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)
|
||||
|
||||
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
|
||||
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
|
||||
)
|
||||
|
||||
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
|
||||
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 Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no
|
||||
// longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more
|
||||
// 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 = startIndex..<endIndex
|
||||
|
||||
let substring = string.substringWithRange(range)
|
||||
|
||||
escaped += substring.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? substring
|
||||
|
||||
index = endIndex
|
||||
}
|
||||
}
|
||||
|
||||
return escaped
|
||||
}
|
||||
}
|
||||
@@ -1,568 +0,0 @@
|
||||
//
|
||||
// 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 }
|
||||
|
||||
var startTime: CFAbsoluteTime?
|
||||
var endTime: CFAbsoluteTime?
|
||||
|
||||
// MARK: - Lifecycle
|
||||
|
||||
init(session: NSURLSession, task: NSURLSessionTask) {
|
||||
self.session = session
|
||||
|
||||
switch task {
|
||||
case is NSURLSessionUploadTask:
|
||||
delegate = UploadTaskDelegate(task: task)
|
||||
case is NSURLSessionDataTask:
|
||||
delegate = DataTaskDelegate(task: task)
|
||||
case is NSURLSessionDownloadTask:
|
||||
delegate = DownloadTaskDelegate(task: task)
|
||||
default:
|
||||
delegate = TaskDelegate(task: task)
|
||||
}
|
||||
|
||||
delegate.queue.addOperationWithBlock { self.endTime = CFAbsoluteTimeGetCurrent() }
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
/**
|
||||
Returns a base64 encoded basic authentication credential as an authorization header dictionary.
|
||||
|
||||
- parameter user: The user.
|
||||
- parameter password: The password.
|
||||
|
||||
- returns: A dictionary with Authorization key and credential value or empty dictionary if encoding fails.
|
||||
*/
|
||||
public static func authorizationHeader(user user: String, password: String) -> [String: String] {
|
||||
guard let data = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding) else { return [:] }
|
||||
|
||||
let credential = data.base64EncodedStringWithOptions([])
|
||||
|
||||
return ["Authorization": "Basic \(credential)"]
|
||||
}
|
||||
|
||||
// MARK: - Progress
|
||||
|
||||
/**
|
||||
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
|
||||
|
||||
/**
|
||||
Resumes the request.
|
||||
*/
|
||||
public func resume() {
|
||||
if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() }
|
||||
|
||||
task.resume()
|
||||
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidResume, object: task)
|
||||
}
|
||||
|
||||
/**
|
||||
Suspends the request.
|
||||
*/
|
||||
public func suspend() {
|
||||
task.suspend()
|
||||
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidSuspend, object: task)
|
||||
}
|
||||
|
||||
/**
|
||||
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()
|
||||
}
|
||||
|
||||
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidCancel, object: task)
|
||||
}
|
||||
|
||||
// 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 initialResponseTime: CFAbsoluteTime?
|
||||
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 = .RejectProtectionSpace
|
||||
} 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 initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
|
||||
|
||||
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()))\"")
|
||||
}
|
||||
}
|
||||
|
||||
var headers: [NSObject: AnyObject] = [:]
|
||||
|
||||
if let additionalHeaders = session.configuration.HTTPAdditionalHeaders {
|
||||
for (field, value) in additionalHeaders where field != "Cookie" {
|
||||
headers[field] = value
|
||||
}
|
||||
}
|
||||
|
||||
if let headerFields = request.allHTTPHeaderFields {
|
||||
for (field, value) in headerFields where field != "Cookie" {
|
||||
headers[field] = value
|
||||
}
|
||||
}
|
||||
|
||||
for (field, value) in headers {
|
||||
components.append("-H \"\(field): \(value)\"")
|
||||
}
|
||||
|
||||
if let
|
||||
HTTPBodyData = request.HTTPBody,
|
||||
HTTPBody = String(data: HTTPBodyData, encoding: NSUTF8StringEncoding)
|
||||
{
|
||||
var escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\\\"", withString: "\\\\\"")
|
||||
escapedBody = escapedBody.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()
|
||||
}
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
//
|
||||
// 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>
|
||||
|
||||
/// The timeline of the complete lifecycle of the `Request`.
|
||||
public let timeline: Timeline
|
||||
|
||||
/**
|
||||
Initializes the `Response` instance with the specified URL request, URL response, server data and response
|
||||
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.
|
||||
- parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`.
|
||||
|
||||
- returns: the new `Response` instance.
|
||||
*/
|
||||
public init(
|
||||
request: NSURLRequest?,
|
||||
response: NSHTTPURLResponse?,
|
||||
data: NSData?,
|
||||
result: Result<Value, Error>,
|
||||
timeline: Timeline = Timeline())
|
||||
{
|
||||
self.request = request
|
||||
self.response = response
|
||||
self.data = data
|
||||
self.result = result
|
||||
self.timeline = timeline
|
||||
}
|
||||
}
|
||||
|
||||
// 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)")
|
||||
output.append("[Timeline]: \(timeline.debugDescription)")
|
||||
|
||||
return output.joinWithSeparator("\n")
|
||||
}
|
||||
}
|
||||
@@ -1,378 +0,0 @@
|
||||
//
|
||||
// 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`.
|
||||
associatedtype SerializedObject
|
||||
|
||||
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
|
||||
associatedtype 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
|
||||
)
|
||||
|
||||
let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent()
|
||||
let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime
|
||||
|
||||
let timeline = Timeline(
|
||||
requestStartTime: self.startTime ?? CFAbsoluteTimeGetCurrent(),
|
||||
initialResponseTime: initialResponseTime,
|
||||
requestCompletedTime: requestCompletedTime,
|
||||
serializationCompletedTime: CFAbsoluteTimeGetCurrent()
|
||||
)
|
||||
|
||||
let response = Response<T.SerializedObject, T.ErrorObject>(
|
||||
request: self.request,
|
||||
response: self.response,
|
||||
data: self.delegate.data,
|
||||
result: result,
|
||||
timeline: timeline
|
||||
)
|
||||
|
||||
dispatch_async(queue ?? dispatch_get_main_queue()) { 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.error(code: .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(
|
||||
queue queue: dispatch_queue_t? = nil,
|
||||
completionHandler: Response<NSData, NSError> -> Void)
|
||||
-> Self
|
||||
{
|
||||
return response(queue: queue, 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(
|
||||
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.error(code: .StringSerializationFailed, failureReason: failureReason)
|
||||
return .Failure(error)
|
||||
}
|
||||
|
||||
var convertedEncoding = encoding
|
||||
|
||||
if let encodingName = response?.textEncodingName where convertedEncoding == nil {
|
||||
convertedEncoding = CFStringConvertEncodingToNSStringEncoding(
|
||||
CFStringConvertIANACharSetNameToEncoding(encodingName)
|
||||
)
|
||||
}
|
||||
|
||||
let actualEncoding = convertedEncoding ?? 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.error(code: .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(
|
||||
queue queue: dispatch_queue_t? = nil,
|
||||
encoding: NSStringEncoding? = nil,
|
||||
completionHandler: Response<String, NSError> -> Void)
|
||||
-> Self
|
||||
{
|
||||
return response(
|
||||
queue: queue,
|
||||
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.error(code: .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(
|
||||
queue queue: dispatch_queue_t? = nil,
|
||||
options: NSJSONReadingOptions = .AllowFragments,
|
||||
completionHandler: Response<AnyObject, NSError> -> Void)
|
||||
-> Self
|
||||
{
|
||||
return response(
|
||||
queue: queue,
|
||||
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.error(code: .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(
|
||||
queue queue: dispatch_queue_t? = nil,
|
||||
options: NSPropertyListReadOptions = NSPropertyListReadOptions(),
|
||||
completionHandler: Response<AnyObject, NSError> -> Void)
|
||||
-> Self
|
||||
{
|
||||
return response(
|
||||
queue: queue,
|
||||
responseSerializer: Request.propertyListResponseSerializer(options: options),
|
||||
completionHandler: completionHandler
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
//
|
||||
// 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)"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,304 +0,0 @@
|
||||
//
|
||||
// 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
|
||||
}
|
||||
}
|
||||
@@ -1,182 +0,0 @@
|
||||
//
|
||||
// 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, tvOS 9.0, *)
|
||||
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, tvOS 9.0, *)
|
||||
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
|
||||
@@ -1,138 +0,0 @@
|
||||
//
|
||||
// Timeline.swift
|
||||
//
|
||||
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Responsible for computing the timing metrics for the complete lifecycle of a `Request`.
|
||||
public struct Timeline {
|
||||
/// The time the request was initialized.
|
||||
public let requestStartTime: CFAbsoluteTime
|
||||
|
||||
/// The time the first bytes were received from or sent to the server.
|
||||
public let initialResponseTime: CFAbsoluteTime
|
||||
|
||||
/// The time when the request was completed.
|
||||
public let requestCompletedTime: CFAbsoluteTime
|
||||
|
||||
/// The time when the response serialization was completed.
|
||||
public let serializationCompletedTime: CFAbsoluteTime
|
||||
|
||||
/// The time interval in seconds from the time the request started to the initial response from the server.
|
||||
public let latency: NSTimeInterval
|
||||
|
||||
/// The time interval in seconds from the time the request started to the time the request completed.
|
||||
public let requestDuration: NSTimeInterval
|
||||
|
||||
/// The time interval in seconds from the time the request completed to the time response serialization completed.
|
||||
public let serializationDuration: NSTimeInterval
|
||||
|
||||
/// The time interval in seconds from the time the request started to the time response serialization completed.
|
||||
public let totalDuration: NSTimeInterval
|
||||
|
||||
/**
|
||||
Creates a new `Timeline` instance with the specified request times.
|
||||
|
||||
- parameter requestStartTime: The time the request was initialized. Defaults to `0.0`.
|
||||
- parameter initialResponseTime: The time the first bytes were received from or sent to the server.
|
||||
Defaults to `0.0`.
|
||||
- parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`.
|
||||
- parameter serializationCompletedTime: The time when the response serialization was completed. Defaults
|
||||
to `0.0`.
|
||||
|
||||
- returns: The new `Timeline` instance.
|
||||
*/
|
||||
public init(
|
||||
requestStartTime: CFAbsoluteTime = 0.0,
|
||||
initialResponseTime: CFAbsoluteTime = 0.0,
|
||||
requestCompletedTime: CFAbsoluteTime = 0.0,
|
||||
serializationCompletedTime: CFAbsoluteTime = 0.0)
|
||||
{
|
||||
self.requestStartTime = requestStartTime
|
||||
self.initialResponseTime = initialResponseTime
|
||||
self.requestCompletedTime = requestCompletedTime
|
||||
self.serializationCompletedTime = serializationCompletedTime
|
||||
|
||||
self.latency = initialResponseTime - requestStartTime
|
||||
self.requestDuration = requestCompletedTime - requestStartTime
|
||||
self.serializationDuration = serializationCompletedTime - requestCompletedTime
|
||||
self.totalDuration = serializationCompletedTime - requestStartTime
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
extension Timeline: CustomStringConvertible {
|
||||
/// The textual representation used when written to an output stream, which includes the latency, the request
|
||||
/// duration and the total duration.
|
||||
public var description: String {
|
||||
let latency = String(format: "%.3f", self.latency)
|
||||
let requestDuration = String(format: "%.3f", self.requestDuration)
|
||||
let serializationDuration = String(format: "%.3f", self.serializationDuration)
|
||||
let totalDuration = String(format: "%.3f", self.totalDuration)
|
||||
|
||||
// NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is
|
||||
// fixed, we should move back to string interpolation by reverting commit 7d4a43b1.
|
||||
let timings = [
|
||||
"\"Latency\": " + latency + " secs",
|
||||
"\"Request Duration\": " + requestDuration + " secs",
|
||||
"\"Serialization Duration\": " + serializationDuration + " secs",
|
||||
"\"Total Duration\": " + totalDuration + " secs"
|
||||
]
|
||||
|
||||
return "Timeline: { " + timings.joinWithSeparator(", ") + " }"
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomDebugStringConvertible
|
||||
|
||||
extension Timeline: CustomDebugStringConvertible {
|
||||
/// The textual representation used when written to an output stream, which includes the request start time, the
|
||||
/// initial response time, the request completed time, the serialization completed time, the latency, the request
|
||||
/// duration and the total duration.
|
||||
public var debugDescription: String {
|
||||
let requestStartTime = String(format: "%.3f", self.requestStartTime)
|
||||
let initialResponseTime = String(format: "%.3f", self.initialResponseTime)
|
||||
let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime)
|
||||
let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime)
|
||||
let latency = String(format: "%.3f", self.latency)
|
||||
let requestDuration = String(format: "%.3f", self.requestDuration)
|
||||
let serializationDuration = String(format: "%.3f", self.serializationDuration)
|
||||
let totalDuration = String(format: "%.3f", self.totalDuration)
|
||||
|
||||
// NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is
|
||||
// fixed, we should move back to string interpolation by reverting commit 7d4a43b1.
|
||||
let timings = [
|
||||
"\"Request Start Time\": " + requestStartTime,
|
||||
"\"Initial Response Time\": " + initialResponseTime,
|
||||
"\"Request Completed Time\": " + requestCompletedTime,
|
||||
"\"Serialization Completed Time\": " + serializationCompletedTime,
|
||||
"\"Latency\": " + latency + " secs",
|
||||
"\"Request Duration\": " + requestDuration + " secs",
|
||||
"\"Serialization Duration\": " + serializationDuration + " secs",
|
||||
"\"Total Duration\": " + totalDuration + " secs"
|
||||
]
|
||||
|
||||
return "Timeline: { " + timings.joinWithSeparator(", ") + " }"
|
||||
}
|
||||
}
|
||||
@@ -1,376 +0,0 @@
|
||||
//
|
||||
// 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 initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
|
||||
|
||||
if let taskDidSendBodyData = taskDidSendBodyData {
|
||||
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
|
||||
} else {
|
||||
progress.totalUnitCount = totalBytesExpectedToSend
|
||||
progress.completedUnitCount = totalBytesSent
|
||||
|
||||
uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,214 +0,0 @@
|
||||
//
|
||||
// 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)"
|
||||
|
||||
let error = NSError(
|
||||
domain: Error.Domain,
|
||||
code: Error.Code.StatusCodeValidationFailed.rawValue,
|
||||
userInfo: [
|
||||
NSLocalizedFailureReasonErrorKey: failureReason,
|
||||
Error.UserInfoKeys.StatusCode: response.statusCode
|
||||
]
|
||||
)
|
||||
|
||||
return .Failure(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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 contentType: String
|
||||
let failureReason: String
|
||||
|
||||
if let responseContentType = response.MIMEType {
|
||||
contentType = responseContentType
|
||||
|
||||
failureReason = (
|
||||
"Response content type \"\(responseContentType)\" does not match any acceptable " +
|
||||
"content types: \(acceptableContentTypes)"
|
||||
)
|
||||
} else {
|
||||
contentType = ""
|
||||
failureReason = "Response content type was missing and acceptable content type does not match \"*/*\""
|
||||
}
|
||||
|
||||
let error = NSError(
|
||||
domain: Error.Domain,
|
||||
code: Error.Code.ContentTypeValidationFailed.rawValue,
|
||||
userInfo: [
|
||||
NSLocalizedFailureReasonErrorKey: failureReason,
|
||||
Error.UserInfoKeys.ContentType: contentType
|
||||
]
|
||||
)
|
||||
|
||||
return .Failure(error)
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
},
|
||||
"authors": "",
|
||||
"license": "Apache License, Version 2.0",
|
||||
"homepage": "https://github.com/swagger-api/swagger-codegen",
|
||||
"summary": "PetstoreClient",
|
||||
"source_files": "PetstoreClient/Classes/Swaggers/**/*.swift",
|
||||
"dependencies": {
|
||||
"Alamofire": [
|
||||
"~> 3.4.1"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
PODS:
|
||||
- Alamofire (3.4.2)
|
||||
- PetstoreClient (0.0.1):
|
||||
- Alamofire (~> 3.4.1)
|
||||
|
||||
DEPENDENCIES:
|
||||
- PetstoreClient (from `../`)
|
||||
|
||||
EXTERNAL SOURCES:
|
||||
PetstoreClient:
|
||||
:path: "../"
|
||||
|
||||
SPEC CHECKSUMS:
|
||||
Alamofire: 6aa33201d20d069e1598891cf928883ff1888c7a
|
||||
PetstoreClient: 7489b461499be1b2c4e0ed6624ca76c8db506297
|
||||
|
||||
PODFILE CHECKSUM: 84472aca2a88b7f7ed9fcd63e9f5fdb5ad4aab94
|
||||
|
||||
COCOAPODS: 1.0.0
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,5 +0,0 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
@interface PodsDummy_Alamofire : NSObject
|
||||
@end
|
||||
@implementation PodsDummy_Alamofire
|
||||
@end
|
||||
@@ -1,4 +0,0 @@
|
||||
#ifdef __OBJC__
|
||||
#import <UIKit/UIKit.h>
|
||||
#endif
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
|
||||
FOUNDATION_EXPORT double AlamofireVersionNumber;
|
||||
FOUNDATION_EXPORT const unsigned char AlamofireVersionString[];
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
framework module Alamofire {
|
||||
umbrella header "Alamofire-umbrella.h"
|
||||
|
||||
export *
|
||||
module * { export * }
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/Alamofire
|
||||
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
|
||||
HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public"
|
||||
OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS"
|
||||
PODS_BUILD_DIR = $BUILD_DIR
|
||||
PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)
|
||||
PODS_ROOT = ${SRCROOT}
|
||||
PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier}
|
||||
SKIP_INSTALL = YES
|
||||
@@ -1,26 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>en</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>${EXECUTABLE_NAME}</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>${PRODUCT_BUNDLE_IDENTIFIER}</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>${PRODUCT_NAME}</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>3.4.2</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>${CURRENT_PROJECT_VERSION}</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
<string></string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,26 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>en</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>${EXECUTABLE_NAME}</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>${PRODUCT_BUNDLE_IDENTIFIER}</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>${PRODUCT_NAME}</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>0.0.1</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>${CURRENT_PROJECT_VERSION}</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
<string></string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,5 +0,0 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
@interface PodsDummy_PetstoreClient : NSObject
|
||||
@end
|
||||
@implementation PodsDummy_PetstoreClient
|
||||
@end
|
||||
@@ -1,4 +0,0 @@
|
||||
#ifdef __OBJC__
|
||||
#import <UIKit/UIKit.h>
|
||||
#endif
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
|
||||
FOUNDATION_EXPORT double PetstoreClientVersionNumber;
|
||||
FOUNDATION_EXPORT const unsigned char PetstoreClientVersionString[];
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
framework module PetstoreClient {
|
||||
umbrella header "PetstoreClient-umbrella.h"
|
||||
|
||||
export *
|
||||
module * { export * }
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/PetstoreClient
|
||||
FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire"
|
||||
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
|
||||
HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public"
|
||||
OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS"
|
||||
PODS_BUILD_DIR = $BUILD_DIR
|
||||
PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)
|
||||
PODS_ROOT = ${SRCROOT}
|
||||
PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier}
|
||||
SKIP_INSTALL = YES
|
||||
@@ -1,26 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>en</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>${EXECUTABLE_NAME}</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>${PRODUCT_BUNDLE_IDENTIFIER}</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>${PRODUCT_NAME}</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>${CURRENT_PROJECT_VERSION}</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
<string></string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,231 +0,0 @@
|
||||
# Acknowledgements
|
||||
This application makes use of the following third party libraries:
|
||||
|
||||
## Alamofire
|
||||
|
||||
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.
|
||||
|
||||
|
||||
## PetstoreClient
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright {yyyy} {name of copyright owner}
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
Generated by CocoaPods - https://cocoapods.org
|
||||
@@ -1,265 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>PreferenceSpecifiers</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>FooterText</key>
|
||||
<string>This application makes use of the following third party libraries:</string>
|
||||
<key>Title</key>
|
||||
<string>Acknowledgements</string>
|
||||
<key>Type</key>
|
||||
<string>PSGroupSpecifier</string>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>FooterText</key>
|
||||
<string>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.
|
||||
</string>
|
||||
<key>Title</key>
|
||||
<string>Alamofire</string>
|
||||
<key>Type</key>
|
||||
<string>PSGroupSpecifier</string>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>FooterText</key>
|
||||
<string> Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright {yyyy} {name of copyright owner}
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
</string>
|
||||
<key>Title</key>
|
||||
<string>PetstoreClient</string>
|
||||
<key>Type</key>
|
||||
<string>PSGroupSpecifier</string>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>FooterText</key>
|
||||
<string>Generated by CocoaPods - https://cocoapods.org</string>
|
||||
<key>Title</key>
|
||||
<string></string>
|
||||
<key>Type</key>
|
||||
<string>PSGroupSpecifier</string>
|
||||
</dict>
|
||||
</array>
|
||||
<key>StringsTable</key>
|
||||
<string>Acknowledgements</string>
|
||||
<key>Title</key>
|
||||
<string>Acknowledgements</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,5 +0,0 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
@interface PodsDummy_Pods_SwaggerClient : NSObject
|
||||
@end
|
||||
@implementation PodsDummy_Pods_SwaggerClient
|
||||
@end
|
||||
@@ -1,93 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
|
||||
mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
|
||||
|
||||
SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}"
|
||||
|
||||
install_framework()
|
||||
{
|
||||
if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then
|
||||
local source="${BUILT_PRODUCTS_DIR}/$1"
|
||||
elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then
|
||||
local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")"
|
||||
elif [ -r "$1" ]; then
|
||||
local source="$1"
|
||||
fi
|
||||
|
||||
local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
|
||||
|
||||
if [ -L "${source}" ]; then
|
||||
echo "Symlinked..."
|
||||
source="$(readlink "${source}")"
|
||||
fi
|
||||
|
||||
# use filter instead of exclude so missing patterns dont' throw errors
|
||||
echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\""
|
||||
rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}"
|
||||
|
||||
local basename
|
||||
basename="$(basename -s .framework "$1")"
|
||||
binary="${destination}/${basename}.framework/${basename}"
|
||||
if ! [ -r "$binary" ]; then
|
||||
binary="${destination}/${basename}"
|
||||
fi
|
||||
|
||||
# Strip invalid architectures so "fat" simulator / device frameworks work on device
|
||||
if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then
|
||||
strip_invalid_archs "$binary"
|
||||
fi
|
||||
|
||||
# Resign the code if required by the build settings to avoid unstable apps
|
||||
code_sign_if_enabled "${destination}/$(basename "$1")"
|
||||
|
||||
# Embed linked Swift runtime libraries. No longer necessary as of Xcode 7.
|
||||
if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then
|
||||
local swift_runtime_libs
|
||||
swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]})
|
||||
for lib in $swift_runtime_libs; do
|
||||
echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\""
|
||||
rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}"
|
||||
code_sign_if_enabled "${destination}/${lib}"
|
||||
done
|
||||
fi
|
||||
}
|
||||
|
||||
# Signs a framework with the provided identity
|
||||
code_sign_if_enabled() {
|
||||
if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then
|
||||
# Use the current code_sign_identitiy
|
||||
echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}"
|
||||
echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements \"$1\""
|
||||
/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements "$1"
|
||||
fi
|
||||
}
|
||||
|
||||
# Strip invalid architectures
|
||||
strip_invalid_archs() {
|
||||
binary="$1"
|
||||
# Get architectures for current file
|
||||
archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)"
|
||||
stripped=""
|
||||
for arch in $archs; do
|
||||
if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then
|
||||
# Strip non-valid architectures in-place
|
||||
lipo -remove "$arch" -output "$binary" "$binary" || exit 1
|
||||
stripped="$stripped $arch"
|
||||
fi
|
||||
done
|
||||
if [[ "$stripped" ]]; then
|
||||
echo "Stripped $binary of architectures:$stripped"
|
||||
fi
|
||||
}
|
||||
|
||||
|
||||
if [[ "$CONFIGURATION" == "Debug" ]]; then
|
||||
install_framework "$BUILT_PRODUCTS_DIR/Alamofire/Alamofire.framework"
|
||||
install_framework "$BUILT_PRODUCTS_DIR/PetstoreClient/PetstoreClient.framework"
|
||||
fi
|
||||
if [[ "$CONFIGURATION" == "Release" ]]; then
|
||||
install_framework "$BUILT_PRODUCTS_DIR/Alamofire/Alamofire.framework"
|
||||
install_framework "$BUILT_PRODUCTS_DIR/PetstoreClient/PetstoreClient.framework"
|
||||
fi
|
||||
@@ -1,102 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
|
||||
|
||||
RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt
|
||||
> "$RESOURCES_TO_COPY"
|
||||
|
||||
XCASSET_FILES=()
|
||||
|
||||
case "${TARGETED_DEVICE_FAMILY}" in
|
||||
1,2)
|
||||
TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone"
|
||||
;;
|
||||
1)
|
||||
TARGET_DEVICE_ARGS="--target-device iphone"
|
||||
;;
|
||||
2)
|
||||
TARGET_DEVICE_ARGS="--target-device ipad"
|
||||
;;
|
||||
*)
|
||||
TARGET_DEVICE_ARGS="--target-device mac"
|
||||
;;
|
||||
esac
|
||||
|
||||
realpath() {
|
||||
DIRECTORY="$(cd "${1%/*}" && pwd)"
|
||||
FILENAME="${1##*/}"
|
||||
echo "$DIRECTORY/$FILENAME"
|
||||
}
|
||||
|
||||
install_resource()
|
||||
{
|
||||
if [[ "$1" = /* ]] ; then
|
||||
RESOURCE_PATH="$1"
|
||||
else
|
||||
RESOURCE_PATH="${PODS_ROOT}/$1"
|
||||
fi
|
||||
if [[ ! -e "$RESOURCE_PATH" ]] ; then
|
||||
cat << EOM
|
||||
error: Resource "$RESOURCE_PATH" not found. Run 'pod install' to update the copy resources script.
|
||||
EOM
|
||||
exit 1
|
||||
fi
|
||||
case $RESOURCE_PATH in
|
||||
*.storyboard)
|
||||
echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}"
|
||||
ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS}
|
||||
;;
|
||||
*.xib)
|
||||
echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT}"
|
||||
ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}"
|
||||
;;
|
||||
*.framework)
|
||||
echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
|
||||
mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
|
||||
echo "rsync -av $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
|
||||
rsync -av "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
|
||||
;;
|
||||
*.xcdatamodel)
|
||||
echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH"`.mom\""
|
||||
xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodel`.mom"
|
||||
;;
|
||||
*.xcdatamodeld)
|
||||
echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd\""
|
||||
xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd"
|
||||
;;
|
||||
*.xcmappingmodel)
|
||||
echo "xcrun mapc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm\""
|
||||
xcrun mapc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm"
|
||||
;;
|
||||
*.xcassets)
|
||||
ABSOLUTE_XCASSET_FILE=$(realpath "$RESOURCE_PATH")
|
||||
XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE")
|
||||
;;
|
||||
*)
|
||||
echo "$RESOURCE_PATH"
|
||||
echo "$RESOURCE_PATH" >> "$RESOURCES_TO_COPY"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
|
||||
rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
|
||||
if [[ "${ACTION}" == "install" ]] && [[ "${SKIP_INSTALL}" == "NO" ]]; then
|
||||
mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
|
||||
rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
|
||||
fi
|
||||
rm -f "$RESOURCES_TO_COPY"
|
||||
|
||||
if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "$XCASSET_FILES" ]
|
||||
then
|
||||
# Find all other xcassets (this unfortunately includes those of path pods and other targets).
|
||||
OTHER_XCASSETS=$(find "$PWD" -iname "*.xcassets" -type d)
|
||||
while read line; do
|
||||
if [[ $line != "`realpath $PODS_ROOT`*" ]]; then
|
||||
XCASSET_FILES+=("$line")
|
||||
fi
|
||||
done <<<"$OTHER_XCASSETS"
|
||||
|
||||
printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
|
||||
fi
|
||||
@@ -1,6 +0,0 @@
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
|
||||
FOUNDATION_EXPORT double Pods_SwaggerClientVersionNumber;
|
||||
FOUNDATION_EXPORT const unsigned char Pods_SwaggerClientVersionString[];
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
EMBEDDED_CONTENT_CONTAINS_SWIFT = YES
|
||||
FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient"
|
||||
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
|
||||
LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks'
|
||||
OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient/PetstoreClient.framework/Headers"
|
||||
OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "PetstoreClient"
|
||||
OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS"
|
||||
PODS_BUILD_DIR = $BUILD_DIR
|
||||
PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)
|
||||
PODS_ROOT = ${SRCROOT}/Pods
|
||||
@@ -1,6 +0,0 @@
|
||||
framework module Pods_SwaggerClient {
|
||||
umbrella header "Pods-SwaggerClient-umbrella.h"
|
||||
|
||||
export *
|
||||
module * { export * }
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
EMBEDDED_CONTENT_CONTAINS_SWIFT = YES
|
||||
FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient"
|
||||
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
|
||||
LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks'
|
||||
OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient/PetstoreClient.framework/Headers"
|
||||
OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "PetstoreClient"
|
||||
OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS"
|
||||
PODS_BUILD_DIR = $BUILD_DIR
|
||||
PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)
|
||||
PODS_ROOT = ${SRCROOT}/Pods
|
||||
@@ -1,26 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>en</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>${EXECUTABLE_NAME}</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>${PRODUCT_BUNDLE_IDENTIFIER}</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>${PRODUCT_NAME}</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>${CURRENT_PROJECT_VERSION}</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
<string></string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,3 +0,0 @@
|
||||
# Acknowledgements
|
||||
This application makes use of the following third party libraries:
|
||||
Generated by CocoaPods - https://cocoapods.org
|
||||
@@ -1,29 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>PreferenceSpecifiers</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>FooterText</key>
|
||||
<string>This application makes use of the following third party libraries:</string>
|
||||
<key>Title</key>
|
||||
<string>Acknowledgements</string>
|
||||
<key>Type</key>
|
||||
<string>PSGroupSpecifier</string>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>FooterText</key>
|
||||
<string>Generated by CocoaPods - https://cocoapods.org</string>
|
||||
<key>Title</key>
|
||||
<string></string>
|
||||
<key>Type</key>
|
||||
<string>PSGroupSpecifier</string>
|
||||
</dict>
|
||||
</array>
|
||||
<key>StringsTable</key>
|
||||
<string>Acknowledgements</string>
|
||||
<key>Title</key>
|
||||
<string>Acknowledgements</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,5 +0,0 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
@interface PodsDummy_Pods_SwaggerClientTests : NSObject
|
||||
@end
|
||||
@implementation PodsDummy_Pods_SwaggerClientTests
|
||||
@end
|
||||
@@ -1,84 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
|
||||
mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
|
||||
|
||||
SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}"
|
||||
|
||||
install_framework()
|
||||
{
|
||||
if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then
|
||||
local source="${BUILT_PRODUCTS_DIR}/$1"
|
||||
elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then
|
||||
local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")"
|
||||
elif [ -r "$1" ]; then
|
||||
local source="$1"
|
||||
fi
|
||||
|
||||
local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
|
||||
|
||||
if [ -L "${source}" ]; then
|
||||
echo "Symlinked..."
|
||||
source="$(readlink "${source}")"
|
||||
fi
|
||||
|
||||
# use filter instead of exclude so missing patterns dont' throw errors
|
||||
echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\""
|
||||
rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}"
|
||||
|
||||
local basename
|
||||
basename="$(basename -s .framework "$1")"
|
||||
binary="${destination}/${basename}.framework/${basename}"
|
||||
if ! [ -r "$binary" ]; then
|
||||
binary="${destination}/${basename}"
|
||||
fi
|
||||
|
||||
# Strip invalid architectures so "fat" simulator / device frameworks work on device
|
||||
if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then
|
||||
strip_invalid_archs "$binary"
|
||||
fi
|
||||
|
||||
# Resign the code if required by the build settings to avoid unstable apps
|
||||
code_sign_if_enabled "${destination}/$(basename "$1")"
|
||||
|
||||
# Embed linked Swift runtime libraries. No longer necessary as of Xcode 7.
|
||||
if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then
|
||||
local swift_runtime_libs
|
||||
swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]})
|
||||
for lib in $swift_runtime_libs; do
|
||||
echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\""
|
||||
rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}"
|
||||
code_sign_if_enabled "${destination}/${lib}"
|
||||
done
|
||||
fi
|
||||
}
|
||||
|
||||
# Signs a framework with the provided identity
|
||||
code_sign_if_enabled() {
|
||||
if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then
|
||||
# Use the current code_sign_identitiy
|
||||
echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}"
|
||||
echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements \"$1\""
|
||||
/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements "$1"
|
||||
fi
|
||||
}
|
||||
|
||||
# Strip invalid architectures
|
||||
strip_invalid_archs() {
|
||||
binary="$1"
|
||||
# Get architectures for current file
|
||||
archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)"
|
||||
stripped=""
|
||||
for arch in $archs; do
|
||||
if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then
|
||||
# Strip non-valid architectures in-place
|
||||
lipo -remove "$arch" -output "$binary" "$binary" || exit 1
|
||||
stripped="$stripped $arch"
|
||||
fi
|
||||
done
|
||||
if [[ "$stripped" ]]; then
|
||||
echo "Stripped $binary of architectures:$stripped"
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -1,102 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
|
||||
|
||||
RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt
|
||||
> "$RESOURCES_TO_COPY"
|
||||
|
||||
XCASSET_FILES=()
|
||||
|
||||
case "${TARGETED_DEVICE_FAMILY}" in
|
||||
1,2)
|
||||
TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone"
|
||||
;;
|
||||
1)
|
||||
TARGET_DEVICE_ARGS="--target-device iphone"
|
||||
;;
|
||||
2)
|
||||
TARGET_DEVICE_ARGS="--target-device ipad"
|
||||
;;
|
||||
*)
|
||||
TARGET_DEVICE_ARGS="--target-device mac"
|
||||
;;
|
||||
esac
|
||||
|
||||
realpath() {
|
||||
DIRECTORY="$(cd "${1%/*}" && pwd)"
|
||||
FILENAME="${1##*/}"
|
||||
echo "$DIRECTORY/$FILENAME"
|
||||
}
|
||||
|
||||
install_resource()
|
||||
{
|
||||
if [[ "$1" = /* ]] ; then
|
||||
RESOURCE_PATH="$1"
|
||||
else
|
||||
RESOURCE_PATH="${PODS_ROOT}/$1"
|
||||
fi
|
||||
if [[ ! -e "$RESOURCE_PATH" ]] ; then
|
||||
cat << EOM
|
||||
error: Resource "$RESOURCE_PATH" not found. Run 'pod install' to update the copy resources script.
|
||||
EOM
|
||||
exit 1
|
||||
fi
|
||||
case $RESOURCE_PATH in
|
||||
*.storyboard)
|
||||
echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}"
|
||||
ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS}
|
||||
;;
|
||||
*.xib)
|
||||
echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT}"
|
||||
ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}"
|
||||
;;
|
||||
*.framework)
|
||||
echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
|
||||
mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
|
||||
echo "rsync -av $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
|
||||
rsync -av "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
|
||||
;;
|
||||
*.xcdatamodel)
|
||||
echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH"`.mom\""
|
||||
xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodel`.mom"
|
||||
;;
|
||||
*.xcdatamodeld)
|
||||
echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd\""
|
||||
xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd"
|
||||
;;
|
||||
*.xcmappingmodel)
|
||||
echo "xcrun mapc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm\""
|
||||
xcrun mapc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm"
|
||||
;;
|
||||
*.xcassets)
|
||||
ABSOLUTE_XCASSET_FILE=$(realpath "$RESOURCE_PATH")
|
||||
XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE")
|
||||
;;
|
||||
*)
|
||||
echo "$RESOURCE_PATH"
|
||||
echo "$RESOURCE_PATH" >> "$RESOURCES_TO_COPY"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
|
||||
rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
|
||||
if [[ "${ACTION}" == "install" ]] && [[ "${SKIP_INSTALL}" == "NO" ]]; then
|
||||
mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
|
||||
rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
|
||||
fi
|
||||
rm -f "$RESOURCES_TO_COPY"
|
||||
|
||||
if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "$XCASSET_FILES" ]
|
||||
then
|
||||
# Find all other xcassets (this unfortunately includes those of path pods and other targets).
|
||||
OTHER_XCASSETS=$(find "$PWD" -iname "*.xcassets" -type d)
|
||||
while read line; do
|
||||
if [[ $line != "`realpath $PODS_ROOT`*" ]]; then
|
||||
XCASSET_FILES+=("$line")
|
||||
fi
|
||||
done <<<"$OTHER_XCASSETS"
|
||||
|
||||
printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
|
||||
fi
|
||||
@@ -1,6 +0,0 @@
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
|
||||
FOUNDATION_EXPORT double Pods_SwaggerClientTestsVersionNumber;
|
||||
FOUNDATION_EXPORT const unsigned char Pods_SwaggerClientTestsVersionString[];
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient"
|
||||
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
|
||||
LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks'
|
||||
OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient/PetstoreClient.framework/Headers"
|
||||
PODS_BUILD_DIR = $BUILD_DIR
|
||||
PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)
|
||||
PODS_ROOT = ${SRCROOT}/Pods
|
||||
@@ -1,6 +0,0 @@
|
||||
framework module Pods_SwaggerClientTests {
|
||||
umbrella header "Pods-SwaggerClientTests-umbrella.h"
|
||||
|
||||
export *
|
||||
module * { export * }
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient"
|
||||
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
|
||||
LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks'
|
||||
OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient/PetstoreClient.framework/Headers"
|
||||
PODS_BUILD_DIR = $BUILD_DIR
|
||||
PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)
|
||||
PODS_ROOT = ${SRCROOT}/Pods
|
||||
@@ -143,7 +143,7 @@
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 6D4EFBAE1C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClient" */;
|
||||
buildPhases = (
|
||||
A16DAFA9EF474E5065B5B1C2 /* 📦 Check Pods Manifest.lock */,
|
||||
A16DAFA9EF474E5065B5B1C2 /* [CP] Check Pods Manifest.lock */,
|
||||
CF310079E3CB0BE5BE604471 /* [CP] Check Pods Manifest.lock */,
|
||||
1F03F780DC2D9727E5E64BA9 /* [CP] Check Pods Manifest.lock */,
|
||||
6D4EFB8D1C692C6300B96B06 /* Sources */,
|
||||
@@ -167,7 +167,7 @@
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 6D4EFBB11C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */;
|
||||
buildPhases = (
|
||||
FE27E864CEDDA2D12F7972B1 /* 📦 Check Pods Manifest.lock */,
|
||||
FE27E864CEDDA2D12F7972B1 /* [CP] Check Pods Manifest.lock */,
|
||||
B4DB169E5F018305D6759D34 /* [CP] Check Pods Manifest.lock */,
|
||||
79FE27B09B2DD354C831BD49 /* [CP] Check Pods Manifest.lock */,
|
||||
6D4EFBA11C692C6300B96B06 /* Sources */,
|
||||
@@ -367,19 +367,19 @@
|
||||
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh\"\n";
|
||||
showEnvVarsInLog = 0;
|
||||
};
|
||||
A16DAFA9EF474E5065B5B1C2 /* 📦 Check Pods Manifest.lock */ = {
|
||||
A16DAFA9EF474E5065B5B1C2 /* [CP] Check Pods Manifest.lock */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
inputPaths = (
|
||||
);
|
||||
name = "📦 Check Pods Manifest.lock";
|
||||
name = "[CP] Check Pods Manifest.lock";
|
||||
outputPaths = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n";
|
||||
shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n";
|
||||
showEnvVarsInLog = 0;
|
||||
};
|
||||
B4DB169E5F018305D6759D34 /* [CP] Check Pods Manifest.lock */ = {
|
||||
@@ -442,19 +442,19 @@
|
||||
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh\"\n";
|
||||
showEnvVarsInLog = 0;
|
||||
};
|
||||
FE27E864CEDDA2D12F7972B1 /* 📦 Check Pods Manifest.lock */ = {
|
||||
FE27E864CEDDA2D12F7972B1 /* [CP] Check Pods Manifest.lock */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
inputPaths = (
|
||||
);
|
||||
name = "📦 Check Pods Manifest.lock";
|
||||
name = "[CP] Check Pods Manifest.lock";
|
||||
outputPaths = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n";
|
||||
shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n";
|
||||
showEnvVarsInLog = 0;
|
||||
};
|
||||
/* End PBXShellScriptBuildPhase section */
|
||||
|
||||
@@ -26,19 +26,6 @@
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>1.2.1</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>install-pods</id>
|
||||
<phase>pre-integration-test</phase>
|
||||
<goals>
|
||||
<goal>exec</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<executable>pod</executable>
|
||||
<arguments>
|
||||
<argument>install</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>xcodebuild-test</id>
|
||||
<phase>integration-test</phase>
|
||||
@@ -46,16 +33,7 @@
|
||||
<goal>exec</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<executable>xcodebuild</executable>
|
||||
<arguments>
|
||||
<argument>-workspace</argument>
|
||||
<argument>SwaggerClient.xcworkspace</argument>
|
||||
<argument>-scheme</argument>
|
||||
<argument>SwaggerClient</argument>
|
||||
<argument>test</argument>
|
||||
<argument>-destination</argument>
|
||||
<argument>platform=iOS Simulator,name=iPhone 6,OS=9.3</argument>
|
||||
</arguments>
|
||||
<executable>./run_xcodebuild.sh</executable>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
#!/bin/sh
|
||||
|
||||
#pod install && xcodebuild clean test -workspace "SwaggerClient.xcworkspace" -scheme "SwaggerClient" -sdk iphonesimulator GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES GCC_GENERATE_TEST_COVERAGE_FILES=YES | xcpretty
|
||||
|
||||
pod install && xcodebuild -workspace "SwaggerClient.xcworkspace" -scheme "SwaggerClient" test -destination "platform=iOS Simulator,name=iPhone 6,OS=9.3" | xcpretty
|
||||
@@ -9,6 +9,6 @@ Pod::Spec.new do |s|
|
||||
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.4.1'
|
||||
s.dependency 'PromiseKit', '~> 3.5.3'
|
||||
s.dependency 'Alamofire', '~> 3.5.1'
|
||||
end
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,370 +0,0 @@
|
||||
//
|
||||
// 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)
|
||||
}
|
||||
@@ -1,248 +0,0 @@
|
||||
//
|
||||
// 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 initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
//
|
||||
// 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
|
||||
}
|
||||
|
||||
/// Custom keys contained within certain NSError `userInfo` dictionaries generated by Alamofire.
|
||||
public struct UserInfoKeys {
|
||||
/// The content type user info key for a `.ContentTypeValidationFailed` error stored as a `String` value.
|
||||
public static let ContentType = "ContentType"
|
||||
|
||||
/// The status code user info key for a `.StatusCodeValidationFailed` error stored as an `Int` value.
|
||||
public static let StatusCode = "StatusCode"
|
||||
}
|
||||
|
||||
/**
|
||||
Creates an `NSError` with the given error code and failure reason.
|
||||
|
||||
- parameter code: The error code.
|
||||
- parameter failureReason: The failure reason.
|
||||
|
||||
- returns: An `NSError` with the given error code and failure reason.
|
||||
*/
|
||||
@available(*, deprecated=3.4.0)
|
||||
public static func errorWithCode(code: Code, failureReason: String) -> NSError {
|
||||
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.
|
||||
*/
|
||||
@available(*, deprecated=3.4.0)
|
||||
public static func errorWithCode(code: Int, failureReason: String) -> NSError {
|
||||
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
|
||||
return NSError(domain: Domain, code: code, userInfo: userInfo)
|
||||
}
|
||||
|
||||
static func error(domain domain: String = Error.Domain, code: Code, failureReason: String) -> NSError {
|
||||
return error(domain: domain, code: code.rawValue, failureReason: failureReason)
|
||||
}
|
||||
|
||||
static func error(domain domain: String = Error.Domain, code: Int, failureReason: String) -> NSError {
|
||||
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
|
||||
return NSError(domain: domain, code: code, userInfo: userInfo)
|
||||
}
|
||||
}
|
||||
@@ -1,778 +0,0 @@
|
||||
//
|
||||
// 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 = info[kCFBundleExecutableKey as String] as? String ?? "Unknown"
|
||||
let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown"
|
||||
let version = info[kCFBundleVersionKey as String] as? String ?? "Unknown"
|
||||
|
||||
let osNameVersion: String = {
|
||||
let versionString: String
|
||||
|
||||
if #available(OSX 10.10, *) {
|
||||
let version = NSProcessInfo.processInfo().operatingSystemVersion
|
||||
versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"
|
||||
} else {
|
||||
versionString = "10.9"
|
||||
}
|
||||
|
||||
let osName: String = {
|
||||
#if os(iOS)
|
||||
return "iOS"
|
||||
#elseif os(watchOS)
|
||||
return "watchOS"
|
||||
#elseif os(tvOS)
|
||||
return "tvOS"
|
||||
#elseif os(OSX)
|
||||
return "OS X"
|
||||
#elseif os(Linux)
|
||||
return "Linux"
|
||||
#else
|
||||
return "Unknown"
|
||||
#endif
|
||||
}()
|
||||
|
||||
return "\(osName) \(versionString)"
|
||||
}()
|
||||
|
||||
return "\(executable)/\(bundle) (\(version); \(osNameVersion))"
|
||||
}
|
||||
|
||||
return "Alamofire"
|
||||
}()
|
||||
|
||||
return [
|
||||
"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)
|
||||
{
|
||||
guard delegate === session.delegate else { return nil }
|
||||
|
||||
self.delegate = delegate
|
||||
self.session = session
|
||||
|
||||
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 class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
|
||||
private var subdelegates: [Int: Request.TaskDelegate] = [:]
|
||||
private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
|
||||
|
||||
/// Access the task delegate for the specified task in a thread-safe manner.
|
||||
public 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 all behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:` and requires the caller to call the `completionHandler`.
|
||||
public var sessionDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`.
|
||||
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))
|
||||
{
|
||||
guard sessionDidReceiveChallengeWithCompletion == nil else {
|
||||
sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler)
|
||||
return
|
||||
}
|
||||
|
||||
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 all behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:` and
|
||||
/// requires the caller to call the `completionHandler`.
|
||||
public var taskWillPerformHTTPRedirectionWithCompletion: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest, NSURLRequest? -> Void) -> Void)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`.
|
||||
public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
|
||||
|
||||
/// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:` and
|
||||
/// requires the caller to call the `completionHandler`.
|
||||
public var taskDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`.
|
||||
public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)?
|
||||
|
||||
/// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:` and
|
||||
/// requires the caller to call the `completionHandler`.
|
||||
public var taskNeedNewBodyStreamWithCompletion: ((NSURLSession, NSURLSessionTask, NSInputStream? -> Void) -> Void)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.
|
||||
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)
|
||||
{
|
||||
guard taskWillPerformHTTPRedirectionWithCompletion == nil else {
|
||||
taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler)
|
||||
return
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
guard taskDidReceiveChallengeWithCompletion == nil else {
|
||||
taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler)
|
||||
return
|
||||
}
|
||||
|
||||
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
|
||||
let result = taskDidReceiveChallenge(session, task, challenge)
|
||||
completionHandler(result.0, result.1)
|
||||
} 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)
|
||||
{
|
||||
guard taskNeedNewBodyStreamWithCompletion == nil else {
|
||||
taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler)
|
||||
return
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidComplete, object: task)
|
||||
|
||||
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 all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:` and
|
||||
/// requires caller to call the `completionHandler`.
|
||||
public var dataTaskDidReceiveResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSURLResponse, NSURLSessionResponseDisposition -> Void) -> Void)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`.
|
||||
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?)?
|
||||
|
||||
/// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:` and
|
||||
/// requires caller to call the `completionHandler`.
|
||||
public var dataTaskWillCacheResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse, NSCachedURLResponse? -> Void) -> Void)?
|
||||
|
||||
// MARK: Delegate Methods
|
||||
|
||||
/**
|
||||
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)
|
||||
{
|
||||
guard dataTaskDidReceiveResponseWithCompletion == nil else {
|
||||
dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler)
|
||||
return
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
guard dataTaskWillCacheResponseWithCompletion == nil else {
|
||||
dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler)
|
||||
return
|
||||
}
|
||||
|
||||
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 {
|
||||
#if !os(OSX)
|
||||
if selector == #selector(NSURLSessionDelegate.URLSessionDidFinishEventsForBackgroundURLSession(_:)) {
|
||||
return sessionDidFinishEventsForBackgroundURLSession != nil
|
||||
}
|
||||
#endif
|
||||
|
||||
switch selector {
|
||||
case #selector(NSURLSessionDelegate.URLSession(_:didBecomeInvalidWithError:)):
|
||||
return sessionDidBecomeInvalidWithError != nil
|
||||
case #selector(NSURLSessionDelegate.URLSession(_:didReceiveChallenge:completionHandler:)):
|
||||
return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil)
|
||||
case #selector(NSURLSessionTaskDelegate.URLSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)):
|
||||
return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil)
|
||||
case #selector(NSURLSessionDataDelegate.URLSession(_:dataTask:didReceiveResponse:completionHandler:)):
|
||||
return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil)
|
||||
default:
|
||||
return self.dynamicType.instancesRespondToSelector(selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,659 +0,0 @@
|
||||
//
|
||||
// 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(code: 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)"
|
||||
setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
|
||||
return
|
||||
}
|
||||
|
||||
//============================================================
|
||||
// Check 2 - is file URL reachable?
|
||||
//============================================================
|
||||
|
||||
var isReachable = true
|
||||
|
||||
if #available(OSX 10.10, *) {
|
||||
isReachable = fileURL.checkPromisedItemIsReachableAndReturnError(nil)
|
||||
}
|
||||
|
||||
guard isReachable else {
|
||||
setBodyPartError(code: NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)")
|
||||
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)"
|
||||
setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
|
||||
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)"
|
||||
setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
|
||||
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)"
|
||||
setBodyPartError(code: NSURLErrorCannotOpenFile, failureReason: failureReason)
|
||||
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.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason)
|
||||
} else if !fileURL.fileURL {
|
||||
let failureReason = "The URL does not point to a valid file: \(fileURL)"
|
||||
throw Error.error(domain: NSURLErrorDomain, code: 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.error(domain: NSURLErrorDomain, code: NSURLErrorCannotOpenFile, failureReason: failureReason)
|
||||
}
|
||||
|
||||
outputStream.open()
|
||||
|
||||
self.bodyParts.first?.hasInitialBoundary = true
|
||||
self.bodyParts.last?.hasFinalBoundary = true
|
||||
|
||||
for bodyPart in self.bodyParts {
|
||||
try writeBodyPart(bodyPart, toOutputStream: outputStream)
|
||||
}
|
||||
|
||||
outputStream.close()
|
||||
}
|
||||
|
||||
// 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.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.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason)
|
||||
break
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
inputStream.close()
|
||||
|
||||
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.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.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason)
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
inputStream.close()
|
||||
}
|
||||
|
||||
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.error(domain: NSURLErrorDomain, code: .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(code code: Int, failureReason: String) {
|
||||
guard bodyPartError == nil else { return }
|
||||
bodyPartError = Error.error(domain: NSURLErrorDomain, code: code, failureReason: failureReason)
|
||||
}
|
||||
}
|
||||
@@ -1,244 +0,0 @@
|
||||
//
|
||||
// NetworkReachabilityManager.swift
|
||||
//
|
||||
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
//
|
||||
|
||||
#if !os(watchOS)
|
||||
|
||||
import Foundation
|
||||
import SystemConfiguration
|
||||
|
||||
/**
|
||||
The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and
|
||||
WiFi network interfaces.
|
||||
|
||||
Reachability can be used to determine background information about why a network operation failed, or to retry
|
||||
network requests when a connection is established. It should not be used to prevent a user from initiating a network
|
||||
request, as it's possible that an initial request may be required to establish reachability.
|
||||
*/
|
||||
public class NetworkReachabilityManager {
|
||||
/**
|
||||
Defines the various states of network reachability.
|
||||
|
||||
- Unknown: It is unknown whether the network is reachable.
|
||||
- NotReachable: The network is not reachable.
|
||||
- ReachableOnWWAN: The network is reachable over the WWAN connection.
|
||||
- ReachableOnWiFi: The network is reachable over the WiFi connection.
|
||||
*/
|
||||
public enum NetworkReachabilityStatus {
|
||||
case Unknown
|
||||
case NotReachable
|
||||
case Reachable(ConnectionType)
|
||||
}
|
||||
|
||||
/**
|
||||
Defines the various connection types detected by reachability flags.
|
||||
|
||||
- EthernetOrWiFi: The connection type is either over Ethernet or WiFi.
|
||||
- WWAN: The connection type is a WWAN connection.
|
||||
*/
|
||||
public enum ConnectionType {
|
||||
case EthernetOrWiFi
|
||||
case WWAN
|
||||
}
|
||||
|
||||
/// A closure executed when the network reachability status changes. The closure takes a single argument: the
|
||||
/// network reachability status.
|
||||
public typealias Listener = NetworkReachabilityStatus -> Void
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
/// Whether the network is currently reachable.
|
||||
public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi }
|
||||
|
||||
/// Whether the network is currently reachable over the WWAN interface.
|
||||
public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .Reachable(.WWAN) }
|
||||
|
||||
/// Whether the network is currently reachable over Ethernet or WiFi interface.
|
||||
public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .Reachable(.EthernetOrWiFi) }
|
||||
|
||||
/// The current network reachability status.
|
||||
public var networkReachabilityStatus: NetworkReachabilityStatus {
|
||||
guard let flags = self.flags else { return .Unknown }
|
||||
return networkReachabilityStatusForFlags(flags)
|
||||
}
|
||||
|
||||
/// The dispatch queue to execute the `listener` closure on.
|
||||
public var listenerQueue: dispatch_queue_t = dispatch_get_main_queue()
|
||||
|
||||
/// A closure executed when the network reachability status changes.
|
||||
public var listener: Listener?
|
||||
|
||||
private var flags: SCNetworkReachabilityFlags? {
|
||||
var flags = SCNetworkReachabilityFlags()
|
||||
|
||||
if SCNetworkReachabilityGetFlags(reachability, &flags) {
|
||||
return flags
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
private let reachability: SCNetworkReachability
|
||||
private var previousFlags: SCNetworkReachabilityFlags
|
||||
|
||||
// MARK: - Initialization
|
||||
|
||||
/**
|
||||
Creates a `NetworkReachabilityManager` instance with the specified host.
|
||||
|
||||
- parameter host: The host used to evaluate network reachability.
|
||||
|
||||
- returns: The new `NetworkReachabilityManager` instance.
|
||||
*/
|
||||
public convenience init?(host: String) {
|
||||
guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil }
|
||||
self.init(reachability: reachability)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0.
|
||||
|
||||
Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing
|
||||
status of the device, both IPv4 and IPv6.
|
||||
|
||||
- returns: The new `NetworkReachabilityManager` instance.
|
||||
*/
|
||||
public convenience init?() {
|
||||
var address = sockaddr_in()
|
||||
address.sin_len = UInt8(sizeofValue(address))
|
||||
address.sin_family = sa_family_t(AF_INET)
|
||||
|
||||
guard let reachability = withUnsafePointer(&address, {
|
||||
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
|
||||
}) else { return nil }
|
||||
|
||||
self.init(reachability: reachability)
|
||||
}
|
||||
|
||||
private init(reachability: SCNetworkReachability) {
|
||||
self.reachability = reachability
|
||||
self.previousFlags = SCNetworkReachabilityFlags()
|
||||
}
|
||||
|
||||
deinit {
|
||||
stopListening()
|
||||
}
|
||||
|
||||
// MARK: - Listening
|
||||
|
||||
/**
|
||||
Starts listening for changes in network reachability status.
|
||||
|
||||
- returns: `true` if listening was started successfully, `false` otherwise.
|
||||
*/
|
||||
public func startListening() -> Bool {
|
||||
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
|
||||
context.info = UnsafeMutablePointer(Unmanaged.passUnretained(self).toOpaque())
|
||||
|
||||
let callbackEnabled = SCNetworkReachabilitySetCallback(
|
||||
reachability,
|
||||
{ (_, flags, info) in
|
||||
let reachability = Unmanaged<NetworkReachabilityManager>.fromOpaque(COpaquePointer(info)).takeUnretainedValue()
|
||||
reachability.notifyListener(flags)
|
||||
},
|
||||
&context
|
||||
)
|
||||
|
||||
let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue)
|
||||
|
||||
dispatch_async(listenerQueue) {
|
||||
self.previousFlags = SCNetworkReachabilityFlags()
|
||||
self.notifyListener(self.flags ?? SCNetworkReachabilityFlags())
|
||||
}
|
||||
|
||||
return callbackEnabled && queueEnabled
|
||||
}
|
||||
|
||||
/**
|
||||
Stops listening for changes in network reachability status.
|
||||
*/
|
||||
public func stopListening() {
|
||||
SCNetworkReachabilitySetCallback(reachability, nil, nil)
|
||||
SCNetworkReachabilitySetDispatchQueue(reachability, nil)
|
||||
}
|
||||
|
||||
// MARK: - Internal - Listener Notification
|
||||
|
||||
func notifyListener(flags: SCNetworkReachabilityFlags) {
|
||||
guard previousFlags != flags else { return }
|
||||
previousFlags = flags
|
||||
|
||||
listener?(networkReachabilityStatusForFlags(flags))
|
||||
}
|
||||
|
||||
// MARK: - Internal - Network Reachability Status
|
||||
|
||||
func networkReachabilityStatusForFlags(flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus {
|
||||
guard flags.contains(.Reachable) else { return .NotReachable }
|
||||
|
||||
var networkStatus: NetworkReachabilityStatus = .NotReachable
|
||||
|
||||
if !flags.contains(.ConnectionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) }
|
||||
|
||||
if flags.contains(.ConnectionOnDemand) || flags.contains(.ConnectionOnTraffic) {
|
||||
if !flags.contains(.InterventionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) }
|
||||
}
|
||||
|
||||
#if os(iOS)
|
||||
if flags.contains(.IsWWAN) { networkStatus = .Reachable(.WWAN) }
|
||||
#endif
|
||||
|
||||
return networkStatus
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {}
|
||||
|
||||
/**
|
||||
Returns whether the two network reachability status values are equal.
|
||||
|
||||
- parameter lhs: The left-hand side value to compare.
|
||||
- parameter rhs: The right-hand side value to compare.
|
||||
|
||||
- returns: `true` if the two values are equal, `false` otherwise.
|
||||
*/
|
||||
public func ==(
|
||||
lhs: NetworkReachabilityManager.NetworkReachabilityStatus,
|
||||
rhs: NetworkReachabilityManager.NetworkReachabilityStatus)
|
||||
-> Bool
|
||||
{
|
||||
switch (lhs, rhs) {
|
||||
case (.Unknown, .Unknown):
|
||||
return true
|
||||
case (.NotReachable, .NotReachable):
|
||||
return true
|
||||
case let (.Reachable(lhsConnectionType), .Reachable(rhsConnectionType)):
|
||||
return lhsConnectionType == rhsConnectionType
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,47 +0,0 @@
|
||||
//
|
||||
// Notifications.swift
|
||||
//
|
||||
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Contains all the `NSNotification` names posted by Alamofire with descriptions of each notification's payload.
|
||||
public struct Notifications {
|
||||
/// Used as a namespace for all `NSURLSessionTask` related notifications.
|
||||
public struct Task {
|
||||
/// Notification posted when an `NSURLSessionTask` is resumed. The notification `object` contains the resumed
|
||||
/// `NSURLSessionTask`.
|
||||
public static let DidResume = "com.alamofire.notifications.task.didResume"
|
||||
|
||||
/// Notification posted when an `NSURLSessionTask` is suspended. The notification `object` contains the
|
||||
/// suspended `NSURLSessionTask`.
|
||||
public static let DidSuspend = "com.alamofire.notifications.task.didSuspend"
|
||||
|
||||
/// Notification posted when an `NSURLSessionTask` is cancelled. The notification `object` contains the
|
||||
/// cancelled `NSURLSessionTask`.
|
||||
public static let DidCancel = "com.alamofire.notifications.task.didCancel"
|
||||
|
||||
/// Notification posted when an `NSURLSessionTask` is completed. The notification `object` contains the
|
||||
/// completed `NSURLSessionTask`.
|
||||
public static let DidComplete = "com.alamofire.notifications.task.didComplete"
|
||||
}
|
||||
}
|
||||
@@ -1,261 +0,0 @@
|
||||
//
|
||||
// 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 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)
|
||||
where !parameters.isEmpty
|
||||
{
|
||||
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)
|
||||
|
||||
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
|
||||
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
|
||||
)
|
||||
|
||||
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
|
||||
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 Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no
|
||||
// longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more
|
||||
// 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 = startIndex..<endIndex
|
||||
|
||||
let substring = string.substringWithRange(range)
|
||||
|
||||
escaped += substring.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? substring
|
||||
|
||||
index = endIndex
|
||||
}
|
||||
}
|
||||
|
||||
return escaped
|
||||
}
|
||||
}
|
||||
@@ -1,568 +0,0 @@
|
||||
//
|
||||
// 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 }
|
||||
|
||||
var startTime: CFAbsoluteTime?
|
||||
var endTime: CFAbsoluteTime?
|
||||
|
||||
// MARK: - Lifecycle
|
||||
|
||||
init(session: NSURLSession, task: NSURLSessionTask) {
|
||||
self.session = session
|
||||
|
||||
switch task {
|
||||
case is NSURLSessionUploadTask:
|
||||
delegate = UploadTaskDelegate(task: task)
|
||||
case is NSURLSessionDataTask:
|
||||
delegate = DataTaskDelegate(task: task)
|
||||
case is NSURLSessionDownloadTask:
|
||||
delegate = DownloadTaskDelegate(task: task)
|
||||
default:
|
||||
delegate = TaskDelegate(task: task)
|
||||
}
|
||||
|
||||
delegate.queue.addOperationWithBlock { self.endTime = CFAbsoluteTimeGetCurrent() }
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
/**
|
||||
Returns a base64 encoded basic authentication credential as an authorization header dictionary.
|
||||
|
||||
- parameter user: The user.
|
||||
- parameter password: The password.
|
||||
|
||||
- returns: A dictionary with Authorization key and credential value or empty dictionary if encoding fails.
|
||||
*/
|
||||
public static func authorizationHeader(user user: String, password: String) -> [String: String] {
|
||||
guard let data = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding) else { return [:] }
|
||||
|
||||
let credential = data.base64EncodedStringWithOptions([])
|
||||
|
||||
return ["Authorization": "Basic \(credential)"]
|
||||
}
|
||||
|
||||
// MARK: - Progress
|
||||
|
||||
/**
|
||||
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
|
||||
|
||||
/**
|
||||
Resumes the request.
|
||||
*/
|
||||
public func resume() {
|
||||
if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() }
|
||||
|
||||
task.resume()
|
||||
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidResume, object: task)
|
||||
}
|
||||
|
||||
/**
|
||||
Suspends the request.
|
||||
*/
|
||||
public func suspend() {
|
||||
task.suspend()
|
||||
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidSuspend, object: task)
|
||||
}
|
||||
|
||||
/**
|
||||
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()
|
||||
}
|
||||
|
||||
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidCancel, object: task)
|
||||
}
|
||||
|
||||
// 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 initialResponseTime: CFAbsoluteTime?
|
||||
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 = .RejectProtectionSpace
|
||||
} 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 initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
|
||||
|
||||
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()))\"")
|
||||
}
|
||||
}
|
||||
|
||||
var headers: [NSObject: AnyObject] = [:]
|
||||
|
||||
if let additionalHeaders = session.configuration.HTTPAdditionalHeaders {
|
||||
for (field, value) in additionalHeaders where field != "Cookie" {
|
||||
headers[field] = value
|
||||
}
|
||||
}
|
||||
|
||||
if let headerFields = request.allHTTPHeaderFields {
|
||||
for (field, value) in headerFields where field != "Cookie" {
|
||||
headers[field] = value
|
||||
}
|
||||
}
|
||||
|
||||
for (field, value) in headers {
|
||||
components.append("-H \"\(field): \(value)\"")
|
||||
}
|
||||
|
||||
if let
|
||||
HTTPBodyData = request.HTTPBody,
|
||||
HTTPBody = String(data: HTTPBodyData, encoding: NSUTF8StringEncoding)
|
||||
{
|
||||
var escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\\\"", withString: "\\\\\"")
|
||||
escapedBody = escapedBody.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()
|
||||
}
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
//
|
||||
// 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>
|
||||
|
||||
/// The timeline of the complete lifecycle of the `Request`.
|
||||
public let timeline: Timeline
|
||||
|
||||
/**
|
||||
Initializes the `Response` instance with the specified URL request, URL response, server data and response
|
||||
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.
|
||||
- parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`.
|
||||
|
||||
- returns: the new `Response` instance.
|
||||
*/
|
||||
public init(
|
||||
request: NSURLRequest?,
|
||||
response: NSHTTPURLResponse?,
|
||||
data: NSData?,
|
||||
result: Result<Value, Error>,
|
||||
timeline: Timeline = Timeline())
|
||||
{
|
||||
self.request = request
|
||||
self.response = response
|
||||
self.data = data
|
||||
self.result = result
|
||||
self.timeline = timeline
|
||||
}
|
||||
}
|
||||
|
||||
// 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)")
|
||||
output.append("[Timeline]: \(timeline.debugDescription)")
|
||||
|
||||
return output.joinWithSeparator("\n")
|
||||
}
|
||||
}
|
||||
@@ -1,378 +0,0 @@
|
||||
//
|
||||
// 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`.
|
||||
associatedtype SerializedObject
|
||||
|
||||
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
|
||||
associatedtype 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
|
||||
)
|
||||
|
||||
let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent()
|
||||
let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime
|
||||
|
||||
let timeline = Timeline(
|
||||
requestStartTime: self.startTime ?? CFAbsoluteTimeGetCurrent(),
|
||||
initialResponseTime: initialResponseTime,
|
||||
requestCompletedTime: requestCompletedTime,
|
||||
serializationCompletedTime: CFAbsoluteTimeGetCurrent()
|
||||
)
|
||||
|
||||
let response = Response<T.SerializedObject, T.ErrorObject>(
|
||||
request: self.request,
|
||||
response: self.response,
|
||||
data: self.delegate.data,
|
||||
result: result,
|
||||
timeline: timeline
|
||||
)
|
||||
|
||||
dispatch_async(queue ?? dispatch_get_main_queue()) { 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.error(code: .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(
|
||||
queue queue: dispatch_queue_t? = nil,
|
||||
completionHandler: Response<NSData, NSError> -> Void)
|
||||
-> Self
|
||||
{
|
||||
return response(queue: queue, 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(
|
||||
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.error(code: .StringSerializationFailed, failureReason: failureReason)
|
||||
return .Failure(error)
|
||||
}
|
||||
|
||||
var convertedEncoding = encoding
|
||||
|
||||
if let encodingName = response?.textEncodingName where convertedEncoding == nil {
|
||||
convertedEncoding = CFStringConvertEncodingToNSStringEncoding(
|
||||
CFStringConvertIANACharSetNameToEncoding(encodingName)
|
||||
)
|
||||
}
|
||||
|
||||
let actualEncoding = convertedEncoding ?? 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.error(code: .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(
|
||||
queue queue: dispatch_queue_t? = nil,
|
||||
encoding: NSStringEncoding? = nil,
|
||||
completionHandler: Response<String, NSError> -> Void)
|
||||
-> Self
|
||||
{
|
||||
return response(
|
||||
queue: queue,
|
||||
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.error(code: .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(
|
||||
queue queue: dispatch_queue_t? = nil,
|
||||
options: NSJSONReadingOptions = .AllowFragments,
|
||||
completionHandler: Response<AnyObject, NSError> -> Void)
|
||||
-> Self
|
||||
{
|
||||
return response(
|
||||
queue: queue,
|
||||
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.error(code: .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(
|
||||
queue queue: dispatch_queue_t? = nil,
|
||||
options: NSPropertyListReadOptions = NSPropertyListReadOptions(),
|
||||
completionHandler: Response<AnyObject, NSError> -> Void)
|
||||
-> Self
|
||||
{
|
||||
return response(
|
||||
queue: queue,
|
||||
responseSerializer: Request.propertyListResponseSerializer(options: options),
|
||||
completionHandler: completionHandler
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
//
|
||||
// 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)"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,304 +0,0 @@
|
||||
//
|
||||
// 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
|
||||
}
|
||||
}
|
||||
@@ -1,182 +0,0 @@
|
||||
//
|
||||
// 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, tvOS 9.0, *)
|
||||
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, tvOS 9.0, *)
|
||||
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
|
||||
@@ -1,138 +0,0 @@
|
||||
//
|
||||
// Timeline.swift
|
||||
//
|
||||
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Responsible for computing the timing metrics for the complete lifecycle of a `Request`.
|
||||
public struct Timeline {
|
||||
/// The time the request was initialized.
|
||||
public let requestStartTime: CFAbsoluteTime
|
||||
|
||||
/// The time the first bytes were received from or sent to the server.
|
||||
public let initialResponseTime: CFAbsoluteTime
|
||||
|
||||
/// The time when the request was completed.
|
||||
public let requestCompletedTime: CFAbsoluteTime
|
||||
|
||||
/// The time when the response serialization was completed.
|
||||
public let serializationCompletedTime: CFAbsoluteTime
|
||||
|
||||
/// The time interval in seconds from the time the request started to the initial response from the server.
|
||||
public let latency: NSTimeInterval
|
||||
|
||||
/// The time interval in seconds from the time the request started to the time the request completed.
|
||||
public let requestDuration: NSTimeInterval
|
||||
|
||||
/// The time interval in seconds from the time the request completed to the time response serialization completed.
|
||||
public let serializationDuration: NSTimeInterval
|
||||
|
||||
/// The time interval in seconds from the time the request started to the time response serialization completed.
|
||||
public let totalDuration: NSTimeInterval
|
||||
|
||||
/**
|
||||
Creates a new `Timeline` instance with the specified request times.
|
||||
|
||||
- parameter requestStartTime: The time the request was initialized. Defaults to `0.0`.
|
||||
- parameter initialResponseTime: The time the first bytes were received from or sent to the server.
|
||||
Defaults to `0.0`.
|
||||
- parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`.
|
||||
- parameter serializationCompletedTime: The time when the response serialization was completed. Defaults
|
||||
to `0.0`.
|
||||
|
||||
- returns: The new `Timeline` instance.
|
||||
*/
|
||||
public init(
|
||||
requestStartTime: CFAbsoluteTime = 0.0,
|
||||
initialResponseTime: CFAbsoluteTime = 0.0,
|
||||
requestCompletedTime: CFAbsoluteTime = 0.0,
|
||||
serializationCompletedTime: CFAbsoluteTime = 0.0)
|
||||
{
|
||||
self.requestStartTime = requestStartTime
|
||||
self.initialResponseTime = initialResponseTime
|
||||
self.requestCompletedTime = requestCompletedTime
|
||||
self.serializationCompletedTime = serializationCompletedTime
|
||||
|
||||
self.latency = initialResponseTime - requestStartTime
|
||||
self.requestDuration = requestCompletedTime - requestStartTime
|
||||
self.serializationDuration = serializationCompletedTime - requestCompletedTime
|
||||
self.totalDuration = serializationCompletedTime - requestStartTime
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
extension Timeline: CustomStringConvertible {
|
||||
/// The textual representation used when written to an output stream, which includes the latency, the request
|
||||
/// duration and the total duration.
|
||||
public var description: String {
|
||||
let latency = String(format: "%.3f", self.latency)
|
||||
let requestDuration = String(format: "%.3f", self.requestDuration)
|
||||
let serializationDuration = String(format: "%.3f", self.serializationDuration)
|
||||
let totalDuration = String(format: "%.3f", self.totalDuration)
|
||||
|
||||
// NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is
|
||||
// fixed, we should move back to string interpolation by reverting commit 7d4a43b1.
|
||||
let timings = [
|
||||
"\"Latency\": " + latency + " secs",
|
||||
"\"Request Duration\": " + requestDuration + " secs",
|
||||
"\"Serialization Duration\": " + serializationDuration + " secs",
|
||||
"\"Total Duration\": " + totalDuration + " secs"
|
||||
]
|
||||
|
||||
return "Timeline: { " + timings.joinWithSeparator(", ") + " }"
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomDebugStringConvertible
|
||||
|
||||
extension Timeline: CustomDebugStringConvertible {
|
||||
/// The textual representation used when written to an output stream, which includes the request start time, the
|
||||
/// initial response time, the request completed time, the serialization completed time, the latency, the request
|
||||
/// duration and the total duration.
|
||||
public var debugDescription: String {
|
||||
let requestStartTime = String(format: "%.3f", self.requestStartTime)
|
||||
let initialResponseTime = String(format: "%.3f", self.initialResponseTime)
|
||||
let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime)
|
||||
let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime)
|
||||
let latency = String(format: "%.3f", self.latency)
|
||||
let requestDuration = String(format: "%.3f", self.requestDuration)
|
||||
let serializationDuration = String(format: "%.3f", self.serializationDuration)
|
||||
let totalDuration = String(format: "%.3f", self.totalDuration)
|
||||
|
||||
// NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is
|
||||
// fixed, we should move back to string interpolation by reverting commit 7d4a43b1.
|
||||
let timings = [
|
||||
"\"Request Start Time\": " + requestStartTime,
|
||||
"\"Initial Response Time\": " + initialResponseTime,
|
||||
"\"Request Completed Time\": " + requestCompletedTime,
|
||||
"\"Serialization Completed Time\": " + serializationCompletedTime,
|
||||
"\"Latency\": " + latency + " secs",
|
||||
"\"Request Duration\": " + requestDuration + " secs",
|
||||
"\"Serialization Duration\": " + serializationDuration + " secs",
|
||||
"\"Total Duration\": " + totalDuration + " secs"
|
||||
]
|
||||
|
||||
return "Timeline: { " + timings.joinWithSeparator(", ") + " }"
|
||||
}
|
||||
}
|
||||
@@ -1,376 +0,0 @@
|
||||
//
|
||||
// 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 initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
|
||||
|
||||
if let taskDidSendBodyData = taskDidSendBodyData {
|
||||
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
|
||||
} else {
|
||||
progress.totalUnitCount = totalBytesExpectedToSend
|
||||
progress.completedUnitCount = totalBytesSent
|
||||
|
||||
uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,214 +0,0 @@
|
||||
//
|
||||
// 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)"
|
||||
|
||||
let error = NSError(
|
||||
domain: Error.Domain,
|
||||
code: Error.Code.StatusCodeValidationFailed.rawValue,
|
||||
userInfo: [
|
||||
NSLocalizedFailureReasonErrorKey: failureReason,
|
||||
Error.UserInfoKeys.StatusCode: response.statusCode
|
||||
]
|
||||
)
|
||||
|
||||
return .Failure(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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 contentType: String
|
||||
let failureReason: String
|
||||
|
||||
if let responseContentType = response.MIMEType {
|
||||
contentType = responseContentType
|
||||
|
||||
failureReason = (
|
||||
"Response content type \"\(responseContentType)\" does not match any acceptable " +
|
||||
"content types: \(acceptableContentTypes)"
|
||||
)
|
||||
} else {
|
||||
contentType = ""
|
||||
failureReason = "Response content type was missing and acceptable content type does not match \"*/*\""
|
||||
}
|
||||
|
||||
let error = NSError(
|
||||
domain: Error.Domain,
|
||||
code: Error.Code.ContentTypeValidationFailed.rawValue,
|
||||
userInfo: [
|
||||
NSLocalizedFailureReasonErrorKey: failureReason,
|
||||
Error.UserInfoKeys.ContentType: contentType
|
||||
]
|
||||
)
|
||||
|
||||
return .Failure(error)
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
},
|
||||
"authors": "",
|
||||
"license": "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.4.1"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
PODS:
|
||||
- Alamofire (3.4.1)
|
||||
- OMGHTTPURLRQ (3.1.3):
|
||||
- OMGHTTPURLRQ/RQ (= 3.1.3)
|
||||
- OMGHTTPURLRQ/FormURLEncode (3.1.3)
|
||||
- OMGHTTPURLRQ/RQ (3.1.3):
|
||||
- OMGHTTPURLRQ/FormURLEncode
|
||||
- OMGHTTPURLRQ/UserAgent
|
||||
- OMGHTTPURLRQ/UserAgent (3.1.3)
|
||||
- PetstoreClient (0.0.1):
|
||||
- Alamofire (~> 3.4.1)
|
||||
- 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: 01a82e2f6c0f860ade35534c8dd88be61bdef40c
|
||||
OMGHTTPURLRQ: a547be1b9721ddfbf9d08aab56ab72dc4c1cc417
|
||||
PetstoreClient: 24135348a992f2cbd76bc324719173b52e864cdc
|
||||
PromiseKit: 4e8127c22a9b29d1b44958ab2ec762ea6115cbfb
|
||||
|
||||
PODFILE CHECKSUM: 84472aca2a88b7f7ed9fcd63e9f5fdb5ad4aab94
|
||||
|
||||
COCOAPODS: 1.0.1
|
||||
@@ -1,145 +0,0 @@
|
||||
# OMGHTTPURLRQ
|
||||
|
||||
Vital extensions to `NSURLRequest` that Apple left out for some reason.
|
||||
|
||||
```objc
|
||||
NSMutableURLRequest *rq = [OMGHTTPURLRQ GET:@"http://api.com":@{@"key": @"value"}];
|
||||
|
||||
// application/x-www-form-urlencoded
|
||||
NSMutableURLRequest *rq = [OMGHTTPURLRQ POST:@"http://api.com":@{@"key": @"value"}];
|
||||
|
||||
// application/json
|
||||
NSMutableURLRequest *rq = [OMGHTTPURLRQ POST:@"http://api.com" JSON:@{@"key": @"value"}];
|
||||
|
||||
// PUT
|
||||
NSMutableURLRequest *rq = [OMGHTTPURLRQ PUT:@"http://api.com":@{@"key": @"value"}];
|
||||
|
||||
// DELETE
|
||||
NSMutableURLRequest *rq = [OMGHTTPURLRQ DELETE:@"http://api.com":@{@"key": @"value"}];
|
||||
```
|
||||
|
||||
You can then pass these to an `NSURLConnection` or `NSURLSession`.
|
||||
|
||||
|
||||
## `multipart/form-data`
|
||||
|
||||
OMG! Constructing multipart/form-data for POST requests is complicated, let us do it for you:
|
||||
|
||||
```objc
|
||||
|
||||
OMGMultipartFormData *multipartFormData = [OMGMultipartFormData new];
|
||||
|
||||
NSData *data1 = [NSData dataWithContentsOfFile:@"myimage1.png"];
|
||||
[multipartFormData addFile:data1 parameterName:@"file1" filename:@"myimage1.png" contentType:@"image/png"];
|
||||
|
||||
// Ideally you would not want to re-encode the PNG, but often it is
|
||||
// tricky to avoid it.
|
||||
UIImage *image2 = [UIImage imageNamed:@"image2"];
|
||||
NSData *data2 = UIImagePNGRepresentation(image2);
|
||||
[multipartFormData addFile:data2 parameterName:@"file2" filename:@"myimage2.png" contentType:@"image/png"];
|
||||
|
||||
// SUPER Ideally you would not want to re-encode the JPEG as the process
|
||||
// is lossy. If your image comes from the AssetLibrary you *CAN* get the
|
||||
// original `NSData`. See stackoverflow.com.
|
||||
UIImage *image3 = [UIImage imageNamed:@"image3"];
|
||||
NSData *data3 = UIImageJPEGRepresentation(image3);
|
||||
[multipartFormData addFile:data3 parameterName:@"file2" filename:@"myimage3.jpeg" contentType:@"image/jpeg"];
|
||||
|
||||
NSMutableURLRequest *rq = [OMGHTTPURLRQ POST:url:multipartFormData];
|
||||
```
|
||||
|
||||
Now feed `rq` to `[NSURLConnection sendSynchronousRequest:returningResponse:error:`.
|
||||
|
||||
|
||||
## Configuring an `NSURLSessionUploadTask`
|
||||
|
||||
If you need to use `NSURLSession`’s `uploadTask:` but you have become frustrated because your endpoint expects a multipart/form-data POST request and `NSURLSession` sends the data *raw*, use this:
|
||||
|
||||
```objc
|
||||
id config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:someID];
|
||||
id session = [NSURLSession sessionWithConfiguration:config delegate:someObject delegateQueue:[NSOperationQueue new]];
|
||||
|
||||
OMGMultipartFormData *multipartFormData = [OMGMultipartFormData new];
|
||||
[multipartFormData addFile:data parameterName:@"file" filename:nil contentType:nil];
|
||||
|
||||
NSURLRequest *rq = [OMGHTTPURLRQ POST:urlString:multipartFormData];
|
||||
|
||||
id path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"upload.NSData"];
|
||||
[rq.HTTPBody writeToFile:path atomically:YES];
|
||||
|
||||
[[session uploadTaskWithRequest:rq fromFile:[NSURL fileURLWithPath:path]] resume];
|
||||
```
|
||||
|
||||
|
||||
## OMGUserAgent
|
||||
|
||||
If you just need a sensible UserAgent string for your application you can `pod OMGHTTPURLRQ/UserAgent` and then:
|
||||
|
||||
```objc
|
||||
#import <OMGHTTPURLRQ/OMGUserAgent.h>
|
||||
|
||||
NSString *userAgent = OMGUserAgent();
|
||||
```
|
||||
|
||||
OMGHTTPURLRQ adds this User-Agent to all requests it generates automatically.
|
||||
|
||||
So for URLRequests generated **other** than by OMGHTTPURLRQ you would do:
|
||||
|
||||
```objc
|
||||
[someURLRequest addValue:OMGUserAgent() forHTTPHeaderField:@"User-Agent"];
|
||||
```
|
||||
|
||||
|
||||
# Twitter Reverse Auth
|
||||
|
||||
You need an OAuth library, here we use the [TDOAuth](https://github.com/tweetdeck/TDOAuth) pod. You also need
|
||||
your API keys that registering at https://dev.twitter.com will provide
|
||||
you.
|
||||
|
||||
```objc
|
||||
NSMutableURLRequest *rq = [TDOAuth URLRequestForPath:@"/oauth/request_token" POSTParameters:@{@"x_auth_mode" : @"reverse_auth"} host:@"api.twitter.com" consumerKey:APIKey consumerSecret:APISecret accessToken:nil tokenSecret:nil];
|
||||
[rq addValue:OMGUserAgent() forHTTPHeaderField:@"User-Agent"];
|
||||
|
||||
[NSURLConnection sendAsynchronousRequest:rq queue:nil completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
|
||||
id oauth = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
|
||||
SLRequest *reverseAuth = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:[NSURL URLWithString:@"https://api.twitter.com/oauth/access_token"] parameters:@{
|
||||
@"x_reverse_auth_target": APIKey,
|
||||
@"x_reverse_auth_parameters": oauth
|
||||
}];
|
||||
reverseAuth.account = account;
|
||||
[reverseAuth performRequestWithHandler:^(NSData *data, NSHTTPURLResponse *urlResponse, NSError *error) {
|
||||
id creds = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
|
||||
id credsDict = [NSMutableDictionary new];
|
||||
for (__strong id pair in [creds componentsSeparatedByString:@"&"]) {
|
||||
pair = [pair componentsSeparatedByString:@"="];
|
||||
credsDict[pair[0]] = pair[1];
|
||||
}
|
||||
NSLog(@"%@", credsDict);
|
||||
}];
|
||||
}];
|
||||
```
|
||||
|
||||
|
||||
# License
|
||||
|
||||
```
|
||||
Copyright 2014 Max Howell <mxcl@me.com>
|
||||
|
||||
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.
|
||||
```
|
||||
@@ -1,22 +0,0 @@
|
||||
#import <Foundation/NSDictionary.h>
|
||||
#import <Foundation/NSObjCRuntime.h>
|
||||
#import <Foundation/NSString.h>
|
||||
|
||||
#if __has_feature(nullability) && defined(NS_ASSUME_NONNULL_BEGIN)
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
#endif
|
||||
|
||||
/**
|
||||
Express this dictionary as a `application/x-www-form-urlencoded` string.
|
||||
|
||||
Most users would recognize the result of this transformation as the query
|
||||
string in a browser bar. For our purposes it is the query string in a GET
|
||||
request and the HTTP body for POST, PUT and DELETE requests.
|
||||
|
||||
If the parameters dictionary is nil or empty, returns nil.
|
||||
*/
|
||||
NSString *OMGFormURLEncode(NSDictionary *parameters);
|
||||
|
||||
#if __has_feature(nullability) && defined(NS_ASSUME_NONNULL_END)
|
||||
NS_ASSUME_NONNULL_END
|
||||
#endif
|
||||
@@ -1,56 +0,0 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "OMGFormURLEncode.h"
|
||||
|
||||
static inline NSString *enc(id in, NSString *ignore) {
|
||||
NSMutableCharacterSet *allowedSet = [NSMutableCharacterSet characterSetWithCharactersInString:ignore];
|
||||
[allowedSet formUnionWithCharacterSet:[NSCharacterSet URLQueryAllowedCharacterSet]];
|
||||
[allowedSet removeCharactersInString:@":/?&=;+!@#$()',*"];
|
||||
|
||||
return [[in description] stringByAddingPercentEncodingWithAllowedCharacters:allowedSet];
|
||||
}
|
||||
|
||||
#define enckey(in) enc(in, @"[]")
|
||||
#define encval(in) enc(in, @"")
|
||||
|
||||
static NSArray *DoQueryMagic(NSString *key, id value) {
|
||||
NSMutableArray *parts = [NSMutableArray new];
|
||||
|
||||
// Sort dictionary keys to ensure consistent ordering in query string,
|
||||
// which is important when deserializing potentially ambiguous sequences,
|
||||
// such as an array of dictionaries
|
||||
#define sortDescriptor [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(compare:)]
|
||||
|
||||
if ([value isKindOfClass:[NSDictionary class]]) {
|
||||
NSDictionary *dictionary = value;
|
||||
for (id nestedKey in [dictionary.allKeys sortedArrayUsingDescriptors:@[sortDescriptor]]) {
|
||||
id recursiveKey = key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey;
|
||||
[parts addObjectsFromArray:DoQueryMagic(recursiveKey, dictionary[nestedKey])];
|
||||
}
|
||||
} else if ([value isKindOfClass:[NSArray class]]) {
|
||||
for (id nestedValue in value)
|
||||
[parts addObjectsFromArray:DoQueryMagic([NSString stringWithFormat:@"%@[]", key], nestedValue)];
|
||||
} else if ([value isKindOfClass:[NSSet class]]) {
|
||||
for (id obj in [value sortedArrayUsingDescriptors:@[sortDescriptor]])
|
||||
[parts addObjectsFromArray:DoQueryMagic(key, obj)];
|
||||
} else {
|
||||
[parts addObjectsFromArray:[NSArray arrayWithObjects:key, value, nil]];
|
||||
}
|
||||
|
||||
return parts;
|
||||
|
||||
#undef sortDescriptor
|
||||
}
|
||||
|
||||
NSString *OMGFormURLEncode(NSDictionary *parameters) {
|
||||
if (parameters.count == 0)
|
||||
return @"";
|
||||
NSMutableString *queryString = [NSMutableString new];
|
||||
NSEnumerator *e = DoQueryMagic(nil, parameters).objectEnumerator;
|
||||
for (;;) {
|
||||
id const obj = e.nextObject;
|
||||
if (!obj) break;
|
||||
[queryString appendFormat:@"%@=%@&", enckey(obj), encval(e.nextObject)];
|
||||
}
|
||||
[queryString deleteCharactersInRange:NSMakeRange(queryString.length - 1, 1)];
|
||||
return queryString;
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
#import <Foundation/NSObjCRuntime.h>
|
||||
|
||||
FOUNDATION_EXPORT double OMGHTTPURLRQVersionNumber;
|
||||
FOUNDATION_EXPORT const unsigned char OMGHTTPURLRQVersionString[];
|
||||
|
||||
#import <Foundation/NSData.h>
|
||||
#import <Foundation/NSDictionary.h>
|
||||
#import <Foundation/NSURLRequest.h>
|
||||
#import <Foundation/NSString.h>
|
||||
#import "OMGFormURLEncode.h"
|
||||
#import "OMGUserAgent.h"
|
||||
|
||||
|
||||
#if __has_feature(nullability) && defined(NS_ASSUME_NONNULL_BEGIN)
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
#else
|
||||
#define nullable
|
||||
#endif
|
||||
|
||||
/**
|
||||
The error will either be a JSON error (NSCocoaDomain :/) or in the NSURLErrorDomain
|
||||
with code: NSURLErrorUnsupportedURL.
|
||||
*/
|
||||
@interface OMGHTTPURLRQ : NSObject
|
||||
|
||||
+ (nullable NSMutableURLRequest *)GET:(NSString *)url :(nullable NSDictionary *)parameters error:(NSError **)error;
|
||||
+ (nullable NSMutableURLRequest *)POST:(NSString *)url :(nullable id)parametersOrMultipartFormData error:(NSError **)error;
|
||||
+ (nullable NSMutableURLRequest *)POST:(NSString *)url JSON:(nullable id)JSONObject error:(NSError **)error;
|
||||
+ (nullable NSMutableURLRequest *)PUT:(NSString *)url :(nullable NSDictionary *)parameters error:(NSError **)error;
|
||||
+ (nullable NSMutableURLRequest *)PUT:(NSString *)url JSON:(nullable id)JSONObject error:(NSError **)error;
|
||||
+ (nullable NSMutableURLRequest *)DELETE:(NSString *)url :(nullable NSDictionary *)parameters error:(NSError **)error;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
/**
|
||||
POST this with `OMGHTTPURLRQ`’s `-POST::` class method.
|
||||
*/
|
||||
@interface OMGMultipartFormData : NSObject
|
||||
|
||||
/**
|
||||
The `filename` parameter is optional. The content-type is optional, and
|
||||
if left `nil` will default to *octet-stream*.
|
||||
*/
|
||||
- (void)addFile:(NSData *)data parameterName:(NSString *)parameterName filename:(nullable NSString *)filename contentType:(nullable NSString *)contentType;
|
||||
|
||||
- (void)addText:(NSString *)text parameterName:(NSString *)parameterName;
|
||||
|
||||
/**
|
||||
Technically adding parameters to a multipart/form-data request is abusing
|
||||
the specification. What we do is add each parameter as a text-item. Any
|
||||
API that expects parameters in a multipart/form-data request will expect
|
||||
the parameters to be encoded in this way.
|
||||
*/
|
||||
- (void)addParameters:(NSDictionary *)parameters;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
#if __has_feature(nullability) && defined(NS_ASSUME_NONNULL_END)
|
||||
NS_ASSUME_NONNULL_END
|
||||
#else
|
||||
#undef nullable
|
||||
#endif
|
||||
@@ -1,171 +0,0 @@
|
||||
#import <CoreFoundation/CFURL.h>
|
||||
#import <Foundation/NSError.h>
|
||||
#import <Foundation/NSJSONSerialization.h>
|
||||
#import <Foundation/NSURL.h>
|
||||
#import <Foundation/NSURLError.h>
|
||||
#import "OMGHTTPURLRQ.h"
|
||||
#import "OMGUserAgent.h"
|
||||
#import "OMGFormURLEncode.h"
|
||||
#import <stdlib.h>
|
||||
|
||||
static inline NSMutableURLRequest *OMGMutableURLRequest() {
|
||||
NSMutableURLRequest *rq = [NSMutableURLRequest new];
|
||||
[rq setValue:OMGUserAgent() forHTTPHeaderField:@"User-Agent"];
|
||||
return rq;
|
||||
}
|
||||
|
||||
#define OMGInvalidURLErrorMake() \
|
||||
[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorUnsupportedURL userInfo:@{NSLocalizedDescriptionKey: @"The provided URL was invalid."}]
|
||||
|
||||
|
||||
@implementation OMGMultipartFormData {
|
||||
@public
|
||||
NSString *boundary;
|
||||
NSMutableData *body;
|
||||
}
|
||||
|
||||
- (instancetype)init {
|
||||
body = [NSMutableData data];
|
||||
boundary = [NSString stringWithFormat:@"------------------------%08X%08X", arc4random(), arc4random()];
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)add:(NSData *)payload :(NSString *)name :(NSString *)filename :(NSString *)contentType {
|
||||
id ln1 = [NSString stringWithFormat:@"--%@\r\n", boundary];
|
||||
id ln2 = ({
|
||||
id s = [NSMutableString stringWithString:@"Content-Disposition: form-data; "];
|
||||
[s appendFormat:@"name=\"%@\"", name];
|
||||
if (filename.length)
|
||||
[s appendFormat:@"; filename=\"%@\"", filename];
|
||||
[s appendString:@"\r\n"];
|
||||
if (contentType.length)
|
||||
[s appendFormat:@"Content-Type: %@\r\n", contentType];
|
||||
[s appendString:@"\r\n"];
|
||||
s;
|
||||
});
|
||||
|
||||
[body appendData:[ln1 dataUsingEncoding:NSUTF8StringEncoding]];
|
||||
[body appendData:[ln2 dataUsingEncoding:NSUTF8StringEncoding]];
|
||||
[body appendData:payload];
|
||||
}
|
||||
|
||||
- (void)addFile:(NSData *)payload parameterName:(NSString *)name filename:(NSString *)filename contentType:(NSString *)contentType
|
||||
{
|
||||
[self add:payload:name:filename:(contentType ?: @"application/octet-stream")];
|
||||
}
|
||||
|
||||
- (void)addText:(NSString *)text parameterName:(NSString *)parameterName {
|
||||
[self add:[text dataUsingEncoding:NSUTF8StringEncoding]:parameterName:nil:nil];
|
||||
}
|
||||
|
||||
- (void)addParameters:(NSDictionary *)parameters {
|
||||
for (id key in parameters)
|
||||
[self addText:[parameters[key] description] parameterName:key];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
|
||||
@implementation OMGHTTPURLRQ
|
||||
|
||||
+ (NSMutableURLRequest *)GET:(NSString *)urlString :(NSDictionary *)params error:(NSError **)error {
|
||||
NSString *queryString = OMGFormURLEncode(params);
|
||||
if (queryString.length) urlString = [urlString stringByAppendingFormat:@"?%@", queryString];
|
||||
|
||||
id url = [NSURL URLWithString:urlString];
|
||||
if (!url) {
|
||||
if (error) *error = OMGInvalidURLErrorMake();
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSMutableURLRequest *rq = OMGMutableURLRequest();
|
||||
rq.HTTPMethod = @"GET";
|
||||
rq.URL = url;
|
||||
return rq;
|
||||
}
|
||||
|
||||
static NSMutableURLRequest *OMGFormURLEncodedRequest(NSString *urlString, NSString *method, NSDictionary *parameters, NSError **error) {
|
||||
id url = [NSURL URLWithString:urlString];
|
||||
if (!url) {
|
||||
if (error) *error = OMGInvalidURLErrorMake();
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSMutableURLRequest *rq = OMGMutableURLRequest();
|
||||
rq.URL = url;
|
||||
rq.HTTPMethod = method;
|
||||
|
||||
id queryString = OMGFormURLEncode(parameters);
|
||||
NSData *data = [queryString dataUsingEncoding:NSUTF8StringEncoding];
|
||||
[rq addValue:@"8bit" forHTTPHeaderField:@"Content-Transfer-Encoding"];
|
||||
[rq addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
|
||||
[rq addValue:@(data.length).description forHTTPHeaderField:@"Content-Length"];
|
||||
[rq setHTTPBody:data];
|
||||
|
||||
return rq;
|
||||
}
|
||||
|
||||
+ (NSMutableURLRequest *)POST:(NSString *)urlString :(id)body error:(NSError **)error {
|
||||
if (![body isKindOfClass:[OMGMultipartFormData class]]) {
|
||||
return OMGFormURLEncodedRequest(urlString, @"POST", body, error);
|
||||
} else {
|
||||
id url = [NSURL URLWithString:urlString];
|
||||
if (!url) {
|
||||
if (error) *error = OMGInvalidURLErrorMake();
|
||||
return nil;
|
||||
}
|
||||
|
||||
OMGMultipartFormData *multipartFormData = (id)body;
|
||||
id const charset = (NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
|
||||
id const contentType = [NSString stringWithFormat:@"multipart/form-data; charset=%@; boundary=%@", charset, multipartFormData->boundary];
|
||||
|
||||
NSMutableData *data = [multipartFormData->body mutableCopy];
|
||||
id lastLine = [NSString stringWithFormat:@"\r\n--%@--\r\n", multipartFormData->boundary];
|
||||
[data appendData:[lastLine dataUsingEncoding:NSUTF8StringEncoding]];
|
||||
|
||||
NSMutableURLRequest *rq = OMGMutableURLRequest();
|
||||
[rq setURL:url];
|
||||
[rq setHTTPMethod:@"POST"];
|
||||
[rq addValue:contentType forHTTPHeaderField:@"Content-Type"];
|
||||
[rq setHTTPBody:data];
|
||||
return rq;
|
||||
}
|
||||
}
|
||||
|
||||
+ (NSMutableURLRequest *)POST:(NSString *)urlString JSON:(id)params error:(NSError **)error {
|
||||
if (error) *error = nil;
|
||||
|
||||
id url = [NSURL URLWithString:urlString];
|
||||
if (!url) {
|
||||
if (error) *error = OMGInvalidURLErrorMake();
|
||||
return nil;
|
||||
}
|
||||
|
||||
id JSONData = [NSJSONSerialization dataWithJSONObject:params options:(NSJSONWritingOptions)0 error:error];
|
||||
if (error && *error) return nil;
|
||||
|
||||
NSMutableURLRequest *rq = OMGMutableURLRequest();
|
||||
[rq setURL:url];
|
||||
[rq setHTTPMethod:@"POST"];
|
||||
[rq setHTTPBody:JSONData];
|
||||
[rq setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
|
||||
[rq setValue:@"json" forHTTPHeaderField:@"Data-Type"];
|
||||
return rq;
|
||||
}
|
||||
|
||||
+ (NSMutableURLRequest *)PUT:(NSString *)url :(NSDictionary *)parameters error:(NSError **)error {
|
||||
return OMGFormURLEncodedRequest(url, @"PUT", parameters, error);
|
||||
}
|
||||
|
||||
+ (NSMutableURLRequest *)PUT:(NSString *)url JSON:(id)params error:(NSError **)error {
|
||||
NSMutableURLRequest *rq = [OMGHTTPURLRQ POST:url JSON:params error:error];
|
||||
rq.HTTPMethod = @"PUT";
|
||||
return rq;
|
||||
}
|
||||
|
||||
+ (NSMutableURLRequest *)DELETE:(NSString *)url :(NSDictionary *)parameters error:(NSError **)error {
|
||||
return OMGFormURLEncodedRequest(url, @"DELETE", parameters, error);
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -1,12 +0,0 @@
|
||||
#import <Foundation/NSObjCRuntime.h>
|
||||
@class NSString;
|
||||
|
||||
#if __has_feature(nullability) && defined(NS_ASSUME_NONNULL_BEGIN)
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
#endif
|
||||
|
||||
NSString *OMGUserAgent();
|
||||
|
||||
#if __has_feature(nullability) && defined(NS_ASSUME_NONNULL_END)
|
||||
NS_ASSUME_NONNULL_END
|
||||
#endif
|
||||
@@ -1,19 +0,0 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "OMGUserAgent.h"
|
||||
|
||||
NSString *OMGUserAgent() {
|
||||
static NSString *ua;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
id info = [NSBundle mainBundle].infoDictionary;
|
||||
id name = info[@"CFBundleDisplayName"] ?: info[(__bridge NSString *)kCFBundleIdentifierKey];
|
||||
id vers = (__bridge id)CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), kCFBundleVersionKey) ?: info[(__bridge NSString *)kCFBundleVersionKey];
|
||||
#ifdef UIKIT_EXTERN
|
||||
float scale = ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] ? [UIScreen mainScreen].scale : 1.0f);
|
||||
ua = [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", name, vers, [UIDevice currentDevice].model, [UIDevice currentDevice].systemVersion, scale];
|
||||
#else
|
||||
ua = [NSString stringWithFormat:@"%@/%@", name, vers];
|
||||
#endif
|
||||
});
|
||||
return ua;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,43 +0,0 @@
|
||||
#import <Foundation/NSNotification.h>
|
||||
#import <PromiseKit/AnyPromise.h>
|
||||
|
||||
|
||||
/**
|
||||
To import the `NSNotificationCenter` category:
|
||||
|
||||
use_frameworks!
|
||||
pod "PromiseKit/Foundation"
|
||||
|
||||
Or `NSNotificationCenter` is one of the categories imported by the umbrella pod:
|
||||
|
||||
use_frameworks!
|
||||
pod "PromiseKit"
|
||||
|
||||
And then in your sources:
|
||||
|
||||
#import <PromiseKit/PromiseKit.h>
|
||||
*/
|
||||
@interface NSNotificationCenter (PromiseKit)
|
||||
/**
|
||||
Observe the named notification once.
|
||||
|
||||
[NSNotificationCenter once:UIKeyboardWillShowNotification].then(^(id note, id userInfo){
|
||||
UIViewAnimationCurve curve = [userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
|
||||
CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
|
||||
|
||||
return [UIView promiseWithDuration:duration delay:0.0 options:(curve << 16) animations:^{
|
||||
|
||||
}];
|
||||
});
|
||||
|
||||
@warning *Important* Promises only resolve once. If you need your block to execute more than once then use `-addObserverForName:object:queue:usingBlock:`.
|
||||
|
||||
@param notificationName The name of the notification for which to register the observer.
|
||||
|
||||
@return A promise that fulfills with two parameters:
|
||||
|
||||
1. The NSNotification object.
|
||||
2. The NSNotification’s userInfo property.
|
||||
*/
|
||||
+ (AnyPromise *)once:(NSString *)notificationName;
|
||||
@end
|
||||
@@ -1,18 +0,0 @@
|
||||
#import <assert.h>
|
||||
#import <Foundation/NSThread.h>
|
||||
#import <Foundation/NSOperation.h>
|
||||
#import "NSNotificationCenter+AnyPromise.h"
|
||||
|
||||
|
||||
@implementation NSNotificationCenter (PromiseKit)
|
||||
|
||||
+ (AnyPromise *)once:(NSString *)name {
|
||||
return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) {
|
||||
__block id identifier = [[NSNotificationCenter defaultCenter] addObserverForName:name object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
|
||||
[[NSNotificationCenter defaultCenter] removeObserver:identifier name:name object:nil];
|
||||
resolve(PMKManifold(note, note.userInfo));
|
||||
}];
|
||||
}];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -1,51 +0,0 @@
|
||||
import Foundation.NSNotification
|
||||
#if !COCOAPODS
|
||||
import PromiseKit
|
||||
#endif
|
||||
|
||||
/**
|
||||
To import the `NSNotificationCenter` category:
|
||||
|
||||
use_frameworks!
|
||||
pod "PromiseKit/Foundation"
|
||||
|
||||
Or `NSNotificationCenter` is one of the categories imported by the umbrella pod:
|
||||
|
||||
use_frameworks!
|
||||
pod "PromiseKit"
|
||||
|
||||
And then in your sources:
|
||||
|
||||
import PromiseKit
|
||||
*/
|
||||
extension NSNotificationCenter {
|
||||
public class func once(name: String) -> NotificationPromise {
|
||||
return NSNotificationCenter.defaultCenter().once(name)
|
||||
}
|
||||
|
||||
public func once(name: String) -> NotificationPromise {
|
||||
let (promise, fulfill) = NotificationPromise.go()
|
||||
let id = addObserverForName(name, object: nil, queue: nil, usingBlock: fulfill)
|
||||
promise.then(on: zalgo) { _ in self.removeObserver(id) }
|
||||
return promise
|
||||
}
|
||||
}
|
||||
|
||||
public class NotificationPromise: Promise<[NSObject: AnyObject]> {
|
||||
private let (parentPromise, parentFulfill, _) = Promise<NSNotification>.pendingPromise()
|
||||
|
||||
public func asNotification() -> Promise<NSNotification> {
|
||||
return parentPromise
|
||||
}
|
||||
|
||||
private class func go() -> (NotificationPromise, (NSNotification) -> Void) {
|
||||
var fulfill: (([NSObject: AnyObject]) -> Void)!
|
||||
let promise = NotificationPromise { f, _ in fulfill = f }
|
||||
promise.parentPromise.then { fulfill($0.userInfo ?? [:]) }
|
||||
return (promise, promise.parentFulfill)
|
||||
}
|
||||
|
||||
private override init(@noescape resolvers: (fulfill: ([NSObject: AnyObject]) -> Void, reject: (ErrorType) -> Void) throws -> Void) {
|
||||
super.init(resolvers: resolvers)
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
import Foundation
|
||||
#if !COCOAPODS
|
||||
import PromiseKit
|
||||
#endif
|
||||
|
||||
/**
|
||||
To import the `NSObject` category:
|
||||
|
||||
use_frameworks!
|
||||
pod "PromiseKit/Foundation"
|
||||
|
||||
Or `NSObject` is one of the categories imported by the umbrella pod:
|
||||
|
||||
use_frameworks!
|
||||
pod "PromiseKit"
|
||||
|
||||
And then in your sources:
|
||||
|
||||
import PromiseKit
|
||||
*/
|
||||
extension NSObject {
|
||||
/**
|
||||
@return A promise that resolves when the provided keyPath changes.
|
||||
|
||||
@warning *Important* The promise must not outlive the object under observation.
|
||||
|
||||
@see Apple’s KVO documentation.
|
||||
*/
|
||||
public func observe<T>(keyPath: String) -> Promise<T> {
|
||||
let (promise, fulfill, reject) = Promise<T>.pendingPromise()
|
||||
let proxy = KVOProxy(observee: self, keyPath: keyPath) { obj in
|
||||
if let obj = obj as? T {
|
||||
fulfill(obj)
|
||||
} else {
|
||||
let info = [NSLocalizedDescriptionKey: "The observed property was not of the requested type."]
|
||||
reject(NSError(domain: PMKErrorDomain, code: PMKInvalidUsageError, userInfo: info))
|
||||
}
|
||||
}
|
||||
proxy.retainCycle = proxy
|
||||
return promise
|
||||
}
|
||||
}
|
||||
|
||||
private class KVOProxy: NSObject {
|
||||
var retainCycle: KVOProxy?
|
||||
let fulfill: (AnyObject?) -> Void
|
||||
|
||||
init(observee: NSObject, keyPath: String, resolve: (AnyObject?) -> Void) {
|
||||
fulfill = resolve
|
||||
super.init()
|
||||
observee.addObserver(self, forKeyPath: keyPath, options: NSKeyValueObservingOptions.New, context: pointer)
|
||||
}
|
||||
|
||||
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
|
||||
if let change = change where context == pointer {
|
||||
defer { retainCycle = nil }
|
||||
fulfill(change[NSKeyValueChangeNewKey])
|
||||
if let object = object, keyPath = keyPath {
|
||||
object.removeObserver(self, forKeyPath: keyPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private lazy var pointer: UnsafeMutablePointer<Void> = {
|
||||
return UnsafeMutablePointer<Void>(Unmanaged<KVOProxy>.passUnretained(self).toOpaque())
|
||||
}()
|
||||
}
|
||||
@@ -1,215 +0,0 @@
|
||||
#import <Foundation/NSDictionary.h>
|
||||
#import <Foundation/NSURLConnection.h>
|
||||
#import <Foundation/NSURLRequest.h>
|
||||
#import <PromiseKit/AnyPromise.h>
|
||||
|
||||
/**
|
||||
To import the `NSURLConnection` category:
|
||||
|
||||
use_frameworks!
|
||||
pod "PromiseKit/Foundation"
|
||||
|
||||
Or `NSURLConnection` is one of the categories imported by the umbrella pod:
|
||||
|
||||
use_frameworks!
|
||||
pod "PromiseKit"
|
||||
|
||||
And then in your sources:
|
||||
|
||||
#import <PromiseKit/PromiseKit.h>
|
||||
|
||||
PromiseKit automatically deserializes the raw HTTP data response into the
|
||||
appropriate rich data type based on the mime type the server provides.
|
||||
Thus if the response is JSON you will get the deserialized JSON response.
|
||||
PromiseKit supports decoding into strings, JSON and UIImages.
|
||||
|
||||
However if your server does not provide a rich content-type, you will
|
||||
just get `NSData`. This is rare, but a good example we came across was
|
||||
downloading files from Dropbox.
|
||||
|
||||
PromiseKit goes to quite some lengths to provide good `NSError` objects
|
||||
for error conditions at all stages of the HTTP to rich-data type
|
||||
pipeline. We provide the following additional `userInfo` keys as
|
||||
appropriate:
|
||||
|
||||
- `PMKURLErrorFailingDataKey`
|
||||
- `PMKURLErrorFailingStringKey`
|
||||
- `PMKURLErrorFailingURLResponseKey`
|
||||
|
||||
PromiseKit uses [OMGHTTPURLRQ](https://github.com/mxcl/OMGHTTPURLRQ) to
|
||||
make its HTTP requests. PromiseKit only provides a convenience layer
|
||||
above OMGHTTPURLRQ, thus if you need more power (eg. a multipartFormData
|
||||
POST), use OMGHTTPURLRQ to generate the `NSURLRequest` and then pass
|
||||
that request to `+promise:`.
|
||||
|
||||
@see https://github.com/mxcl/OMGHTTPURLRQ
|
||||
*/
|
||||
@interface NSURLConnection (PromiseKit)
|
||||
|
||||
/**
|
||||
Makes a GET request to the provided URL.
|
||||
|
||||
[NSURLConnection GET:@"http://placekitten.com/320/320"].then(^(UIImage *img){
|
||||
// PromiseKit decodes the image (if it’s an image)
|
||||
});
|
||||
|
||||
@param urlStringFormatOrURL The `NSURL` or string format to request.
|
||||
|
||||
@return A promise that fulfills with three parameters:
|
||||
|
||||
1) The deserialized data response.
|
||||
2) The `NSHTTPURLResponse`.
|
||||
3) The raw `NSData` response.
|
||||
*/
|
||||
+ (AnyPromise *)GET:(id)urlStringFormatOrURL, ...;
|
||||
|
||||
/**
|
||||
Makes a GET request with the provided query parameters.
|
||||
|
||||
id url = @"http://jsonplaceholder.typicode.com/comments";
|
||||
id params = @{@"postId": @1};
|
||||
[NSURLConnection GET:url query:params].then(^(NSDictionary *jsonResponse){
|
||||
// PromiseKit decodes the JSON dictionary (if it’s JSON)
|
||||
});
|
||||
|
||||
@param urlString The `NSURL` or URL string format to request.
|
||||
|
||||
@param parameters The parameters to be encoded as the query string for the GET request.
|
||||
|
||||
@return A promise that fulfills with three parameters:
|
||||
|
||||
1) The deserialized data response.
|
||||
2) The `NSHTTPURLResponse`.
|
||||
3) The raw `NSData` response.
|
||||
*/
|
||||
+ (AnyPromise *)GET:(NSString *)urlString query:(NSDictionary *)parameters;
|
||||
|
||||
/**
|
||||
Makes a POST request to the provided URL passing form URL encoded
|
||||
parameters.
|
||||
|
||||
Form URL-encoding is the standard way to POST on the Internet, so
|
||||
probably this is what you want. If it doesn’t work, try the `+POST:JSON`
|
||||
variant.
|
||||
|
||||
id url = @"http://jsonplaceholder.typicode.com/posts";
|
||||
id params = @{@"title": @"foo", @"body": @"bar", @"userId": @1};
|
||||
[NSURLConnection POST:url formURLEncodedParameters:params].then(^(NSDictionary *jsonResponse){
|
||||
// PromiseKit decodes the JSON dictionary (if it’s JSON)
|
||||
});
|
||||
|
||||
@param urlString The URL to request.
|
||||
|
||||
@param parameters The parameters to be form URL-encoded and passed as the POST body.
|
||||
|
||||
@return A promise that fulfills with three parameters:
|
||||
|
||||
1) The deserialized data response.
|
||||
2) The `NSHTTPURLResponse`.
|
||||
3) The raw `NSData` response.
|
||||
*/
|
||||
+ (AnyPromise *)POST:(NSString *)urlString formURLEncodedParameters:(NSDictionary *)parameters;
|
||||
|
||||
/**
|
||||
Makes a POST request to the provided URL passing JSON encoded parameters.
|
||||
|
||||
Most web servers nowadays support POST with either JSON or form
|
||||
URL-encoding. If in doubt try form URL-encoded parameters first.
|
||||
|
||||
id url = @"http://jsonplaceholder.typicode.com/posts";
|
||||
id params = @{@"title": @"foo", @"body": @"bar", @"userId": @1};
|
||||
[NSURLConnection POST:url JSON:params].then(^(NSDictionary *jsonResponse){
|
||||
// PromiseKit decodes the JSON dictionary (if it’s JSON)
|
||||
});
|
||||
|
||||
@param urlString The URL to request.
|
||||
|
||||
@param JSONParameters The parameters to be JSON encoded and passed as the POST body.
|
||||
|
||||
@return A promise that fulfills with three parameters:
|
||||
|
||||
1) The deserialized data response.
|
||||
2) The `NSHTTPURLResponse`.
|
||||
3) The raw `NSData` response.
|
||||
*/
|
||||
+ (AnyPromise *)POST:(NSString *)urlString JSON:(NSDictionary *)JSONParameters;
|
||||
|
||||
/**
|
||||
Makes a PUT request to the provided URL passing form URL-encoded
|
||||
parameters.
|
||||
|
||||
id url = @"http://jsonplaceholder.typicode.com/posts/1";
|
||||
id params = @{@"id": @1, @"title": @"foo", @"body": @"bar", @"userId": @1};
|
||||
[NSURLConnection PUT:url formURLEncodedParameters:params].then(^(NSDictionary *jsonResponse){
|
||||
// PromiseKit decodes the JSON dictionary (if it’s JSON)
|
||||
});
|
||||
|
||||
@param urlString The URL to request.
|
||||
|
||||
@param parameters The parameters to be form URL-encoded and passed as the HTTP body.
|
||||
|
||||
@return A promise that fulfills with three parameters:
|
||||
|
||||
1) The deserialized data response.
|
||||
2) The `NSHTTPURLResponse`.
|
||||
3) The raw `NSData` response.
|
||||
*/
|
||||
+ (AnyPromise *)PUT:(NSString *)urlString formURLEncodedParameters:(NSDictionary *)params;
|
||||
|
||||
/**
|
||||
Makes a DELETE request to the provided URL passing form URL-encoded
|
||||
parameters.
|
||||
|
||||
id url = @"http://jsonplaceholder.typicode.com/posts/1";
|
||||
id params = nil;
|
||||
[NSURLConnection DELETE:url formURLEncodedParameters:params].then(^(NSDictionary *jsonResponse){
|
||||
// PromiseKit decodes the JSON dictionary (if it’s JSON)
|
||||
});
|
||||
|
||||
@param urlString The URL to request.
|
||||
|
||||
@param parameters The parameters to be form URL-encoded and passed as the HTTP body.
|
||||
|
||||
@return A promise that fulfills with three parameters:
|
||||
|
||||
1) The deserialized data response.
|
||||
2) The `NSHTTPURLResponse`.
|
||||
3) The raw `NSData` response.
|
||||
*/
|
||||
+ (AnyPromise *)DELETE:(NSString *)urlString formURLEncodedParameters:(NSDictionary *)params;
|
||||
|
||||
/**
|
||||
Makes an HTTP request using the parameters specified by the provided URL
|
||||
request.
|
||||
|
||||
This variant is less convenient, but provides you complete control over
|
||||
your `NSURLRequest`. Often this is necessary if your API requires
|
||||
authentication in the HTTP headers.
|
||||
|
||||
Also, for example, if you need to send a multipart form request then
|
||||
PromiseKit provides no convenience method for this, however using
|
||||
OMGHTTPURLRQ (a dependency of this category), we can accomplish our
|
||||
requirements:
|
||||
|
||||
OMGMultipartFormData *multipartFormData = [OMGMultipartFormData new];
|
||||
|
||||
NSData *data1 = [NSData dataWithContentsOfFile:@"myimage1.png"];
|
||||
[multipartFormData addFile:data1 parameterName:@"file1" filename:@"myimage1.png" contentType:@"image/png"];
|
||||
|
||||
NSMutableURLRequest *rq = [OMGHTTPURLRQ POST:url:multipartFormData];
|
||||
|
||||
[NSURLConnection promise:rq].then(^(id response){
|
||||
//…
|
||||
});
|
||||
|
||||
@param request The URL request.
|
||||
|
||||
@return A promise that fulfills with three parameters:
|
||||
|
||||
1) The deserialized data response.
|
||||
2) The `NSHTTPURLResponse`.
|
||||
3) The raw `NSData` response.
|
||||
*/
|
||||
+ (AnyPromise *)promise:(NSURLRequest *)request;
|
||||
|
||||
@end
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user