mirror of
https://github.com/valitydev/openapi-generator.git
synced 2024-11-08 03:18:53 +00:00
add in pods
This commit is contained in:
parent
bc0658e81c
commit
4a0c7966a1
4
samples/client/petstore/swift/SwaggerClientTests/Podfile
Normal file
4
samples/client/petstore/swift/SwaggerClientTests/Podfile
Normal file
@ -0,0 +1,4 @@
|
||||
use_frameworks!
|
||||
source 'https://github.com/CocoaPods/Specs.git'
|
||||
pod "PetstoreClient", :path => "../"
|
||||
|
@ -0,0 +1,39 @@
|
||||
PODS:
|
||||
- Alamofire (3.1.5)
|
||||
- OMGHTTPURLRQ (3.1.1):
|
||||
- OMGHTTPURLRQ/RQ (= 3.1.1)
|
||||
- OMGHTTPURLRQ/FormURLEncode (3.1.1)
|
||||
- OMGHTTPURLRQ/RQ (3.1.1):
|
||||
- OMGHTTPURLRQ/FormURLEncode
|
||||
- OMGHTTPURLRQ/UserAgent
|
||||
- OMGHTTPURLRQ/UserAgent (3.1.1)
|
||||
- PetstoreClient (0.0.1):
|
||||
- Alamofire (~> 3.1.4)
|
||||
- PromiseKit (~> 3.0.0)
|
||||
- PromiseKit (3.0.2):
|
||||
- PromiseKit/Foundation (= 3.0.2)
|
||||
- PromiseKit/QuartzCore (= 3.0.2)
|
||||
- PromiseKit/UIKit (= 3.0.2)
|
||||
- PromiseKit/CorePromise (3.0.2)
|
||||
- PromiseKit/Foundation (3.0.2):
|
||||
- OMGHTTPURLRQ (~> 3.1.0)
|
||||
- PromiseKit/CorePromise
|
||||
- PromiseKit/QuartzCore (3.0.2):
|
||||
- PromiseKit/CorePromise
|
||||
- PromiseKit/UIKit (3.0.2):
|
||||
- PromiseKit/CorePromise
|
||||
|
||||
DEPENDENCIES:
|
||||
- PetstoreClient (from `../`)
|
||||
|
||||
EXTERNAL SOURCES:
|
||||
PetstoreClient:
|
||||
:path: ../
|
||||
|
||||
SPEC CHECKSUMS:
|
||||
Alamofire: 5f730ba29fd113b7ddd71c1e65d0c630acf5d7b0
|
||||
OMGHTTPURLRQ: 633f98ee745aeda02345935a52eec1784cddb589
|
||||
PetstoreClient: c9a3d06cf7954479a767135676406c4922cd3c4a
|
||||
PromiseKit: ab1a380f7a30cf8cce663a2411e8b3580b10313d
|
||||
|
||||
COCOAPODS: 0.39.0
|
19
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/LICENSE
generated
Normal file
19
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/LICENSE
generated
Normal file
@ -0,0 +1,19 @@
|
||||
Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
1149
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/README.md
generated
Normal file
1149
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/README.md
generated
Normal file
File diff suppressed because it is too large
Load Diff
368
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift
generated
Normal file
368
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift
generated
Normal file
@ -0,0 +1,368 @@
|
||||
// Alamofire.swift
|
||||
//
|
||||
// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
// MARK: - URLStringConvertible
|
||||
|
||||
/**
|
||||
Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to
|
||||
construct URL requests.
|
||||
*/
|
||||
public protocol URLStringConvertible {
|
||||
/**
|
||||
A URL that conforms to RFC 2396.
|
||||
|
||||
Methods accepting a `URLStringConvertible` type parameter parse it according to RFCs 1738 and 1808.
|
||||
|
||||
See https://tools.ietf.org/html/rfc2396
|
||||
See https://tools.ietf.org/html/rfc1738
|
||||
See https://tools.ietf.org/html/rfc1808
|
||||
*/
|
||||
var URLString: String { get }
|
||||
}
|
||||
|
||||
extension String: URLStringConvertible {
|
||||
public var URLString: String {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
extension NSURL: URLStringConvertible {
|
||||
public var URLString: String {
|
||||
return absoluteString
|
||||
}
|
||||
}
|
||||
|
||||
extension NSURLComponents: URLStringConvertible {
|
||||
public var URLString: String {
|
||||
return URL!.URLString
|
||||
}
|
||||
}
|
||||
|
||||
extension NSURLRequest: URLStringConvertible {
|
||||
public var URLString: String {
|
||||
return URL!.URLString
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - URLRequestConvertible
|
||||
|
||||
/**
|
||||
Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests.
|
||||
*/
|
||||
public protocol URLRequestConvertible {
|
||||
/// The URL request.
|
||||
var URLRequest: NSMutableURLRequest { get }
|
||||
}
|
||||
|
||||
extension NSURLRequest: URLRequestConvertible {
|
||||
public var URLRequest: NSMutableURLRequest {
|
||||
return self.mutableCopy() as! NSMutableURLRequest
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Convenience
|
||||
|
||||
func URLRequest(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
headers: [String: String]? = nil)
|
||||
-> NSMutableURLRequest
|
||||
{
|
||||
let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString)!)
|
||||
mutableURLRequest.HTTPMethod = method.rawValue
|
||||
|
||||
if let headers = headers {
|
||||
for (headerField, headerValue) in headers {
|
||||
mutableURLRequest.setValue(headerValue, forHTTPHeaderField: headerField)
|
||||
}
|
||||
}
|
||||
|
||||
return mutableURLRequest
|
||||
}
|
||||
|
||||
// MARK: - Request Methods
|
||||
|
||||
/**
|
||||
Creates a request using the shared manager instance for the specified method, URL string, parameters, and
|
||||
parameter encoding.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter parameters: The parameters. `nil` by default.
|
||||
- parameter encoding: The parameter encoding. `.URL` by default.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
|
||||
- returns: The created request.
|
||||
*/
|
||||
public func request(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
parameters: [String: AnyObject]? = nil,
|
||||
encoding: ParameterEncoding = .URL,
|
||||
headers: [String: String]? = nil)
|
||||
-> Request
|
||||
{
|
||||
return Manager.sharedInstance.request(
|
||||
method,
|
||||
URLString,
|
||||
parameters: parameters,
|
||||
encoding: encoding,
|
||||
headers: headers
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a request using the shared manager instance for the specified URL request.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter URLRequest: The URL request
|
||||
|
||||
- returns: The created request.
|
||||
*/
|
||||
public func request(URLRequest: URLRequestConvertible) -> Request {
|
||||
return Manager.sharedInstance.request(URLRequest.URLRequest)
|
||||
}
|
||||
|
||||
// MARK: - Upload Methods
|
||||
|
||||
// MARK: File
|
||||
|
||||
/**
|
||||
Creates an upload request using the shared manager instance for the specified method, URL string, and file.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter file: The file to upload.
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
headers: [String: String]? = nil,
|
||||
file: NSURL)
|
||||
-> Request
|
||||
{
|
||||
return Manager.sharedInstance.upload(method, URLString, headers: headers, file: file)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates an upload request using the shared manager instance for the specified URL request and file.
|
||||
|
||||
- parameter URLRequest: The URL request.
|
||||
- parameter file: The file to upload.
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request {
|
||||
return Manager.sharedInstance.upload(URLRequest, file: file)
|
||||
}
|
||||
|
||||
// MARK: Data
|
||||
|
||||
/**
|
||||
Creates an upload request using the shared manager instance for the specified method, URL string, and data.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter data: The data to upload.
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
headers: [String: String]? = nil,
|
||||
data: NSData)
|
||||
-> Request
|
||||
{
|
||||
return Manager.sharedInstance.upload(method, URLString, headers: headers, data: data)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates an upload request using the shared manager instance for the specified URL request and data.
|
||||
|
||||
- parameter URLRequest: The URL request.
|
||||
- parameter data: The data to upload.
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request {
|
||||
return Manager.sharedInstance.upload(URLRequest, data: data)
|
||||
}
|
||||
|
||||
// MARK: Stream
|
||||
|
||||
/**
|
||||
Creates an upload request using the shared manager instance for the specified method, URL string, and stream.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter stream: The stream to upload.
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
headers: [String: String]? = nil,
|
||||
stream: NSInputStream)
|
||||
-> Request
|
||||
{
|
||||
return Manager.sharedInstance.upload(method, URLString, headers: headers, stream: stream)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates an upload request using the shared manager instance for the specified URL request and stream.
|
||||
|
||||
- parameter URLRequest: The URL request.
|
||||
- parameter stream: The stream to upload.
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request {
|
||||
return Manager.sharedInstance.upload(URLRequest, stream: stream)
|
||||
}
|
||||
|
||||
// MARK: MultipartFormData
|
||||
|
||||
/**
|
||||
Creates an upload request using the shared manager instance for the specified method and URL string.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
|
||||
- parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
|
||||
`MultipartFormDataEncodingMemoryThreshold` by default.
|
||||
- parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
|
||||
*/
|
||||
public func upload(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
headers: [String: String]? = nil,
|
||||
multipartFormData: MultipartFormData -> Void,
|
||||
encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold,
|
||||
encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?)
|
||||
{
|
||||
return Manager.sharedInstance.upload(
|
||||
method,
|
||||
URLString,
|
||||
headers: headers,
|
||||
multipartFormData: multipartFormData,
|
||||
encodingMemoryThreshold: encodingMemoryThreshold,
|
||||
encodingCompletion: encodingCompletion
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates an upload request using the shared manager instance for the specified method and URL string.
|
||||
|
||||
- parameter URLRequest: The URL request.
|
||||
- parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
|
||||
- parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
|
||||
`MultipartFormDataEncodingMemoryThreshold` by default.
|
||||
- parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
|
||||
*/
|
||||
public func upload(
|
||||
URLRequest: URLRequestConvertible,
|
||||
multipartFormData: MultipartFormData -> Void,
|
||||
encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold,
|
||||
encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?)
|
||||
{
|
||||
return Manager.sharedInstance.upload(
|
||||
URLRequest,
|
||||
multipartFormData: multipartFormData,
|
||||
encodingMemoryThreshold: encodingMemoryThreshold,
|
||||
encodingCompletion: encodingCompletion
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Download Methods
|
||||
|
||||
// MARK: URL Request
|
||||
|
||||
/**
|
||||
Creates a download request using the shared manager instance for the specified method and URL string.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter parameters: The parameters. `nil` by default.
|
||||
- parameter encoding: The parameter encoding. `.URL` by default.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter destination: The closure used to determine the destination of the downloaded file.
|
||||
|
||||
- returns: The created download request.
|
||||
*/
|
||||
public func download(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
parameters: [String: AnyObject]? = nil,
|
||||
encoding: ParameterEncoding = .URL,
|
||||
headers: [String: String]? = nil,
|
||||
destination: Request.DownloadFileDestination)
|
||||
-> Request
|
||||
{
|
||||
return Manager.sharedInstance.download(
|
||||
method,
|
||||
URLString,
|
||||
parameters: parameters,
|
||||
encoding: encoding,
|
||||
headers: headers,
|
||||
destination: destination
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a download request using the shared manager instance for the specified URL request.
|
||||
|
||||
- parameter URLRequest: The URL request.
|
||||
- parameter destination: The closure used to determine the destination of the downloaded file.
|
||||
|
||||
- returns: The created download request.
|
||||
*/
|
||||
public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request {
|
||||
return Manager.sharedInstance.download(URLRequest, destination: destination)
|
||||
}
|
||||
|
||||
// MARK: Resume Data
|
||||
|
||||
/**
|
||||
Creates a request using the shared manager instance for downloading from the resume data produced from a
|
||||
previous request cancellation.
|
||||
|
||||
- parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask`
|
||||
when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional
|
||||
information.
|
||||
- parameter destination: The closure used to determine the destination of the downloaded file.
|
||||
|
||||
- returns: The created download request.
|
||||
*/
|
||||
public func download(resumeData data: NSData, destination: Request.DownloadFileDestination) -> Request {
|
||||
return Manager.sharedInstance.download(data, destination: destination)
|
||||
}
|
244
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Download.swift
generated
Normal file
244
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Download.swift
generated
Normal file
@ -0,0 +1,244 @@
|
||||
// Download.swift
|
||||
//
|
||||
// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
extension Manager {
|
||||
private enum Downloadable {
|
||||
case Request(NSURLRequest)
|
||||
case ResumeData(NSData)
|
||||
}
|
||||
|
||||
private func download(downloadable: Downloadable, destination: Request.DownloadFileDestination) -> Request {
|
||||
var downloadTask: NSURLSessionDownloadTask!
|
||||
|
||||
switch downloadable {
|
||||
case .Request(let request):
|
||||
dispatch_sync(queue) {
|
||||
downloadTask = self.session.downloadTaskWithRequest(request)
|
||||
}
|
||||
case .ResumeData(let resumeData):
|
||||
dispatch_sync(queue) {
|
||||
downloadTask = self.session.downloadTaskWithResumeData(resumeData)
|
||||
}
|
||||
}
|
||||
|
||||
let request = Request(session: session, task: downloadTask)
|
||||
|
||||
if let downloadDelegate = request.delegate as? Request.DownloadTaskDelegate {
|
||||
downloadDelegate.downloadTaskDidFinishDownloadingToURL = { session, downloadTask, URL in
|
||||
return destination(URL, downloadTask.response as! NSHTTPURLResponse)
|
||||
}
|
||||
}
|
||||
|
||||
delegate[request.delegate.task] = request.delegate
|
||||
|
||||
if startRequestsImmediately {
|
||||
request.resume()
|
||||
}
|
||||
|
||||
return request
|
||||
}
|
||||
|
||||
// MARK: Request
|
||||
|
||||
/**
|
||||
Creates a download request for the specified method, URL string, parameters, parameter encoding, headers
|
||||
and destination.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter parameters: The parameters. `nil` by default.
|
||||
- parameter encoding: The parameter encoding. `.URL` by default.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter destination: The closure used to determine the destination of the downloaded file.
|
||||
|
||||
- returns: The created download request.
|
||||
*/
|
||||
public func download(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
parameters: [String: AnyObject]? = nil,
|
||||
encoding: ParameterEncoding = .URL,
|
||||
headers: [String: String]? = nil,
|
||||
destination: Request.DownloadFileDestination)
|
||||
-> Request
|
||||
{
|
||||
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
|
||||
let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0
|
||||
|
||||
return download(encodedURLRequest, destination: destination)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a request for downloading from the specified URL request.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter URLRequest: The URL request
|
||||
- parameter destination: The closure used to determine the destination of the downloaded file.
|
||||
|
||||
- returns: The created download request.
|
||||
*/
|
||||
public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request {
|
||||
return download(.Request(URLRequest.URLRequest), destination: destination)
|
||||
}
|
||||
|
||||
// MARK: Resume Data
|
||||
|
||||
/**
|
||||
Creates a request for downloading from the resume data produced from a previous request cancellation.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask`
|
||||
when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for
|
||||
additional information.
|
||||
- parameter destination: The closure used to determine the destination of the downloaded file.
|
||||
|
||||
- returns: The created download request.
|
||||
*/
|
||||
public func download(resumeData: NSData, destination: Request.DownloadFileDestination) -> Request {
|
||||
return download(.ResumeData(resumeData), destination: destination)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
extension Request {
|
||||
/**
|
||||
A closure executed once a request has successfully completed in order to determine where to move the temporary
|
||||
file written to during the download process. The closure takes two arguments: the temporary file URL and the URL
|
||||
response, and returns a single argument: the file URL where the temporary file should be moved.
|
||||
*/
|
||||
public typealias DownloadFileDestination = (NSURL, NSHTTPURLResponse) -> NSURL
|
||||
|
||||
/**
|
||||
Creates a download file destination closure which uses the default file manager to move the temporary file to a
|
||||
file URL in the first available directory with the specified search path directory and search path domain mask.
|
||||
|
||||
- parameter directory: The search path directory. `.DocumentDirectory` by default.
|
||||
- parameter domain: The search path domain mask. `.UserDomainMask` by default.
|
||||
|
||||
- returns: A download file destination closure.
|
||||
*/
|
||||
public class func suggestedDownloadDestination(
|
||||
directory directory: NSSearchPathDirectory = .DocumentDirectory,
|
||||
domain: NSSearchPathDomainMask = .UserDomainMask)
|
||||
-> DownloadFileDestination
|
||||
{
|
||||
return { temporaryURL, response -> NSURL in
|
||||
let directoryURLs = NSFileManager.defaultManager().URLsForDirectory(directory, inDomains: domain)
|
||||
|
||||
if !directoryURLs.isEmpty {
|
||||
return directoryURLs[0].URLByAppendingPathComponent(response.suggestedFilename!)
|
||||
}
|
||||
|
||||
return temporaryURL
|
||||
}
|
||||
}
|
||||
|
||||
/// The resume data of the underlying download task if available after a failure.
|
||||
public var resumeData: NSData? {
|
||||
var data: NSData?
|
||||
|
||||
if let delegate = delegate as? DownloadTaskDelegate {
|
||||
data = delegate.resumeData
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
// MARK: - DownloadTaskDelegate
|
||||
|
||||
class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate {
|
||||
var downloadTask: NSURLSessionDownloadTask? { return task as? NSURLSessionDownloadTask }
|
||||
var downloadProgress: ((Int64, Int64, Int64) -> Void)?
|
||||
|
||||
var resumeData: NSData?
|
||||
override var data: NSData? { return resumeData }
|
||||
|
||||
// MARK: - NSURLSessionDownloadDelegate
|
||||
|
||||
// MARK: Override Closures
|
||||
|
||||
var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> NSURL)?
|
||||
var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
|
||||
var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)?
|
||||
|
||||
// MARK: Delegate Methods
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
downloadTask: NSURLSessionDownloadTask,
|
||||
didFinishDownloadingToURL location: NSURL)
|
||||
{
|
||||
if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL {
|
||||
do {
|
||||
let destination = downloadTaskDidFinishDownloadingToURL(session, downloadTask, location)
|
||||
try NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination)
|
||||
} catch {
|
||||
self.error = error as NSError
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
downloadTask: NSURLSessionDownloadTask,
|
||||
didWriteData bytesWritten: Int64,
|
||||
totalBytesWritten: Int64,
|
||||
totalBytesExpectedToWrite: Int64)
|
||||
{
|
||||
if let downloadTaskDidWriteData = downloadTaskDidWriteData {
|
||||
downloadTaskDidWriteData(
|
||||
session,
|
||||
downloadTask,
|
||||
bytesWritten,
|
||||
totalBytesWritten,
|
||||
totalBytesExpectedToWrite
|
||||
)
|
||||
} else {
|
||||
progress.totalUnitCount = totalBytesExpectedToWrite
|
||||
progress.completedUnitCount = totalBytesWritten
|
||||
|
||||
downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
|
||||
}
|
||||
}
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
downloadTask: NSURLSessionDownloadTask,
|
||||
didResumeAtOffset fileOffset: Int64,
|
||||
expectedTotalBytes: Int64)
|
||||
{
|
||||
if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
|
||||
downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
|
||||
} else {
|
||||
progress.totalUnitCount = expectedTotalBytes
|
||||
progress.completedUnitCount = fileOffset
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
66
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Error.swift
generated
Normal file
66
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Error.swift
generated
Normal file
@ -0,0 +1,66 @@
|
||||
// Error.swift
|
||||
//
|
||||
// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
/// The `Error` struct provides a convenience for creating custom Alamofire NSErrors.
|
||||
public struct Error {
|
||||
/// The domain used for creating all Alamofire errors.
|
||||
public static let Domain = "com.alamofire.error"
|
||||
|
||||
/// The custom error codes generated by Alamofire.
|
||||
public enum Code: Int {
|
||||
case InputStreamReadFailed = -6000
|
||||
case OutputStreamWriteFailed = -6001
|
||||
case ContentTypeValidationFailed = -6002
|
||||
case StatusCodeValidationFailed = -6003
|
||||
case DataSerializationFailed = -6004
|
||||
case StringSerializationFailed = -6005
|
||||
case JSONSerializationFailed = -6006
|
||||
case PropertyListSerializationFailed = -6007
|
||||
}
|
||||
|
||||
/**
|
||||
Creates an `NSError` with the given error code and failure reason.
|
||||
|
||||
- parameter code: The error code.
|
||||
- parameter failureReason: The failure reason.
|
||||
|
||||
- returns: An `NSError` with the given error code and failure reason.
|
||||
*/
|
||||
public static func errorWithCode(code: Code, failureReason: String) -> NSError {
|
||||
return errorWithCode(code.rawValue, failureReason: failureReason)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates an `NSError` with the given error code and failure reason.
|
||||
|
||||
- parameter code: The error code.
|
||||
- parameter failureReason: The failure reason.
|
||||
|
||||
- returns: An `NSError` with the given error code and failure reason.
|
||||
*/
|
||||
public static func errorWithCode(code: Int, failureReason: String) -> NSError {
|
||||
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
|
||||
return NSError(domain: Domain, code: code, userInfo: userInfo)
|
||||
}
|
||||
}
|
693
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift
generated
Normal file
693
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift
generated
Normal file
@ -0,0 +1,693 @@
|
||||
// Manager.swift
|
||||
//
|
||||
// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`.
|
||||
*/
|
||||
public class Manager {
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
/**
|
||||
A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly
|
||||
for any ad hoc requests.
|
||||
*/
|
||||
public static let sharedInstance: Manager = {
|
||||
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
|
||||
configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders
|
||||
|
||||
return Manager(configuration: configuration)
|
||||
}()
|
||||
|
||||
/**
|
||||
Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers.
|
||||
*/
|
||||
public static let defaultHTTPHeaders: [String: String] = {
|
||||
// Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3
|
||||
let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5"
|
||||
|
||||
// Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5
|
||||
let acceptLanguage = NSLocale.preferredLanguages().prefix(6).enumerate().map { index, languageCode in
|
||||
let quality = 1.0 - (Double(index) * 0.1)
|
||||
return "\(languageCode);q=\(quality)"
|
||||
}.joinWithSeparator(", ")
|
||||
|
||||
// User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3
|
||||
let userAgent: String = {
|
||||
if let info = NSBundle.mainBundle().infoDictionary {
|
||||
let executable: AnyObject = info[kCFBundleExecutableKey as String] ?? "Unknown"
|
||||
let bundle: AnyObject = info[kCFBundleIdentifierKey as String] ?? "Unknown"
|
||||
let version: AnyObject = info[kCFBundleVersionKey as String] ?? "Unknown"
|
||||
let os: AnyObject = NSProcessInfo.processInfo().operatingSystemVersionString ?? "Unknown"
|
||||
|
||||
var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString
|
||||
let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString
|
||||
|
||||
if CFStringTransform(mutableUserAgent, UnsafeMutablePointer<CFRange>(nil), transform, false) {
|
||||
return mutableUserAgent as String
|
||||
}
|
||||
}
|
||||
|
||||
return "Alamofire"
|
||||
}()
|
||||
|
||||
return [
|
||||
"Accept-Encoding": acceptEncoding,
|
||||
"Accept-Language": acceptLanguage,
|
||||
"User-Agent": userAgent
|
||||
]
|
||||
}()
|
||||
|
||||
let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL)
|
||||
|
||||
/// The underlying session.
|
||||
public let session: NSURLSession
|
||||
|
||||
/// The session delegate handling all the task and session delegate callbacks.
|
||||
public let delegate: SessionDelegate
|
||||
|
||||
/// Whether to start requests immediately after being constructed. `true` by default.
|
||||
public var startRequestsImmediately: Bool = true
|
||||
|
||||
/**
|
||||
The background completion handler closure provided by the UIApplicationDelegate
|
||||
`application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background
|
||||
completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation
|
||||
will automatically call the handler.
|
||||
|
||||
If you need to handle your own events before the handler is called, then you need to override the
|
||||
SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished.
|
||||
|
||||
`nil` by default.
|
||||
*/
|
||||
public var backgroundCompletionHandler: (() -> Void)?
|
||||
|
||||
// MARK: - Lifecycle
|
||||
|
||||
/**
|
||||
Initializes the `Manager` instance with the specified configuration, delegate and server trust policy.
|
||||
|
||||
- parameter configuration: The configuration used to construct the managed session.
|
||||
`NSURLSessionConfiguration.defaultSessionConfiguration()` by default.
|
||||
- parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by
|
||||
default.
|
||||
- parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
|
||||
challenges. `nil` by default.
|
||||
|
||||
- returns: The new `Manager` instance.
|
||||
*/
|
||||
public init(
|
||||
configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration(),
|
||||
delegate: SessionDelegate = SessionDelegate(),
|
||||
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
|
||||
{
|
||||
self.delegate = delegate
|
||||
self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
|
||||
|
||||
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
|
||||
}
|
||||
|
||||
/**
|
||||
Initializes the `Manager` instance with the specified session, delegate and server trust policy.
|
||||
|
||||
- parameter session: The URL session.
|
||||
- parameter delegate: The delegate of the URL session. Must equal the URL session's delegate.
|
||||
- parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
|
||||
challenges. `nil` by default.
|
||||
|
||||
- returns: The new `Manager` instance if the URL session's delegate matches the delegate parameter.
|
||||
*/
|
||||
public init?(
|
||||
session: NSURLSession,
|
||||
delegate: SessionDelegate,
|
||||
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
|
||||
{
|
||||
self.delegate = delegate
|
||||
self.session = session
|
||||
|
||||
guard delegate === session.delegate else { return nil }
|
||||
|
||||
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
|
||||
}
|
||||
|
||||
private func commonInit(serverTrustPolicyManager serverTrustPolicyManager: ServerTrustPolicyManager?) {
|
||||
session.serverTrustPolicyManager = serverTrustPolicyManager
|
||||
|
||||
delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in
|
||||
guard let strongSelf = self else { return }
|
||||
dispatch_async(dispatch_get_main_queue()) { strongSelf.backgroundCompletionHandler?() }
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
session.invalidateAndCancel()
|
||||
}
|
||||
|
||||
// MARK: - Request
|
||||
|
||||
/**
|
||||
Creates a request for the specified method, URL string, parameters, parameter encoding and headers.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter parameters: The parameters. `nil` by default.
|
||||
- parameter encoding: The parameter encoding. `.URL` by default.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
|
||||
- returns: The created request.
|
||||
*/
|
||||
public func request(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
parameters: [String: AnyObject]? = nil,
|
||||
encoding: ParameterEncoding = .URL,
|
||||
headers: [String: String]? = nil)
|
||||
-> Request
|
||||
{
|
||||
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
|
||||
let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0
|
||||
return request(encodedURLRequest)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a request for the specified URL request.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter URLRequest: The URL request
|
||||
|
||||
- returns: The created request.
|
||||
*/
|
||||
public func request(URLRequest: URLRequestConvertible) -> Request {
|
||||
var dataTask: NSURLSessionDataTask!
|
||||
dispatch_sync(queue) { dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest) }
|
||||
|
||||
let request = Request(session: session, task: dataTask)
|
||||
delegate[request.delegate.task] = request.delegate
|
||||
|
||||
if startRequestsImmediately {
|
||||
request.resume()
|
||||
}
|
||||
|
||||
return request
|
||||
}
|
||||
|
||||
// MARK: - SessionDelegate
|
||||
|
||||
/**
|
||||
Responsible for handling all delegate callbacks for the underlying session.
|
||||
*/
|
||||
public final class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
|
||||
private var subdelegates: [Int: Request.TaskDelegate] = [:]
|
||||
private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
|
||||
|
||||
subscript(task: NSURLSessionTask) -> Request.TaskDelegate? {
|
||||
get {
|
||||
var subdelegate: Request.TaskDelegate?
|
||||
dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] }
|
||||
|
||||
return subdelegate
|
||||
}
|
||||
|
||||
set {
|
||||
dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Initializes the `SessionDelegate` instance.
|
||||
|
||||
- returns: The new `SessionDelegate` instance.
|
||||
*/
|
||||
public override init() {
|
||||
super.init()
|
||||
}
|
||||
|
||||
// MARK: - NSURLSessionDelegate
|
||||
|
||||
// MARK: Override Closures
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didBecomeInvalidWithError:`.
|
||||
public var sessionDidBecomeInvalidWithError: ((NSURLSession, NSError?) -> Void)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`.
|
||||
public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`.
|
||||
public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)?
|
||||
|
||||
// MARK: Delegate Methods
|
||||
|
||||
/**
|
||||
Tells the delegate that the session has been invalidated.
|
||||
|
||||
- parameter session: The session object that was invalidated.
|
||||
- parameter error: The error that caused invalidation, or nil if the invalidation was explicit.
|
||||
*/
|
||||
public func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) {
|
||||
sessionDidBecomeInvalidWithError?(session, error)
|
||||
}
|
||||
|
||||
/**
|
||||
Requests credentials from the delegate in response to a session-level authentication request from the remote server.
|
||||
|
||||
- parameter session: The session containing the task that requested authentication.
|
||||
- parameter challenge: An object that contains the request for authentication.
|
||||
- parameter completionHandler: A handler that your delegate method must call providing the disposition and credential.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
|
||||
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void))
|
||||
{
|
||||
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
|
||||
var credential: NSURLCredential?
|
||||
|
||||
if let sessionDidReceiveChallenge = sessionDidReceiveChallenge {
|
||||
(disposition, credential) = sessionDidReceiveChallenge(session, challenge)
|
||||
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
|
||||
let host = challenge.protectionSpace.host
|
||||
|
||||
if let
|
||||
serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host),
|
||||
serverTrust = challenge.protectionSpace.serverTrust
|
||||
{
|
||||
if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) {
|
||||
disposition = .UseCredential
|
||||
credential = NSURLCredential(forTrust: serverTrust)
|
||||
} else {
|
||||
disposition = .CancelAuthenticationChallenge
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
completionHandler(disposition, credential)
|
||||
}
|
||||
|
||||
/**
|
||||
Tells the delegate that all messages enqueued for a session have been delivered.
|
||||
|
||||
- parameter session: The session that no longer has any outstanding requests.
|
||||
*/
|
||||
public func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) {
|
||||
sessionDidFinishEventsForBackgroundURLSession?(session)
|
||||
}
|
||||
|
||||
// MARK: - NSURLSessionTaskDelegate
|
||||
|
||||
// MARK: Override Closures
|
||||
|
||||
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`.
|
||||
public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`.
|
||||
public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`.
|
||||
public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream!)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.
|
||||
public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didCompleteWithError:`.
|
||||
public var taskDidComplete: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)?
|
||||
|
||||
// MARK: Delegate Methods
|
||||
|
||||
/**
|
||||
Tells the delegate that the remote server requested an HTTP redirect.
|
||||
|
||||
- parameter session: The session containing the task whose request resulted in a redirect.
|
||||
- parameter task: The task whose request resulted in a redirect.
|
||||
- parameter response: An object containing the server’s response to the original request.
|
||||
- parameter request: A URL request object filled out with the new location.
|
||||
- parameter completionHandler: A closure that your handler should call with either the value of the request
|
||||
parameter, a modified URL request object, or NULL to refuse the redirect and
|
||||
return the body of the redirect response.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
task: NSURLSessionTask,
|
||||
willPerformHTTPRedirection response: NSHTTPURLResponse,
|
||||
newRequest request: NSURLRequest,
|
||||
completionHandler: ((NSURLRequest?) -> Void))
|
||||
{
|
||||
var redirectRequest: NSURLRequest? = request
|
||||
|
||||
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
|
||||
redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
|
||||
}
|
||||
|
||||
completionHandler(redirectRequest)
|
||||
}
|
||||
|
||||
/**
|
||||
Requests credentials from the delegate in response to an authentication request from the remote server.
|
||||
|
||||
- parameter session: The session containing the task whose request requires authentication.
|
||||
- parameter task: The task whose request requires authentication.
|
||||
- parameter challenge: An object that contains the request for authentication.
|
||||
- parameter completionHandler: A handler that your delegate method must call providing the disposition and credential.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
task: NSURLSessionTask,
|
||||
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
|
||||
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void))
|
||||
{
|
||||
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
|
||||
completionHandler(taskDidReceiveChallenge(session, task, challenge))
|
||||
} else if let delegate = self[task] {
|
||||
delegate.URLSession(
|
||||
session,
|
||||
task: task,
|
||||
didReceiveChallenge: challenge,
|
||||
completionHandler: completionHandler
|
||||
)
|
||||
} else {
|
||||
URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Tells the delegate when a task requires a new request body stream to send to the remote server.
|
||||
|
||||
- parameter session: The session containing the task that needs a new body stream.
|
||||
- parameter task: The task that needs a new body stream.
|
||||
- parameter completionHandler: A completion handler that your delegate method should call with the new body stream.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
task: NSURLSessionTask,
|
||||
needNewBodyStream completionHandler: ((NSInputStream?) -> Void))
|
||||
{
|
||||
if let taskNeedNewBodyStream = taskNeedNewBodyStream {
|
||||
completionHandler(taskNeedNewBodyStream(session, task))
|
||||
} else if let delegate = self[task] {
|
||||
delegate.URLSession(session, task: task, needNewBodyStream: completionHandler)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Periodically informs the delegate of the progress of sending body content to the server.
|
||||
|
||||
- parameter session: The session containing the data task.
|
||||
- parameter task: The data task.
|
||||
- parameter bytesSent: The number of bytes sent since the last time this delegate method was called.
|
||||
- parameter totalBytesSent: The total number of bytes sent so far.
|
||||
- parameter totalBytesExpectedToSend: The expected length of the body data.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
task: NSURLSessionTask,
|
||||
didSendBodyData bytesSent: Int64,
|
||||
totalBytesSent: Int64,
|
||||
totalBytesExpectedToSend: Int64)
|
||||
{
|
||||
if let taskDidSendBodyData = taskDidSendBodyData {
|
||||
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
|
||||
} else if let delegate = self[task] as? Request.UploadTaskDelegate {
|
||||
delegate.URLSession(
|
||||
session,
|
||||
task: task,
|
||||
didSendBodyData: bytesSent,
|
||||
totalBytesSent: totalBytesSent,
|
||||
totalBytesExpectedToSend: totalBytesExpectedToSend
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Tells the delegate that the task finished transferring data.
|
||||
|
||||
- parameter session: The session containing the task whose request finished transferring data.
|
||||
- parameter task: The task whose request finished transferring data.
|
||||
- parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil.
|
||||
*/
|
||||
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
|
||||
if let taskDidComplete = taskDidComplete {
|
||||
taskDidComplete(session, task, error)
|
||||
} else if let delegate = self[task] {
|
||||
delegate.URLSession(session, task: task, didCompleteWithError: error)
|
||||
}
|
||||
|
||||
self[task] = nil
|
||||
}
|
||||
|
||||
// MARK: - NSURLSessionDataDelegate
|
||||
|
||||
// MARK: Override Closures
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`.
|
||||
public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`.
|
||||
public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveData:`.
|
||||
public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`.
|
||||
public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse!)?
|
||||
|
||||
// MARK: Delegate Methods
|
||||
|
||||
/**
|
||||
Tells the delegate that the data task received the initial reply (headers) from the server.
|
||||
|
||||
- parameter session: The session containing the data task that received an initial reply.
|
||||
- parameter dataTask: The data task that received an initial reply.
|
||||
- parameter response: A URL response object populated with headers.
|
||||
- parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a
|
||||
constant to indicate whether the transfer should continue as a data task or
|
||||
should become a download task.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
dataTask: NSURLSessionDataTask,
|
||||
didReceiveResponse response: NSURLResponse,
|
||||
completionHandler: ((NSURLSessionResponseDisposition) -> Void))
|
||||
{
|
||||
var disposition: NSURLSessionResponseDisposition = .Allow
|
||||
|
||||
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
|
||||
disposition = dataTaskDidReceiveResponse(session, dataTask, response)
|
||||
}
|
||||
|
||||
completionHandler(disposition)
|
||||
}
|
||||
|
||||
/**
|
||||
Tells the delegate that the data task was changed to a download task.
|
||||
|
||||
- parameter session: The session containing the task that was replaced by a download task.
|
||||
- parameter dataTask: The data task that was replaced by a download task.
|
||||
- parameter downloadTask: The new download task that replaced the data task.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
dataTask: NSURLSessionDataTask,
|
||||
didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask)
|
||||
{
|
||||
if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask {
|
||||
dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask)
|
||||
} else {
|
||||
let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask)
|
||||
self[downloadTask] = downloadDelegate
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Tells the delegate that the data task has received some of the expected data.
|
||||
|
||||
- parameter session: The session containing the data task that provided data.
|
||||
- parameter dataTask: The data task that provided data.
|
||||
- parameter data: A data object containing the transferred data.
|
||||
*/
|
||||
public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
|
||||
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
|
||||
dataTaskDidReceiveData(session, dataTask, data)
|
||||
} else if let delegate = self[dataTask] as? Request.DataTaskDelegate {
|
||||
delegate.URLSession(session, dataTask: dataTask, didReceiveData: data)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Asks the delegate whether the data (or upload) task should store the response in the cache.
|
||||
|
||||
- parameter session: The session containing the data (or upload) task.
|
||||
- parameter dataTask: The data (or upload) task.
|
||||
- parameter proposedResponse: The default caching behavior. This behavior is determined based on the current
|
||||
caching policy and the values of certain received headers, such as the Pragma
|
||||
and Cache-Control headers.
|
||||
- parameter completionHandler: A block that your handler must call, providing either the original proposed
|
||||
response, a modified version of that response, or NULL to prevent caching the
|
||||
response. If your delegate implements this method, it must call this completion
|
||||
handler; otherwise, your app leaks memory.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
dataTask: NSURLSessionDataTask,
|
||||
willCacheResponse proposedResponse: NSCachedURLResponse,
|
||||
completionHandler: ((NSCachedURLResponse?) -> Void))
|
||||
{
|
||||
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
|
||||
completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse))
|
||||
} else if let delegate = self[dataTask] as? Request.DataTaskDelegate {
|
||||
delegate.URLSession(
|
||||
session,
|
||||
dataTask: dataTask,
|
||||
willCacheResponse: proposedResponse,
|
||||
completionHandler: completionHandler
|
||||
)
|
||||
} else {
|
||||
completionHandler(proposedResponse)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - NSURLSessionDownloadDelegate
|
||||
|
||||
// MARK: Override Closures
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didFinishDownloadingToURL:`.
|
||||
public var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> Void)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`.
|
||||
public var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
|
||||
|
||||
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`.
|
||||
public var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)?
|
||||
|
||||
// MARK: Delegate Methods
|
||||
|
||||
/**
|
||||
Tells the delegate that a download task has finished downloading.
|
||||
|
||||
- parameter session: The session containing the download task that finished.
|
||||
- parameter downloadTask: The download task that finished.
|
||||
- parameter location: A file URL for the temporary file. Because the file is temporary, you must either
|
||||
open the file for reading or move it to a permanent location in your app’s sandbox
|
||||
container directory before returning from this delegate method.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
downloadTask: NSURLSessionDownloadTask,
|
||||
didFinishDownloadingToURL location: NSURL)
|
||||
{
|
||||
if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL {
|
||||
downloadTaskDidFinishDownloadingToURL(session, downloadTask, location)
|
||||
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
|
||||
delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Periodically informs the delegate about the download’s progress.
|
||||
|
||||
- parameter session: The session containing the download task.
|
||||
- parameter downloadTask: The download task.
|
||||
- parameter bytesWritten: The number of bytes transferred since the last time this delegate
|
||||
method was called.
|
||||
- parameter totalBytesWritten: The total number of bytes transferred so far.
|
||||
- parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length
|
||||
header. If this header was not provided, the value is
|
||||
`NSURLSessionTransferSizeUnknown`.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
downloadTask: NSURLSessionDownloadTask,
|
||||
didWriteData bytesWritten: Int64,
|
||||
totalBytesWritten: Int64,
|
||||
totalBytesExpectedToWrite: Int64)
|
||||
{
|
||||
if let downloadTaskDidWriteData = downloadTaskDidWriteData {
|
||||
downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
|
||||
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
|
||||
delegate.URLSession(
|
||||
session,
|
||||
downloadTask: downloadTask,
|
||||
didWriteData: bytesWritten,
|
||||
totalBytesWritten: totalBytesWritten,
|
||||
totalBytesExpectedToWrite: totalBytesExpectedToWrite
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Tells the delegate that the download task has resumed downloading.
|
||||
|
||||
- parameter session: The session containing the download task that finished.
|
||||
- parameter downloadTask: The download task that resumed. See explanation in the discussion.
|
||||
- parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the
|
||||
existing content, then this value is zero. Otherwise, this value is an
|
||||
integer representing the number of bytes on disk that do not need to be
|
||||
retrieved again.
|
||||
- parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header.
|
||||
If this header was not provided, the value is NSURLSessionTransferSizeUnknown.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
downloadTask: NSURLSessionDownloadTask,
|
||||
didResumeAtOffset fileOffset: Int64,
|
||||
expectedTotalBytes: Int64)
|
||||
{
|
||||
if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
|
||||
downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
|
||||
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
|
||||
delegate.URLSession(
|
||||
session,
|
||||
downloadTask: downloadTask,
|
||||
didResumeAtOffset: fileOffset,
|
||||
expectedTotalBytes: expectedTotalBytes
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - NSURLSessionStreamDelegate
|
||||
|
||||
var _streamTaskReadClosed: Any?
|
||||
var _streamTaskWriteClosed: Any?
|
||||
var _streamTaskBetterRouteDiscovered: Any?
|
||||
var _streamTaskDidBecomeInputStream: Any?
|
||||
|
||||
// MARK: - NSObject
|
||||
|
||||
public override func respondsToSelector(selector: Selector) -> Bool {
|
||||
switch selector {
|
||||
case "URLSession:didBecomeInvalidWithError:":
|
||||
return sessionDidBecomeInvalidWithError != nil
|
||||
case "URLSession:didReceiveChallenge:completionHandler:":
|
||||
return sessionDidReceiveChallenge != nil
|
||||
case "URLSessionDidFinishEventsForBackgroundURLSession:":
|
||||
return sessionDidFinishEventsForBackgroundURLSession != nil
|
||||
case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:":
|
||||
return taskWillPerformHTTPRedirection != nil
|
||||
case "URLSession:dataTask:didReceiveResponse:completionHandler:":
|
||||
return dataTaskDidReceiveResponse != nil
|
||||
default:
|
||||
return self.dynamicType.instancesRespondToSelector(selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
669
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift
generated
Normal file
669
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift
generated
Normal file
@ -0,0 +1,669 @@
|
||||
// MultipartFormData.swift
|
||||
//
|
||||
// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
#if os(iOS) || os(watchOS) || os(tvOS)
|
||||
import MobileCoreServices
|
||||
#elseif os(OSX)
|
||||
import CoreServices
|
||||
#endif
|
||||
|
||||
/**
|
||||
Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode
|
||||
multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead
|
||||
to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the
|
||||
data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for
|
||||
larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset.
|
||||
|
||||
For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well
|
||||
and the w3 form documentation.
|
||||
|
||||
- https://www.ietf.org/rfc/rfc2388.txt
|
||||
- https://www.ietf.org/rfc/rfc2045.txt
|
||||
- https://www.w3.org/TR/html401/interact/forms.html#h-17.13
|
||||
*/
|
||||
public class MultipartFormData {
|
||||
|
||||
// MARK: - Helper Types
|
||||
|
||||
struct EncodingCharacters {
|
||||
static let CRLF = "\r\n"
|
||||
}
|
||||
|
||||
struct BoundaryGenerator {
|
||||
enum BoundaryType {
|
||||
case Initial, Encapsulated, Final
|
||||
}
|
||||
|
||||
static func randomBoundary() -> String {
|
||||
return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random())
|
||||
}
|
||||
|
||||
static func boundaryData(boundaryType boundaryType: BoundaryType, boundary: String) -> NSData {
|
||||
let boundaryText: String
|
||||
|
||||
switch boundaryType {
|
||||
case .Initial:
|
||||
boundaryText = "--\(boundary)\(EncodingCharacters.CRLF)"
|
||||
case .Encapsulated:
|
||||
boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)\(EncodingCharacters.CRLF)"
|
||||
case .Final:
|
||||
boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)--\(EncodingCharacters.CRLF)"
|
||||
}
|
||||
|
||||
return boundaryText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
|
||||
}
|
||||
}
|
||||
|
||||
class BodyPart {
|
||||
let headers: [String: String]
|
||||
let bodyStream: NSInputStream
|
||||
let bodyContentLength: UInt64
|
||||
var hasInitialBoundary = false
|
||||
var hasFinalBoundary = false
|
||||
|
||||
init(headers: [String: String], bodyStream: NSInputStream, bodyContentLength: UInt64) {
|
||||
self.headers = headers
|
||||
self.bodyStream = bodyStream
|
||||
self.bodyContentLength = bodyContentLength
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
/// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`.
|
||||
public var contentType: String { return "multipart/form-data; boundary=\(boundary)" }
|
||||
|
||||
/// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries.
|
||||
public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } }
|
||||
|
||||
/// The boundary used to separate the body parts in the encoded form data.
|
||||
public let boundary: String
|
||||
|
||||
private var bodyParts: [BodyPart]
|
||||
private var bodyPartError: NSError?
|
||||
private let streamBufferSize: Int
|
||||
|
||||
// MARK: - Lifecycle
|
||||
|
||||
/**
|
||||
Creates a multipart form data object.
|
||||
|
||||
- returns: The multipart form data object.
|
||||
*/
|
||||
public init() {
|
||||
self.boundary = BoundaryGenerator.randomBoundary()
|
||||
self.bodyParts = []
|
||||
|
||||
/**
|
||||
* The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more
|
||||
* information, please refer to the following article:
|
||||
* - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html
|
||||
*/
|
||||
|
||||
self.streamBufferSize = 1024
|
||||
}
|
||||
|
||||
// MARK: - Body Parts
|
||||
|
||||
/**
|
||||
Creates a body part from the data and appends it to the multipart form data object.
|
||||
|
||||
The body part data will be encoded using the following format:
|
||||
|
||||
- `Content-Disposition: form-data; name=#{name}` (HTTP Header)
|
||||
- Encoded data
|
||||
- Multipart form boundary
|
||||
|
||||
- parameter data: The data to encode into the multipart form data.
|
||||
- parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
|
||||
*/
|
||||
public func appendBodyPart(data data: NSData, name: String) {
|
||||
let headers = contentHeaders(name: name)
|
||||
let stream = NSInputStream(data: data)
|
||||
let length = UInt64(data.length)
|
||||
|
||||
appendBodyPart(stream: stream, length: length, headers: headers)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a body part from the data and appends it to the multipart form data object.
|
||||
|
||||
The body part data will be encoded using the following format:
|
||||
|
||||
- `Content-Disposition: form-data; name=#{name}` (HTTP Header)
|
||||
- `Content-Type: #{generated mimeType}` (HTTP Header)
|
||||
- Encoded data
|
||||
- Multipart form boundary
|
||||
|
||||
- parameter data: The data to encode into the multipart form data.
|
||||
- parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
|
||||
- parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header.
|
||||
*/
|
||||
public func appendBodyPart(data data: NSData, name: String, mimeType: String) {
|
||||
let headers = contentHeaders(name: name, mimeType: mimeType)
|
||||
let stream = NSInputStream(data: data)
|
||||
let length = UInt64(data.length)
|
||||
|
||||
appendBodyPart(stream: stream, length: length, headers: headers)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a body part from the data and appends it to the multipart form data object.
|
||||
|
||||
The body part data will be encoded using the following format:
|
||||
|
||||
- `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
|
||||
- `Content-Type: #{mimeType}` (HTTP Header)
|
||||
- Encoded file data
|
||||
- Multipart form boundary
|
||||
|
||||
- parameter data: The data to encode into the multipart form data.
|
||||
- parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
|
||||
- parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header.
|
||||
- parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header.
|
||||
*/
|
||||
public func appendBodyPart(data data: NSData, name: String, fileName: String, mimeType: String) {
|
||||
let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
|
||||
let stream = NSInputStream(data: data)
|
||||
let length = UInt64(data.length)
|
||||
|
||||
appendBodyPart(stream: stream, length: length, headers: headers)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a body part from the file and appends it to the multipart form data object.
|
||||
|
||||
The body part data will be encoded using the following format:
|
||||
|
||||
- `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header)
|
||||
- `Content-Type: #{generated mimeType}` (HTTP Header)
|
||||
- Encoded file data
|
||||
- Multipart form boundary
|
||||
|
||||
The filename in the `Content-Disposition` HTTP header is generated from the last path component of the
|
||||
`fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the
|
||||
system associated MIME type.
|
||||
|
||||
- parameter fileURL: The URL of the file whose content will be encoded into the multipart form data.
|
||||
- parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header.
|
||||
*/
|
||||
public func appendBodyPart(fileURL fileURL: NSURL, name: String) {
|
||||
if let
|
||||
fileName = fileURL.lastPathComponent,
|
||||
pathExtension = fileURL.pathExtension
|
||||
{
|
||||
let mimeType = mimeTypeForPathExtension(pathExtension)
|
||||
appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType)
|
||||
} else {
|
||||
let failureReason = "Failed to extract the fileName of the provided URL: \(fileURL)"
|
||||
setBodyPartError(Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a body part from the file and appends it to the multipart form data object.
|
||||
|
||||
The body part data will be encoded using the following format:
|
||||
|
||||
- Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header)
|
||||
- Content-Type: #{mimeType} (HTTP Header)
|
||||
- Encoded file data
|
||||
- Multipart form boundary
|
||||
|
||||
- parameter fileURL: The URL of the file whose content will be encoded into the multipart form data.
|
||||
- parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header.
|
||||
- parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header.
|
||||
- parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header.
|
||||
*/
|
||||
public func appendBodyPart(fileURL fileURL: NSURL, name: String, fileName: String, mimeType: String) {
|
||||
let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
|
||||
|
||||
//============================================================
|
||||
// Check 1 - is file URL?
|
||||
//============================================================
|
||||
|
||||
guard fileURL.fileURL else {
|
||||
let failureReason = "The file URL does not point to a file URL: \(fileURL)"
|
||||
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
|
||||
setBodyPartError(error)
|
||||
return
|
||||
}
|
||||
|
||||
//============================================================
|
||||
// Check 2 - is file URL reachable?
|
||||
//============================================================
|
||||
|
||||
var isReachable = true
|
||||
|
||||
if #available(OSX 10.10, *) {
|
||||
isReachable = fileURL.checkPromisedItemIsReachableAndReturnError(nil)
|
||||
}
|
||||
|
||||
guard isReachable else {
|
||||
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)")
|
||||
setBodyPartError(error)
|
||||
return
|
||||
}
|
||||
|
||||
//============================================================
|
||||
// Check 3 - is file URL a directory?
|
||||
//============================================================
|
||||
|
||||
var isDirectory: ObjCBool = false
|
||||
|
||||
guard let
|
||||
path = fileURL.path
|
||||
where NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) && !isDirectory else
|
||||
{
|
||||
let failureReason = "The file URL is a directory, not a file: \(fileURL)"
|
||||
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
|
||||
setBodyPartError(error)
|
||||
return
|
||||
}
|
||||
|
||||
//============================================================
|
||||
// Check 4 - can the file size be extracted?
|
||||
//============================================================
|
||||
|
||||
var bodyContentLength: UInt64?
|
||||
|
||||
do {
|
||||
if let
|
||||
path = fileURL.path,
|
||||
fileSize = try NSFileManager.defaultManager().attributesOfItemAtPath(path)[NSFileSize] as? NSNumber
|
||||
{
|
||||
bodyContentLength = fileSize.unsignedLongLongValue
|
||||
}
|
||||
} catch {
|
||||
// No-op
|
||||
}
|
||||
|
||||
guard let length = bodyContentLength else {
|
||||
let failureReason = "Could not fetch attributes from the file URL: \(fileURL)"
|
||||
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
|
||||
setBodyPartError(error)
|
||||
return
|
||||
}
|
||||
|
||||
//============================================================
|
||||
// Check 5 - can a stream be created from file URL?
|
||||
//============================================================
|
||||
|
||||
guard let stream = NSInputStream(URL: fileURL) else {
|
||||
let failureReason = "Failed to create an input stream from the file URL: \(fileURL)"
|
||||
let error = Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason)
|
||||
setBodyPartError(error)
|
||||
return
|
||||
}
|
||||
|
||||
appendBodyPart(stream: stream, length: length, headers: headers)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a body part from the stream and appends it to the multipart form data object.
|
||||
|
||||
The body part data will be encoded using the following format:
|
||||
|
||||
- `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
|
||||
- `Content-Type: #{mimeType}` (HTTP Header)
|
||||
- Encoded stream data
|
||||
- Multipart form boundary
|
||||
|
||||
- parameter stream: The input stream to encode in the multipart form data.
|
||||
- parameter length: The content length of the stream.
|
||||
- parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header.
|
||||
- parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header.
|
||||
- parameter mimeType: The MIME type to associate with the stream content in the `Content-Type` HTTP header.
|
||||
*/
|
||||
public func appendBodyPart(
|
||||
stream stream: NSInputStream,
|
||||
length: UInt64,
|
||||
name: String,
|
||||
fileName: String,
|
||||
mimeType: String)
|
||||
{
|
||||
let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
|
||||
appendBodyPart(stream: stream, length: length, headers: headers)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a body part with the headers, stream and length and appends it to the multipart form data object.
|
||||
|
||||
The body part data will be encoded using the following format:
|
||||
|
||||
- HTTP headers
|
||||
- Encoded stream data
|
||||
- Multipart form boundary
|
||||
|
||||
- parameter stream: The input stream to encode in the multipart form data.
|
||||
- parameter length: The content length of the stream.
|
||||
- parameter headers: The HTTP headers for the body part.
|
||||
*/
|
||||
public func appendBodyPart(stream stream: NSInputStream, length: UInt64, headers: [String: String]) {
|
||||
let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length)
|
||||
bodyParts.append(bodyPart)
|
||||
}
|
||||
|
||||
// MARK: - Data Encoding
|
||||
|
||||
/**
|
||||
Encodes all the appended body parts into a single `NSData` object.
|
||||
|
||||
It is important to note that this method will load all the appended body parts into memory all at the same
|
||||
time. This method should only be used when the encoded data will have a small memory footprint. For large data
|
||||
cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method.
|
||||
|
||||
- throws: An `NSError` if encoding encounters an error.
|
||||
|
||||
- returns: The encoded `NSData` if encoding is successful.
|
||||
*/
|
||||
public func encode() throws -> NSData {
|
||||
if let bodyPartError = bodyPartError {
|
||||
throw bodyPartError
|
||||
}
|
||||
|
||||
let encoded = NSMutableData()
|
||||
|
||||
bodyParts.first?.hasInitialBoundary = true
|
||||
bodyParts.last?.hasFinalBoundary = true
|
||||
|
||||
for bodyPart in bodyParts {
|
||||
let encodedData = try encodeBodyPart(bodyPart)
|
||||
encoded.appendData(encodedData)
|
||||
}
|
||||
|
||||
return encoded
|
||||
}
|
||||
|
||||
/**
|
||||
Writes the appended body parts into the given file URL.
|
||||
|
||||
This process is facilitated by reading and writing with input and output streams, respectively. Thus,
|
||||
this approach is very memory efficient and should be used for large body part data.
|
||||
|
||||
- parameter fileURL: The file URL to write the multipart form data into.
|
||||
|
||||
- throws: An `NSError` if encoding encounters an error.
|
||||
*/
|
||||
public func writeEncodedDataToDisk(fileURL: NSURL) throws {
|
||||
if let bodyPartError = bodyPartError {
|
||||
throw bodyPartError
|
||||
}
|
||||
|
||||
if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) {
|
||||
let failureReason = "A file already exists at the given file URL: \(fileURL)"
|
||||
throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
|
||||
} else if !fileURL.fileURL {
|
||||
let failureReason = "The URL does not point to a valid file: \(fileURL)"
|
||||
throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
|
||||
}
|
||||
|
||||
let outputStream: NSOutputStream
|
||||
|
||||
if let possibleOutputStream = NSOutputStream(URL: fileURL, append: false) {
|
||||
outputStream = possibleOutputStream
|
||||
} else {
|
||||
let failureReason = "Failed to create an output stream with the given URL: \(fileURL)"
|
||||
throw Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason)
|
||||
}
|
||||
|
||||
outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
outputStream.open()
|
||||
|
||||
self.bodyParts.first?.hasInitialBoundary = true
|
||||
self.bodyParts.last?.hasFinalBoundary = true
|
||||
|
||||
for bodyPart in self.bodyParts {
|
||||
try writeBodyPart(bodyPart, toOutputStream: outputStream)
|
||||
}
|
||||
|
||||
outputStream.close()
|
||||
outputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
}
|
||||
|
||||
// MARK: - Private - Body Part Encoding
|
||||
|
||||
private func encodeBodyPart(bodyPart: BodyPart) throws -> NSData {
|
||||
let encoded = NSMutableData()
|
||||
|
||||
let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
|
||||
encoded.appendData(initialData)
|
||||
|
||||
let headerData = encodeHeaderDataForBodyPart(bodyPart)
|
||||
encoded.appendData(headerData)
|
||||
|
||||
let bodyStreamData = try encodeBodyStreamDataForBodyPart(bodyPart)
|
||||
encoded.appendData(bodyStreamData)
|
||||
|
||||
if bodyPart.hasFinalBoundary {
|
||||
encoded.appendData(finalBoundaryData())
|
||||
}
|
||||
|
||||
return encoded
|
||||
}
|
||||
|
||||
private func encodeHeaderDataForBodyPart(bodyPart: BodyPart) -> NSData {
|
||||
var headerText = ""
|
||||
|
||||
for (key, value) in bodyPart.headers {
|
||||
headerText += "\(key): \(value)\(EncodingCharacters.CRLF)"
|
||||
}
|
||||
headerText += EncodingCharacters.CRLF
|
||||
|
||||
return headerText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
|
||||
}
|
||||
|
||||
private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) throws -> NSData {
|
||||
let inputStream = bodyPart.bodyStream
|
||||
inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
inputStream.open()
|
||||
|
||||
var error: NSError?
|
||||
let encoded = NSMutableData()
|
||||
|
||||
while inputStream.hasBytesAvailable {
|
||||
var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0)
|
||||
let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
|
||||
|
||||
if inputStream.streamError != nil {
|
||||
error = inputStream.streamError
|
||||
break
|
||||
}
|
||||
|
||||
if bytesRead > 0 {
|
||||
encoded.appendBytes(buffer, length: bytesRead)
|
||||
} else if bytesRead < 0 {
|
||||
let failureReason = "Failed to read from input stream: \(inputStream)"
|
||||
error = Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason)
|
||||
break
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
inputStream.close()
|
||||
inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
|
||||
if let error = error {
|
||||
throw error
|
||||
}
|
||||
|
||||
return encoded
|
||||
}
|
||||
|
||||
// MARK: - Private - Writing Body Part to Output Stream
|
||||
|
||||
private func writeBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
|
||||
try writeInitialBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream)
|
||||
try writeHeaderDataForBodyPart(bodyPart, toOutputStream: outputStream)
|
||||
try writeBodyStreamForBodyPart(bodyPart, toOutputStream: outputStream)
|
||||
try writeFinalBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream)
|
||||
}
|
||||
|
||||
private func writeInitialBoundaryDataForBodyPart(
|
||||
bodyPart: BodyPart,
|
||||
toOutputStream outputStream: NSOutputStream)
|
||||
throws
|
||||
{
|
||||
let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
|
||||
return try writeData(initialData, toOutputStream: outputStream)
|
||||
}
|
||||
|
||||
private func writeHeaderDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
|
||||
let headerData = encodeHeaderDataForBodyPart(bodyPart)
|
||||
return try writeData(headerData, toOutputStream: outputStream)
|
||||
}
|
||||
|
||||
private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
|
||||
let inputStream = bodyPart.bodyStream
|
||||
inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
inputStream.open()
|
||||
|
||||
while inputStream.hasBytesAvailable {
|
||||
var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0)
|
||||
let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
|
||||
|
||||
if let streamError = inputStream.streamError {
|
||||
throw streamError
|
||||
}
|
||||
|
||||
if bytesRead > 0 {
|
||||
if buffer.count != bytesRead {
|
||||
buffer = Array(buffer[0..<bytesRead])
|
||||
}
|
||||
|
||||
try writeBuffer(&buffer, toOutputStream: outputStream)
|
||||
} else if bytesRead < 0 {
|
||||
let failureReason = "Failed to read from input stream: \(inputStream)"
|
||||
throw Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason)
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
inputStream.close()
|
||||
inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
}
|
||||
|
||||
private func writeFinalBoundaryDataForBodyPart(
|
||||
bodyPart: BodyPart,
|
||||
toOutputStream outputStream: NSOutputStream)
|
||||
throws
|
||||
{
|
||||
if bodyPart.hasFinalBoundary {
|
||||
return try writeData(finalBoundaryData(), toOutputStream: outputStream)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Private - Writing Buffered Data to Output Stream
|
||||
|
||||
private func writeData(data: NSData, toOutputStream outputStream: NSOutputStream) throws {
|
||||
var buffer = [UInt8](count: data.length, repeatedValue: 0)
|
||||
data.getBytes(&buffer, length: data.length)
|
||||
|
||||
return try writeBuffer(&buffer, toOutputStream: outputStream)
|
||||
}
|
||||
|
||||
private func writeBuffer(inout buffer: [UInt8], toOutputStream outputStream: NSOutputStream) throws {
|
||||
var bytesToWrite = buffer.count
|
||||
|
||||
while bytesToWrite > 0 {
|
||||
if outputStream.hasSpaceAvailable {
|
||||
let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite)
|
||||
|
||||
if let streamError = outputStream.streamError {
|
||||
throw streamError
|
||||
}
|
||||
|
||||
if bytesWritten < 0 {
|
||||
let failureReason = "Failed to write to output stream: \(outputStream)"
|
||||
throw Error.errorWithCode(.OutputStreamWriteFailed, failureReason: failureReason)
|
||||
}
|
||||
|
||||
bytesToWrite -= bytesWritten
|
||||
|
||||
if bytesToWrite > 0 {
|
||||
buffer = Array(buffer[bytesWritten..<buffer.count])
|
||||
}
|
||||
} else if let streamError = outputStream.streamError {
|
||||
throw streamError
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Private - Mime Type
|
||||
|
||||
private func mimeTypeForPathExtension(pathExtension: String) -> String {
|
||||
if let
|
||||
id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil)?.takeRetainedValue(),
|
||||
contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue()
|
||||
{
|
||||
return contentType as String
|
||||
}
|
||||
|
||||
return "application/octet-stream"
|
||||
}
|
||||
|
||||
// MARK: - Private - Content Headers
|
||||
|
||||
private func contentHeaders(name name: String) -> [String: String] {
|
||||
return ["Content-Disposition": "form-data; name=\"\(name)\""]
|
||||
}
|
||||
|
||||
private func contentHeaders(name name: String, mimeType: String) -> [String: String] {
|
||||
return [
|
||||
"Content-Disposition": "form-data; name=\"\(name)\"",
|
||||
"Content-Type": "\(mimeType)"
|
||||
]
|
||||
}
|
||||
|
||||
private func contentHeaders(name name: String, fileName: String, mimeType: String) -> [String: String] {
|
||||
return [
|
||||
"Content-Disposition": "form-data; name=\"\(name)\"; filename=\"\(fileName)\"",
|
||||
"Content-Type": "\(mimeType)"
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Private - Boundary Encoding
|
||||
|
||||
private func initialBoundaryData() -> NSData {
|
||||
return BoundaryGenerator.boundaryData(boundaryType: .Initial, boundary: boundary)
|
||||
}
|
||||
|
||||
private func encapsulatedBoundaryData() -> NSData {
|
||||
return BoundaryGenerator.boundaryData(boundaryType: .Encapsulated, boundary: boundary)
|
||||
}
|
||||
|
||||
private func finalBoundaryData() -> NSData {
|
||||
return BoundaryGenerator.boundaryData(boundaryType: .Final, boundary: boundary)
|
||||
}
|
||||
|
||||
// MARK: - Private - Errors
|
||||
|
||||
private func setBodyPartError(error: NSError) {
|
||||
if bodyPartError == nil {
|
||||
bodyPartError = error
|
||||
}
|
||||
}
|
||||
}
|
251
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift
generated
Normal file
251
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift
generated
Normal file
@ -0,0 +1,251 @@
|
||||
// ParameterEncoding.swift
|
||||
//
|
||||
// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
HTTP method definitions.
|
||||
|
||||
See https://tools.ietf.org/html/rfc7231#section-4.3
|
||||
*/
|
||||
public enum Method: String {
|
||||
case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT
|
||||
}
|
||||
|
||||
// MARK: ParameterEncoding
|
||||
|
||||
/**
|
||||
Used to specify the way in which a set of parameters are applied to a URL request.
|
||||
|
||||
- `URL`: Creates a query string to be set as or appended to any existing URL query for `GET`, `HEAD`,
|
||||
and `DELETE` requests, or set as the body for requests with any other HTTP method. The
|
||||
`Content-Type` HTTP header field of an encoded request with HTTP body is set to
|
||||
`application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification
|
||||
for how to encode collection types, the convention of appending `[]` to the key for array
|
||||
values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested
|
||||
dictionary values (`foo[bar]=baz`).
|
||||
|
||||
- `URLEncodedInURL`: Creates query string to be set as or appended to any existing URL query. Uses the same
|
||||
implementation as the `.URL` case, but always applies the encoded result to the URL.
|
||||
|
||||
- `JSON`: Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is
|
||||
set as the body of the request. The `Content-Type` HTTP header field of an encoded request is
|
||||
set to `application/json`.
|
||||
|
||||
- `PropertyList`: Uses `NSPropertyListSerialization` to create a plist representation of the parameters object,
|
||||
according to the associated format and write options values, which is set as the body of the
|
||||
request. The `Content-Type` HTTP header field of an encoded request is set to
|
||||
`application/x-plist`.
|
||||
|
||||
- `Custom`: Uses the associated closure value to construct a new request given an existing request and
|
||||
parameters.
|
||||
*/
|
||||
public enum ParameterEncoding {
|
||||
case URL
|
||||
case URLEncodedInURL
|
||||
case JSON
|
||||
case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
|
||||
case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?))
|
||||
|
||||
/**
|
||||
Creates a URL request by encoding parameters and applying them onto an existing request.
|
||||
|
||||
- parameter URLRequest: The request to have parameters applied
|
||||
- parameter parameters: The parameters to apply
|
||||
|
||||
- returns: A tuple containing the constructed request and the error that occurred during parameter encoding,
|
||||
if any.
|
||||
*/
|
||||
public func encode(
|
||||
URLRequest: URLRequestConvertible,
|
||||
parameters: [String: AnyObject]?)
|
||||
-> (NSMutableURLRequest, NSError?)
|
||||
{
|
||||
var mutableURLRequest = URLRequest.URLRequest
|
||||
|
||||
guard let parameters = parameters where !parameters.isEmpty else {
|
||||
return (mutableURLRequest, nil)
|
||||
}
|
||||
|
||||
var encodingError: NSError? = nil
|
||||
|
||||
switch self {
|
||||
case .URL, .URLEncodedInURL:
|
||||
func query(parameters: [String: AnyObject]) -> String {
|
||||
var components: [(String, String)] = []
|
||||
|
||||
for key in parameters.keys.sort(<) {
|
||||
let value = parameters[key]!
|
||||
components += queryComponents(key, value)
|
||||
}
|
||||
|
||||
return (components.map { "\($0)=\($1)" } as [String]).joinWithSeparator("&")
|
||||
}
|
||||
|
||||
func encodesParametersInURL(method: Method) -> Bool {
|
||||
switch self {
|
||||
case .URLEncodedInURL:
|
||||
return true
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
switch method {
|
||||
case .GET, .HEAD, .DELETE:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) {
|
||||
if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) {
|
||||
let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
|
||||
URLComponents.percentEncodedQuery = percentEncodedQuery
|
||||
mutableURLRequest.URL = URLComponents.URL
|
||||
}
|
||||
} else {
|
||||
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
|
||||
mutableURLRequest.setValue(
|
||||
"application/x-www-form-urlencoded; charset=utf-8",
|
||||
forHTTPHeaderField: "Content-Type"
|
||||
)
|
||||
}
|
||||
|
||||
mutableURLRequest.HTTPBody = query(parameters).dataUsingEncoding(
|
||||
NSUTF8StringEncoding,
|
||||
allowLossyConversion: false
|
||||
)
|
||||
}
|
||||
case .JSON:
|
||||
do {
|
||||
let options = NSJSONWritingOptions()
|
||||
let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options)
|
||||
|
||||
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
mutableURLRequest.HTTPBody = data
|
||||
} catch {
|
||||
encodingError = error as NSError
|
||||
}
|
||||
case .PropertyList(let format, let options):
|
||||
do {
|
||||
let data = try NSPropertyListSerialization.dataWithPropertyList(
|
||||
parameters,
|
||||
format: format,
|
||||
options: options
|
||||
)
|
||||
mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
|
||||
mutableURLRequest.HTTPBody = data
|
||||
} catch {
|
||||
encodingError = error as NSError
|
||||
}
|
||||
case .Custom(let closure):
|
||||
(mutableURLRequest, encodingError) = closure(mutableURLRequest, parameters)
|
||||
}
|
||||
|
||||
return (mutableURLRequest, encodingError)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion.
|
||||
|
||||
- parameter key: The key of the query component.
|
||||
- parameter value: The value of the query component.
|
||||
|
||||
- returns: The percent-escaped, URL encoded query string components.
|
||||
*/
|
||||
public func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
|
||||
var components: [(String, String)] = []
|
||||
|
||||
if let dictionary = value as? [String: AnyObject] {
|
||||
for (nestedKey, value) in dictionary {
|
||||
components += queryComponents("\(key)[\(nestedKey)]", value)
|
||||
}
|
||||
} else if let array = value as? [AnyObject] {
|
||||
for value in array {
|
||||
components += queryComponents("\(key)[]", value)
|
||||
}
|
||||
} else {
|
||||
components.append((escape(key), escape("\(value)")))
|
||||
}
|
||||
|
||||
return components
|
||||
}
|
||||
|
||||
/**
|
||||
Returns a percent-escaped string following RFC 3986 for a query string key or value.
|
||||
|
||||
RFC 3986 states that the following characters are "reserved" characters.
|
||||
|
||||
- General Delimiters: ":", "#", "[", "]", "@", "?", "/"
|
||||
- Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
|
||||
|
||||
In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
|
||||
query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
|
||||
should be percent-escaped in the query string.
|
||||
|
||||
- parameter string: The string to be percent-escaped.
|
||||
|
||||
- returns: The percent-escaped string.
|
||||
*/
|
||||
public func escape(string: String) -> String {
|
||||
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
|
||||
let subDelimitersToEncode = "!$&'()*+,;="
|
||||
|
||||
let allowedCharacterSet = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet
|
||||
allowedCharacterSet.removeCharactersInString(generalDelimitersToEncode + subDelimitersToEncode)
|
||||
|
||||
var escaped = ""
|
||||
|
||||
//==========================================================================================================
|
||||
//
|
||||
// Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few
|
||||
// hundred Chinense characters causes various malloc error crashes. To avoid this issue until iOS 8 is no
|
||||
// longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more
|
||||
// info, please refer to:
|
||||
//
|
||||
// - https://github.com/Alamofire/Alamofire/issues/206
|
||||
//
|
||||
//==========================================================================================================
|
||||
|
||||
if #available(iOS 8.3, OSX 10.10, *) {
|
||||
escaped = string.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? string
|
||||
} else {
|
||||
let batchSize = 50
|
||||
var index = string.startIndex
|
||||
|
||||
while index != string.endIndex {
|
||||
let startIndex = index
|
||||
let endIndex = index.advancedBy(batchSize, limit: string.endIndex)
|
||||
let range = Range(start: startIndex, end: endIndex)
|
||||
|
||||
let substring = string.substringWithRange(range)
|
||||
|
||||
escaped += substring.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? substring
|
||||
|
||||
index = endIndex
|
||||
}
|
||||
}
|
||||
|
||||
return escaped
|
||||
}
|
||||
}
|
538
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Request.swift
generated
Normal file
538
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Request.swift
generated
Normal file
@ -0,0 +1,538 @@
|
||||
// Request.swift
|
||||
//
|
||||
// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Responsible for sending a request and receiving the response and associated data from the server, as well as
|
||||
managing its underlying `NSURLSessionTask`.
|
||||
*/
|
||||
public class Request {
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
/// The delegate for the underlying task.
|
||||
public let delegate: TaskDelegate
|
||||
|
||||
/// The underlying task.
|
||||
public var task: NSURLSessionTask { return delegate.task }
|
||||
|
||||
/// The session belonging to the underlying task.
|
||||
public let session: NSURLSession
|
||||
|
||||
/// The request sent or to be sent to the server.
|
||||
public var request: NSURLRequest? { return task.originalRequest }
|
||||
|
||||
/// The response received from the server, if any.
|
||||
public var response: NSHTTPURLResponse? { return task.response as? NSHTTPURLResponse }
|
||||
|
||||
/// The progress of the request lifecycle.
|
||||
public var progress: NSProgress { return delegate.progress }
|
||||
|
||||
// MARK: - Lifecycle
|
||||
|
||||
init(session: NSURLSession, task: NSURLSessionTask) {
|
||||
self.session = session
|
||||
|
||||
switch task {
|
||||
case is NSURLSessionUploadTask:
|
||||
self.delegate = UploadTaskDelegate(task: task)
|
||||
case is NSURLSessionDataTask:
|
||||
self.delegate = DataTaskDelegate(task: task)
|
||||
case is NSURLSessionDownloadTask:
|
||||
self.delegate = DownloadTaskDelegate(task: task)
|
||||
default:
|
||||
self.delegate = TaskDelegate(task: task)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Authentication
|
||||
|
||||
/**
|
||||
Associates an HTTP Basic credential with the request.
|
||||
|
||||
- parameter user: The user.
|
||||
- parameter password: The password.
|
||||
- parameter persistence: The URL credential persistence. `.ForSession` by default.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func authenticate(
|
||||
user user: String,
|
||||
password: String,
|
||||
persistence: NSURLCredentialPersistence = .ForSession)
|
||||
-> Self
|
||||
{
|
||||
let credential = NSURLCredential(user: user, password: password, persistence: persistence)
|
||||
|
||||
return authenticate(usingCredential: credential)
|
||||
}
|
||||
|
||||
/**
|
||||
Associates a specified credential with the request.
|
||||
|
||||
- parameter credential: The credential.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func authenticate(usingCredential credential: NSURLCredential) -> Self {
|
||||
delegate.credential = credential
|
||||
|
||||
return self
|
||||
}
|
||||
|
||||
// MARK: - Progress
|
||||
|
||||
/**
|
||||
Sets a closure to be called periodically during the lifecycle of the request as data is written to or read
|
||||
from the server.
|
||||
|
||||
- For uploads, the progress closure returns the bytes written, total bytes written, and total bytes expected
|
||||
to write.
|
||||
- For downloads and data tasks, the progress closure returns the bytes read, total bytes read, and total bytes
|
||||
expected to read.
|
||||
|
||||
- parameter closure: The code to be executed periodically during the lifecycle of the request.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self {
|
||||
if let uploadDelegate = delegate as? UploadTaskDelegate {
|
||||
uploadDelegate.uploadProgress = closure
|
||||
} else if let dataDelegate = delegate as? DataTaskDelegate {
|
||||
dataDelegate.dataProgress = closure
|
||||
} else if let downloadDelegate = delegate as? DownloadTaskDelegate {
|
||||
downloadDelegate.downloadProgress = closure
|
||||
}
|
||||
|
||||
return self
|
||||
}
|
||||
|
||||
/**
|
||||
Sets a closure to be called periodically during the lifecycle of the request as data is read from the server.
|
||||
|
||||
This closure returns the bytes most recently received from the server, not including data from previous calls.
|
||||
If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is
|
||||
also important to note that the `response` closure will be called with nil `responseData`.
|
||||
|
||||
- parameter closure: The code to be executed periodically during the lifecycle of the request.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func stream(closure: (NSData -> Void)? = nil) -> Self {
|
||||
if let dataDelegate = delegate as? DataTaskDelegate {
|
||||
dataDelegate.dataStream = closure
|
||||
}
|
||||
|
||||
return self
|
||||
}
|
||||
|
||||
// MARK: - State
|
||||
|
||||
/**
|
||||
Suspends the request.
|
||||
*/
|
||||
public func suspend() {
|
||||
task.suspend()
|
||||
}
|
||||
|
||||
/**
|
||||
Resumes the request.
|
||||
*/
|
||||
public func resume() {
|
||||
task.resume()
|
||||
}
|
||||
|
||||
/**
|
||||
Cancels the request.
|
||||
*/
|
||||
public func cancel() {
|
||||
if let
|
||||
downloadDelegate = delegate as? DownloadTaskDelegate,
|
||||
downloadTask = downloadDelegate.downloadTask
|
||||
{
|
||||
downloadTask.cancelByProducingResumeData { data in
|
||||
downloadDelegate.resumeData = data
|
||||
}
|
||||
} else {
|
||||
task.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - TaskDelegate
|
||||
|
||||
/**
|
||||
The task delegate is responsible for handling all delegate callbacks for the underlying task as well as
|
||||
executing all operations attached to the serial operation queue upon task completion.
|
||||
*/
|
||||
public class TaskDelegate: NSObject {
|
||||
|
||||
/// The serial operation queue used to execute all operations after the task completes.
|
||||
public let queue: NSOperationQueue
|
||||
|
||||
let task: NSURLSessionTask
|
||||
let progress: NSProgress
|
||||
|
||||
var data: NSData? { return nil }
|
||||
var error: NSError?
|
||||
|
||||
var credential: NSURLCredential?
|
||||
|
||||
init(task: NSURLSessionTask) {
|
||||
self.task = task
|
||||
self.progress = NSProgress(totalUnitCount: 0)
|
||||
self.queue = {
|
||||
let operationQueue = NSOperationQueue()
|
||||
operationQueue.maxConcurrentOperationCount = 1
|
||||
operationQueue.suspended = true
|
||||
|
||||
if #available(OSX 10.10, *) {
|
||||
operationQueue.qualityOfService = NSQualityOfService.Utility
|
||||
}
|
||||
|
||||
return operationQueue
|
||||
}()
|
||||
}
|
||||
|
||||
deinit {
|
||||
queue.cancelAllOperations()
|
||||
queue.suspended = false
|
||||
}
|
||||
|
||||
// MARK: - NSURLSessionTaskDelegate
|
||||
|
||||
// MARK: Override Closures
|
||||
|
||||
var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)?
|
||||
var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
|
||||
var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)?
|
||||
var taskDidCompleteWithError: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)?
|
||||
|
||||
// MARK: Delegate Methods
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
task: NSURLSessionTask,
|
||||
willPerformHTTPRedirection response: NSHTTPURLResponse,
|
||||
newRequest request: NSURLRequest,
|
||||
completionHandler: ((NSURLRequest?) -> Void))
|
||||
{
|
||||
var redirectRequest: NSURLRequest? = request
|
||||
|
||||
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
|
||||
redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
|
||||
}
|
||||
|
||||
completionHandler(redirectRequest)
|
||||
}
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
task: NSURLSessionTask,
|
||||
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
|
||||
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void))
|
||||
{
|
||||
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
|
||||
var credential: NSURLCredential?
|
||||
|
||||
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
|
||||
(disposition, credential) = taskDidReceiveChallenge(session, task, challenge)
|
||||
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
|
||||
let host = challenge.protectionSpace.host
|
||||
|
||||
if let
|
||||
serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host),
|
||||
serverTrust = challenge.protectionSpace.serverTrust
|
||||
{
|
||||
if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) {
|
||||
disposition = .UseCredential
|
||||
credential = NSURLCredential(forTrust: serverTrust)
|
||||
} else {
|
||||
disposition = .CancelAuthenticationChallenge
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if challenge.previousFailureCount > 0 {
|
||||
disposition = .CancelAuthenticationChallenge
|
||||
} else {
|
||||
credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)
|
||||
|
||||
if credential != nil {
|
||||
disposition = .UseCredential
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
completionHandler(disposition, credential)
|
||||
}
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
task: NSURLSessionTask,
|
||||
needNewBodyStream completionHandler: ((NSInputStream?) -> Void))
|
||||
{
|
||||
var bodyStream: NSInputStream?
|
||||
|
||||
if let taskNeedNewBodyStream = taskNeedNewBodyStream {
|
||||
bodyStream = taskNeedNewBodyStream(session, task)
|
||||
}
|
||||
|
||||
completionHandler(bodyStream)
|
||||
}
|
||||
|
||||
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
|
||||
if let taskDidCompleteWithError = taskDidCompleteWithError {
|
||||
taskDidCompleteWithError(session, task, error)
|
||||
} else {
|
||||
if let error = error {
|
||||
self.error = error
|
||||
|
||||
if let
|
||||
downloadDelegate = self as? DownloadTaskDelegate,
|
||||
userInfo = error.userInfo as? [String: AnyObject],
|
||||
resumeData = userInfo[NSURLSessionDownloadTaskResumeData] as? NSData
|
||||
{
|
||||
downloadDelegate.resumeData = resumeData
|
||||
}
|
||||
}
|
||||
|
||||
queue.suspended = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - DataTaskDelegate
|
||||
|
||||
class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate {
|
||||
var dataTask: NSURLSessionDataTask? { return task as? NSURLSessionDataTask }
|
||||
|
||||
private var totalBytesReceived: Int64 = 0
|
||||
private var mutableData: NSMutableData
|
||||
override var data: NSData? {
|
||||
if dataStream != nil {
|
||||
return nil
|
||||
} else {
|
||||
return mutableData
|
||||
}
|
||||
}
|
||||
|
||||
private var expectedContentLength: Int64?
|
||||
private var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)?
|
||||
private var dataStream: ((data: NSData) -> Void)?
|
||||
|
||||
override init(task: NSURLSessionTask) {
|
||||
mutableData = NSMutableData()
|
||||
super.init(task: task)
|
||||
}
|
||||
|
||||
// MARK: - NSURLSessionDataDelegate
|
||||
|
||||
// MARK: Override Closures
|
||||
|
||||
var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)?
|
||||
var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)?
|
||||
var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)?
|
||||
var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)?
|
||||
|
||||
// MARK: Delegate Methods
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
dataTask: NSURLSessionDataTask,
|
||||
didReceiveResponse response: NSURLResponse,
|
||||
completionHandler: (NSURLSessionResponseDisposition -> Void))
|
||||
{
|
||||
var disposition: NSURLSessionResponseDisposition = .Allow
|
||||
|
||||
expectedContentLength = response.expectedContentLength
|
||||
|
||||
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
|
||||
disposition = dataTaskDidReceiveResponse(session, dataTask, response)
|
||||
}
|
||||
|
||||
completionHandler(disposition)
|
||||
}
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
dataTask: NSURLSessionDataTask,
|
||||
didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask)
|
||||
{
|
||||
dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask)
|
||||
}
|
||||
|
||||
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
|
||||
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
|
||||
dataTaskDidReceiveData(session, dataTask, data)
|
||||
} else {
|
||||
if let dataStream = dataStream {
|
||||
dataStream(data: data)
|
||||
} else {
|
||||
mutableData.appendData(data)
|
||||
}
|
||||
|
||||
totalBytesReceived += data.length
|
||||
let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
|
||||
|
||||
progress.totalUnitCount = totalBytesExpected
|
||||
progress.completedUnitCount = totalBytesReceived
|
||||
|
||||
dataProgress?(
|
||||
bytesReceived: Int64(data.length),
|
||||
totalBytesReceived: totalBytesReceived,
|
||||
totalBytesExpectedToReceive: totalBytesExpected
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
dataTask: NSURLSessionDataTask,
|
||||
willCacheResponse proposedResponse: NSCachedURLResponse,
|
||||
completionHandler: ((NSCachedURLResponse?) -> Void))
|
||||
{
|
||||
var cachedResponse: NSCachedURLResponse? = proposedResponse
|
||||
|
||||
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
|
||||
cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse)
|
||||
}
|
||||
|
||||
completionHandler(cachedResponse)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
extension Request: CustomStringConvertible {
|
||||
|
||||
/**
|
||||
The textual representation used when written to an output stream, which includes the HTTP method and URL, as
|
||||
well as the response status code if a response has been received.
|
||||
*/
|
||||
public var description: String {
|
||||
var components: [String] = []
|
||||
|
||||
if let HTTPMethod = request?.HTTPMethod {
|
||||
components.append(HTTPMethod)
|
||||
}
|
||||
|
||||
if let URLString = request?.URL?.absoluteString {
|
||||
components.append(URLString)
|
||||
}
|
||||
|
||||
if let response = response {
|
||||
components.append("(\(response.statusCode))")
|
||||
}
|
||||
|
||||
return components.joinWithSeparator(" ")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomDebugStringConvertible
|
||||
|
||||
extension Request: CustomDebugStringConvertible {
|
||||
func cURLRepresentation() -> String {
|
||||
var components = ["$ curl -i"]
|
||||
|
||||
guard let
|
||||
request = self.request,
|
||||
URL = request.URL,
|
||||
host = URL.host
|
||||
else {
|
||||
return "$ curl command could not be created"
|
||||
}
|
||||
|
||||
if let HTTPMethod = request.HTTPMethod where HTTPMethod != "GET" {
|
||||
components.append("-X \(HTTPMethod)")
|
||||
}
|
||||
|
||||
if let credentialStorage = self.session.configuration.URLCredentialStorage {
|
||||
let protectionSpace = NSURLProtectionSpace(
|
||||
host: host,
|
||||
port: URL.port?.integerValue ?? 0,
|
||||
`protocol`: URL.scheme,
|
||||
realm: host,
|
||||
authenticationMethod: NSURLAuthenticationMethodHTTPBasic
|
||||
)
|
||||
|
||||
if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values {
|
||||
for credential in credentials {
|
||||
components.append("-u \(credential.user!):\(credential.password!)")
|
||||
}
|
||||
} else {
|
||||
if let credential = delegate.credential {
|
||||
components.append("-u \(credential.user!):\(credential.password!)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if session.configuration.HTTPShouldSetCookies {
|
||||
if let
|
||||
cookieStorage = session.configuration.HTTPCookieStorage,
|
||||
cookies = cookieStorage.cookiesForURL(URL) where !cookies.isEmpty
|
||||
{
|
||||
let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value ?? String());" }
|
||||
components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"")
|
||||
}
|
||||
}
|
||||
|
||||
if let headerFields = request.allHTTPHeaderFields {
|
||||
for (field, value) in headerFields {
|
||||
switch field {
|
||||
case "Cookie":
|
||||
continue
|
||||
default:
|
||||
components.append("-H \"\(field): \(value)\"")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let additionalHeaders = session.configuration.HTTPAdditionalHeaders {
|
||||
for (field, value) in additionalHeaders {
|
||||
switch field {
|
||||
case "Cookie":
|
||||
continue
|
||||
default:
|
||||
components.append("-H \"\(field): \(value)\"")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let
|
||||
HTTPBodyData = request.HTTPBody,
|
||||
HTTPBody = String(data: HTTPBodyData, encoding: NSUTF8StringEncoding)
|
||||
{
|
||||
let escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
|
||||
components.append("-d \"\(escapedBody)\"")
|
||||
}
|
||||
|
||||
components.append("\"\(URL.absoluteString)\"")
|
||||
|
||||
return components.joinWithSeparator(" \\\n\t")
|
||||
}
|
||||
|
||||
/// The textual representation used when written to an output stream, in the form of a cURL command.
|
||||
public var debugDescription: String {
|
||||
return cURLRepresentation()
|
||||
}
|
||||
}
|
83
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Response.swift
generated
Normal file
83
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Response.swift
generated
Normal file
@ -0,0 +1,83 @@
|
||||
// Response.swift
|
||||
//
|
||||
// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Used to store all response data returned from a completed `Request`.
|
||||
public struct Response<Value, Error: ErrorType> {
|
||||
/// The URL request sent to the server.
|
||||
public let request: NSURLRequest?
|
||||
|
||||
/// The server's response to the URL request.
|
||||
public let response: NSHTTPURLResponse?
|
||||
|
||||
/// The data returned by the server.
|
||||
public let data: NSData?
|
||||
|
||||
/// The result of response serialization.
|
||||
public let result: Result<Value, Error>
|
||||
|
||||
/**
|
||||
Initializes the `Response` instance with the specified URL request, URL response, server data and response
|
||||
serialization result.
|
||||
|
||||
- parameter request: The URL request sent to the server.
|
||||
- parameter response: The server's response to the URL request.
|
||||
- parameter data: The data returned by the server.
|
||||
- parameter result: The result of response serialization.
|
||||
|
||||
- returns: the new `Response` instance.
|
||||
*/
|
||||
public init(request: NSURLRequest?, response: NSHTTPURLResponse?, data: NSData?, result: Result<Value, Error>) {
|
||||
self.request = request
|
||||
self.response = response
|
||||
self.data = data
|
||||
self.result = result
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
extension Response: CustomStringConvertible {
|
||||
/// The textual representation used when written to an output stream, which includes whether the result was a
|
||||
/// success or failure.
|
||||
public var description: String {
|
||||
return result.debugDescription
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomDebugStringConvertible
|
||||
|
||||
extension Response: CustomDebugStringConvertible {
|
||||
/// The debug textual representation used when written to an output stream, which includes the URL request, the URL
|
||||
/// response, the server data and the response serialization result.
|
||||
public var debugDescription: String {
|
||||
var output: [String] = []
|
||||
|
||||
output.append(request != nil ? "[Request]: \(request!)" : "[Request]: nil")
|
||||
output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil")
|
||||
output.append("[Data]: \(data?.length ?? 0) bytes")
|
||||
output.append("[Result]: \(result.debugDescription)")
|
||||
|
||||
return output.joinWithSeparator("\n")
|
||||
}
|
||||
}
|
355
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift
generated
Normal file
355
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift
generated
Normal file
@ -0,0 +1,355 @@
|
||||
// ResponseSerialization.swift
|
||||
//
|
||||
// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
// MARK: ResponseSerializer
|
||||
|
||||
/**
|
||||
The type in which all response serializers must conform to in order to serialize a response.
|
||||
*/
|
||||
public protocol ResponseSerializerType {
|
||||
/// The type of serialized object to be created by this `ResponseSerializerType`.
|
||||
typealias SerializedObject
|
||||
|
||||
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
|
||||
typealias ErrorObject: ErrorType
|
||||
|
||||
/**
|
||||
A closure used by response handlers that takes a request, response, data and error and returns a result.
|
||||
*/
|
||||
var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<SerializedObject, ErrorObject> { get }
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
/**
|
||||
A generic `ResponseSerializerType` used to serialize a request, response, and data into a serialized object.
|
||||
*/
|
||||
public struct ResponseSerializer<Value, Error: ErrorType>: ResponseSerializerType {
|
||||
/// The type of serialized object to be created by this `ResponseSerializer`.
|
||||
public typealias SerializedObject = Value
|
||||
|
||||
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
|
||||
public typealias ErrorObject = Error
|
||||
|
||||
/**
|
||||
A closure used by response handlers that takes a request, response, data and error and returns a result.
|
||||
*/
|
||||
public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>
|
||||
|
||||
/**
|
||||
Initializes the `ResponseSerializer` instance with the given serialize response closure.
|
||||
|
||||
- parameter serializeResponse: The closure used to serialize the response.
|
||||
|
||||
- returns: The new generic response serializer instance.
|
||||
*/
|
||||
public init(serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>) {
|
||||
self.serializeResponse = serializeResponse
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Default
|
||||
|
||||
extension Request {
|
||||
|
||||
/**
|
||||
Adds a handler to be called once the request has finished.
|
||||
|
||||
- parameter queue: The queue on which the completion handler is dispatched.
|
||||
- parameter completionHandler: The code to be executed once the request has finished.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func response(
|
||||
queue queue: dispatch_queue_t? = nil,
|
||||
completionHandler: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Void)
|
||||
-> Self
|
||||
{
|
||||
delegate.queue.addOperationWithBlock {
|
||||
dispatch_async(queue ?? dispatch_get_main_queue()) {
|
||||
completionHandler(self.request, self.response, self.delegate.data, self.delegate.error)
|
||||
}
|
||||
}
|
||||
|
||||
return self
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler to be called once the request has finished.
|
||||
|
||||
- parameter queue: The queue on which the completion handler is dispatched.
|
||||
- parameter responseSerializer: The response serializer responsible for serializing the request, response,
|
||||
and data.
|
||||
- parameter completionHandler: The code to be executed once the request has finished.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func response<T: ResponseSerializerType>(
|
||||
queue queue: dispatch_queue_t? = nil,
|
||||
responseSerializer: T,
|
||||
completionHandler: Response<T.SerializedObject, T.ErrorObject> -> Void)
|
||||
-> Self
|
||||
{
|
||||
delegate.queue.addOperationWithBlock {
|
||||
let result = responseSerializer.serializeResponse(
|
||||
self.request,
|
||||
self.response,
|
||||
self.delegate.data,
|
||||
self.delegate.error
|
||||
)
|
||||
|
||||
dispatch_async(queue ?? dispatch_get_main_queue()) {
|
||||
let response = Response<T.SerializedObject, T.ErrorObject>(
|
||||
request: self.request,
|
||||
response: self.response,
|
||||
data: self.delegate.data,
|
||||
result: result
|
||||
)
|
||||
|
||||
completionHandler(response)
|
||||
}
|
||||
}
|
||||
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Data
|
||||
|
||||
extension Request {
|
||||
|
||||
/**
|
||||
Creates a response serializer that returns the associated data as-is.
|
||||
|
||||
- returns: A data response serializer.
|
||||
*/
|
||||
public static func dataResponseSerializer() -> ResponseSerializer<NSData, NSError> {
|
||||
return ResponseSerializer { _, response, data, error in
|
||||
guard error == nil else { return .Failure(error!) }
|
||||
|
||||
if let response = response where response.statusCode == 204 { return .Success(NSData()) }
|
||||
|
||||
guard let validData = data else {
|
||||
let failureReason = "Data could not be serialized. Input data was nil."
|
||||
let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
|
||||
return .Failure(error)
|
||||
}
|
||||
|
||||
return .Success(validData)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler to be called once the request has finished.
|
||||
|
||||
- parameter completionHandler: The code to be executed once the request has finished.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func responseData(completionHandler: Response<NSData, NSError> -> Void) -> Self {
|
||||
return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - String
|
||||
|
||||
extension Request {
|
||||
|
||||
/**
|
||||
Creates a response serializer that returns a string initialized from the response data with the specified
|
||||
string encoding.
|
||||
|
||||
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
|
||||
response, falling back to the default HTTP default character set, ISO-8859-1.
|
||||
|
||||
- returns: A string response serializer.
|
||||
*/
|
||||
public static func stringResponseSerializer(
|
||||
var encoding encoding: NSStringEncoding? = nil)
|
||||
-> ResponseSerializer<String, NSError>
|
||||
{
|
||||
return ResponseSerializer { _, response, data, error in
|
||||
guard error == nil else { return .Failure(error!) }
|
||||
|
||||
if let response = response where response.statusCode == 204 { return .Success("") }
|
||||
|
||||
guard let validData = data else {
|
||||
let failureReason = "String could not be serialized. Input data was nil."
|
||||
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
|
||||
return .Failure(error)
|
||||
}
|
||||
|
||||
if let encodingName = response?.textEncodingName where encoding == nil {
|
||||
encoding = CFStringConvertEncodingToNSStringEncoding(
|
||||
CFStringConvertIANACharSetNameToEncoding(encodingName)
|
||||
)
|
||||
}
|
||||
|
||||
let actualEncoding = encoding ?? NSISOLatin1StringEncoding
|
||||
|
||||
if let string = String(data: validData, encoding: actualEncoding) {
|
||||
return .Success(string)
|
||||
} else {
|
||||
let failureReason = "String could not be serialized with encoding: \(actualEncoding)"
|
||||
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
|
||||
return .Failure(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler to be called once the request has finished.
|
||||
|
||||
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
|
||||
server response, falling back to the default HTTP default character set,
|
||||
ISO-8859-1.
|
||||
- parameter completionHandler: A closure to be executed once the request has finished.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func responseString(
|
||||
encoding encoding: NSStringEncoding? = nil,
|
||||
completionHandler: Response<String, NSError> -> Void)
|
||||
-> Self
|
||||
{
|
||||
return response(
|
||||
responseSerializer: Request.stringResponseSerializer(encoding: encoding),
|
||||
completionHandler: completionHandler
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - JSON
|
||||
|
||||
extension Request {
|
||||
|
||||
/**
|
||||
Creates a response serializer that returns a JSON object constructed from the response data using
|
||||
`NSJSONSerialization` with the specified reading options.
|
||||
|
||||
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
|
||||
|
||||
- returns: A JSON object response serializer.
|
||||
*/
|
||||
public static func JSONResponseSerializer(
|
||||
options options: NSJSONReadingOptions = .AllowFragments)
|
||||
-> ResponseSerializer<AnyObject, NSError>
|
||||
{
|
||||
return ResponseSerializer { _, response, data, error in
|
||||
guard error == nil else { return .Failure(error!) }
|
||||
|
||||
if let response = response where response.statusCode == 204 { return .Success(NSNull()) }
|
||||
|
||||
guard let validData = data where validData.length > 0 else {
|
||||
let failureReason = "JSON could not be serialized. Input data was nil or zero length."
|
||||
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
|
||||
return .Failure(error)
|
||||
}
|
||||
|
||||
do {
|
||||
let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: options)
|
||||
return .Success(JSON)
|
||||
} catch {
|
||||
return .Failure(error as NSError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler to be called once the request has finished.
|
||||
|
||||
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
|
||||
- parameter completionHandler: A closure to be executed once the request has finished.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func responseJSON(
|
||||
options options: NSJSONReadingOptions = .AllowFragments,
|
||||
completionHandler: Response<AnyObject, NSError> -> Void)
|
||||
-> Self
|
||||
{
|
||||
return response(
|
||||
responseSerializer: Request.JSONResponseSerializer(options: options),
|
||||
completionHandler: completionHandler
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Property List
|
||||
|
||||
extension Request {
|
||||
|
||||
/**
|
||||
Creates a response serializer that returns an object constructed from the response data using
|
||||
`NSPropertyListSerialization` with the specified reading options.
|
||||
|
||||
- parameter options: The property list reading options. `NSPropertyListReadOptions()` by default.
|
||||
|
||||
- returns: A property list object response serializer.
|
||||
*/
|
||||
public static func propertyListResponseSerializer(
|
||||
options options: NSPropertyListReadOptions = NSPropertyListReadOptions())
|
||||
-> ResponseSerializer<AnyObject, NSError>
|
||||
{
|
||||
return ResponseSerializer { _, response, data, error in
|
||||
guard error == nil else { return .Failure(error!) }
|
||||
|
||||
if let response = response where response.statusCode == 204 { return .Success(NSNull()) }
|
||||
|
||||
guard let validData = data where validData.length > 0 else {
|
||||
let failureReason = "Property list could not be serialized. Input data was nil or zero length."
|
||||
let error = Error.errorWithCode(.PropertyListSerializationFailed, failureReason: failureReason)
|
||||
return .Failure(error)
|
||||
}
|
||||
|
||||
do {
|
||||
let plist = try NSPropertyListSerialization.propertyListWithData(validData, options: options, format: nil)
|
||||
return .Success(plist)
|
||||
} catch {
|
||||
return .Failure(error as NSError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler to be called once the request has finished.
|
||||
|
||||
- parameter options: The property list reading options. `0` by default.
|
||||
- parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3
|
||||
arguments: the URL request, the URL response, the server data and the result
|
||||
produced while creating the property list.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func responsePropertyList(
|
||||
options options: NSPropertyListReadOptions = NSPropertyListReadOptions(),
|
||||
completionHandler: Response<AnyObject, NSError> -> Void)
|
||||
-> Self
|
||||
{
|
||||
return response(
|
||||
responseSerializer: Request.propertyListResponseSerializer(options: options),
|
||||
completionHandler: completionHandler
|
||||
)
|
||||
}
|
||||
}
|
101
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Result.swift
generated
Normal file
101
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Result.swift
generated
Normal file
@ -0,0 +1,101 @@
|
||||
// Result.swift
|
||||
//
|
||||
// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Used to represent whether a request was successful or encountered an error.
|
||||
|
||||
- Success: The request and all post processing operations were successful resulting in the serialization of the
|
||||
provided associated value.
|
||||
- Failure: The request encountered an error resulting in a failure. The associated values are the original data
|
||||
provided by the server as well as the error that caused the failure.
|
||||
*/
|
||||
public enum Result<Value, Error: ErrorType> {
|
||||
case Success(Value)
|
||||
case Failure(Error)
|
||||
|
||||
/// Returns `true` if the result is a success, `false` otherwise.
|
||||
public var isSuccess: Bool {
|
||||
switch self {
|
||||
case .Success:
|
||||
return true
|
||||
case .Failure:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `true` if the result is a failure, `false` otherwise.
|
||||
public var isFailure: Bool {
|
||||
return !isSuccess
|
||||
}
|
||||
|
||||
/// Returns the associated value if the result is a success, `nil` otherwise.
|
||||
public var value: Value? {
|
||||
switch self {
|
||||
case .Success(let value):
|
||||
return value
|
||||
case .Failure:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the associated error value if the result is a failure, `nil` otherwise.
|
||||
public var error: Error? {
|
||||
switch self {
|
||||
case .Success:
|
||||
return nil
|
||||
case .Failure(let error):
|
||||
return error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
extension Result: CustomStringConvertible {
|
||||
/// The textual representation used when written to an output stream, which includes whether the result was a
|
||||
/// success or failure.
|
||||
public var description: String {
|
||||
switch self {
|
||||
case .Success:
|
||||
return "SUCCESS"
|
||||
case .Failure:
|
||||
return "FAILURE"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomDebugStringConvertible
|
||||
|
||||
extension Result: CustomDebugStringConvertible {
|
||||
/// The debug textual representation used when written to an output stream, which includes whether the result was a
|
||||
/// success or failure in addition to the value or error.
|
||||
public var debugDescription: String {
|
||||
switch self {
|
||||
case .Success(let value):
|
||||
return "SUCCESS: \(value)"
|
||||
case .Failure(let error):
|
||||
return "FAILURE: \(error)"
|
||||
}
|
||||
}
|
||||
}
|
302
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift
generated
Normal file
302
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift
generated
Normal file
@ -0,0 +1,302 @@
|
||||
// ServerTrustPolicy.swift
|
||||
//
|
||||
// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host.
|
||||
public class ServerTrustPolicyManager {
|
||||
/// The dictionary of policies mapped to a particular host.
|
||||
public let policies: [String: ServerTrustPolicy]
|
||||
|
||||
/**
|
||||
Initializes the `ServerTrustPolicyManager` instance with the given policies.
|
||||
|
||||
Since different servers and web services can have different leaf certificates, intermediate and even root
|
||||
certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This
|
||||
allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key
|
||||
pinning for host3 and disabling evaluation for host4.
|
||||
|
||||
- parameter policies: A dictionary of all policies mapped to a particular host.
|
||||
|
||||
- returns: The new `ServerTrustPolicyManager` instance.
|
||||
*/
|
||||
public init(policies: [String: ServerTrustPolicy]) {
|
||||
self.policies = policies
|
||||
}
|
||||
|
||||
/**
|
||||
Returns the `ServerTrustPolicy` for the given host if applicable.
|
||||
|
||||
By default, this method will return the policy that perfectly matches the given host. Subclasses could override
|
||||
this method and implement more complex mapping implementations such as wildcards.
|
||||
|
||||
- parameter host: The host to use when searching for a matching policy.
|
||||
|
||||
- returns: The server trust policy for the given host if found.
|
||||
*/
|
||||
public func serverTrustPolicyForHost(host: String) -> ServerTrustPolicy? {
|
||||
return policies[host]
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
extension NSURLSession {
|
||||
private struct AssociatedKeys {
|
||||
static var ManagerKey = "NSURLSession.ServerTrustPolicyManager"
|
||||
}
|
||||
|
||||
var serverTrustPolicyManager: ServerTrustPolicyManager? {
|
||||
get {
|
||||
return objc_getAssociatedObject(self, &AssociatedKeys.ManagerKey) as? ServerTrustPolicyManager
|
||||
}
|
||||
set (manager) {
|
||||
objc_setAssociatedObject(self, &AssociatedKeys.ManagerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ServerTrustPolicy
|
||||
|
||||
/**
|
||||
The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when
|
||||
connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust
|
||||
with a given set of criteria to determine whether the server trust is valid and the connection should be made.
|
||||
|
||||
Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other
|
||||
vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged
|
||||
to route all communication over an HTTPS connection with pinning enabled.
|
||||
|
||||
- PerformDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to
|
||||
validate the host provided by the challenge. Applications are encouraged to always
|
||||
validate the host in production environments to guarantee the validity of the server's
|
||||
certificate chain.
|
||||
|
||||
- PinCertificates: Uses the pinned certificates to validate the server trust. The server trust is
|
||||
considered valid if one of the pinned certificates match one of the server certificates.
|
||||
By validating both the certificate chain and host, certificate pinning provides a very
|
||||
secure form of server trust validation mitigating most, if not all, MITM attacks.
|
||||
Applications are encouraged to always validate the host and require a valid certificate
|
||||
chain in production environments.
|
||||
|
||||
- PinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered
|
||||
valid if one of the pinned public keys match one of the server certificate public keys.
|
||||
By validating both the certificate chain and host, public key pinning provides a very
|
||||
secure form of server trust validation mitigating most, if not all, MITM attacks.
|
||||
Applications are encouraged to always validate the host and require a valid certificate
|
||||
chain in production environments.
|
||||
|
||||
- DisableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid.
|
||||
|
||||
- CustomEvaluation: Uses the associated closure to evaluate the validity of the server trust.
|
||||
*/
|
||||
public enum ServerTrustPolicy {
|
||||
case PerformDefaultEvaluation(validateHost: Bool)
|
||||
case PinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool)
|
||||
case PinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool)
|
||||
case DisableEvaluation
|
||||
case CustomEvaluation((serverTrust: SecTrust, host: String) -> Bool)
|
||||
|
||||
// MARK: - Bundle Location
|
||||
|
||||
/**
|
||||
Returns all certificates within the given bundle with a `.cer` file extension.
|
||||
|
||||
- parameter bundle: The bundle to search for all `.cer` files.
|
||||
|
||||
- returns: All certificates within the given bundle.
|
||||
*/
|
||||
public static func certificatesInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecCertificate] {
|
||||
var certificates: [SecCertificate] = []
|
||||
|
||||
let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in
|
||||
bundle.pathsForResourcesOfType(fileExtension, inDirectory: nil)
|
||||
}.flatten())
|
||||
|
||||
for path in paths {
|
||||
if let
|
||||
certificateData = NSData(contentsOfFile: path),
|
||||
certificate = SecCertificateCreateWithData(nil, certificateData)
|
||||
{
|
||||
certificates.append(certificate)
|
||||
}
|
||||
}
|
||||
|
||||
return certificates
|
||||
}
|
||||
|
||||
/**
|
||||
Returns all public keys within the given bundle with a `.cer` file extension.
|
||||
|
||||
- parameter bundle: The bundle to search for all `*.cer` files.
|
||||
|
||||
- returns: All public keys within the given bundle.
|
||||
*/
|
||||
public static func publicKeysInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecKey] {
|
||||
var publicKeys: [SecKey] = []
|
||||
|
||||
for certificate in certificatesInBundle(bundle) {
|
||||
if let publicKey = publicKeyForCertificate(certificate) {
|
||||
publicKeys.append(publicKey)
|
||||
}
|
||||
}
|
||||
|
||||
return publicKeys
|
||||
}
|
||||
|
||||
// MARK: - Evaluation
|
||||
|
||||
/**
|
||||
Evaluates whether the server trust is valid for the given host.
|
||||
|
||||
- parameter serverTrust: The server trust to evaluate.
|
||||
- parameter host: The host of the challenge protection space.
|
||||
|
||||
- returns: Whether the server trust is valid.
|
||||
*/
|
||||
public func evaluateServerTrust(serverTrust: SecTrust, isValidForHost host: String) -> Bool {
|
||||
var serverTrustIsValid = false
|
||||
|
||||
switch self {
|
||||
case let .PerformDefaultEvaluation(validateHost):
|
||||
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
|
||||
SecTrustSetPolicies(serverTrust, [policy])
|
||||
|
||||
serverTrustIsValid = trustIsValid(serverTrust)
|
||||
case let .PinCertificates(pinnedCertificates, validateCertificateChain, validateHost):
|
||||
if validateCertificateChain {
|
||||
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
|
||||
SecTrustSetPolicies(serverTrust, [policy])
|
||||
|
||||
SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates)
|
||||
SecTrustSetAnchorCertificatesOnly(serverTrust, true)
|
||||
|
||||
serverTrustIsValid = trustIsValid(serverTrust)
|
||||
} else {
|
||||
let serverCertificatesDataArray = certificateDataForTrust(serverTrust)
|
||||
let pinnedCertificatesDataArray = certificateDataForCertificates(pinnedCertificates)
|
||||
|
||||
outerLoop: for serverCertificateData in serverCertificatesDataArray {
|
||||
for pinnedCertificateData in pinnedCertificatesDataArray {
|
||||
if serverCertificateData.isEqualToData(pinnedCertificateData) {
|
||||
serverTrustIsValid = true
|
||||
break outerLoop
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
case let .PinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost):
|
||||
var certificateChainEvaluationPassed = true
|
||||
|
||||
if validateCertificateChain {
|
||||
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
|
||||
SecTrustSetPolicies(serverTrust, [policy])
|
||||
|
||||
certificateChainEvaluationPassed = trustIsValid(serverTrust)
|
||||
}
|
||||
|
||||
if certificateChainEvaluationPassed {
|
||||
outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeysForTrust(serverTrust) as [AnyObject] {
|
||||
for pinnedPublicKey in pinnedPublicKeys as [AnyObject] {
|
||||
if serverPublicKey.isEqual(pinnedPublicKey) {
|
||||
serverTrustIsValid = true
|
||||
break outerLoop
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
case .DisableEvaluation:
|
||||
serverTrustIsValid = true
|
||||
case let .CustomEvaluation(closure):
|
||||
serverTrustIsValid = closure(serverTrust: serverTrust, host: host)
|
||||
}
|
||||
|
||||
return serverTrustIsValid
|
||||
}
|
||||
|
||||
// MARK: - Private - Trust Validation
|
||||
|
||||
private func trustIsValid(trust: SecTrust) -> Bool {
|
||||
var isValid = false
|
||||
|
||||
var result = SecTrustResultType(kSecTrustResultInvalid)
|
||||
let status = SecTrustEvaluate(trust, &result)
|
||||
|
||||
if status == errSecSuccess {
|
||||
let unspecified = SecTrustResultType(kSecTrustResultUnspecified)
|
||||
let proceed = SecTrustResultType(kSecTrustResultProceed)
|
||||
|
||||
isValid = result == unspecified || result == proceed
|
||||
}
|
||||
|
||||
return isValid
|
||||
}
|
||||
|
||||
// MARK: - Private - Certificate Data
|
||||
|
||||
private func certificateDataForTrust(trust: SecTrust) -> [NSData] {
|
||||
var certificates: [SecCertificate] = []
|
||||
|
||||
for index in 0..<SecTrustGetCertificateCount(trust) {
|
||||
if let certificate = SecTrustGetCertificateAtIndex(trust, index) {
|
||||
certificates.append(certificate)
|
||||
}
|
||||
}
|
||||
|
||||
return certificateDataForCertificates(certificates)
|
||||
}
|
||||
|
||||
private func certificateDataForCertificates(certificates: [SecCertificate]) -> [NSData] {
|
||||
return certificates.map { SecCertificateCopyData($0) as NSData }
|
||||
}
|
||||
|
||||
// MARK: - Private - Public Key Extraction
|
||||
|
||||
private static func publicKeysForTrust(trust: SecTrust) -> [SecKey] {
|
||||
var publicKeys: [SecKey] = []
|
||||
|
||||
for index in 0..<SecTrustGetCertificateCount(trust) {
|
||||
if let
|
||||
certificate = SecTrustGetCertificateAtIndex(trust, index),
|
||||
publicKey = publicKeyForCertificate(certificate)
|
||||
{
|
||||
publicKeys.append(publicKey)
|
||||
}
|
||||
}
|
||||
|
||||
return publicKeys
|
||||
}
|
||||
|
||||
private static func publicKeyForCertificate(certificate: SecCertificate) -> SecKey? {
|
||||
var publicKey: SecKey?
|
||||
|
||||
let policy = SecPolicyCreateBasicX509()
|
||||
var trust: SecTrust?
|
||||
let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust)
|
||||
|
||||
if let trust = trust where trustCreationStatus == errSecSuccess {
|
||||
publicKey = SecTrustCopyPublicKey(trust)
|
||||
}
|
||||
|
||||
return publicKey
|
||||
}
|
||||
}
|
180
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift
generated
Normal file
180
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift
generated
Normal file
@ -0,0 +1,180 @@
|
||||
// Stream.swift
|
||||
//
|
||||
// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
#if !os(watchOS)
|
||||
|
||||
@available(iOS 9.0, OSX 10.11, *)
|
||||
extension Manager {
|
||||
private enum Streamable {
|
||||
case Stream(String, Int)
|
||||
case NetService(NSNetService)
|
||||
}
|
||||
|
||||
private func stream(streamable: Streamable) -> Request {
|
||||
var streamTask: NSURLSessionStreamTask!
|
||||
|
||||
switch streamable {
|
||||
case .Stream(let hostName, let port):
|
||||
dispatch_sync(queue) {
|
||||
streamTask = self.session.streamTaskWithHostName(hostName, port: port)
|
||||
}
|
||||
case .NetService(let netService):
|
||||
dispatch_sync(queue) {
|
||||
streamTask = self.session.streamTaskWithNetService(netService)
|
||||
}
|
||||
}
|
||||
|
||||
let request = Request(session: session, task: streamTask)
|
||||
|
||||
delegate[request.delegate.task] = request.delegate
|
||||
|
||||
if startRequestsImmediately {
|
||||
request.resume()
|
||||
}
|
||||
|
||||
return request
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a request for bidirectional streaming with the given hostname and port.
|
||||
|
||||
- parameter hostName: The hostname of the server to connect to.
|
||||
- parameter port: The port of the server to connect to.
|
||||
|
||||
:returns: The created stream request.
|
||||
*/
|
||||
public func stream(hostName hostName: String, port: Int) -> Request {
|
||||
return stream(.Stream(hostName, port))
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a request for bidirectional streaming with the given `NSNetService`.
|
||||
|
||||
- parameter netService: The net service used to identify the endpoint.
|
||||
|
||||
- returns: The created stream request.
|
||||
*/
|
||||
public func stream(netService netService: NSNetService) -> Request {
|
||||
return stream(.NetService(netService))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
@available(iOS 9.0, OSX 10.11, *)
|
||||
extension Manager.SessionDelegate: NSURLSessionStreamDelegate {
|
||||
|
||||
// MARK: Override Closures
|
||||
|
||||
/// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:readClosedForStreamTask:`.
|
||||
public var streamTaskReadClosed: ((NSURLSession, NSURLSessionStreamTask) -> Void)? {
|
||||
get {
|
||||
return _streamTaskReadClosed as? (NSURLSession, NSURLSessionStreamTask) -> Void
|
||||
}
|
||||
set {
|
||||
_streamTaskReadClosed = newValue
|
||||
}
|
||||
}
|
||||
|
||||
/// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:writeClosedForStreamTask:`.
|
||||
public var streamTaskWriteClosed: ((NSURLSession, NSURLSessionStreamTask) -> Void)? {
|
||||
get {
|
||||
return _streamTaskWriteClosed as? (NSURLSession, NSURLSessionStreamTask) -> Void
|
||||
}
|
||||
set {
|
||||
_streamTaskWriteClosed = newValue
|
||||
}
|
||||
}
|
||||
|
||||
/// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:betterRouteDiscoveredForStreamTask:`.
|
||||
public var streamTaskBetterRouteDiscovered: ((NSURLSession, NSURLSessionStreamTask) -> Void)? {
|
||||
get {
|
||||
return _streamTaskBetterRouteDiscovered as? (NSURLSession, NSURLSessionStreamTask) -> Void
|
||||
}
|
||||
set {
|
||||
_streamTaskBetterRouteDiscovered = newValue
|
||||
}
|
||||
}
|
||||
|
||||
/// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:streamTask:didBecomeInputStream:outputStream:`.
|
||||
public var streamTaskDidBecomeInputStream: ((NSURLSession, NSURLSessionStreamTask, NSInputStream, NSOutputStream) -> Void)? {
|
||||
get {
|
||||
return _streamTaskDidBecomeInputStream as? (NSURLSession, NSURLSessionStreamTask, NSInputStream, NSOutputStream) -> Void
|
||||
}
|
||||
set {
|
||||
_streamTaskDidBecomeInputStream = newValue
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Delegate Methods
|
||||
|
||||
/**
|
||||
Tells the delegate that the read side of the connection has been closed.
|
||||
|
||||
- parameter session: The session.
|
||||
- parameter streamTask: The stream task.
|
||||
*/
|
||||
public func URLSession(session: NSURLSession, readClosedForStreamTask streamTask: NSURLSessionStreamTask) {
|
||||
streamTaskReadClosed?(session, streamTask)
|
||||
}
|
||||
|
||||
/**
|
||||
Tells the delegate that the write side of the connection has been closed.
|
||||
|
||||
- parameter session: The session.
|
||||
- parameter streamTask: The stream task.
|
||||
*/
|
||||
public func URLSession(session: NSURLSession, writeClosedForStreamTask streamTask: NSURLSessionStreamTask) {
|
||||
streamTaskWriteClosed?(session, streamTask)
|
||||
}
|
||||
|
||||
/**
|
||||
Tells the delegate that the system has determined that a better route to the host is available.
|
||||
|
||||
- parameter session: The session.
|
||||
- parameter streamTask: The stream task.
|
||||
*/
|
||||
public func URLSession(session: NSURLSession, betterRouteDiscoveredForStreamTask streamTask: NSURLSessionStreamTask) {
|
||||
streamTaskBetterRouteDiscovered?(session, streamTask)
|
||||
}
|
||||
|
||||
/**
|
||||
Tells the delegate that the stream task has been completed and provides the unopened stream objects.
|
||||
|
||||
- parameter session: The session.
|
||||
- parameter streamTask: The stream task.
|
||||
- parameter inputStream: The new input stream.
|
||||
- parameter outputStream: The new output stream.
|
||||
*/
|
||||
public func URLSession(
|
||||
session: NSURLSession,
|
||||
streamTask: NSURLSessionStreamTask,
|
||||
didBecomeInputStream inputStream: NSInputStream,
|
||||
outputStream: NSOutputStream)
|
||||
{
|
||||
streamTaskDidBecomeInputStream?(session, streamTask, inputStream, outputStream)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
372
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift
generated
Normal file
372
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift
generated
Normal file
@ -0,0 +1,372 @@
|
||||
// Upload.swift
|
||||
//
|
||||
// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
extension Manager {
|
||||
private enum Uploadable {
|
||||
case Data(NSURLRequest, NSData)
|
||||
case File(NSURLRequest, NSURL)
|
||||
case Stream(NSURLRequest, NSInputStream)
|
||||
}
|
||||
|
||||
private func upload(uploadable: Uploadable) -> Request {
|
||||
var uploadTask: NSURLSessionUploadTask!
|
||||
var HTTPBodyStream: NSInputStream?
|
||||
|
||||
switch uploadable {
|
||||
case .Data(let request, let data):
|
||||
dispatch_sync(queue) {
|
||||
uploadTask = self.session.uploadTaskWithRequest(request, fromData: data)
|
||||
}
|
||||
case .File(let request, let fileURL):
|
||||
dispatch_sync(queue) {
|
||||
uploadTask = self.session.uploadTaskWithRequest(request, fromFile: fileURL)
|
||||
}
|
||||
case .Stream(let request, let stream):
|
||||
dispatch_sync(queue) {
|
||||
uploadTask = self.session.uploadTaskWithStreamedRequest(request)
|
||||
}
|
||||
|
||||
HTTPBodyStream = stream
|
||||
}
|
||||
|
||||
let request = Request(session: session, task: uploadTask)
|
||||
|
||||
if HTTPBodyStream != nil {
|
||||
request.delegate.taskNeedNewBodyStream = { _, _ in
|
||||
return HTTPBodyStream
|
||||
}
|
||||
}
|
||||
|
||||
delegate[request.delegate.task] = request.delegate
|
||||
|
||||
if startRequestsImmediately {
|
||||
request.resume()
|
||||
}
|
||||
|
||||
return request
|
||||
}
|
||||
|
||||
// MARK: File
|
||||
|
||||
/**
|
||||
Creates a request for uploading a file to the specified URL request.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter URLRequest: The URL request
|
||||
- parameter file: The file to upload
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request {
|
||||
return upload(.File(URLRequest.URLRequest, file))
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a request for uploading a file to the specified URL request.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter file: The file to upload
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
headers: [String: String]? = nil,
|
||||
file: NSURL)
|
||||
-> Request
|
||||
{
|
||||
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
|
||||
return upload(mutableURLRequest, file: file)
|
||||
}
|
||||
|
||||
// MARK: Data
|
||||
|
||||
/**
|
||||
Creates a request for uploading data to the specified URL request.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter URLRequest: The URL request.
|
||||
- parameter data: The data to upload.
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request {
|
||||
return upload(.Data(URLRequest.URLRequest, data))
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a request for uploading data to the specified URL request.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter data: The data to upload
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
headers: [String: String]? = nil,
|
||||
data: NSData)
|
||||
-> Request
|
||||
{
|
||||
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
|
||||
|
||||
return upload(mutableURLRequest, data: data)
|
||||
}
|
||||
|
||||
// MARK: Stream
|
||||
|
||||
/**
|
||||
Creates a request for uploading a stream to the specified URL request.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter URLRequest: The URL request.
|
||||
- parameter stream: The stream to upload.
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request {
|
||||
return upload(.Stream(URLRequest.URLRequest, stream))
|
||||
}
|
||||
|
||||
/**
|
||||
Creates a request for uploading a stream to the specified URL request.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter stream: The stream to upload.
|
||||
|
||||
- returns: The created upload request.
|
||||
*/
|
||||
public func upload(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
headers: [String: String]? = nil,
|
||||
stream: NSInputStream)
|
||||
-> Request
|
||||
{
|
||||
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
|
||||
|
||||
return upload(mutableURLRequest, stream: stream)
|
||||
}
|
||||
|
||||
// MARK: MultipartFormData
|
||||
|
||||
/// Default memory threshold used when encoding `MultipartFormData`.
|
||||
public static let MultipartFormDataEncodingMemoryThreshold: UInt64 = 10 * 1024 * 1024
|
||||
|
||||
/**
|
||||
Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as
|
||||
associated values.
|
||||
|
||||
- Success: Represents a successful `MultipartFormData` encoding and contains the new `Request` along with
|
||||
streaming information.
|
||||
- Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding
|
||||
error.
|
||||
*/
|
||||
public enum MultipartFormDataEncodingResult {
|
||||
case Success(request: Request, streamingFromDisk: Bool, streamFileURL: NSURL?)
|
||||
case Failure(ErrorType)
|
||||
}
|
||||
|
||||
/**
|
||||
Encodes the `MultipartFormData` and creates a request to upload the result to the specified URL request.
|
||||
|
||||
It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
|
||||
payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
|
||||
efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
|
||||
be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
|
||||
footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
|
||||
used for larger payloads such as video content.
|
||||
|
||||
The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
|
||||
or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
|
||||
encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
|
||||
during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
|
||||
technique was used.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter method: The HTTP method.
|
||||
- parameter URLString: The URL string.
|
||||
- parameter headers: The HTTP headers. `nil` by default.
|
||||
- parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
|
||||
- parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
|
||||
`MultipartFormDataEncodingMemoryThreshold` by default.
|
||||
- parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
|
||||
*/
|
||||
public func upload(
|
||||
method: Method,
|
||||
_ URLString: URLStringConvertible,
|
||||
headers: [String: String]? = nil,
|
||||
multipartFormData: MultipartFormData -> Void,
|
||||
encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold,
|
||||
encodingCompletion: (MultipartFormDataEncodingResult -> Void)?)
|
||||
{
|
||||
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
|
||||
|
||||
return upload(
|
||||
mutableURLRequest,
|
||||
multipartFormData: multipartFormData,
|
||||
encodingMemoryThreshold: encodingMemoryThreshold,
|
||||
encodingCompletion: encodingCompletion
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
Encodes the `MultipartFormData` and creates a request to upload the result to the specified URL request.
|
||||
|
||||
It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
|
||||
payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
|
||||
efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
|
||||
be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
|
||||
footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
|
||||
used for larger payloads such as video content.
|
||||
|
||||
The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
|
||||
or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
|
||||
encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
|
||||
during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
|
||||
technique was used.
|
||||
|
||||
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
|
||||
|
||||
- parameter URLRequest: The URL request.
|
||||
- parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
|
||||
- parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
|
||||
`MultipartFormDataEncodingMemoryThreshold` by default.
|
||||
- parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
|
||||
*/
|
||||
public func upload(
|
||||
URLRequest: URLRequestConvertible,
|
||||
multipartFormData: MultipartFormData -> Void,
|
||||
encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold,
|
||||
encodingCompletion: (MultipartFormDataEncodingResult -> Void)?)
|
||||
{
|
||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
|
||||
let formData = MultipartFormData()
|
||||
multipartFormData(formData)
|
||||
|
||||
let URLRequestWithContentType = URLRequest.URLRequest
|
||||
URLRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type")
|
||||
|
||||
let isBackgroundSession = self.session.configuration.identifier != nil
|
||||
|
||||
if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession {
|
||||
do {
|
||||
let data = try formData.encode()
|
||||
let encodingResult = MultipartFormDataEncodingResult.Success(
|
||||
request: self.upload(URLRequestWithContentType, data: data),
|
||||
streamingFromDisk: false,
|
||||
streamFileURL: nil
|
||||
)
|
||||
|
||||
dispatch_async(dispatch_get_main_queue()) {
|
||||
encodingCompletion?(encodingResult)
|
||||
}
|
||||
} catch {
|
||||
dispatch_async(dispatch_get_main_queue()) {
|
||||
encodingCompletion?(.Failure(error as NSError))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let fileManager = NSFileManager.defaultManager()
|
||||
let tempDirectoryURL = NSURL(fileURLWithPath: NSTemporaryDirectory())
|
||||
let directoryURL = tempDirectoryURL.URLByAppendingPathComponent("com.alamofire.manager/multipart.form.data")
|
||||
let fileName = NSUUID().UUIDString
|
||||
let fileURL = directoryURL.URLByAppendingPathComponent(fileName)
|
||||
|
||||
do {
|
||||
try fileManager.createDirectoryAtURL(directoryURL, withIntermediateDirectories: true, attributes: nil)
|
||||
try formData.writeEncodedDataToDisk(fileURL)
|
||||
|
||||
dispatch_async(dispatch_get_main_queue()) {
|
||||
let encodingResult = MultipartFormDataEncodingResult.Success(
|
||||
request: self.upload(URLRequestWithContentType, file: fileURL),
|
||||
streamingFromDisk: true,
|
||||
streamFileURL: fileURL
|
||||
)
|
||||
encodingCompletion?(encodingResult)
|
||||
}
|
||||
} catch {
|
||||
dispatch_async(dispatch_get_main_queue()) {
|
||||
encodingCompletion?(.Failure(error as NSError))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
extension Request {
|
||||
|
||||
// MARK: - UploadTaskDelegate
|
||||
|
||||
class UploadTaskDelegate: DataTaskDelegate {
|
||||
var uploadTask: NSURLSessionUploadTask? { return task as? NSURLSessionUploadTask }
|
||||
var uploadProgress: ((Int64, Int64, Int64) -> Void)!
|
||||
|
||||
// MARK: - NSURLSessionTaskDelegate
|
||||
|
||||
// MARK: Override Closures
|
||||
|
||||
var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)?
|
||||
|
||||
// MARK: Delegate Methods
|
||||
|
||||
func URLSession(
|
||||
session: NSURLSession,
|
||||
task: NSURLSessionTask,
|
||||
didSendBodyData bytesSent: Int64,
|
||||
totalBytesSent: Int64,
|
||||
totalBytesExpectedToSend: Int64)
|
||||
{
|
||||
if let taskDidSendBodyData = taskDidSendBodyData {
|
||||
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
|
||||
} else {
|
||||
progress.totalUnitCount = totalBytesExpectedToSend
|
||||
progress.completedUnitCount = totalBytesSent
|
||||
|
||||
uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
189
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift
generated
Normal file
189
samples/client/petstore/swift/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift
generated
Normal file
@ -0,0 +1,189 @@
|
||||
// Validation.swift
|
||||
//
|
||||
// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
extension Request {
|
||||
|
||||
/**
|
||||
Used to represent whether validation was successful or encountered an error resulting in a failure.
|
||||
|
||||
- Success: The validation was successful.
|
||||
- Failure: The validation failed encountering the provided error.
|
||||
*/
|
||||
public enum ValidationResult {
|
||||
case Success
|
||||
case Failure(NSError)
|
||||
}
|
||||
|
||||
/**
|
||||
A closure used to validate a request that takes a URL request and URL response, and returns whether the
|
||||
request was valid.
|
||||
*/
|
||||
public typealias Validation = (NSURLRequest?, NSHTTPURLResponse) -> ValidationResult
|
||||
|
||||
/**
|
||||
Validates the request, using the specified closure.
|
||||
|
||||
If validation fails, subsequent calls to response handlers will have an associated error.
|
||||
|
||||
- parameter validation: A closure to validate the request.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func validate(validation: Validation) -> Self {
|
||||
delegate.queue.addOperationWithBlock {
|
||||
if let
|
||||
response = self.response where self.delegate.error == nil,
|
||||
case let .Failure(error) = validation(self.request, response)
|
||||
{
|
||||
self.delegate.error = error
|
||||
}
|
||||
}
|
||||
|
||||
return self
|
||||
}
|
||||
|
||||
// MARK: - Status Code
|
||||
|
||||
/**
|
||||
Validates that the response has a status code in the specified range.
|
||||
|
||||
If validation fails, subsequent calls to response handlers will have an associated error.
|
||||
|
||||
- parameter range: The range of acceptable status codes.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func validate<S: SequenceType where S.Generator.Element == Int>(statusCode acceptableStatusCode: S) -> Self {
|
||||
return validate { _, response in
|
||||
if acceptableStatusCode.contains(response.statusCode) {
|
||||
return .Success
|
||||
} else {
|
||||
let failureReason = "Response status code was unacceptable: \(response.statusCode)"
|
||||
return .Failure(Error.errorWithCode(.StatusCodeValidationFailed, failureReason: failureReason))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Content-Type
|
||||
|
||||
private struct MIMEType {
|
||||
let type: String
|
||||
let subtype: String
|
||||
|
||||
init?(_ string: String) {
|
||||
let components: [String] = {
|
||||
let stripped = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
|
||||
let split = stripped.substringToIndex(stripped.rangeOfString(";")?.startIndex ?? stripped.endIndex)
|
||||
return split.componentsSeparatedByString("/")
|
||||
}()
|
||||
|
||||
if let
|
||||
type = components.first,
|
||||
subtype = components.last
|
||||
{
|
||||
self.type = type
|
||||
self.subtype = subtype
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func matches(MIME: MIMEType) -> Bool {
|
||||
switch (type, subtype) {
|
||||
case (MIME.type, MIME.subtype), (MIME.type, "*"), ("*", MIME.subtype), ("*", "*"):
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Validates that the response has a content type in the specified array.
|
||||
|
||||
If validation fails, subsequent calls to response handlers will have an associated error.
|
||||
|
||||
- parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func validate<S : SequenceType where S.Generator.Element == String>(contentType acceptableContentTypes: S) -> Self {
|
||||
return validate { _, response in
|
||||
guard let validData = self.delegate.data where validData.length > 0 else { return .Success }
|
||||
|
||||
if let
|
||||
responseContentType = response.MIMEType,
|
||||
responseMIMEType = MIMEType(responseContentType)
|
||||
{
|
||||
for contentType in acceptableContentTypes {
|
||||
if let acceptableMIMEType = MIMEType(contentType) where acceptableMIMEType.matches(responseMIMEType) {
|
||||
return .Success
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for contentType in acceptableContentTypes {
|
||||
if let MIMEType = MIMEType(contentType) where MIMEType.type == "*" && MIMEType.subtype == "*" {
|
||||
return .Success
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let failureReason: String
|
||||
|
||||
if let responseContentType = response.MIMEType {
|
||||
failureReason = (
|
||||
"Response content type \"\(responseContentType)\" does not match any acceptable " +
|
||||
"content types: \(acceptableContentTypes)"
|
||||
)
|
||||
} else {
|
||||
failureReason = "Response content type was missing and acceptable content type does not match \"*/*\""
|
||||
}
|
||||
|
||||
return .Failure(Error.errorWithCode(.ContentTypeValidationFailed, failureReason: failureReason))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Automatic
|
||||
|
||||
/**
|
||||
Validates that the response has a status code in the default acceptable range of 200...299, and that the content
|
||||
type matches any specified in the Accept HTTP header field.
|
||||
|
||||
If validation fails, subsequent calls to response handlers will have an associated error.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func validate() -> Self {
|
||||
let acceptableStatusCodes: Range<Int> = 200..<300
|
||||
let acceptableContentTypes: [String] = {
|
||||
if let accept = request?.valueForHTTPHeaderField("Accept") {
|
||||
return accept.componentsSeparatedByString(",")
|
||||
}
|
||||
|
||||
return ["*/*"]
|
||||
}()
|
||||
|
||||
return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes)
|
||||
}
|
||||
}
|
1
samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/OMGHTTPURLRQ/OMGFormURLEncode.h
generated
Symbolic link
1
samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/OMGHTTPURLRQ/OMGFormURLEncode.h
generated
Symbolic link
@ -0,0 +1 @@
|
||||
../../../OMGHTTPURLRQ/Sources/OMGFormURLEncode.h
|
1
samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/OMGHTTPURLRQ/OMGHTTPURLRQ.h
generated
Symbolic link
1
samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/OMGHTTPURLRQ/OMGHTTPURLRQ.h
generated
Symbolic link
@ -0,0 +1 @@
|
||||
../../../OMGHTTPURLRQ/Sources/OMGHTTPURLRQ.h
|
1
samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/OMGHTTPURLRQ/OMGUserAgent.h
generated
Symbolic link
1
samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/OMGHTTPURLRQ/OMGUserAgent.h
generated
Symbolic link
@ -0,0 +1 @@
|
||||
../../../OMGHTTPURLRQ/Sources/OMGUserAgent.h
|
1
samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/AnyPromise.h
generated
Symbolic link
1
samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/AnyPromise.h
generated
Symbolic link
@ -0,0 +1 @@
|
||||
../../../PromiseKit/Sources/AnyPromise.h
|
1
samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/CALayer+AnyPromise.h
generated
Symbolic link
1
samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/CALayer+AnyPromise.h
generated
Symbolic link
@ -0,0 +1 @@
|
||||
../../../PromiseKit/Categories/QuartzCore/CALayer+AnyPromise.h
|
1
samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/NSError+Cancellation.h
generated
Symbolic link
1
samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/NSError+Cancellation.h
generated
Symbolic link
@ -0,0 +1 @@
|
||||
../../../PromiseKit/Sources/NSError+Cancellation.h
|
@ -0,0 +1 @@
|
||||
../../../PromiseKit/Categories/Foundation/NSNotificationCenter+AnyPromise.h
|
@ -0,0 +1 @@
|
||||
../../../PromiseKit/Categories/Foundation/NSURLConnection+AnyPromise.h
|
1
samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/PromiseKit.h
generated
Symbolic link
1
samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/PromiseKit.h
generated
Symbolic link
@ -0,0 +1 @@
|
||||
../../../PromiseKit/Sources/PromiseKit.h
|
@ -0,0 +1 @@
|
||||
../../../PromiseKit/Categories/UIKit/UIActionSheet+AnyPromise.h
|
@ -0,0 +1 @@
|
||||
../../../PromiseKit/Categories/UIKit/UIAlertView+AnyPromise.h
|
1
samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/UIView+AnyPromise.h
generated
Symbolic link
1
samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/UIView+AnyPromise.h
generated
Symbolic link
@ -0,0 +1 @@
|
||||
../../../PromiseKit/Categories/UIKit/UIView+AnyPromise.h
|
@ -0,0 +1 @@
|
||||
../../../PromiseKit/Categories/UIKit/UIViewController+AnyPromise.h
|
1
samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/Umbrella.h
generated
Symbolic link
1
samples/client/petstore/swift/SwaggerClientTests/Pods/Headers/Private/PromiseKit/Umbrella.h
generated
Symbolic link
@ -0,0 +1 @@
|
||||
../../../PromiseKit/Sources/Umbrella.h
|
22
samples/client/petstore/swift/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json
generated
Normal file
22
samples/client/petstore/swift/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json
generated
Normal file
@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "PetstoreClient",
|
||||
"platforms": {
|
||||
"ios": "8.0",
|
||||
"osx": "10.9"
|
||||
},
|
||||
"version": "0.0.1",
|
||||
"source": {
|
||||
"git": "git@github.com:swagger-api/swagger-mustache.git",
|
||||
"tag": "v1.0.0"
|
||||
},
|
||||
"license": "Apache License, Version 2.0",
|
||||
"source_files": "PetstoreClient/Classes/Swaggers/**/*.swift",
|
||||
"dependencies": {
|
||||
"PromiseKit": [
|
||||
"~> 3.0.0"
|
||||
],
|
||||
"Alamofire": [
|
||||
"~> 3.1.4"
|
||||
]
|
||||
}
|
||||
}
|
39
samples/client/petstore/swift/SwaggerClientTests/Pods/Manifest.lock
generated
Normal file
39
samples/client/petstore/swift/SwaggerClientTests/Pods/Manifest.lock
generated
Normal file
@ -0,0 +1,39 @@
|
||||
PODS:
|
||||
- Alamofire (3.1.5)
|
||||
- OMGHTTPURLRQ (3.1.1):
|
||||
- OMGHTTPURLRQ/RQ (= 3.1.1)
|
||||
- OMGHTTPURLRQ/FormURLEncode (3.1.1)
|
||||
- OMGHTTPURLRQ/RQ (3.1.1):
|
||||
- OMGHTTPURLRQ/FormURLEncode
|
||||
- OMGHTTPURLRQ/UserAgent
|
||||
- OMGHTTPURLRQ/UserAgent (3.1.1)
|
||||
- PetstoreClient (0.0.1):
|
||||
- Alamofire (~> 3.1.4)
|
||||
- PromiseKit (~> 3.0.0)
|
||||
- PromiseKit (3.0.2):
|
||||
- PromiseKit/Foundation (= 3.0.2)
|
||||
- PromiseKit/QuartzCore (= 3.0.2)
|
||||
- PromiseKit/UIKit (= 3.0.2)
|
||||
- PromiseKit/CorePromise (3.0.2)
|
||||
- PromiseKit/Foundation (3.0.2):
|
||||
- OMGHTTPURLRQ (~> 3.1.0)
|
||||
- PromiseKit/CorePromise
|
||||
- PromiseKit/QuartzCore (3.0.2):
|
||||
- PromiseKit/CorePromise
|
||||
- PromiseKit/UIKit (3.0.2):
|
||||
- PromiseKit/CorePromise
|
||||
|
||||
DEPENDENCIES:
|
||||
- PetstoreClient (from `../`)
|
||||
|
||||
EXTERNAL SOURCES:
|
||||
PetstoreClient:
|
||||
:path: ../
|
||||
|
||||
SPEC CHECKSUMS:
|
||||
Alamofire: 5f730ba29fd113b7ddd71c1e65d0c630acf5d7b0
|
||||
OMGHTTPURLRQ: 633f98ee745aeda02345935a52eec1784cddb589
|
||||
PetstoreClient: c9a3d06cf7954479a767135676406c4922cd3c4a
|
||||
PromiseKit: ab1a380f7a30cf8cce663a2411e8b3580b10313d
|
||||
|
||||
COCOAPODS: 0.39.0
|
145
samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/README.markdown
generated
Normal file
145
samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/README.markdown
generated
Normal file
@ -0,0 +1,145 @@
|
||||
# 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 you 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.
|
||||
```
|
22
samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGFormURLEncode.h
generated
Normal file
22
samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGFormURLEncode.h
generated
Normal file
@ -0,0 +1,22 @@
|
||||
#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
|
56
samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGFormURLEncode.m
generated
Normal file
56
samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGFormURLEncode.m
generated
Normal file
@ -0,0 +1,56 @@
|
||||
#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;
|
||||
}
|
64
samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGHTTPURLRQ.h
generated
Normal file
64
samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGHTTPURLRQ.h
generated
Normal file
@ -0,0 +1,64 @@
|
||||
#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
|
172
samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGHTTPURLRQ.m
generated
Normal file
172
samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGHTTPURLRQ.m
generated
Normal file
@ -0,0 +1,172 @@
|
||||
#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];
|
||||
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
|
||||
}
|
||||
|
||||
- (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 {
|
||||
id queryString = OMGFormURLEncode(params);
|
||||
if (queryString) 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
|
12
samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGUserAgent.h
generated
Normal file
12
samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGUserAgent.h
generated
Normal file
@ -0,0 +1,12 @@
|
||||
#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
|
19
samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGUserAgent.m
generated
Normal file
19
samples/client/petstore/swift/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGUserAgent.m
generated
Normal file
@ -0,0 +1,19 @@
|
||||
#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;
|
||||
}
|
1434
samples/client/petstore/swift/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj
generated
Normal file
1434
samples/client/petstore/swift/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj
generated
Normal file
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,60 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0700"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForAnalyzing = "YES"
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = 'primary'
|
||||
BlueprintIdentifier = '4A19A333BD680B246281C6BF'
|
||||
BlueprintName = 'PetstoreClient'
|
||||
ReferencedContainer = 'container:Pods.xcodeproj'
|
||||
BuildableName = 'PetstoreClient.framework'>
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
buildConfiguration = "Debug">
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
buildConfiguration = "Debug"
|
||||
allowLocationSimulation = "YES">
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
@ -0,0 +1,60 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0700"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForAnalyzing = "YES"
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = 'primary'
|
||||
BlueprintIdentifier = '2FEA473E6DE73F79AE5ED1B1'
|
||||
BlueprintName = 'Alamofire'
|
||||
ReferencedContainer = 'container:Pods.xcodeproj'
|
||||
BuildableName = 'Alamofire.framework'>
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
buildConfiguration = "Debug">
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
buildConfiguration = "Debug"
|
||||
allowLocationSimulation = "YES">
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
@ -0,0 +1,60 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0700"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForAnalyzing = "YES"
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = 'primary'
|
||||
BlueprintIdentifier = '982B28FEF02A556B9E587637'
|
||||
BlueprintName = 'OMGHTTPURLRQ'
|
||||
ReferencedContainer = 'container:Pods.xcodeproj'
|
||||
BuildableName = 'OMGHTTPURLRQ.framework'>
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
buildConfiguration = "Debug">
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
buildConfiguration = "Debug"
|
||||
allowLocationSimulation = "YES">
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
@ -0,0 +1,60 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0700"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForAnalyzing = "YES"
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = 'primary'
|
||||
BlueprintIdentifier = 'E207018CA101AA8B4C13DB7F'
|
||||
BlueprintName = 'Pods'
|
||||
ReferencedContainer = 'container:Pods.xcodeproj'
|
||||
BuildableName = 'Pods.framework'>
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
buildConfiguration = "Debug">
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
buildConfiguration = "Debug"
|
||||
allowLocationSimulation = "YES">
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
@ -0,0 +1,60 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0700"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForAnalyzing = "YES"
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = 'primary'
|
||||
BlueprintIdentifier = 'AC4E1F91EF9FE06D171AB972'
|
||||
BlueprintName = 'PromiseKit'
|
||||
ReferencedContainer = 'container:Pods.xcodeproj'
|
||||
BuildableName = 'PromiseKit.framework'>
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
buildConfiguration = "Debug">
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
buildConfiguration = "Debug"
|
||||
allowLocationSimulation = "YES">
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
@ -0,0 +1,62 @@
|
||||
<?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>SchemeUserState</key>
|
||||
<dict>
|
||||
<key>Alamofire.xcscheme</key>
|
||||
<dict>
|
||||
<key>isShown</key>
|
||||
<false/>
|
||||
</dict>
|
||||
<key>OMGHTTPURLRQ.xcscheme</key>
|
||||
<dict>
|
||||
<key>isShown</key>
|
||||
<false/>
|
||||
</dict>
|
||||
<key>PetstoreClient.xcscheme</key>
|
||||
<dict>
|
||||
<key>isShown</key>
|
||||
<false/>
|
||||
</dict>
|
||||
<key>Pods.xcscheme</key>
|
||||
<dict>
|
||||
<key>isShown</key>
|
||||
<false/>
|
||||
</dict>
|
||||
<key>PromiseKit.xcscheme</key>
|
||||
<dict>
|
||||
<key>isShown</key>
|
||||
<false/>
|
||||
</dict>
|
||||
</dict>
|
||||
<key>SuppressBuildableAutocreation</key>
|
||||
<dict>
|
||||
<key>190ACD3A51BC90B85EADB13E9CDD207B</key>
|
||||
<dict>
|
||||
<key>primary</key>
|
||||
<true/>
|
||||
</dict>
|
||||
<key>25EDA9CFC641C69402B3857A2C4A39F0</key>
|
||||
<dict>
|
||||
<key>primary</key>
|
||||
<true/>
|
||||
</dict>
|
||||
<key>2FD913B4E24277823983BABFDB071664</key>
|
||||
<dict>
|
||||
<key>primary</key>
|
||||
<true/>
|
||||
</dict>
|
||||
<key>432ECC54282C84882B482CCB4CF227FC</key>
|
||||
<dict>
|
||||
<key>primary</key>
|
||||
<true/>
|
||||
</dict>
|
||||
<key>7A5DBD588D2CC1C0CB1C42D4ED613FE4</key>
|
||||
<dict>
|
||||
<key>primary</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</dict>
|
||||
</dict>
|
||||
</plist>
|
@ -0,0 +1,43 @@
|
||||
#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
|
@ -0,0 +1,18 @@
|
||||
#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
|
@ -0,0 +1,51 @@
|
||||
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)
|
||||
}
|
||||
}
|
@ -0,0 +1,67 @@
|
||||
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())
|
||||
}()
|
||||
}
|
@ -0,0 +1,215 @@
|
||||
#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
|
@ -0,0 +1,178 @@
|
||||
#import <CoreFoundation/CFString.h>
|
||||
#import <CoreFoundation/CFURL.h>
|
||||
#import <Foundation/NSArray.h>
|
||||
#import <Foundation/NSError.h>
|
||||
#import <Foundation/NSJSONSerialization.h>
|
||||
#import <Foundation/NSOperation.h>
|
||||
#import <Foundation/NSThread.h>
|
||||
#import <Foundation/NSURLError.h>
|
||||
#import <Foundation/NSURL.h>
|
||||
#import <Foundation/NSURLResponse.h>
|
||||
#import "NSURLConnection+AnyPromise.h"
|
||||
#import <PromiseKit/PromiseKit.h>
|
||||
#import <OMGHTTPURLRQ/OMGHTTPURLRQ.h>
|
||||
#import <OMGHTTPURLRQ/OMGUserAgent.h>
|
||||
|
||||
|
||||
@implementation NSURLConnection (PromiseKit)
|
||||
|
||||
+ (AnyPromise *)GET:(id)urlFormat, ... {
|
||||
if ([urlFormat isKindOfClass:[NSString class]]) {
|
||||
va_list arguments;
|
||||
va_start(arguments, urlFormat);
|
||||
urlFormat = [[NSString alloc] initWithFormat:urlFormat arguments:arguments];
|
||||
va_end(arguments);
|
||||
} else if ([urlFormat isKindOfClass:[NSURL class]]) {
|
||||
NSMutableURLRequest *rq = [[NSMutableURLRequest alloc] initWithURL:urlFormat];
|
||||
[rq setValue:OMGUserAgent() forHTTPHeaderField:@"User-Agent"];
|
||||
return [self promise:rq];
|
||||
} else {
|
||||
urlFormat = [urlFormat description];
|
||||
}
|
||||
id err;
|
||||
id rq = [OMGHTTPURLRQ GET:urlFormat:nil error:&err];
|
||||
if (err) return [AnyPromise promiseWithValue:err];
|
||||
return [self promise:rq];
|
||||
}
|
||||
|
||||
+ (AnyPromise *)GET:(NSString *)url query:(NSDictionary *)params {
|
||||
id err;
|
||||
id rq = [OMGHTTPURLRQ GET:url:params error:&err];
|
||||
if (err) return [AnyPromise promiseWithValue:err];
|
||||
return [self promise:rq];
|
||||
}
|
||||
|
||||
+ (AnyPromise *)POST:(NSString *)url formURLEncodedParameters:(NSDictionary *)params {
|
||||
id err;
|
||||
id rq = [OMGHTTPURLRQ POST:url:params error:&err];
|
||||
if (err) return [AnyPromise promiseWithValue:err];
|
||||
return [self promise:rq];
|
||||
}
|
||||
|
||||
+ (AnyPromise *)POST:(NSString *)urlString JSON:(NSDictionary *)params {
|
||||
id err;
|
||||
id rq = [OMGHTTPURLRQ POST:urlString JSON:params error:&err];
|
||||
if (err) [AnyPromise promiseWithValue:err];
|
||||
return [self promise:rq];
|
||||
}
|
||||
|
||||
+ (AnyPromise *)PUT:(NSString *)url formURLEncodedParameters:(NSDictionary *)params {
|
||||
id err;
|
||||
id rq = [OMGHTTPURLRQ PUT:url:params error:&err];
|
||||
if (err) [AnyPromise promiseWithValue:err];
|
||||
return [self promise:rq];
|
||||
|
||||
}
|
||||
|
||||
+ (AnyPromise *)DELETE:(NSString *)url formURLEncodedParameters:(NSDictionary *)params {
|
||||
id err;
|
||||
id rq = [OMGHTTPURLRQ DELETE:url :params error:&err];
|
||||
if (err) [AnyPromise promiseWithValue:err];
|
||||
return [self promise:rq];
|
||||
}
|
||||
|
||||
+ (AnyPromise *)promise:(NSURLRequest *)rq {
|
||||
static id q = nil;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
q = [NSOperationQueue new];
|
||||
});
|
||||
|
||||
return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) {
|
||||
[NSURLConnection sendAsynchronousRequest:rq queue:q completionHandler:^(id rsp, id data, id urlError) {
|
||||
assert(![NSThread isMainThread]);
|
||||
|
||||
PMKResolver fulfiller = ^(id responseObject){
|
||||
resolve(PMKManifold(responseObject, rsp, data));
|
||||
};
|
||||
PMKResolver rejecter = ^(NSError *error){
|
||||
id userInfo = error.userInfo.mutableCopy ?: [NSMutableDictionary new];
|
||||
if (data) userInfo[PMKURLErrorFailingDataKey] = data;
|
||||
if (rsp) userInfo[PMKURLErrorFailingURLResponseKey] = rsp;
|
||||
error = [NSError errorWithDomain:error.domain code:error.code userInfo:userInfo];
|
||||
resolve(error);
|
||||
};
|
||||
|
||||
NSStringEncoding (^stringEncoding)() = ^NSStringEncoding{
|
||||
id encodingName = [rsp textEncodingName];
|
||||
if (encodingName) {
|
||||
CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)encodingName);
|
||||
if (encoding != kCFStringEncodingInvalidId)
|
||||
return CFStringConvertEncodingToNSStringEncoding(encoding);
|
||||
}
|
||||
return NSUTF8StringEncoding;
|
||||
};
|
||||
|
||||
if (urlError) {
|
||||
rejecter(urlError);
|
||||
} else if (![rsp isKindOfClass:[NSHTTPURLResponse class]]) {
|
||||
fulfiller(data);
|
||||
} else if ([rsp statusCode] < 200 || [rsp statusCode] >= 300) {
|
||||
id info = @{
|
||||
NSLocalizedDescriptionKey: @"The server returned a bad HTTP response code",
|
||||
NSURLErrorFailingURLStringErrorKey: rq.URL.absoluteString,
|
||||
NSURLErrorFailingURLErrorKey: rq.URL
|
||||
};
|
||||
id err = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadServerResponse userInfo:info];
|
||||
rejecter(err);
|
||||
} else if (PMKHTTPURLResponseIsJSON(rsp)) {
|
||||
// work around ever-so-common Rails workaround: https://github.com/rails/rails/issues/1742
|
||||
if ([rsp expectedContentLength] == 1 && [data isEqualToData:[NSData dataWithBytes:" " length:1]])
|
||||
return fulfiller(nil);
|
||||
|
||||
NSError *err = nil;
|
||||
id json = [NSJSONSerialization JSONObjectWithData:data options:PMKJSONDeserializationOptions error:&err];
|
||||
if (!err) {
|
||||
fulfiller(json);
|
||||
} else {
|
||||
id userInfo = err.userInfo.mutableCopy;
|
||||
if (data) {
|
||||
NSString *string = [[NSString alloc] initWithData:data encoding:stringEncoding()];
|
||||
if (string)
|
||||
userInfo[PMKURLErrorFailingStringKey] = string;
|
||||
}
|
||||
long long length = [rsp expectedContentLength];
|
||||
id bytes = length <= 0 ? @"" : [NSString stringWithFormat:@"%lld bytes", length];
|
||||
id fmt = @"The server claimed a %@ JSON response, but decoding failed with: %@";
|
||||
userInfo[NSLocalizedDescriptionKey] = [NSString stringWithFormat:fmt, bytes, userInfo[NSLocalizedDescriptionKey]];
|
||||
err = [NSError errorWithDomain:err.domain code:err.code userInfo:userInfo];
|
||||
rejecter(err);
|
||||
}
|
||||
#ifdef UIKIT_EXTERN
|
||||
} else if (PMKHTTPURLResponseIsImage(rsp)) {
|
||||
UIImage *image = [[UIImage alloc] initWithData:data];
|
||||
image = [[UIImage alloc] initWithCGImage:[image CGImage] scale:image.scale orientation:image.imageOrientation];
|
||||
if (image)
|
||||
fulfiller(image);
|
||||
else {
|
||||
id info = @{
|
||||
NSLocalizedDescriptionKey: @"The server returned invalid image data",
|
||||
NSURLErrorFailingURLStringErrorKey: rq.URL.absoluteString,
|
||||
NSURLErrorFailingURLErrorKey: rq.URL
|
||||
};
|
||||
id err = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:info];
|
||||
rejecter(err);
|
||||
}
|
||||
#endif
|
||||
} else if (PMKHTTPURLResponseIsText(rsp)) {
|
||||
id str = [[NSString alloc] initWithData:data encoding:stringEncoding()];
|
||||
if (str)
|
||||
fulfiller(str);
|
||||
else {
|
||||
id info = @{
|
||||
NSLocalizedDescriptionKey: @"The server returned invalid string data",
|
||||
NSURLErrorFailingURLStringErrorKey: rq.URL.absoluteString,
|
||||
NSURLErrorFailingURLErrorKey: rq.URL
|
||||
};
|
||||
id err = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:info];
|
||||
rejecter(err);
|
||||
}
|
||||
} else
|
||||
fulfiller(data);
|
||||
}];
|
||||
}];
|
||||
|
||||
#undef fulfiller
|
||||
}
|
||||
|
||||
@end
|
@ -0,0 +1,74 @@
|
||||
import Foundation
|
||||
import OMGHTTPURLRQ
|
||||
#if !COCOAPODS
|
||||
import PromiseKit
|
||||
#endif
|
||||
|
||||
/**
|
||||
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
|
||||
*/
|
||||
extension NSURLConnection {
|
||||
public class func GET(URL: String, query: [NSObject:AnyObject]? = nil) -> URLDataPromise {
|
||||
return go(try OMGHTTPURLRQ.GET(URL, query))
|
||||
}
|
||||
|
||||
public class func POST(URL: String, formData: [NSObject:AnyObject]? = nil) -> URLDataPromise {
|
||||
return go(try OMGHTTPURLRQ.POST(URL, formData))
|
||||
}
|
||||
|
||||
public class func POST(URL: String, JSON: [NSObject:AnyObject]) -> URLDataPromise {
|
||||
return go(try OMGHTTPURLRQ.POST(URL, JSON: JSON))
|
||||
}
|
||||
|
||||
public class func POST(URL: String, multipartFormData: OMGMultipartFormData) -> URLDataPromise {
|
||||
return go(try OMGHTTPURLRQ.POST(URL, multipartFormData))
|
||||
}
|
||||
|
||||
public class func PUT(URL: String, formData: [NSObject:AnyObject]? = nil) -> URLDataPromise {
|
||||
return go(try OMGHTTPURLRQ.PUT(URL, formData))
|
||||
}
|
||||
|
||||
public class func PUT(URL: String, JSON: [NSObject:AnyObject]) -> URLDataPromise {
|
||||
return go(try OMGHTTPURLRQ.PUT(URL, JSON: JSON))
|
||||
}
|
||||
|
||||
public class func DELETE(URL: String) -> URLDataPromise {
|
||||
return go(try OMGHTTPURLRQ.DELETE(URL, nil))
|
||||
}
|
||||
|
||||
public class func promise(request: NSURLRequest) -> URLDataPromise {
|
||||
return go(request)
|
||||
}
|
||||
}
|
||||
|
||||
private func go(@autoclosure body: () throws -> NSURLRequest) -> URLDataPromise {
|
||||
do {
|
||||
var request = try body()
|
||||
|
||||
if request.valueForHTTPHeaderField("User-Agent") == nil {
|
||||
let rq = request.mutableCopy() as! NSMutableURLRequest
|
||||
rq.setValue(OMGUserAgent(), forHTTPHeaderField: "User-Agent")
|
||||
request = rq
|
||||
}
|
||||
|
||||
return URLDataPromise.go(request) { completionHandler in
|
||||
NSURLConnection.sendAsynchronousRequest(request, queue: Q, completionHandler: { completionHandler($1, $0, $2) })
|
||||
}
|
||||
} catch {
|
||||
return URLDataPromise(error: error)
|
||||
}
|
||||
}
|
||||
|
||||
private let Q = NSOperationQueue()
|
@ -0,0 +1,71 @@
|
||||
import Foundation
|
||||
import OMGHTTPURLRQ
|
||||
#if !COCOAPODS
|
||||
import PromiseKit
|
||||
#endif
|
||||
|
||||
//TODO cancellation
|
||||
|
||||
/**
|
||||
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
|
||||
|
||||
We provide convenience categories for the `sharedSession`, or
|
||||
an instance method `promise`. If you need more complicated behavior
|
||||
we recommend wrapping that usage in a Promise initializer.
|
||||
*/
|
||||
extension NSURLSession {
|
||||
public class func GET(URL: String, query: [NSObject: AnyObject]? = nil) -> URLDataPromise {
|
||||
return start(try OMGHTTPURLRQ.GET(URL, query))
|
||||
}
|
||||
|
||||
public class func POST(URL: String, formData: [NSObject: AnyObject]? = nil) -> URLDataPromise {
|
||||
return start(try OMGHTTPURLRQ.POST(URL, formData))
|
||||
}
|
||||
|
||||
public class func POST(URL: String, multipartFormData: OMGMultipartFormData) -> URLDataPromise {
|
||||
return start(try OMGHTTPURLRQ.POST(URL, multipartFormData))
|
||||
}
|
||||
|
||||
public class func PUT(URL: String) -> URLDataPromise {
|
||||
return start(try OMGHTTPURLRQ.PUT(URL, nil))
|
||||
}
|
||||
|
||||
public class func DELETE(URL: String) -> URLDataPromise {
|
||||
return start(try OMGHTTPURLRQ.DELETE(URL, nil))
|
||||
}
|
||||
|
||||
public func promise(request: NSURLRequest) -> URLDataPromise {
|
||||
return start(request, session: self)
|
||||
}
|
||||
}
|
||||
|
||||
private func start(@autoclosure body: () throws -> NSURLRequest, session: NSURLSession = NSURLSession.sharedSession()) -> URLDataPromise {
|
||||
do {
|
||||
var request = try body()
|
||||
|
||||
if request.valueForHTTPHeaderField("User-Agent") == nil {
|
||||
let rq = request.mutableCopy() as! NSMutableURLRequest
|
||||
rq.setValue(OMGUserAgent(), forHTTPHeaderField: "User-Agent")
|
||||
request = rq
|
||||
}
|
||||
|
||||
return URLDataPromise.go(request) { completionHandler in
|
||||
let task = session.dataTaskWithRequest(request, completionHandler: completionHandler)
|
||||
task.resume()
|
||||
}
|
||||
} catch {
|
||||
return URLDataPromise(error: error)
|
||||
}
|
||||
}
|
@ -0,0 +1,29 @@
|
||||
import Foundation
|
||||
#if !COCOAPODS
|
||||
import PromiseKit
|
||||
#endif
|
||||
|
||||
/**
|
||||
@return A promise that resolves when the provided object deallocates
|
||||
|
||||
@warning *Important* The promise is not guarenteed to resolve immediately
|
||||
when the provided object is deallocated. So you cannot write code that
|
||||
depends on exact timing.
|
||||
*/
|
||||
public func after(life object: NSObject) -> Promise<Void> {
|
||||
var reaper = objc_getAssociatedObject(object, &handle) as? GrimReaper
|
||||
if reaper == nil {
|
||||
reaper = GrimReaper()
|
||||
objc_setAssociatedObject(object, &handle, reaper, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
|
||||
}
|
||||
return reaper!.promise
|
||||
}
|
||||
|
||||
private var handle: UInt8 = 0
|
||||
|
||||
private class GrimReaper: NSObject {
|
||||
deinit {
|
||||
fulfill()
|
||||
}
|
||||
let (promise, fulfill, _) = Promise<Void>.pendingPromise()
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
//
|
||||
// CALayer+AnyPromise.h
|
||||
//
|
||||
// Created by María Patricia Montalvo Dzib on 24/11/14.
|
||||
// Copyright (c) 2014 Aluxoft SCP. All rights reserved.
|
||||
//
|
||||
|
||||
#import <QuartzCore/QuartzCore.h>
|
||||
#import <PromiseKit/AnyPromise.h>
|
||||
|
||||
/**
|
||||
To import the `CALayer` category:
|
||||
|
||||
use_frameworks!
|
||||
pod "PromiseKit/QuartzCore"
|
||||
|
||||
Or `CALayer` is one of the categories imported by the umbrella pod:
|
||||
|
||||
use_frameworks!
|
||||
pod "PromiseKit"
|
||||
|
||||
And then in your sources:
|
||||
|
||||
#import <PromiseKit/PromiseKit.h>
|
||||
*/
|
||||
@interface CALayer (PromiseKit)
|
||||
|
||||
/**
|
||||
Add the specified animation object to the layer’s render tree.
|
||||
|
||||
@return A promise that thens two parameters:
|
||||
|
||||
1. `@YES` if the animation progressed entirely to completion.
|
||||
2. The `CAAnimation` object.
|
||||
|
||||
@see addAnimation:forKey
|
||||
*/
|
||||
- (AnyPromise *)promiseAnimation:(CAAnimation *)animation forKey:(NSString *)key;
|
||||
|
||||
@end
|
@ -0,0 +1,39 @@
|
||||
//
|
||||
// CALayer+PromiseKit.m
|
||||
//
|
||||
// Created by María Patricia Montalvo Dzib on 24/11/14.
|
||||
// Copyright (c) 2014 Aluxoft SCP. All rights reserved.
|
||||
//
|
||||
|
||||
#import <QuartzCore/CAAnimation.h>
|
||||
#import "CALayer+AnyPromise.h"
|
||||
|
||||
|
||||
@interface PMKCAAnimationDelegate : NSObject {
|
||||
@public
|
||||
PMKResolver resolve;
|
||||
CAAnimation *animation;
|
||||
}
|
||||
@end
|
||||
|
||||
@implementation PMKCAAnimationDelegate
|
||||
|
||||
- (void)animationDidStop:(CAAnimation *)ignoreOrRetainCycleHappens finished:(BOOL)flag {
|
||||
resolve(PMKManifold(@(flag), animation));
|
||||
animation.delegate = nil;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
|
||||
@implementation CALayer (PromiseKit)
|
||||
|
||||
- (AnyPromise *)promiseAnimation:(CAAnimation *)animation forKey:(NSString *)key {
|
||||
PMKCAAnimationDelegate *d = animation.delegate = [PMKCAAnimationDelegate new];
|
||||
d->animation = animation;
|
||||
[self addAnimation:animation forKey:key];
|
||||
return [[AnyPromise alloc] initWithResolver:&d->resolve];
|
||||
}
|
||||
|
||||
@end
|
@ -0,0 +1,75 @@
|
||||
import UIKit
|
||||
#if !COCOAPODS
|
||||
import PromiseKit
|
||||
#endif
|
||||
|
||||
//TODO tests
|
||||
//TODO NSCoding
|
||||
|
||||
/**
|
||||
A “promisable” UIAlertController.
|
||||
|
||||
UIAlertController is not a suitable API for an extension; it has closure
|
||||
handlers on its main API for each button and an extension would have to
|
||||
either replace all these when the controller is presented or force you to
|
||||
use an extended addAction method, which would be easy to forget part of
|
||||
the time. Hence we provide a facade pattern that can be promised.
|
||||
|
||||
let alert = PMKAlertController("OHAI")
|
||||
let sup = alert.addActionWithTitle("SUP")
|
||||
let bye = alert.addActionWithTitle("BYE")
|
||||
promiseViewController(alert).then { action in
|
||||
switch action {
|
||||
case is sup:
|
||||
//…
|
||||
case is bye:
|
||||
//…
|
||||
}
|
||||
}
|
||||
*/
|
||||
public class PMKAlertController {
|
||||
public var title: String? { return UIAlertController.title }
|
||||
public var message: String? { return UIAlertController.message }
|
||||
public var preferredStyle: UIAlertControllerStyle { return UIAlertController.preferredStyle }
|
||||
public var actions: [UIAlertAction] { return UIAlertController.actions }
|
||||
public var textFields: [UITextField]? { return UIAlertController.textFields }
|
||||
|
||||
public required init(title: String?, message: String? = nil, preferredStyle: UIAlertControllerStyle = .Alert) {
|
||||
UIAlertController = UIKit.UIAlertController(title: title, message: message, preferredStyle: preferredStyle)
|
||||
}
|
||||
|
||||
public func addActionWithTitle(title: String, style: UIAlertActionStyle = .Default) -> UIAlertAction {
|
||||
let action = UIAlertAction(title: title, style: style) { action in
|
||||
if style != UIAlertActionStyle.Cancel {
|
||||
self.fulfill(action)
|
||||
} else {
|
||||
self.reject(Error.Cancelled)
|
||||
}
|
||||
}
|
||||
UIAlertController.addAction(action)
|
||||
return action
|
||||
}
|
||||
|
||||
public func addTextFieldWithConfigurationHandler(configurationHandler: ((UITextField) -> Void)?) {
|
||||
UIAlertController.addTextFieldWithConfigurationHandler(configurationHandler)
|
||||
}
|
||||
|
||||
private let UIAlertController: UIKit.UIAlertController
|
||||
private let (promise, fulfill, reject) = Promise<UIAlertAction>.pendingPromise()
|
||||
private var retainCycle: PMKAlertController?
|
||||
|
||||
public enum Error: ErrorType {
|
||||
case Cancelled
|
||||
}
|
||||
}
|
||||
|
||||
extension UIViewController {
|
||||
public func promiseViewController(vc: PMKAlertController, animated: Bool = true, completion: (() -> Void)? = nil) -> Promise<UIAlertAction> {
|
||||
vc.retainCycle = vc
|
||||
presentViewController(vc.UIAlertController, animated: true, completion: nil)
|
||||
vc.promise.always { _ -> Void in
|
||||
vc.retainCycle = nil
|
||||
}
|
||||
return vc.promise
|
||||
}
|
||||
}
|
@ -0,0 +1,42 @@
|
||||
#import <PromiseKit/AnyPromise.h>
|
||||
#import <UIKit/UIActionSheet.h>
|
||||
|
||||
/**
|
||||
To import the `UIActionSheet` category:
|
||||
|
||||
use_frameworks!
|
||||
pod "PromiseKit/UIKit"
|
||||
|
||||
Or `UIKit` is one of the categories imported by the umbrella pod:
|
||||
|
||||
use_frameworks!
|
||||
pod "PromiseKit"
|
||||
|
||||
And then in your sources:
|
||||
|
||||
#import <PromiseKit/PromiseKit.h>
|
||||
*/
|
||||
@interface UIActionSheet (PromiseKit)
|
||||
|
||||
/**
|
||||
Displays the action sheet originating from the specified view.
|
||||
|
||||
UIActionSheet *sheet = [UIActionSheet new];
|
||||
sheet.title = @"OHAI";
|
||||
[sheet addButtonWithTitle:@"OK"];
|
||||
[sheet promiseInView:nil].then(^(NSNumber *dismissedButtonIndex){
|
||||
//…
|
||||
});
|
||||
|
||||
@param view The view from which the action sheet originates.
|
||||
|
||||
@warning *Important* If a cancelButtonIndex is set the promise will be *cancelled* if that button is pressed. Cancellation in PromiseKit has special behavior, see the relevant documentation for more details.
|
||||
|
||||
@return A promise that fulfills with two parameters:
|
||||
|
||||
1) The index (NSNumber) of the button that was tapped to dismiss the sheet.
|
||||
2) This action sheet.
|
||||
*/
|
||||
- (AnyPromise *)promiseInView:(UIView *)view;
|
||||
|
||||
@end
|
@ -0,0 +1,41 @@
|
||||
#import <PromiseKit/PromiseKit.h>
|
||||
#import "UIActionSheet+AnyPromise.h"
|
||||
|
||||
|
||||
@interface PMKActionSheetDelegate : NSObject <UIActionSheetDelegate> {
|
||||
@public
|
||||
id retainCycle;
|
||||
PMKResolver resolve;
|
||||
}
|
||||
@end
|
||||
|
||||
|
||||
@implementation PMKActionSheetDelegate
|
||||
|
||||
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {
|
||||
if (buttonIndex == actionSheet.cancelButtonIndex) {
|
||||
resolve([NSError cancelledError]);
|
||||
} else {
|
||||
resolve(PMKManifold(@(buttonIndex), actionSheet));
|
||||
}
|
||||
retainCycle = nil;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@implementation UIActionSheet (PromiseKit)
|
||||
|
||||
- (AnyPromise *)promiseInView:(UIView *)view {
|
||||
PMKActionSheetDelegate *d = [PMKActionSheetDelegate new];
|
||||
d->retainCycle = self.delegate = d;
|
||||
[self showInView:view];
|
||||
|
||||
if (self.numberOfButtons == 1 && self.cancelButtonIndex == 0) {
|
||||
NSLog(@"PromiseKit: An action sheet is being promised with a single button that is set as the cancelButtonIndex. The promise *will* be cancelled which may result in unexpected behavior. See http://promisekit.org/PromiseKit-2.0-Released/ for cancellation documentation.");
|
||||
}
|
||||
|
||||
return [[AnyPromise alloc] initWithResolver:&d->resolve];
|
||||
}
|
||||
|
||||
@end
|
@ -0,0 +1,59 @@
|
||||
import UIKit.UIActionSheet
|
||||
#if !COCOAPODS
|
||||
import PromiseKit
|
||||
#endif
|
||||
|
||||
/**
|
||||
To import the `UIActionSheet` category:
|
||||
|
||||
use_frameworks!
|
||||
pod "PromiseKit/UIKit"
|
||||
|
||||
Or `UIKit` is one of the categories imported by the umbrella pod:
|
||||
|
||||
use_frameworks!
|
||||
pod "PromiseKit"
|
||||
|
||||
And then in your sources:
|
||||
|
||||
import PromiseKit
|
||||
*/
|
||||
extension UIActionSheet {
|
||||
public func promiseInView(view: UIView) -> Promise<Int> {
|
||||
let proxy = PMKActionSheetDelegate()
|
||||
delegate = proxy
|
||||
proxy.retainCycle = proxy
|
||||
showInView(view)
|
||||
|
||||
if numberOfButtons == 1 && cancelButtonIndex == 0 {
|
||||
NSLog("PromiseKit: An action sheet is being promised with a single button that is set as the cancelButtonIndex. The promise *will* be cancelled which may result in unexpected behavior. See http://promisekit.org/PromiseKit-2.0-Released/ for cancellation documentation.")
|
||||
}
|
||||
|
||||
return proxy.promise
|
||||
}
|
||||
|
||||
public enum Error: CancellableErrorType {
|
||||
case Cancelled
|
||||
|
||||
public var cancelled: Bool {
|
||||
switch self {
|
||||
case .Cancelled: return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class PMKActionSheetDelegate: NSObject, UIActionSheetDelegate {
|
||||
let (promise, fulfill, reject) = Promise<Int>.pendingPromise()
|
||||
var retainCycle: NSObject?
|
||||
|
||||
@objc func actionSheet(actionSheet: UIActionSheet, didDismissWithButtonIndex buttonIndex: Int) {
|
||||
defer { retainCycle = nil }
|
||||
|
||||
if buttonIndex != actionSheet.cancelButtonIndex {
|
||||
fulfill(buttonIndex)
|
||||
} else {
|
||||
reject(UIActionSheet.Error.Cancelled)
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
#import <PromiseKit/AnyPromise.h>
|
||||
#import <UIKit/UIAlertView.h>
|
||||
|
||||
/**
|
||||
To import the `UIAlertView` category:
|
||||
|
||||
use_frameworks!
|
||||
pod "PromiseKit/UIKit"
|
||||
|
||||
Or `UIKit` is one of the categories imported by the umbrella pod:
|
||||
|
||||
use_frameworks!
|
||||
pod "PromiseKit"
|
||||
|
||||
And then in your sources:
|
||||
|
||||
#import <PromiseKit/PromiseKit.h>
|
||||
*/
|
||||
@interface UIAlertView (PromiseKit)
|
||||
|
||||
/**
|
||||
Displays the alert view.
|
||||
|
||||
UIAlertView *alert = [UIAlertView new];
|
||||
alert.title = @"OHAI";
|
||||
[alert addButtonWithTitle:@"OK"];
|
||||
[alert promise].then(^(NSNumber *dismissedButtonIndex){
|
||||
//…
|
||||
});
|
||||
|
||||
@warning *Important* If a cancelButtonIndex is set the promise will be *cancelled* if that button is pressed. Cancellation in PromiseKit has special behavior, see the relevant documentation for more details.
|
||||
|
||||
@return A promise the fulfills with two parameters:
|
||||
|
||||
1) The index of the button that was tapped to dismiss the alert.
|
||||
2) This alert view.
|
||||
*/
|
||||
- (AnyPromise *)promise;
|
||||
|
||||
@end
|
@ -0,0 +1,41 @@
|
||||
#import <PromiseKit/PromiseKit.h>
|
||||
#import "UIAlertView+AnyPromise.h"
|
||||
|
||||
|
||||
@interface PMKAlertViewDelegate : NSObject <UIAlertViewDelegate> {
|
||||
@public
|
||||
PMKResolver resolve;
|
||||
id retainCycle;
|
||||
}
|
||||
@end
|
||||
|
||||
|
||||
@implementation PMKAlertViewDelegate
|
||||
|
||||
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
|
||||
if (buttonIndex != alertView.cancelButtonIndex) {
|
||||
resolve(PMKManifold(@(buttonIndex), alertView));
|
||||
} else {
|
||||
resolve([NSError cancelledError]);
|
||||
}
|
||||
retainCycle = nil;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@implementation UIAlertView (PromiseKit)
|
||||
|
||||
- (AnyPromise *)promise {
|
||||
PMKAlertViewDelegate *d = [PMKAlertViewDelegate new];
|
||||
d->retainCycle = self.delegate = d;
|
||||
[self show];
|
||||
|
||||
if (self.numberOfButtons == 1 && self.cancelButtonIndex == 0) {
|
||||
NSLog(@"PromiseKit: An alert view is being promised with a single button that is set as the cancelButtonIndex. The promise *will* be cancelled which may result in unexpected behavior. See http://promisekit.org/PromiseKit-2.0-Released/ for cancellation documentation.");
|
||||
}
|
||||
|
||||
return [[AnyPromise alloc] initWithResolver:&d->resolve];
|
||||
}
|
||||
|
||||
@end
|
@ -0,0 +1,58 @@
|
||||
import Foundation
|
||||
import UIKit.UIAlertView
|
||||
#if !COCOAPODS
|
||||
import PromiseKit
|
||||
#endif
|
||||
|
||||
/**
|
||||
To import the `UIActionSheet` category:
|
||||
|
||||
use_frameworks!
|
||||
pod "PromiseKit/UIKit"
|
||||
|
||||
Or `UIKit` is one of the categories imported by the umbrella pod:
|
||||
|
||||
use_frameworks!
|
||||
pod "PromiseKit"
|
||||
|
||||
And then in your sources:
|
||||
|
||||
import PromiseKit
|
||||
*/
|
||||
extension UIAlertView {
|
||||
public func promise() -> Promise<Int> {
|
||||
let proxy = PMKAlertViewDelegate()
|
||||
delegate = proxy
|
||||
proxy.retainCycle = proxy
|
||||
show()
|
||||
|
||||
if numberOfButtons == 1 && cancelButtonIndex == 0 {
|
||||
NSLog("PromiseKit: An alert view is being promised with a single button that is set as the cancelButtonIndex. The promise *will* be cancelled which may result in unexpected behavior. See http://promisekit.org/PromiseKit-2.0-Released/ for cancellation documentation.")
|
||||
}
|
||||
|
||||
return proxy.promise
|
||||
}
|
||||
|
||||
public enum Error: CancellableErrorType {
|
||||
case Cancelled
|
||||
|
||||
public var cancelled: Bool {
|
||||
switch self {
|
||||
case .Cancelled: return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class PMKAlertViewDelegate: NSObject, UIAlertViewDelegate {
|
||||
let (promise, fulfill, reject) = Promise<Int>.pendingPromise()
|
||||
var retainCycle: NSObject?
|
||||
|
||||
@objc func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) {
|
||||
if buttonIndex != alertView.cancelButtonIndex {
|
||||
fulfill(buttonIndex)
|
||||
} else {
|
||||
reject(UIAlertView.Error.Cancelled)
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,80 @@
|
||||
#import <PromiseKit/AnyPromise.h>
|
||||
#import <UIKit/UIView.h>
|
||||
|
||||
// Created by Masafumi Yoshida on 2014/07/11.
|
||||
// Copyright (c) 2014年 DeNA. All rights reserved.
|
||||
|
||||
/**
|
||||
To import the `UIView` category:
|
||||
|
||||
use_frameworks!
|
||||
pod "PromiseKit/UIKit"
|
||||
|
||||
Or `UIKit` is one of the categories imported by the umbrella pod:
|
||||
|
||||
use_frameworks!
|
||||
pod "PromiseKit"
|
||||
|
||||
And then in your sources:
|
||||
|
||||
#import <PromiseKit/PromiseKit.h>
|
||||
*/
|
||||
@interface UIView (PromiseKit)
|
||||
|
||||
/**
|
||||
Animate changes to one or more views using the specified duration.
|
||||
|
||||
@param duration The total duration of the animations, measured in
|
||||
seconds. If you specify a negative value or 0, the changes are made
|
||||
without animating them.
|
||||
|
||||
@param animations A block object containing the changes to commit to the
|
||||
views.
|
||||
|
||||
@return A promise that fulfills with a boolean NSNumber indicating
|
||||
whether or not the animations actually finished.
|
||||
*/
|
||||
+ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations;
|
||||
|
||||
/**
|
||||
Animate changes to one or more views using the specified duration, delay,
|
||||
options, and completion handler.
|
||||
|
||||
@param duration The total duration of the animations, measured in
|
||||
seconds. If you specify a negative value or 0, the changes are made
|
||||
without animating them.
|
||||
|
||||
@param delay The amount of time (measured in seconds) to wait before
|
||||
beginning the animations. Specify a value of 0 to begin the animations
|
||||
immediately.
|
||||
|
||||
@param options A mask of options indicating how you want to perform the
|
||||
animations. For a list of valid constants, see UIViewAnimationOptions.
|
||||
|
||||
@param animations A block object containing the changes to commit to the
|
||||
views.
|
||||
|
||||
@return A promise that fulfills with a boolean NSNumber indicating
|
||||
whether or not the animations actually finished.
|
||||
*/
|
||||
+ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewAnimationOptions)options animations:(void (^)(void))animations;
|
||||
|
||||
/**
|
||||
Performs a view animation using a timing curve corresponding to the
|
||||
motion of a physical spring.
|
||||
|
||||
@return A promise that fulfills with a boolean NSNumber indicating
|
||||
whether or not the animations actually finished.
|
||||
*/
|
||||
+ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay usingSpringWithDamping:(CGFloat)dampingRatio initialSpringVelocity:(CGFloat)velocity options:(UIViewAnimationOptions)options animations:(void (^)(void))animations;
|
||||
|
||||
/**
|
||||
Creates an animation block object that can be used to set up
|
||||
keyframe-based animations for the current view.
|
||||
|
||||
@return A promise that fulfills with a boolean NSNumber indicating
|
||||
whether or not the animations actually finished.
|
||||
*/
|
||||
+ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewKeyframeAnimationOptions)options keyframeAnimations:(void (^)(void))animations;
|
||||
|
||||
@end
|
@ -0,0 +1,64 @@
|
||||
//
|
||||
// UIView+PromiseKit_UIAnimation.m
|
||||
// YahooDenaStudy
|
||||
//
|
||||
// Created by Masafumi Yoshida on 2014/07/11.
|
||||
// Copyright (c) 2014年 DeNA. All rights reserved.
|
||||
//
|
||||
|
||||
#import <PromiseKit/PromiseKit.h>
|
||||
#import "UIView+AnyPromise.h"
|
||||
|
||||
|
||||
#define CopyPasta \
|
||||
NSAssert([NSThread isMainThread], @"UIKit animation must be performed on the main thread"); \
|
||||
\
|
||||
if (![NSThread isMainThread]) { \
|
||||
id error = [NSError errorWithDomain:PMKErrorDomain code:PMKInvalidUsageError userInfo:@{NSLocalizedDescriptionKey: @"Animation was attempted on a background thread"}]; \
|
||||
return [AnyPromise promiseWithValue:error]; \
|
||||
} \
|
||||
\
|
||||
PMKResolver resolve = nil; \
|
||||
AnyPromise *promise = [[AnyPromise alloc] initWithResolver:&resolve];
|
||||
|
||||
|
||||
@implementation UIView (PromiseKit)
|
||||
|
||||
+ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations {
|
||||
return [self promiseWithDuration:duration delay:0 options:0 animations:animations];
|
||||
}
|
||||
|
||||
+ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewAnimationOptions)options animations:(void(^)(void))animations
|
||||
{
|
||||
CopyPasta;
|
||||
|
||||
[UIView animateWithDuration:duration delay:delay options:options animations:animations completion:^(BOOL finished) {
|
||||
resolve(@(finished));
|
||||
}];
|
||||
|
||||
return promise;
|
||||
}
|
||||
|
||||
+ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay usingSpringWithDamping:(CGFloat)dampingRatio initialSpringVelocity:(CGFloat)velocity options:(UIViewAnimationOptions)options animations:(void(^)(void))animations
|
||||
{
|
||||
CopyPasta;
|
||||
|
||||
[UIView animateWithDuration:duration delay:delay usingSpringWithDamping:dampingRatio initialSpringVelocity:velocity options:options animations:animations completion:^(BOOL finished) {
|
||||
resolve(@(finished));
|
||||
}];
|
||||
|
||||
return promise;
|
||||
}
|
||||
|
||||
+ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewKeyframeAnimationOptions)options keyframeAnimations:(void(^)(void))animations
|
||||
{
|
||||
CopyPasta;
|
||||
|
||||
[UIView animateKeyframesWithDuration:duration delay:delay options:options animations:animations completion:^(BOOL finished) {
|
||||
resolve(@(finished));
|
||||
}];
|
||||
|
||||
return promise;
|
||||
}
|
||||
|
||||
@end
|
@ -0,0 +1,48 @@
|
||||
import UIKit.UIView
|
||||
#if !COCOAPODS
|
||||
import PromiseKit
|
||||
#endif
|
||||
|
||||
/**
|
||||
To import the `UIView` category:
|
||||
|
||||
use_frameworks!
|
||||
pod "PromiseKit/UIKit"
|
||||
|
||||
Or `UIKit` is one of the categories imported by the umbrella pod:
|
||||
|
||||
use_frameworks!
|
||||
pod "PromiseKit"
|
||||
|
||||
And then in your sources:
|
||||
|
||||
import PromiseKit
|
||||
*/
|
||||
extension UIView {
|
||||
/**
|
||||
Animate changes to one or more views using the specified duration, delay,
|
||||
options, and completion handler.
|
||||
|
||||
@param duration The total duration of the animations, measured in
|
||||
seconds. If you specify a negative value or 0, the changes are made
|
||||
without animating them.
|
||||
|
||||
@param delay The amount of time (measured in seconds) to wait before
|
||||
beginning the animations. Specify a value of 0 to begin the animations
|
||||
immediately.
|
||||
|
||||
@param options A mask of options indicating how you want to perform the
|
||||
animations. For a list of valid constants, see UIViewAnimationOptions.
|
||||
|
||||
@param animations A block object containing the changes to commit to the
|
||||
views.
|
||||
|
||||
@return A promise that fulfills with a boolean NSNumber indicating
|
||||
whether or not the animations actually finished.
|
||||
*/
|
||||
public class func animate(duration duration: NSTimeInterval = 0.3, delay: NSTimeInterval = 0, options: UIViewAnimationOptions = UIViewAnimationOptions(), animations: () -> Void) -> Promise<Bool> {
|
||||
return Promise { fulfill, _ in
|
||||
self.animateWithDuration(duration, delay: delay, options: options, animations: animations, completion: fulfill)
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,90 @@
|
||||
#import <PromiseKit/AnyPromise.h>
|
||||
#import <UIKit/UIViewController.h>
|
||||
|
||||
/**
|
||||
To import the `UIViewController` category:
|
||||
|
||||
use_frameworks!
|
||||
pod "PromiseKit/UIKit"
|
||||
|
||||
Or `UIKit` is one of the categories imported by the umbrella pod:
|
||||
|
||||
use_frameworks!
|
||||
pod "PromiseKit"
|
||||
|
||||
And then in your sources:
|
||||
|
||||
#import <PromiseKit/PromiseKit.h>
|
||||
*/
|
||||
@interface UIViewController (PromiseKit)
|
||||
|
||||
/**
|
||||
Presents a view controller modally.
|
||||
|
||||
If the view controller is one of the following:
|
||||
|
||||
- MFMailComposeViewController
|
||||
- MFMessageComposeViewController
|
||||
- UIImagePickerController
|
||||
- SLComposeViewController
|
||||
|
||||
Then PromiseKit presents the view controller returning a promise that is
|
||||
resolved as per the documentation for those classes. Eg. if you present a
|
||||
`UIImagePickerController` the view controller will be presented for you
|
||||
and the returned promise will resolve with the media the user selected.
|
||||
|
||||
[self promiseViewController:[MFMailComposeViewController new] animated:YES completion:nil].then(^{
|
||||
//…
|
||||
});
|
||||
|
||||
Otherwise PromiseKit expects your view controller to implement a
|
||||
`promise` property. This promise will be returned from this method and
|
||||
presentation and dismissal of the presented view controller will be
|
||||
managed for you.
|
||||
|
||||
@interface MyViewController: UIViewController
|
||||
@property (readonly) AnyPromise *promise;
|
||||
@end
|
||||
|
||||
@implementation MyViewController {
|
||||
PMKResolver resolve;
|
||||
}
|
||||
|
||||
- (void)viewDidLoad {
|
||||
_promise = [AnyPromise promiseWithResolver:&resolve];
|
||||
}
|
||||
|
||||
- (void)later {
|
||||
resolve(@"some fulfilled value");
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
|
||||
[self promiseViewController:[MyViewController new] aniamted:YES completion:nil].then(^(id value){
|
||||
// value == @"some fulfilled value"
|
||||
});
|
||||
|
||||
@return A promise that can be resolved by the presented view controller.
|
||||
*/
|
||||
- (AnyPromise *)promiseViewController:(UIViewController *)vc animated:(BOOL)animated completion:(void (^)(void))block;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
|
||||
@interface UIViewController (PMKUnavailable)
|
||||
|
||||
#define PMKRationale \
|
||||
"The promiseViewController system has been rennovated: the fullfil and " \
|
||||
"reject category methods have been removed due to runtime safety " \
|
||||
"concerns and instead you should implement a -promise property on your " \
|
||||
"view controller subclass. @see promiseViewController:animated:completion:"
|
||||
|
||||
- (void)fulfill:(id)value __attribute__((unavailable(PMKRationale)));
|
||||
- (void)reject:(NSError *)value __attribute__((unavailable(PMKRationale)));
|
||||
|
||||
#undef PMKRationale
|
||||
|
||||
@end
|
@ -0,0 +1,130 @@
|
||||
#import <PromiseKit/PromiseKit.h>
|
||||
#import <UIKit/UINavigationController.h>
|
||||
#import <UIKit/UIImagePickerController.h>
|
||||
#import "UIViewController+AnyPromise.h"
|
||||
|
||||
@interface PMKGenericDelegate : NSObject <UIImagePickerControllerDelegate, UINavigationControllerDelegate> {
|
||||
@public
|
||||
PMKResolver resolve;
|
||||
}
|
||||
+ (instancetype)delegateWithPromise:(AnyPromise **)promise;
|
||||
@end
|
||||
|
||||
|
||||
@implementation UIViewController (PromiseKit)
|
||||
|
||||
- (AnyPromise *)promiseViewController:(UIViewController *)vc animated:(BOOL)animated completion:(void (^)(void))block
|
||||
{
|
||||
id vc2present = vc;
|
||||
AnyPromise *promise = nil;
|
||||
|
||||
if ([vc isKindOfClass:NSClassFromString(@"MFMailComposeViewController")]) {
|
||||
PMKGenericDelegate *delegate = [PMKGenericDelegate delegateWithPromise:&promise];
|
||||
[vc setValue:delegate forKey:@"mailComposeDelegate"];
|
||||
}
|
||||
else if ([vc isKindOfClass:NSClassFromString(@"MFMessageComposeViewController")]) {
|
||||
PMKGenericDelegate *delegate = [PMKGenericDelegate delegateWithPromise:&promise];
|
||||
[vc setValue:delegate forKey:@"messageComposeDelegate"];
|
||||
}
|
||||
else if ([vc isKindOfClass:NSClassFromString(@"UIImagePickerController")]) {
|
||||
PMKGenericDelegate *delegate = [PMKGenericDelegate delegateWithPromise:&promise];
|
||||
((UIImagePickerController *)vc).delegate = delegate;
|
||||
}
|
||||
else if ([vc isKindOfClass:NSClassFromString(@"SLComposeViewController")]) {
|
||||
PMKResolver resolve;
|
||||
promise = [[AnyPromise alloc] initWithResolver:&resolve];
|
||||
[vc setValue:^(NSInteger result){
|
||||
if (result == 0) {
|
||||
resolve([NSError cancelledError]);
|
||||
} else {
|
||||
resolve(@(result));
|
||||
}
|
||||
} forKey:@"completionHandler"];
|
||||
}
|
||||
else if ([vc isKindOfClass:[UINavigationController class]])
|
||||
vc = [(id)vc viewControllers].firstObject;
|
||||
|
||||
if (!vc) {
|
||||
id userInfo = @{NSLocalizedDescriptionKey: @"nil or effective nil passed to promiseViewController"};
|
||||
id err = [NSError errorWithDomain:PMKErrorDomain code:PMKInvalidUsageError userInfo:userInfo];
|
||||
return [AnyPromise promiseWithValue:err];
|
||||
}
|
||||
|
||||
if (!promise) {
|
||||
if (![vc respondsToSelector:NSSelectorFromString(@"promise")]) {
|
||||
id userInfo = @{NSLocalizedDescriptionKey: @"ViewController is not promisable"};
|
||||
id err = [NSError errorWithDomain:PMKErrorDomain code:PMKInvalidUsageError userInfo:userInfo];
|
||||
return [AnyPromise promiseWithValue:err];
|
||||
}
|
||||
|
||||
promise = [vc valueForKey:@"promise"];
|
||||
|
||||
if (![promise isKindOfClass:[AnyPromise class]]) {
|
||||
id userInfo = @{NSLocalizedDescriptionKey: @"The promise property is nil or not of type AnyPromise"};
|
||||
id err = [NSError errorWithDomain:PMKErrorDomain code:PMKInvalidUsageError userInfo:userInfo];
|
||||
return [AnyPromise promiseWithValue:err];
|
||||
}
|
||||
}
|
||||
|
||||
if (!promise.pending)
|
||||
return promise;
|
||||
|
||||
[self presentViewController:vc2present animated:animated completion:block];
|
||||
|
||||
promise.finally(^{
|
||||
//TODO can we be more specific?
|
||||
[self dismissViewControllerAnimated:animated completion:nil];
|
||||
});
|
||||
|
||||
return promise;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
|
||||
@implementation PMKGenericDelegate {
|
||||
id retainCycle;
|
||||
}
|
||||
|
||||
+ (instancetype)delegateWithPromise:(AnyPromise **)promise; {
|
||||
PMKGenericDelegate *d = [PMKGenericDelegate new];
|
||||
d->retainCycle = d;
|
||||
*promise = [[AnyPromise alloc] initWithResolver:&d->resolve];
|
||||
return d;
|
||||
}
|
||||
|
||||
- (void)mailComposeController:(id)controller didFinishWithResult:(int)result error:(NSError *)error {
|
||||
if (error != nil) {
|
||||
resolve(error);
|
||||
} else if (result == 0) {
|
||||
resolve([NSError cancelledError]);
|
||||
} else {
|
||||
resolve(@(result));
|
||||
}
|
||||
retainCycle = nil;
|
||||
}
|
||||
|
||||
- (void)messageComposeViewController:(id)controller didFinishWithResult:(int)result {
|
||||
if (result == 2) {
|
||||
id userInfo = @{NSLocalizedDescriptionKey: @"The user’s attempt to save or send the message was unsuccessful."};
|
||||
id error = [NSError errorWithDomain:PMKErrorDomain code:PMKOperationFailed userInfo:userInfo];
|
||||
resolve(error);
|
||||
} else {
|
||||
resolve(@(result));
|
||||
}
|
||||
retainCycle = nil;
|
||||
}
|
||||
|
||||
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
|
||||
id img = info[UIImagePickerControllerEditedImage] ?: info[UIImagePickerControllerOriginalImage];
|
||||
resolve(PMKManifold(img, info));
|
||||
retainCycle = nil;
|
||||
}
|
||||
|
||||
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
|
||||
resolve([NSError cancelledError]);
|
||||
retainCycle = nil;
|
||||
}
|
||||
|
||||
@end
|
@ -0,0 +1,136 @@
|
||||
import Foundation.NSError
|
||||
import UIKit
|
||||
#if !COCOAPODS
|
||||
import PromiseKit
|
||||
#endif
|
||||
|
||||
/**
|
||||
To import this `UIViewController` category:
|
||||
|
||||
use_frameworks!
|
||||
pod "PromiseKit/UIKit"
|
||||
|
||||
Or `UIKit` is one of the categories imported by the umbrella pod:
|
||||
|
||||
use_frameworks!
|
||||
pod "PromiseKit"
|
||||
|
||||
And then in your sources:
|
||||
|
||||
import PromiseKit
|
||||
*/
|
||||
extension UIViewController {
|
||||
|
||||
public enum Error: ErrorType {
|
||||
case NavigationControllerEmpty
|
||||
case NoImageFound
|
||||
case NotPromisable
|
||||
case NotGenericallyPromisable
|
||||
case NilPromisable
|
||||
}
|
||||
|
||||
public func promiseViewController<T>(vc: UIViewController, animated: Bool = true, completion: (() -> Void)? = nil) -> Promise<T> {
|
||||
|
||||
let p: Promise<T> = promise(vc)
|
||||
if p.pending {
|
||||
presentViewController(vc, animated: animated, completion: completion)
|
||||
p.always {
|
||||
self.dismissViewControllerAnimated(animated, completion: nil)
|
||||
}
|
||||
}
|
||||
|
||||
return p
|
||||
}
|
||||
|
||||
public func promiseViewController<T>(nc: UINavigationController, animated: Bool = true, completion:(()->Void)? = nil) -> Promise<T> {
|
||||
if let vc = nc.viewControllers.first {
|
||||
let p: Promise<T> = promise(vc)
|
||||
if p.pending {
|
||||
presentViewController(nc, animated: animated, completion: completion)
|
||||
p.always {
|
||||
self.dismissViewControllerAnimated(animated, completion: nil)
|
||||
}
|
||||
}
|
||||
return p
|
||||
} else {
|
||||
return Promise(error: Error.NavigationControllerEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
public func promiseViewController(vc: UIImagePickerController, animated: Bool = true, completion: (() -> Void)? = nil) -> Promise<UIImage> {
|
||||
let proxy = UIImagePickerControllerProxy()
|
||||
vc.delegate = proxy
|
||||
vc.mediaTypes = ["public.image"] // this promise can only resolve with a UIImage
|
||||
presentViewController(vc, animated: animated, completion: completion)
|
||||
return proxy.promise.then(on: zalgo) { info -> UIImage in
|
||||
if let img = info[UIImagePickerControllerEditedImage] as? UIImage {
|
||||
return img
|
||||
}
|
||||
if let img = info[UIImagePickerControllerOriginalImage] as? UIImage {
|
||||
return img
|
||||
}
|
||||
throw Error.NoImageFound
|
||||
}.always {
|
||||
self.dismissViewControllerAnimated(animated, completion: nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc public protocol Promisable {
|
||||
/**
|
||||
Provide a promise for promiseViewController here.
|
||||
|
||||
The resulting property must be annotated with @objc.
|
||||
|
||||
Obviously return a Promise<T>. There is an issue with generics and Swift and
|
||||
protocols currently so we couldn't specify that.
|
||||
*/
|
||||
var promise: AnyObject! { get }
|
||||
}
|
||||
|
||||
private func promise<T>(vc: UIViewController) -> Promise<T> {
|
||||
if !vc.conformsToProtocol(Promisable) {
|
||||
return Promise(error: UIViewController.Error.NotPromisable)
|
||||
} else if let promise = vc.valueForKeyPath("promise") as? Promise<T> {
|
||||
return promise
|
||||
} else if let _: AnyObject = vc.valueForKeyPath("promise") {
|
||||
return Promise(error: UIViewController.Error.NotGenericallyPromisable)
|
||||
} else {
|
||||
return Promise(error: UIViewController.Error.NilPromisable)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// internal scope because used by ALAssetsLibrary extension
|
||||
@objc class UIImagePickerControllerProxy: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
|
||||
let (promise, fulfill, reject) = Promise<[NSObject : AnyObject]>.pendingPromise()
|
||||
var retainCycle: AnyObject?
|
||||
|
||||
required override init() {
|
||||
super.init()
|
||||
retainCycle = self
|
||||
}
|
||||
|
||||
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
|
||||
fulfill(info)
|
||||
retainCycle = nil
|
||||
}
|
||||
|
||||
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
|
||||
reject(UIImagePickerController.Error.Cancelled)
|
||||
retainCycle = nil
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
extension UIImagePickerController {
|
||||
public enum Error: CancellableErrorType {
|
||||
case Cancelled
|
||||
|
||||
public var cancelled: Bool {
|
||||
switch self {
|
||||
case .Cancelled: return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
120
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/README.markdown
generated
Normal file
120
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/README.markdown
generated
Normal file
@ -0,0 +1,120 @@
|
||||
![PromiseKit](http://methylblue.com/junk/PMKBanner.png)
|
||||
|
||||
Modern development is highly asynchronous: isn’t it about time we had tools that made programming asynchronously powerful, easy and delightful?
|
||||
|
||||
```swift
|
||||
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
|
||||
|
||||
when(fetchImage(), getLocation()).then { image, location in
|
||||
self.imageView.image = image;
|
||||
self.label.text = "Buy your cat a house in \(location)"
|
||||
}.always {
|
||||
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
|
||||
}.error { error in
|
||||
UIAlertView(…).show()
|
||||
}
|
||||
```
|
||||
|
||||
PromiseKit is a thoughtful and complete implementation of promises for iOS and OS X with first-class support for **both** Objective-C *and* Swift.
|
||||
|
||||
[![Join the chat at https://gitter.im/mxcl/PromiseKit](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/mxcl/PromiseKit?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) ![](https://img.shields.io/cocoapods/v/PromiseKit.svg?label=Current%20Release) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg)](https://github.com/Carthage/Carthage)
|
||||
|
||||
|
||||
# Which PromiseKit Should I Use?
|
||||
|
||||
If you are writing a library, **use PromiseKit 1.6**. This is because PromiseKit > 2 breaks everytime Swift changes. While Swift is in flux it is not feasible to depend on a library that will break every time Xcode updates.
|
||||
|
||||
If you are making an app then PromiseKit 3 is the best PromiseKit, you may have to make some fixes when Xcode updates, but probably you will be OK as long as you update PromiseKit when Xcode updates.
|
||||
|
||||
PromiseKit 1 and 3 can be installed in parallel if necessary, but CocoaPods will not support this.
|
||||
|
||||
Once Swift becomes ABI or API stable we can all just move to the latest PromiseKit.
|
||||
|
||||
Thus we intend to support PromiseKit 1.x for longer than expected.
|
||||
|
||||
|
||||
# PromiseKit 3
|
||||
|
||||
In Swift 2.0 `catch` and `defer` became reserved keywords mandating we rename our functions with these names. This forced a major semantic version change on PromiseKit and thus we took the opportunity to make other minor (source compatability breaking) improvements.
|
||||
|
||||
Thus if you cannot afford to adapt to PromiseKit 3 but still want to use Xcode-7.0/Swift-2.0 we provide a [minimal changes branch] where `catch` and `defer` are renamed `catch_` and `defer_` and all other changes are the bare minimum to make PromiseKit 2 compile against Swift 2.
|
||||
|
||||
If you still are using Xcode 6 and Swift 1.2 then use PromiseKit 2.
|
||||
|
||||
[minimal changes branch]: https://github.com/mxcl/PromiseKit/tree/swift-2.0-minimal-changes
|
||||
|
||||
# PromiseKit 2
|
||||
|
||||
PromiseKit 2 contains many interesting and important additions. Check out our our [release announcement](http://promisekit.org/PromiseKit-2.0-Released/) for full details.
|
||||
|
||||
# PromiseKit 1
|
||||
|
||||
The original, nice to use with Objective-C, less nice to use with Swift, hence PromiseKit 2.
|
||||
|
||||
|
||||
# How To Get Started
|
||||
|
||||
* Check out the complete, comprehensive [PromiseKit documentation](http://promisekit.org).
|
||||
* Read the [API documentation](http://cocoadocs.org/docsets/PromiseKit/), (note the documentation is not 100% currently as CocoaDocs is not good with Swift, you may have better luck reading the comments in the sources).
|
||||
* [Integrate](http://promisekit.org/getting-started) promises into your existing projects.
|
||||
|
||||
## Quick Start Guide
|
||||
|
||||
### CocoaPods
|
||||
|
||||
```ruby
|
||||
use_frameworks!
|
||||
|
||||
pod "PromiseKit", "~> 2.0"
|
||||
```
|
||||
|
||||
### Carthage
|
||||
```ruby
|
||||
github "mxcl/PromiseKit" ~> 2.0
|
||||
```
|
||||
|
||||
*Note*: In order to avoid linking nearly all system frameworks with PromiseKit, the convenience categories have not been included with the Carthage framework . You must manually copy the categories you need in from the Carthage checkout.
|
||||
|
||||
### Standalone Distributions
|
||||
|
||||
* [iOS 8 & OS X 10.9 Frameworks](https://github.com/mxcl/PromiseKit/releases/download/2.2.2/PromiseKit-2.2.2.zip) (Binaries)
|
||||
|
||||
*Please note*, the preferred way to integrate PromiseKit is CocoaPods or Carthage.
|
||||
|
||||
### iOS 7 And Below
|
||||
|
||||
Neither CocoaPods or Carthage will install PromiseKit 2 for an iOS 7 target. Your options are:
|
||||
|
||||
1. `pod "PromiseKit", "~> 1.5"` †‡
|
||||
2. Use our [iOS 7 EZ-Bake](https://github.com/PromiseKit/EZiOS7)
|
||||
3. Download our pre-built static framework (coming soon!)
|
||||
|
||||
† There is no Swift support with PromiseKit 1.x installed via CocoaPods.<br>‡ PromiseKit 1.x will work as far back as iOS 5 if required.
|
||||
|
||||
|
||||
# Donations
|
||||
|
||||
PromiseKit is hundreds of hours of work almost completely by just me: [Max Howell](https://twitter.com/mxcl). I thoroughly enjoyed making PromiseKit, but nevertheless if you have found it useful then your bitcoin will give me a warm fuzzy feeling from my head right down to my toes: 1JDbV5zuym3jFw4kBCc5Z758maUD8e4dKR.
|
||||
|
||||
|
||||
# License
|
||||
|
||||
Copyright 2015, 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.
|
47
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise+Private.h
generated
Normal file
47
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise+Private.h
generated
Normal file
@ -0,0 +1,47 @@
|
||||
@import Foundation.NSError;
|
||||
@import Foundation.NSPointerArray;
|
||||
|
||||
#if TARGET_OS_IPHONE
|
||||
#define NSPointerArrayMake(N) ({ \
|
||||
NSPointerArray *aa = [NSPointerArray strongObjectsPointerArray]; \
|
||||
aa.count = N; \
|
||||
aa; \
|
||||
})
|
||||
#else
|
||||
static inline NSPointerArray * __nonnull NSPointerArrayMake(NSUInteger count) {
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
|
||||
NSPointerArray *aa = [[NSPointerArray class] respondsToSelector:@selector(strongObjectsPointerArray)]
|
||||
? [NSPointerArray strongObjectsPointerArray]
|
||||
: [NSPointerArray pointerArrayWithStrongObjects];
|
||||
#pragma clang diagnostic pop
|
||||
aa.count = count;
|
||||
return aa;
|
||||
}
|
||||
#endif
|
||||
|
||||
#define IsError(o) [o isKindOfClass:[NSError class]]
|
||||
#define IsPromise(o) [o isKindOfClass:[AnyPromise class]]
|
||||
|
||||
#import "AnyPromise.h"
|
||||
|
||||
@interface AnyPromise (Swift)
|
||||
- (void)pipe:(void (^ __nonnull)(id __nonnull))body;
|
||||
- (AnyPromise * __nonnull)initWithBridge:(void (^ __nonnull)(PMKResolver __nonnull))resolver;
|
||||
@end
|
||||
|
||||
extern NSError * __nullable PMKProcessUnhandledException(id __nonnull thrown);
|
||||
|
||||
// TODO really this is not valid, we should instead nest the errors with NSUnderlyingError
|
||||
// since a special error subclass may be being used and we may not set it up correctly
|
||||
// with our copy
|
||||
#define NSErrorSupplement(_err, supplements) ({ \
|
||||
NSError *err = _err; \
|
||||
id userInfo = err.userInfo.mutableCopy ?: [NSMutableArray new]; \
|
||||
[userInfo addEntriesFromDictionary:supplements]; \
|
||||
[[[err class] alloc] initWithDomain:err.domain code:err.code userInfo:userInfo]; \
|
||||
})
|
||||
|
||||
@interface NSError (PMKUnhandledErrorHandler)
|
||||
- (void)pmk_consume;
|
||||
@end
|
268
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.h
generated
Normal file
268
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.h
generated
Normal file
@ -0,0 +1,268 @@
|
||||
#import <dispatch/object.h>
|
||||
#import <dispatch/queue.h>
|
||||
#import <Foundation/NSObject.h>
|
||||
#import "Umbrella.h"
|
||||
|
||||
typedef void (^PMKResolver)(id __nullable);
|
||||
|
||||
typedef NS_ENUM(NSInteger, PMKCatchPolicy) {
|
||||
PMKCatchPolicyAllErrors,
|
||||
PMKCatchPolicyAllErrorsExceptCancellation
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
@see AnyPromise.swift
|
||||
*/
|
||||
@interface AnyPromise (objc)
|
||||
|
||||
/**
|
||||
The provided block is executed when its receiver is resolved.
|
||||
|
||||
If you provide a block that takes a parameter, the value of the receiver will be passed as that parameter.
|
||||
|
||||
@param block The block that is executed when the receiver is resolved.
|
||||
|
||||
[NSURLConnection GET:url].then(^(NSData *data){
|
||||
// do something with data
|
||||
});
|
||||
|
||||
@return A new promise that is resolved with the value returned from the provided block. For example:
|
||||
|
||||
[NSURLConnection GET:url].then(^(NSData *data){
|
||||
return data.length;
|
||||
}).then(^(NSNumber *number){
|
||||
//…
|
||||
});
|
||||
|
||||
@warning *Important* The block passed to `then` may take zero, one, two or three arguments, and return an object or return nothing. This flexibility is why the method signature for then is `id`, which means you will not get completion for the block parameter, and must type it yourself. It is safe to type any block syntax here, so to start with try just: `^{}`.
|
||||
|
||||
@warning *Important* If an exception is thrown inside your block, or you return an `NSError` object the next `Promise` will be rejected. See `catch` for documentation on error handling.
|
||||
|
||||
@warning *Important* `then` is always executed on the main queue.
|
||||
|
||||
@see thenOn
|
||||
@see thenInBackground
|
||||
*/
|
||||
- (AnyPromise * __nonnull (^ __nonnull)(id __nonnull))then;
|
||||
|
||||
|
||||
/**
|
||||
The provided block is executed on the default queue when the receiver is fulfilled.
|
||||
|
||||
This method is provided as a convenience for `thenOn`.
|
||||
|
||||
@see then
|
||||
@see thenOn
|
||||
*/
|
||||
- (AnyPromise * __nonnull(^ __nonnull)(id __nonnull))thenInBackground;
|
||||
|
||||
/**
|
||||
The provided block is executed on the dispatch queue of your choice when the receiver is fulfilled.
|
||||
|
||||
@see then
|
||||
@see thenInBackground
|
||||
*/
|
||||
- (AnyPromise * __nonnull(^ __nonnull)(dispatch_queue_t __nonnull, id __nonnull))thenOn;
|
||||
|
||||
#ifndef __cplusplus
|
||||
/**
|
||||
The provided block is executed when the receiver is rejected.
|
||||
|
||||
Provide a block of form `^(NSError *){}` or simply `^{}`. The parameter has type `id` to give you the freedom to choose either.
|
||||
|
||||
The provided block always runs on the main queue.
|
||||
|
||||
@warning *Note* Cancellation errors are not caught.
|
||||
|
||||
@warning *Note* Since catch is a c++ keyword, this method is not availble in Objective-C++ files. Instead use catchWithPolicy.
|
||||
|
||||
@see catchWithPolicy
|
||||
*/
|
||||
- (AnyPromise * __nonnull(^ __nonnull)(id __nonnull))catch;
|
||||
#endif
|
||||
|
||||
/**
|
||||
The provided block is executed when the receiver is rejected with the specified policy.
|
||||
|
||||
@param policy The policy with which to catch. Either for all errors, or all errors *except* cancellation errors.
|
||||
|
||||
@see catch
|
||||
*/
|
||||
- (AnyPromise * __nonnull(^ __nonnull)(PMKCatchPolicy, id __nonnull))catchWithPolicy;
|
||||
|
||||
/**
|
||||
The provided block is executed when the receiver is resolved.
|
||||
|
||||
The provided block always runs on the main queue.
|
||||
|
||||
@see finallyOn
|
||||
*/
|
||||
- (AnyPromise * __nonnull(^ __nonnull)(dispatch_block_t __nonnull))finally;
|
||||
|
||||
/**
|
||||
The provided block is executed on the dispatch queue of your choice when the receiver is resolved.
|
||||
|
||||
@see finally
|
||||
*/
|
||||
- (AnyPromise * __nonnull(^ __nonnull)(dispatch_queue_t __nonnull, dispatch_block_t __nonnull))finallyOn;
|
||||
|
||||
/**
|
||||
The value of the asynchronous task this promise represents.
|
||||
|
||||
A promise has `nil` value if the asynchronous task it represents has not
|
||||
finished. If the value is `nil` the promise is still `pending`.
|
||||
|
||||
@warning *Note* Our Swift variant’s value property returns nil if the
|
||||
promise is rejected where AnyPromise will return the error object. This
|
||||
fits with the pattern where AnyPromise is not strictly typed and is more
|
||||
dynamic, but you should be aware of the distinction.
|
||||
|
||||
@return If `resolved`, the object that was used to resolve this promise;
|
||||
if `pending`, nil.
|
||||
*/
|
||||
- (id __nullable)value;
|
||||
|
||||
/**
|
||||
Creates a resolved promise.
|
||||
|
||||
When developing your own promise systems, it is ocassionally useful to be able to return an already resolved promise.
|
||||
|
||||
@param value The value with which to resolve this promise. Passing an `NSError` will cause the promise to be rejected, otherwise the promise will be fulfilled.
|
||||
|
||||
@return A resolved promise.
|
||||
*/
|
||||
+ (instancetype __nonnull)promiseWithValue:(id __nullable)value;
|
||||
|
||||
/**
|
||||
Create a new promise that resolves with the provided block.
|
||||
|
||||
Use this method when wrapping asynchronous code that does *not* use
|
||||
promises so that this code can be used in promise chains.
|
||||
|
||||
If `resolve` is called with an `NSError` object, the promise is
|
||||
rejected, otherwise the promise is fulfilled.
|
||||
|
||||
Don’t use this method if you already have promises! Instead, just
|
||||
return your promise.
|
||||
|
||||
Should you need to fulfill a promise but have no sensical value to use:
|
||||
your promise is a `void` promise: fulfill with `nil`.
|
||||
|
||||
The block you pass is executed immediately on the calling thread.
|
||||
|
||||
@param block The provided block is immediately executed, inside the block
|
||||
call `resolve` to resolve this promise and cause any attached handlers to
|
||||
execute. If you are wrapping a delegate-based system, we recommend
|
||||
instead to use: promiseWithResolver:
|
||||
|
||||
@return A new promise.
|
||||
|
||||
@warning *Important* Resolving a promise with `nil` fulfills it.
|
||||
|
||||
@see http://promisekit.org/sealing-your-own-promises/
|
||||
@see http://promisekit.org/wrapping-delegation/
|
||||
*/
|
||||
+ (instancetype __nonnull)promiseWithResolverBlock:(void (^ __nonnull)(PMKResolver __nonnull resolve))resolverBlock;
|
||||
|
||||
/**
|
||||
Create a new promise with an associated resolver.
|
||||
|
||||
Use this method when wrapping asynchronous code that does *not* use
|
||||
promises so that this code can be used in promise chains. Generally,
|
||||
prefer resolverWithBlock: as the resulting code is more elegant.
|
||||
|
||||
PMKResolver resolve;
|
||||
AnyPromise *promise = [AnyPromise promiseWithResolver:&resolve];
|
||||
|
||||
// later
|
||||
resolve(@"foo");
|
||||
|
||||
@param resolver A reference to a block pointer of PMKResolver type.
|
||||
You can then call your resolver to resolve this promise.
|
||||
|
||||
@return A new promise.
|
||||
|
||||
@warning *Important* The resolver strongly retains the promise.
|
||||
|
||||
@see promiseWithResolverBlock:
|
||||
*/
|
||||
- (instancetype __nonnull)initWithResolver:(PMKResolver __strong __nonnull * __nonnull)resolver;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
|
||||
@interface AnyPromise (Unavailable)
|
||||
|
||||
- (instancetype __nonnull)init __attribute__((unavailable("It is illegal to create an unresolvable promise.")));
|
||||
+ (instancetype __nonnull)new __attribute__((unavailable("It is illegal to create an unresolvable promise.")));
|
||||
|
||||
@end
|
||||
|
||||
|
||||
|
||||
typedef void (^PMKAdapter)(id __nullable, NSError * __nullable);
|
||||
typedef void (^PMKIntegerAdapter)(NSInteger, NSError * __nullable);
|
||||
typedef void (^PMKBooleanAdapter)(BOOL, NSError * __nullable);
|
||||
|
||||
@interface AnyPromise (Adapters)
|
||||
|
||||
/**
|
||||
Create a new promise by adapting an existing asynchronous system.
|
||||
|
||||
The pattern of a completion block that passes two parameters, the first
|
||||
the result and the second an `NSError` object is so common that we
|
||||
provide this convenience adapter to make wrapping such systems more
|
||||
elegant.
|
||||
|
||||
return [PMKPromise promiseWithAdapter:^(PMKAdapter adapter){
|
||||
PFQuery *query = [PFQuery …];
|
||||
[query findObjectsInBackgroundWithBlock:adapter];
|
||||
}];
|
||||
|
||||
@warning *Important* If both parameters are nil, the promise fulfills,
|
||||
if both are non-nil the promise rejects. This is per the convention.
|
||||
|
||||
@see http://promisekit.org/sealing-your-own-promises/
|
||||
*/
|
||||
+ (instancetype __nonnull)promiseWithAdapterBlock:(void (^ __nonnull)(PMKAdapter __nonnull adapter))block;
|
||||
|
||||
/**
|
||||
Create a new promise by adapting an existing asynchronous system.
|
||||
|
||||
Adapts asynchronous systems that complete with `^(NSInteger, NSError *)`.
|
||||
NSInteger will cast to enums provided the enum has been wrapped with
|
||||
`NS_ENUM`. All of Apple’s enums are, so if you find one that hasn’t you
|
||||
may need to make a pull-request.
|
||||
|
||||
@see promiseWithAdapter
|
||||
*/
|
||||
+ (instancetype __nonnull)promiseWithIntegerAdapterBlock:(void (^ __nonnull)(PMKIntegerAdapter __nonnull adapter))block;
|
||||
|
||||
/**
|
||||
Create a new promise by adapting an existing asynchronous system.
|
||||
|
||||
Adapts asynchronous systems that complete with `^(BOOL, NSError *)`.
|
||||
|
||||
@see promiseWithAdapter
|
||||
*/
|
||||
+ (instancetype __nonnull)promiseWithBooleanAdapterBlock:(void (^ __nonnull)(PMKBooleanAdapter __nonnull adapter))block;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
|
||||
/**
|
||||
Whenever resolving a promise you may resolve with a tuple, eg.
|
||||
returning from a `then` or `catch` handler or resolving a new promise.
|
||||
|
||||
Consumers of your Promise are not compelled to consume any arguments and
|
||||
in fact will often only consume the first parameter. Thus ensure the
|
||||
order of parameters is: from most-important to least-important.
|
||||
|
||||
Currently PromiseKit limits you to THREE parameters to the manifold.
|
||||
*/
|
||||
#define PMKManifold(...) __PMKManifold(__VA_ARGS__, 3, 2, 1)
|
||||
#define __PMKManifold(_1, _2, _3, N, ...) __PMKArrayWithCount(N, _1, _2, _3)
|
||||
extern id __nonnull __PMKArrayWithCount(NSUInteger, ...);
|
154
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.m
generated
Normal file
154
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.m
generated
Normal file
@ -0,0 +1,154 @@
|
||||
#import "AnyPromise.h"
|
||||
#import "AnyPromise+Private.h"
|
||||
@import Foundation.NSKeyValueCoding;
|
||||
#import "PMKCallVariadicBlock.m"
|
||||
|
||||
NSString *const PMKErrorDomain = @"PMKErrorDomain";
|
||||
|
||||
|
||||
@implementation AnyPromise (objc)
|
||||
|
||||
- (instancetype)initWithResolver:(PMKResolver __strong *)resolver {
|
||||
return [self initWithBridge:^(PMKResolver resolve){
|
||||
*resolver = resolve;
|
||||
}];
|
||||
}
|
||||
|
||||
+ (instancetype)promiseWithResolverBlock:(void (^)(PMKResolver))resolveBlock {
|
||||
return [[self alloc] initWithBridge:resolveBlock];
|
||||
}
|
||||
|
||||
+ (instancetype)promiseWithValue:(id)value {
|
||||
return [[self alloc] initWithBridge:^(PMKResolver resolve){
|
||||
resolve(value);
|
||||
}];
|
||||
}
|
||||
|
||||
static inline AnyPromise *AnyPromiseWhen(AnyPromise *when, void(^then)(id, PMKResolver)) {
|
||||
return [[AnyPromise alloc] initWithBridge:^(PMKResolver resolve){
|
||||
[when pipe:^(id obj){
|
||||
then(obj, resolve);
|
||||
}];
|
||||
}];
|
||||
}
|
||||
|
||||
static inline AnyPromise *__then(AnyPromise *self, dispatch_queue_t queue, id block) {
|
||||
return AnyPromiseWhen(self, ^(id obj, PMKResolver resolve) {
|
||||
if (IsError(obj)) {
|
||||
resolve(obj);
|
||||
} else dispatch_async(queue, ^{
|
||||
resolve(PMKCallVariadicBlock(block, obj));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
- (AnyPromise *(^)(id))then {
|
||||
return ^(id block) {
|
||||
return __then(self, dispatch_get_main_queue(), block);
|
||||
};
|
||||
}
|
||||
|
||||
- (AnyPromise *(^)(dispatch_queue_t, id))thenOn {
|
||||
return ^(dispatch_queue_t queue, id block) {
|
||||
return __then(self, queue, block);
|
||||
};
|
||||
}
|
||||
|
||||
- (AnyPromise *(^)(id))thenInBackground {
|
||||
return ^(id block) {
|
||||
return __then(self, dispatch_get_global_queue(0, 0), block);
|
||||
};
|
||||
}
|
||||
|
||||
static inline AnyPromise *__catch(AnyPromise *self, BOOL includeCancellation, id block) {
|
||||
return AnyPromiseWhen(self, ^(id obj, PMKResolver resolve) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
if (IsError(obj) && (includeCancellation || ![obj cancelled])) {
|
||||
[obj pmk_consume];
|
||||
resolve(PMKCallVariadicBlock(block, obj));
|
||||
} else {
|
||||
resolve(obj);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
- (AnyPromise *(^)(id))catch {
|
||||
return ^(id block) {
|
||||
return __catch(self, NO, block);
|
||||
};
|
||||
}
|
||||
|
||||
- (AnyPromise *(^)(PMKCatchPolicy, id))catchWithPolicy {
|
||||
return ^(PMKCatchPolicy policy, id block) {
|
||||
return __catch(self, policy == PMKCatchPolicyAllErrors, block);
|
||||
};
|
||||
}
|
||||
|
||||
static inline AnyPromise *__finally(AnyPromise *self, dispatch_queue_t queue, dispatch_block_t block) {
|
||||
return AnyPromiseWhen(self, ^(id obj, PMKResolver resolve) {
|
||||
dispatch_async(queue, ^{
|
||||
block();
|
||||
resolve(obj);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
- (AnyPromise *(^)(dispatch_block_t))finally {
|
||||
return ^(dispatch_block_t block) {
|
||||
return __finally(self, dispatch_get_main_queue(), block);
|
||||
};
|
||||
}
|
||||
|
||||
- (AnyPromise *(^)(dispatch_queue_t, dispatch_block_t))finallyOn {
|
||||
return ^(dispatch_queue_t queue, dispatch_block_t block) {
|
||||
return __finally(self, queue, block);
|
||||
};
|
||||
}
|
||||
|
||||
- (id)value {
|
||||
id result = [self valueForKey:@"__value"];
|
||||
return [result isKindOfClass:[PMKArray class]]
|
||||
? result[0]
|
||||
: result;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
|
||||
@implementation AnyPromise (Adapters)
|
||||
|
||||
+ (instancetype)promiseWithAdapterBlock:(void (^)(PMKAdapter))block {
|
||||
return [self promiseWithResolverBlock:^(PMKResolver resolve) {
|
||||
block(^(id value, id error){
|
||||
resolve(error ?: value);
|
||||
});
|
||||
}];
|
||||
}
|
||||
|
||||
+ (instancetype)promiseWithIntegerAdapterBlock:(void (^)(PMKIntegerAdapter))block {
|
||||
return [self promiseWithResolverBlock:^(PMKResolver resolve) {
|
||||
block(^(NSInteger value, id error){
|
||||
if (error) {
|
||||
resolve(error);
|
||||
} else {
|
||||
resolve(@(value));
|
||||
}
|
||||
});
|
||||
}];
|
||||
}
|
||||
|
||||
+ (instancetype)promiseWithBooleanAdapterBlock:(void (^)(PMKBooleanAdapter adapter))block {
|
||||
return [self promiseWithResolverBlock:^(PMKResolver resolve) {
|
||||
block(^(BOOL value, id error){
|
||||
if (error) {
|
||||
resolve(error);
|
||||
} else {
|
||||
resolve(@(value));
|
||||
}
|
||||
});
|
||||
}];
|
||||
}
|
||||
|
||||
@end
|
215
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.swift
generated
Normal file
215
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.swift
generated
Normal file
@ -0,0 +1,215 @@
|
||||
import Foundation.NSError
|
||||
|
||||
@objc(AnyPromise) public class AnyPromise: NSObject {
|
||||
|
||||
private var state: State
|
||||
|
||||
/**
|
||||
- Returns: A new AnyPromise bound to a Promise<T?>.
|
||||
The two promises represent the same task, any changes to either will instantly reflect on both.
|
||||
*/
|
||||
public init<T: AnyObject>(bound: Promise<T?>) {
|
||||
var resolve: ((AnyObject?) -> Void)!
|
||||
state = State(resolver: &resolve)
|
||||
bound.pipe { resolution in
|
||||
switch resolution {
|
||||
case .Fulfilled(let value):
|
||||
resolve(value)
|
||||
case .Rejected(let error, let token):
|
||||
let nserror = error as NSError
|
||||
unconsume(error: nserror, reusingToken: token)
|
||||
resolve(nserror)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
- Returns: A new AnyPromise bound to a Promise<T>.
|
||||
The two promises represent the same task, any changes to either will instantly reflect on both.
|
||||
*/
|
||||
convenience public init<T: AnyObject>(bound: Promise<T>) {
|
||||
// FIXME efficiency. Allocating the extra promise for conversion sucks.
|
||||
self.init(bound: bound.then(on: zalgo){ Optional.Some($0) })
|
||||
}
|
||||
|
||||
/**
|
||||
- Returns: A new `AnyPromise` bound to a `Promise<[T]>`.
|
||||
The two promises represent the same task, any changes to either will instantly reflect on both.
|
||||
The value is converted to an NSArray so Objective-C can use it.
|
||||
*/
|
||||
convenience public init<T: AnyObject>(bound: Promise<[T]>) {
|
||||
self.init(bound: bound.then(on: zalgo) { NSArray(array: $0) })
|
||||
}
|
||||
|
||||
/**
|
||||
- Returns: A new AnyPromise bound to a `Promise<[T:U]>`.
|
||||
The two promises represent the same task, any changes to either will instantly reflect on both.
|
||||
The value is converted to an NSDictionary so Objective-C can use it.
|
||||
*/
|
||||
convenience public init<T: AnyObject, U: AnyObject>(bound: Promise<[T:U]>) {
|
||||
self.init(bound: bound.then(on: zalgo) { NSDictionary(dictionary: $0) })
|
||||
}
|
||||
|
||||
/**
|
||||
- Returns: A new AnyPromise bound to a `Promise<Int>`.
|
||||
The two promises represent the same task, any changes to either will instantly reflect on both.
|
||||
The value is converted to an NSNumber so Objective-C can use it.
|
||||
*/
|
||||
convenience public init(bound: Promise<Int>) {
|
||||
self.init(bound: bound.then(on: zalgo) { NSNumber(integer: $0) })
|
||||
}
|
||||
|
||||
/**
|
||||
- Returns: A new AnyPromise bound to a `Promise<Void>`.
|
||||
The two promises represent the same task, any changes to either will instantly reflect on both.
|
||||
*/
|
||||
convenience public init(bound: Promise<Void>) {
|
||||
self.init(bound: bound.then(on: zalgo) { Optional<AnyObject>.None })
|
||||
}
|
||||
|
||||
@objc init(@noescape bridge: ((AnyObject?) -> Void) -> Void) {
|
||||
var resolve: ((AnyObject?) -> Void)!
|
||||
state = State(resolver: &resolve)
|
||||
bridge { result in
|
||||
if let next = result as? AnyPromise {
|
||||
next.pipe(resolve)
|
||||
} else {
|
||||
resolve(result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc func pipe(body: (AnyObject?) -> Void) {
|
||||
state.get { seal in
|
||||
switch seal {
|
||||
case .Pending(let handlers):
|
||||
handlers.append(body)
|
||||
case .Resolved(let value):
|
||||
body(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc var __value: AnyObject? {
|
||||
return state.get() ?? nil
|
||||
}
|
||||
|
||||
/**
|
||||
A promise starts pending and eventually resolves.
|
||||
- Returns: `true` if the promise has not yet resolved.
|
||||
*/
|
||||
@objc public var pending: Bool {
|
||||
return state.get() == nil
|
||||
}
|
||||
|
||||
/**
|
||||
A promise starts pending and eventually resolves.
|
||||
- Returns: `true` if the promise has resolved.
|
||||
*/
|
||||
@objc public var resolved: Bool {
|
||||
return !pending
|
||||
}
|
||||
|
||||
/**
|
||||
A fulfilled promise has resolved successfully.
|
||||
- Returns: `true` if the promise was fulfilled.
|
||||
*/
|
||||
@objc public var fulfilled: Bool {
|
||||
switch state.get() {
|
||||
case .Some(let obj) where obj is NSError:
|
||||
return false
|
||||
case .Some:
|
||||
return true
|
||||
case .None:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
A rejected promise has resolved without success.
|
||||
- Returns: `true` if the promise was rejected.
|
||||
*/
|
||||
@objc public var rejected: Bool {
|
||||
switch state.get() {
|
||||
case .Some(let obj) where obj is NSError:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Continue a Promise<T> chain from an AnyPromise.
|
||||
*/
|
||||
public func then<T>(on q: dispatch_queue_t = dispatch_get_main_queue(), body: (AnyObject?) throws -> T) -> Promise<T> {
|
||||
return Promise(sealant: { resolve in
|
||||
pipe { object in
|
||||
if let error = object as? NSError {
|
||||
resolve(.Rejected(error, error.token))
|
||||
} else {
|
||||
contain_zalgo(q, rejecter: resolve) {
|
||||
resolve(.Fulfilled(try body(self.valueForKey("value"))))
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
Continue a Promise<T> chain from an AnyPromise.
|
||||
*/
|
||||
public func then(on q: dispatch_queue_t = dispatch_get_main_queue(), body: (AnyObject?) -> AnyPromise) -> Promise<AnyObject?> {
|
||||
return Promise { fulfill, reject in
|
||||
pipe { object in
|
||||
if let error = object as? NSError {
|
||||
reject(error)
|
||||
} else {
|
||||
contain_zalgo(q) {
|
||||
body(object).pipe { object in
|
||||
if let error = object as? NSError {
|
||||
reject(error)
|
||||
} else {
|
||||
fulfill(object)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Continue a Promise<T> chain from an AnyPromise.
|
||||
*/
|
||||
public func then<T>(on q: dispatch_queue_t = dispatch_get_main_queue(), body: (AnyObject?) -> Promise<T>) -> Promise<T> {
|
||||
return Promise(sealant: { resolve in
|
||||
pipe { object in
|
||||
if let error = object as? NSError {
|
||||
resolve(.Rejected(error, error.token))
|
||||
} else {
|
||||
contain_zalgo(q) {
|
||||
body(object).pipe(resolve)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private class State: UnsealedState<AnyObject?> {
|
||||
required init(inout resolver: ((AnyObject?) -> Void)!) {
|
||||
var preresolve: ((AnyObject?) -> Void)!
|
||||
super.init(resolver: &preresolve)
|
||||
resolver = { obj in
|
||||
if let error = obj as? NSError { unconsume(error: error) }
|
||||
preresolve(obj)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
extension AnyPromise {
|
||||
override public var description: String {
|
||||
return "AnyPromise: \(state)"
|
||||
}
|
||||
}
|
216
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/Error.swift
generated
Normal file
216
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/Error.swift
generated
Normal file
@ -0,0 +1,216 @@
|
||||
import Dispatch
|
||||
import Foundation.NSError
|
||||
import Foundation.NSURLError
|
||||
|
||||
public enum Error: ErrorType {
|
||||
/**
|
||||
The ErrorType for a rejected `when`.
|
||||
- Parameter 0: The index of the promise that was rejected.
|
||||
- Parameter 1: The error from the promise that rejected this `when`.
|
||||
*/
|
||||
case When(Int, ErrorType)
|
||||
|
||||
/**
|
||||
The ErrorType for a rejected `join`.
|
||||
- Parameter 0: The promises passed to this `join` that did not *all* fulfill.
|
||||
- Note: The array is untyped because Swift generics are fussy with enums.
|
||||
*/
|
||||
case Join([AnyObject])
|
||||
|
||||
/**
|
||||
The closure with form (T?, ErrorType?) was called with (nil, nil)
|
||||
This is invalid as per the calling convention.
|
||||
*/
|
||||
case DoubleOhSux0r
|
||||
|
||||
/**
|
||||
A handler returned its own promise. 99% of the time, this is likely a
|
||||
programming error. It is also invalid per Promises/A+.
|
||||
*/
|
||||
case ReturnedSelf
|
||||
}
|
||||
|
||||
public enum URLError: ErrorType {
|
||||
/**
|
||||
The URLRequest succeeded but a valid UIImage could not be decoded from
|
||||
the data that was received.
|
||||
*/
|
||||
case InvalidImageData(NSURLRequest, NSData)
|
||||
|
||||
/**
|
||||
An NSError was received from an underlying Cocoa function.
|
||||
FIXME sucks?
|
||||
*/
|
||||
case UnderlyingCocoaError(NSURLRequest, NSData?, NSURLResponse?, NSError)
|
||||
|
||||
/**
|
||||
The HTTP request returned a non-200 status code.
|
||||
*/
|
||||
case BadResponse(NSURLRequest, NSData?, NSURLResponse?)
|
||||
|
||||
/**
|
||||
The data could not be decoded using the encoding specified by the HTTP
|
||||
response headers.
|
||||
*/
|
||||
case StringEncoding(NSURLRequest, NSData, NSURLResponse)
|
||||
|
||||
/**
|
||||
Usually the `NSURLResponse` is actually an `NSHTTPURLResponse`, if so you
|
||||
can access it using this property. Since it is returned as an unwrapped
|
||||
optional: be sure.
|
||||
*/
|
||||
public var NSHTTPURLResponse: Foundation.NSHTTPURLResponse! {
|
||||
switch self {
|
||||
case .InvalidImageData:
|
||||
return nil
|
||||
case .UnderlyingCocoaError(_, _, let rsp, _):
|
||||
return rsp as! Foundation.NSHTTPURLResponse
|
||||
case .BadResponse(_, _, let rsp):
|
||||
return rsp as! Foundation.NSHTTPURLResponse
|
||||
case .StringEncoding(_, _, let rsp):
|
||||
return rsp as! Foundation.NSHTTPURLResponse
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public enum JSONError: ErrorType {
|
||||
case UnexpectedRootNode(AnyObject)
|
||||
}
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////// Cancellation
|
||||
private struct ErrorPair: Hashable {
|
||||
let domain: String
|
||||
let code: Int
|
||||
init(_ d: String, _ c: Int) {
|
||||
domain = d; code = c
|
||||
}
|
||||
var hashValue: Int {
|
||||
return "\(domain):\(code)".hashValue
|
||||
}
|
||||
}
|
||||
|
||||
private func ==(lhs: ErrorPair, rhs: ErrorPair) -> Bool {
|
||||
return lhs.domain == rhs.domain && lhs.code == rhs.code
|
||||
}
|
||||
|
||||
extension NSError {
|
||||
@objc public class func cancelledError() -> NSError {
|
||||
let info: [NSObject: AnyObject] = [NSLocalizedDescriptionKey: "The operation was cancelled"]
|
||||
return NSError(domain: PMKErrorDomain, code: PMKOperationCancelled, userInfo: info)
|
||||
}
|
||||
|
||||
/**
|
||||
- Warning: You may only call this method on the main thread.
|
||||
*/
|
||||
@objc public class func registerCancelledErrorDomain(domain: String, code: Int) {
|
||||
cancelledErrorIdentifiers.insert(ErrorPair(domain, code))
|
||||
}
|
||||
}
|
||||
|
||||
public protocol CancellableErrorType: ErrorType {
|
||||
var cancelled: Bool { get }
|
||||
}
|
||||
|
||||
extension NSError: CancellableErrorType {
|
||||
/**
|
||||
- Warning: You may only call this method on the main thread.
|
||||
*/
|
||||
@objc public var cancelled: Bool {
|
||||
if !NSThread.isMainThread() {
|
||||
NSLog("PromiseKit: Warning: `cancelled` called on background thread.")
|
||||
}
|
||||
|
||||
return cancelledErrorIdentifiers.contains(ErrorPair(domain, code))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
////////////////////////////////////////// Predefined Cancellation Errors
|
||||
private var cancelledErrorIdentifiers = Set([
|
||||
ErrorPair(PMKErrorDomain, PMKOperationCancelled),
|
||||
ErrorPair(NSURLErrorDomain, NSURLErrorCancelled)
|
||||
])
|
||||
|
||||
extension NSURLError: CancellableErrorType {
|
||||
public var cancelled: Bool {
|
||||
return self == .Cancelled
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////// Unhandled Errors
|
||||
/**
|
||||
The unhandled error handler.
|
||||
|
||||
If a promise is rejected and no catch handler is called in its chain,
|
||||
the provided handler is called. The default handler logs the error.
|
||||
|
||||
PMKUnhandledErrorHandler = { error in
|
||||
mylogf("Unhandled error: \(error)")
|
||||
}
|
||||
|
||||
- Warning: *Important* The handler is executed on an undefined queue.
|
||||
- Warning: *Important* Don’t use promises in your handler, or you risk an infinite error loop.
|
||||
- Returns: The previous unhandled error handler.
|
||||
*/
|
||||
public var PMKUnhandledErrorHandler = { (error: ErrorType) -> Void in
|
||||
dispatch_async(dispatch_get_main_queue()) {
|
||||
let cancelled = (error as? CancellableErrorType)?.cancelled ?? false
|
||||
// ^-------^ must be called on main queue
|
||||
if !cancelled {
|
||||
NSLog("PromiseKit: Unhandled Error: %@", "\(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class ErrorConsumptionToken {
|
||||
var consumed = false
|
||||
let error: ErrorType!
|
||||
|
||||
init(_ error: ErrorType) {
|
||||
self.error = error
|
||||
}
|
||||
|
||||
init(_ error: NSError) {
|
||||
self.error = error.copy() as! NSError
|
||||
}
|
||||
|
||||
deinit {
|
||||
if !consumed {
|
||||
PMKUnhandledErrorHandler(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var handle: UInt8 = 0
|
||||
|
||||
extension NSError {
|
||||
@objc func pmk_consume() {
|
||||
// The association could be nil if the objc_setAssociatedObject
|
||||
// has taken a *really* long time. Or perhaps the user has
|
||||
// overused `zalgo`. Thus we ignore it. This is an unlikely edge
|
||||
// case and the unhandled-error feature is not mission-critical.
|
||||
|
||||
if let token = objc_getAssociatedObject(self, &handle) as? ErrorConsumptionToken {
|
||||
token.consumed = true
|
||||
}
|
||||
}
|
||||
|
||||
var token: ErrorConsumptionToken! {
|
||||
return objc_getAssociatedObject(self, &handle) as? ErrorConsumptionToken
|
||||
}
|
||||
}
|
||||
|
||||
func unconsume(error error: NSError, var reusingToken token: ErrorConsumptionToken? = nil) {
|
||||
if token != nil {
|
||||
objc_setAssociatedObject(error, &handle, token, .OBJC_ASSOCIATION_RETAIN)
|
||||
} else {
|
||||
token = objc_getAssociatedObject(error, &handle) as? ErrorConsumptionToken
|
||||
if token == nil {
|
||||
token = ErrorConsumptionToken(error)
|
||||
objc_setAssociatedObject(error, &handle, token, .OBJC_ASSOCIATION_RETAIN)
|
||||
}
|
||||
}
|
||||
token!.consumed = false
|
||||
}
|
16
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/NSError+Cancellation.h
generated
Normal file
16
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/NSError+Cancellation.h
generated
Normal file
@ -0,0 +1,16 @@
|
||||
#import <Foundation/NSError.h>
|
||||
|
||||
#if !defined(SWIFT_PASTE)
|
||||
# define SWIFT_PASTE_HELPER(x, y) x##y
|
||||
# define SWIFT_PASTE(x, y) SWIFT_PASTE_HELPER(x, y)
|
||||
#endif
|
||||
|
||||
#if !defined(SWIFT_EXTENSION)
|
||||
# define SWIFT_EXTENSION(M) SWIFT_PASTE(M##_Swift_, __LINE__)
|
||||
#endif
|
||||
|
||||
@interface NSError (SWIFT_EXTENSION(PromiseKit))
|
||||
+ (NSError * __nonnull)cancelledError;
|
||||
+ (void)registerCancelledErrorDomain:(NSString * __nonnull)domain code:(NSInteger)code;
|
||||
@property (nonatomic, readonly) BOOL cancelled;
|
||||
@end
|
77
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/NSMethodSignatureForBlock.m
generated
Normal file
77
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/NSMethodSignatureForBlock.m
generated
Normal file
@ -0,0 +1,77 @@
|
||||
#import <Foundation/NSMethodSignature.h>
|
||||
|
||||
struct PMKBlockLiteral {
|
||||
void *isa; // initialized to &_NSConcreteStackBlock or &_NSConcreteGlobalBlock
|
||||
int flags;
|
||||
int reserved;
|
||||
void (*invoke)(void *, ...);
|
||||
struct block_descriptor {
|
||||
unsigned long int reserved; // NULL
|
||||
unsigned long int size; // sizeof(struct Block_literal_1)
|
||||
// optional helper functions
|
||||
void (*copy_helper)(void *dst, void *src); // IFF (1<<25)
|
||||
void (*dispose_helper)(void *src); // IFF (1<<25)
|
||||
// required ABI.2010.3.16
|
||||
const char *signature; // IFF (1<<30)
|
||||
} *descriptor;
|
||||
// imported variables
|
||||
};
|
||||
|
||||
typedef NS_OPTIONS(NSUInteger, PMKBlockDescriptionFlags) {
|
||||
PMKBlockDescriptionFlagsHasCopyDispose = (1 << 25),
|
||||
PMKBlockDescriptionFlagsHasCtor = (1 << 26), // helpers have C++ code
|
||||
PMKBlockDescriptionFlagsIsGlobal = (1 << 28),
|
||||
PMKBlockDescriptionFlagsHasStret = (1 << 29), // IFF BLOCK_HAS_SIGNATURE
|
||||
PMKBlockDescriptionFlagsHasSignature = (1 << 30)
|
||||
};
|
||||
|
||||
// It appears 10.7 doesn't support quotes in method signatures. Remove them
|
||||
// via @rabovik's method. See https://github.com/OliverLetterer/SLObjectiveCRuntimeAdditions/pull/2
|
||||
#if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_8
|
||||
NS_INLINE static const char * pmk_removeQuotesFromMethodSignature(const char *str){
|
||||
char *result = malloc(strlen(str) + 1);
|
||||
BOOL skip = NO;
|
||||
char *to = result;
|
||||
char c;
|
||||
while ((c = *str++)) {
|
||||
if ('"' == c) {
|
||||
skip = !skip;
|
||||
continue;
|
||||
}
|
||||
if (skip) continue;
|
||||
*to++ = c;
|
||||
}
|
||||
*to = '\0';
|
||||
return result;
|
||||
}
|
||||
#endif
|
||||
|
||||
static NSMethodSignature *NSMethodSignatureForBlock(id block) {
|
||||
if (!block)
|
||||
return nil;
|
||||
|
||||
struct PMKBlockLiteral *blockRef = (__bridge struct PMKBlockLiteral *)block;
|
||||
PMKBlockDescriptionFlags flags = (PMKBlockDescriptionFlags)blockRef->flags;
|
||||
|
||||
if (flags & PMKBlockDescriptionFlagsHasSignature) {
|
||||
void *signatureLocation = blockRef->descriptor;
|
||||
signatureLocation += sizeof(unsigned long int);
|
||||
signatureLocation += sizeof(unsigned long int);
|
||||
|
||||
if (flags & PMKBlockDescriptionFlagsHasCopyDispose) {
|
||||
signatureLocation += sizeof(void(*)(void *dst, void *src));
|
||||
signatureLocation += sizeof(void (*)(void *src));
|
||||
}
|
||||
|
||||
const char *signature = (*(const char **)signatureLocation);
|
||||
#if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_8
|
||||
signature = pmk_removeQuotesFromMethodSignature(signature);
|
||||
NSMethodSignature *nsSignature = [NSMethodSignature signatureWithObjCTypes:signature];
|
||||
free((void *)signature);
|
||||
|
||||
return nsSignature;
|
||||
#endif
|
||||
return [NSMethodSignature signatureWithObjCTypes:signature];
|
||||
}
|
||||
return 0;
|
||||
}
|
32
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/PMK.modulemap
generated
Normal file
32
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/PMK.modulemap
generated
Normal file
@ -0,0 +1,32 @@
|
||||
framework module PromiseKit {
|
||||
umbrella header "Umbrella.h"
|
||||
|
||||
header "NSError+Cancellation.h"
|
||||
|
||||
exclude header "AnyPromise.h"
|
||||
exclude header "PromiseKit.h"
|
||||
exclude header "PMKPromise.h"
|
||||
exclude header "Promise.h"
|
||||
|
||||
exclude header "Pods-PromiseKit-umbrella.h"
|
||||
|
||||
exclude header "ACAccountStore+AnyPromise.h"
|
||||
exclude header "AVAudioSession+AnyPromise.h"
|
||||
exclude header "CKContainer+AnyPromise.h"
|
||||
exclude header "CKDatabase+AnyPromise.h"
|
||||
exclude header "CLGeocoder+AnyPromise.h"
|
||||
exclude header "CLLocationManager+AnyPromise.h"
|
||||
exclude header "NSNotificationCenter+AnyPromise.h"
|
||||
exclude header "NSTask+AnyPromise.h"
|
||||
exclude header "NSURLConnection+AnyPromise.h"
|
||||
exclude header "MKDirections+AnyPromise.h"
|
||||
exclude header "MKMapSnapshotter+AnyPromise.h"
|
||||
exclude header "CALayer+AnyPromise.h"
|
||||
exclude header "SLRequest+AnyPromise.h"
|
||||
exclude header "SKRequest+AnyPromise.h"
|
||||
exclude header "SCNetworkReachability+AnyPromise.h"
|
||||
exclude header "UIActionSheet+AnyPromise.h"
|
||||
exclude header "UIAlertView+AnyPromise.h"
|
||||
exclude header "UIView+AnyPromise.h"
|
||||
exclude header "UIViewController+AnyPromise.h"
|
||||
}
|
145
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/PMKCallVariadicBlock.m
generated
Normal file
145
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/PMKCallVariadicBlock.m
generated
Normal file
@ -0,0 +1,145 @@
|
||||
#import <dispatch/once.h>
|
||||
#import <Foundation/NSDictionary.h>
|
||||
#import <Foundation/NSError.h>
|
||||
#import <Foundation/NSException.h>
|
||||
#import "NSMethodSignatureForBlock.m"
|
||||
#import <PromiseKit/Umbrella.h>
|
||||
#import <PromiseKit/PromiseKit.h>
|
||||
#import <string.h>
|
||||
|
||||
#ifndef PMKLog
|
||||
#define PMKLog NSLog
|
||||
#endif
|
||||
|
||||
@interface PMKArray : NSObject {
|
||||
@public
|
||||
id objs[3];
|
||||
NSUInteger count;
|
||||
} @end
|
||||
|
||||
@implementation PMKArray
|
||||
|
||||
- (id)objectAtIndexedSubscript:(NSUInteger)idx {
|
||||
if (count <= idx) {
|
||||
// this check is necessary due to lack of checks in `pmk_safely_call_block`
|
||||
return nil;
|
||||
}
|
||||
return objs[idx];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
id __PMKArrayWithCount(NSUInteger count, ...) {
|
||||
PMKArray *this = [PMKArray new];
|
||||
this->count = count;
|
||||
va_list args;
|
||||
va_start(args, count);
|
||||
for (NSUInteger x = 0; x < count; ++x)
|
||||
this->objs[x] = va_arg(args, id);
|
||||
va_end(args);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
static inline id _PMKCallVariadicBlock(id frock, id result) {
|
||||
NSCAssert(frock, @"");
|
||||
|
||||
NSMethodSignature *sig = NSMethodSignatureForBlock(frock);
|
||||
const NSUInteger nargs = sig.numberOfArguments;
|
||||
const char rtype = sig.methodReturnType[0];
|
||||
|
||||
#define call_block_with_rtype(type) ({^type{ \
|
||||
switch (nargs) { \
|
||||
case 1: \
|
||||
return ((type(^)(void))frock)(); \
|
||||
case 2: { \
|
||||
const id arg = [result class] == [PMKArray class] ? result[0] : result; \
|
||||
return ((type(^)(id))frock)(arg); \
|
||||
} \
|
||||
case 3: { \
|
||||
type (^block)(id, id) = frock; \
|
||||
return [result class] == [PMKArray class] \
|
||||
? block(result[0], result[1]) \
|
||||
: block(result, nil); \
|
||||
} \
|
||||
case 4: { \
|
||||
type (^block)(id, id, id) = frock; \
|
||||
return [result class] == [PMKArray class] \
|
||||
? block(result[0], result[1], result[2]) \
|
||||
: block(result, nil, nil); \
|
||||
} \
|
||||
default: \
|
||||
@throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"PromiseKit: The provided block’s argument count is unsupported." userInfo:nil]; \
|
||||
}}();})
|
||||
|
||||
switch (rtype) {
|
||||
case 'v':
|
||||
call_block_with_rtype(void);
|
||||
return nil;
|
||||
case '@':
|
||||
return call_block_with_rtype(id) ?: nil;
|
||||
case '*': {
|
||||
char *str = call_block_with_rtype(char *);
|
||||
return str ? @(str) : nil;
|
||||
}
|
||||
case 'c': return @(call_block_with_rtype(char));
|
||||
case 'i': return @(call_block_with_rtype(int));
|
||||
case 's': return @(call_block_with_rtype(short));
|
||||
case 'l': return @(call_block_with_rtype(long));
|
||||
case 'q': return @(call_block_with_rtype(long long));
|
||||
case 'C': return @(call_block_with_rtype(unsigned char));
|
||||
case 'I': return @(call_block_with_rtype(unsigned int));
|
||||
case 'S': return @(call_block_with_rtype(unsigned short));
|
||||
case 'L': return @(call_block_with_rtype(unsigned long));
|
||||
case 'Q': return @(call_block_with_rtype(unsigned long long));
|
||||
case 'f': return @(call_block_with_rtype(float));
|
||||
case 'd': return @(call_block_with_rtype(double));
|
||||
case 'B': return @(call_block_with_rtype(_Bool));
|
||||
case '^':
|
||||
if (strcmp(sig.methodReturnType, "^v") == 0) {
|
||||
call_block_with_rtype(void);
|
||||
return nil;
|
||||
}
|
||||
// else fall through!
|
||||
default:
|
||||
@throw [NSException exceptionWithName:@"PromiseKit" reason:@"PromiseKit: Unsupported method signature." userInfo:nil];
|
||||
}
|
||||
}
|
||||
|
||||
static id PMKCallVariadicBlock(id frock, id result) {
|
||||
@try {
|
||||
return _PMKCallVariadicBlock(frock, result);
|
||||
} @catch (id thrown) {
|
||||
return PMKProcessUnhandledException(thrown);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static dispatch_once_t onceToken;
|
||||
static NSError *(^PMKUnhandledExceptionHandler)(id);
|
||||
|
||||
NSError *PMKProcessUnhandledException(id thrown) {
|
||||
|
||||
dispatch_once(&onceToken, ^{
|
||||
PMKUnhandledExceptionHandler = ^id(id reason){
|
||||
if ([reason isKindOfClass:[NSError class]])
|
||||
return reason;
|
||||
if ([reason isKindOfClass:[NSString class]])
|
||||
return [NSError errorWithDomain:PMKErrorDomain code:PMKUnexpectedError userInfo:@{NSLocalizedDescriptionKey: reason}];
|
||||
return nil;
|
||||
};
|
||||
});
|
||||
|
||||
id err = PMKUnhandledExceptionHandler(thrown);
|
||||
if (!err) {
|
||||
NSLog(@"PromiseKit no longer catches *all* exceptions. However you can change this behavior by setting a new PMKProcessUnhandledException handler.");
|
||||
@throw thrown;
|
||||
}
|
||||
return err;
|
||||
}
|
||||
|
||||
void PMKSetUnhandledExceptionHandler(NSError *(^newHandler)(id)) {
|
||||
dispatch_once(&onceToken, ^{
|
||||
PMKUnhandledExceptionHandler = newHandler;
|
||||
});
|
||||
}
|
57
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/Promise+Properties.swift
generated
Normal file
57
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/Promise+Properties.swift
generated
Normal file
@ -0,0 +1,57 @@
|
||||
extension Promise {
|
||||
/**
|
||||
- Returns: The error with which this promise was rejected; `nil` if this promise is not rejected.
|
||||
*/
|
||||
public var error: ErrorType? {
|
||||
switch state.get() {
|
||||
case .None:
|
||||
return nil
|
||||
case .Some(.Fulfilled):
|
||||
return nil
|
||||
case .Some(.Rejected(let error, _)):
|
||||
return error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
- Returns: `true` if the promise has not yet resolved.
|
||||
*/
|
||||
public var pending: Bool {
|
||||
return state.get() == nil
|
||||
}
|
||||
|
||||
/**
|
||||
- Returns: `true` if the promise has resolved.
|
||||
*/
|
||||
public var resolved: Bool {
|
||||
return !pending
|
||||
}
|
||||
|
||||
/**
|
||||
- Returns: `true` if the promise was fulfilled.
|
||||
*/
|
||||
public var fulfilled: Bool {
|
||||
return value != nil
|
||||
}
|
||||
|
||||
/**
|
||||
- Returns: `true` if the promise was rejected.
|
||||
*/
|
||||
public var rejected: Bool {
|
||||
return error != nil
|
||||
}
|
||||
|
||||
/**
|
||||
- Returns: The value with which this promise was fulfilled or `nil` if this promise is pending or rejected.
|
||||
*/
|
||||
public var value: T? {
|
||||
switch state.get() {
|
||||
case .None:
|
||||
return nil
|
||||
case .Some(.Fulfilled(let value)):
|
||||
return value
|
||||
case .Some(.Rejected):
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
655
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/Promise.swift
generated
Normal file
655
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/Promise.swift
generated
Normal file
@ -0,0 +1,655 @@
|
||||
import Dispatch
|
||||
import Foundation.NSError
|
||||
|
||||
/**
|
||||
A *promise* represents the future value of a task.
|
||||
|
||||
To obtain the value of a promise we call `then`.
|
||||
|
||||
Promises are chainable: `then` returns a promise, you can call `then` on
|
||||
that promise, which returns a promise, you can call `then` on that
|
||||
promise, et cetera.
|
||||
|
||||
Promises start in a pending state and *resolve* with a value to become
|
||||
*fulfilled* or with an `ErrorType` to become rejected.
|
||||
|
||||
- SeeAlso: [PromiseKit `then` Guide](http://promisekit.org/then/)
|
||||
- SeeAlso: [PromiseKit Chaining Guide](http://promisekit.org/chaining/)
|
||||
*/
|
||||
public class Promise<T> {
|
||||
let state: State<Resolution<T>>
|
||||
|
||||
/**
|
||||
Create a new pending promise.
|
||||
|
||||
Use this method when wrapping asynchronous systems that do *not* use
|
||||
promises so that they can be involved in promise chains.
|
||||
|
||||
Don’t use this method if you already have promises! Instead, just return
|
||||
your promise!
|
||||
|
||||
The closure you pass is executed immediately on the calling thread.
|
||||
|
||||
func fetchKitten() -> Promise<UIImage> {
|
||||
return Promise { fulfill, reject in
|
||||
KittenFetcher.fetchWithCompletionBlock({ img, err in
|
||||
if err == nil {
|
||||
if img.size.width > 0 {
|
||||
fulfill(img)
|
||||
} else {
|
||||
reject(Error.ImageTooSmall)
|
||||
}
|
||||
} else {
|
||||
reject(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
- Parameter resolvers: The provided closure is called immediately.
|
||||
Inside, execute your asynchronous system, calling fulfill if it suceeds
|
||||
and reject for any errors.
|
||||
|
||||
- Returns: return A new promise.
|
||||
|
||||
- Note: If you are wrapping a delegate-based system, we recommend
|
||||
to use instead: Promise.pendingPromise()
|
||||
|
||||
- SeeAlso: http://promisekit.org/sealing-your-own-promises/
|
||||
- SeeAlso: http://promisekit.org/wrapping-delegation/
|
||||
- SeeAlso: init(resolver:)
|
||||
*/
|
||||
public init(@noescape resolvers: (fulfill: (T) -> Void, reject: (ErrorType) -> Void) throws -> Void) {
|
||||
var resolve: ((Resolution<T>) -> Void)!
|
||||
state = UnsealedState(resolver: &resolve)
|
||||
do {
|
||||
try resolvers(fulfill: { resolve(.Fulfilled($0)) }, reject: { error in
|
||||
if self.pending {
|
||||
resolve(.Rejected(error, ErrorConsumptionToken(error)))
|
||||
} else {
|
||||
NSLog("PromiseKit: Warning: reject called on already rejected Promise: %@", "\(error)")
|
||||
}
|
||||
})
|
||||
} catch {
|
||||
resolve(.Rejected(error, ErrorConsumptionToken(error)))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Create a new pending promise.
|
||||
|
||||
This initializer is convenient when wrapping asynchronous systems that
|
||||
use common patterns. For example:
|
||||
|
||||
func fetchKitten() -> Promise<UIImage> {
|
||||
return Promise { resolve in
|
||||
KittenFetcher.fetchWithCompletionBlock(resolve)
|
||||
}
|
||||
}
|
||||
|
||||
- SeeAlso: init(resolvers:)
|
||||
*/
|
||||
public convenience init(@noescape resolver: ((T?, NSError?) -> Void) throws -> Void) {
|
||||
self.init(sealant: { resolve in
|
||||
try resolver { obj, err in
|
||||
if let obj = obj {
|
||||
resolve(.Fulfilled(obj))
|
||||
} else if let err = err {
|
||||
resolve(.Rejected(err, ErrorConsumptionToken(err as ErrorType)))
|
||||
} else {
|
||||
resolve(.Rejected(Error.DoubleOhSux0r, ErrorConsumptionToken(Error.DoubleOhSux0r)))
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
Create a new pending promise.
|
||||
|
||||
This initializer is convenient when wrapping asynchronous systems that
|
||||
use common patterns. For example:
|
||||
|
||||
func fetchKitten() -> Promise<UIImage> {
|
||||
return Promise { resolve in
|
||||
KittenFetcher.fetchWithCompletionBlock(resolve)
|
||||
}
|
||||
}
|
||||
|
||||
- SeeAlso: init(resolvers:)
|
||||
*/
|
||||
public convenience init(@noescape resolver: ((T, NSError?) -> Void) throws -> Void) {
|
||||
self.init(sealant: { resolve in
|
||||
try resolver { obj, err in
|
||||
if let err = err {
|
||||
resolve(.Rejected(err, ErrorConsumptionToken(err)))
|
||||
} else {
|
||||
resolve(.Fulfilled(obj))
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
Create a new fulfilled promise.
|
||||
*/
|
||||
public init(_ value: T) {
|
||||
state = SealedState(resolution: .Fulfilled(value))
|
||||
}
|
||||
|
||||
@available(*, unavailable, message="T cannot conform to ErrorType")
|
||||
public init<T: ErrorType>(_ value: T) { abort() }
|
||||
|
||||
/**
|
||||
Create a new rejected promise.
|
||||
*/
|
||||
public init(error: ErrorType) {
|
||||
/**
|
||||
Implementation note, the error label is necessary to prevent:
|
||||
|
||||
let p = Promise(ErrorType())
|
||||
|
||||
Resulting in Promise<ErrorType>. The above @available annotation
|
||||
does not help for some reason. A work-around is:
|
||||
|
||||
let p: Promise<Void> = Promise(ErrorType())
|
||||
|
||||
But I can’t expect users to do this.
|
||||
*/
|
||||
state = SealedState(resolution: .Rejected(error, ErrorConsumptionToken(error)))
|
||||
}
|
||||
|
||||
/**
|
||||
Careful with this, it is imperative that sealant can only be called once
|
||||
or you will end up with spurious unhandled-errors due to possible double
|
||||
rejections and thus immediately deallocated ErrorConsumptionTokens.
|
||||
*/
|
||||
init(@noescape sealant: ((Resolution<T>) -> Void) throws -> Void) {
|
||||
var resolve: ((Resolution<T>) -> Void)!
|
||||
state = UnsealedState(resolver: &resolve)
|
||||
do {
|
||||
try sealant(resolve)
|
||||
} catch {
|
||||
resolve(.Rejected(error, ErrorConsumptionToken(error)))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Making promises that wrap asynchronous delegation systems or other larger asynchronous systems without a simple completion handler is easier with pendingPromise.
|
||||
|
||||
class Foo: BarDelegate {
|
||||
let (promise, fulfill, reject) = Promise<Int>.pendingPromise()
|
||||
|
||||
func barDidFinishWithResult(result: Int) {
|
||||
fulfill(result)
|
||||
}
|
||||
|
||||
func barDidError(error: NSError) {
|
||||
reject(error)
|
||||
}
|
||||
}
|
||||
|
||||
- Returns: A tuple consisting of:
|
||||
1) A promise
|
||||
2) A function that fulfills that promise
|
||||
3) A function that rejects that promise
|
||||
*/
|
||||
public class func pendingPromise() -> (promise: Promise, fulfill: (T) -> Void, reject: (ErrorType) -> Void) {
|
||||
var fulfill: ((T) -> Void)!
|
||||
var reject: ((ErrorType) -> Void)!
|
||||
let promise = Promise { fulfill = $0; reject = $1 }
|
||||
return (promise, fulfill, reject)
|
||||
}
|
||||
|
||||
func pipe(body: (Resolution<T>) -> Void) {
|
||||
state.get { seal in
|
||||
switch seal {
|
||||
case .Pending(let handlers):
|
||||
handlers.append(body)
|
||||
case .Resolved(let resolution):
|
||||
body(resolution)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private convenience init<U>(when: Promise<U>, body: (Resolution<U>, (Resolution<T>) -> Void) -> Void) {
|
||||
self.init { resolve in
|
||||
when.pipe { resolution in
|
||||
body(resolution, resolve)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
The provided closure is executed when this Promise is resolved.
|
||||
|
||||
- Parameter on: The queue on which body should be executed.
|
||||
- Parameter body: The closure that is executed when this Promise is fulfilled.
|
||||
- Returns: A new promise that is resolved with the value returned from the provided closure. For example:
|
||||
|
||||
NSURLConnection.GET(url).then { (data: NSData) -> Int in
|
||||
//…
|
||||
return data.length
|
||||
}.then { length in
|
||||
//…
|
||||
}
|
||||
|
||||
- SeeAlso: `thenInBackground`
|
||||
*/
|
||||
public func then<U>(on q: dispatch_queue_t = dispatch_get_main_queue(), _ body: (T) throws -> U) -> Promise<U> {
|
||||
return Promise<U>(when: self) { resolution, resolve in
|
||||
switch resolution {
|
||||
case .Rejected(let error):
|
||||
resolve(.Rejected(error))
|
||||
case .Fulfilled(let value):
|
||||
contain_zalgo(q, rejecter: resolve) {
|
||||
resolve(.Fulfilled(try body(value)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
The provided closure is executed when this Promise is resolved.
|
||||
|
||||
- Parameter on: The queue on which body should be executed.
|
||||
- Parameter body: The closure that is executed when this Promise is fulfilled.
|
||||
- Returns: A new promise that is resolved when the Promise returned from the provided closure resolves. For example:
|
||||
|
||||
NSURLSession.GET(url1).then { (data: NSData) -> Promise<NSData> in
|
||||
//…
|
||||
return NSURLSession.GET(url2)
|
||||
}.then { data in
|
||||
//…
|
||||
}
|
||||
|
||||
- SeeAlso: `thenInBackground`
|
||||
*/
|
||||
public func then<U>(on q: dispatch_queue_t = dispatch_get_main_queue(), _ body: (T) throws -> Promise<U>) -> Promise<U> {
|
||||
return Promise<U>(when: self) { resolution, resolve in
|
||||
switch resolution {
|
||||
case .Rejected(let error):
|
||||
resolve(.Rejected(error))
|
||||
case .Fulfilled(let value):
|
||||
contain_zalgo(q, rejecter: resolve) {
|
||||
let promise = try body(value)
|
||||
guard promise !== self else { throw Error.ReturnedSelf }
|
||||
promise.pipe(resolve)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
public func then<U>(on: dispatch_queue_t = dispatch_get_main_queue(), _ body: (T) throws -> Promise<U>?) -> Promise<U> { abort() }
|
||||
|
||||
/**
|
||||
The provided closure is executed when this Promise is resolved.
|
||||
|
||||
- Parameter on: The queue on which body should be executed.
|
||||
- Parameter body: The closure that is executed when this Promise is fulfilled.
|
||||
- Returns: A new promise that is resolved when the AnyPromise returned from the provided closure resolves. For example:
|
||||
|
||||
NSURLSession.GET(url).then { (data: NSData) -> AnyPromise in
|
||||
//…
|
||||
return SCNetworkReachability()
|
||||
}.then { _ in
|
||||
//…
|
||||
}
|
||||
|
||||
- SeeAlso: `thenInBackground`
|
||||
*/
|
||||
public func then(on q: dispatch_queue_t = dispatch_get_main_queue(), body: (T) throws -> AnyPromise) -> Promise<AnyObject?> {
|
||||
return Promise<AnyObject?>(when: self) { resolution, resolve in
|
||||
switch resolution {
|
||||
case .Rejected(let error):
|
||||
resolve(.Rejected(error))
|
||||
case .Fulfilled(let value):
|
||||
contain_zalgo(q, rejecter: resolve) {
|
||||
try body(value).pipe(resolve)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
public func then(on: dispatch_queue_t = dispatch_get_main_queue(), body: (T) throws -> AnyPromise?) -> Promise<AnyObject?> { abort() }
|
||||
|
||||
/**
|
||||
The provided closure is executed on the default background queue when this Promise is fulfilled.
|
||||
|
||||
This method is provided as a convenience for `then`.
|
||||
|
||||
- SeeAlso: `then`
|
||||
*/
|
||||
public func thenInBackground<U>(body: (T) throws -> U) -> Promise<U> {
|
||||
return then(on: dispatch_get_global_queue(0, 0), body)
|
||||
}
|
||||
|
||||
/**
|
||||
The provided closure is executed on the default background queue when this Promise is fulfilled.
|
||||
|
||||
This method is provided as a convenience for `then`.
|
||||
|
||||
- SeeAlso: `then`
|
||||
*/
|
||||
public func thenInBackground<U>(body: (T) throws -> Promise<U>) -> Promise<U> {
|
||||
return then(on: dispatch_get_global_queue(0, 0), body)
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
public func thenInBackground<U>(body: (T) throws -> Promise<U>?) -> Promise<U> { abort() }
|
||||
|
||||
/**
|
||||
The provided closure is executed when this promise is rejected.
|
||||
|
||||
Rejecting a promise cascades: rejecting all subsequent promises (unless
|
||||
recover is invoked) thus you will typically place your catch at the end
|
||||
of a chain. Often utility promises will not have a catch, instead
|
||||
delegating the error handling to the caller.
|
||||
|
||||
The provided closure always runs on the main queue.
|
||||
|
||||
- Parameter policy: The default policy does not execute your handler for cancellation errors. See registerCancellationError for more documentation.
|
||||
- Parameter body: The handler to execute if this promise is rejected.
|
||||
- SeeAlso: `registerCancellationError`
|
||||
*/
|
||||
public func error(policy policy: ErrorPolicy = .AllErrorsExceptCancellation, _ body: (ErrorType) -> Void) {
|
||||
|
||||
func consume(error: ErrorType, _ token: ErrorConsumptionToken) {
|
||||
token.consumed = true
|
||||
body(error)
|
||||
}
|
||||
|
||||
pipe { resolution in
|
||||
switch (resolution, policy) {
|
||||
case (let .Rejected(error, token), .AllErrorsExceptCancellation):
|
||||
dispatch_async(dispatch_get_main_queue()) {
|
||||
guard let cancellableError = error as? CancellableErrorType where cancellableError.cancelled else {
|
||||
consume(error, token)
|
||||
return
|
||||
}
|
||||
}
|
||||
case (let .Rejected(error, token), _):
|
||||
dispatch_async(dispatch_get_main_queue()) {
|
||||
consume(error, token)
|
||||
}
|
||||
case (.Fulfilled, _):
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
The provided closure is executed when this promise is rejected giving you
|
||||
an opportunity to recover from the error and continue the promise chain.
|
||||
*/
|
||||
public func recover(on q: dispatch_queue_t = dispatch_get_main_queue(), _ body: (ErrorType) throws -> Promise) -> Promise {
|
||||
return Promise(when: self) { resolution, resolve in
|
||||
switch resolution {
|
||||
case .Rejected(let error, let token):
|
||||
contain_zalgo(q, rejecter: resolve) {
|
||||
token.consumed = true
|
||||
let promise = try body(error)
|
||||
guard promise !== self else { throw Error.ReturnedSelf }
|
||||
promise.pipe(resolve)
|
||||
}
|
||||
case .Fulfilled:
|
||||
resolve(resolution)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
public func recover(on: dispatch_queue_t = dispatch_get_main_queue(), _ body: (ErrorType) throws -> Promise?) -> Promise { abort() }
|
||||
|
||||
public func recover(on q: dispatch_queue_t = dispatch_get_main_queue(), _ body: (ErrorType) throws -> T) -> Promise {
|
||||
return Promise(when: self) { resolution, resolve in
|
||||
switch resolution {
|
||||
case .Rejected(let error, let token):
|
||||
contain_zalgo(q, rejecter: resolve) {
|
||||
token.consumed = true
|
||||
resolve(.Fulfilled(try body(error)))
|
||||
}
|
||||
case .Fulfilled:
|
||||
resolve(resolution)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
The provided closure is executed when this Promise is resolved.
|
||||
|
||||
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
|
||||
somePromise().then {
|
||||
//…
|
||||
}.always {
|
||||
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
|
||||
}
|
||||
|
||||
- Parameter on: The queue on which body should be executed.
|
||||
- Parameter body: The closure that is executed when this Promise is resolved.
|
||||
*/
|
||||
public func always(on q: dispatch_queue_t = dispatch_get_main_queue(), _ body: () -> Void) -> Promise {
|
||||
return Promise(when: self) { resolution, resolve in
|
||||
contain_zalgo(q) {
|
||||
body()
|
||||
resolve(resolution)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, unavailable, renamed="ensure")
|
||||
public func finally(on: dispatch_queue_t = dispatch_get_main_queue(), body: () -> Void) -> Promise { abort() }
|
||||
|
||||
@available(*, unavailable, renamed="report")
|
||||
public func catch_(policy policy: ErrorPolicy = .AllErrorsExceptCancellation, body: () -> Void) -> Promise { abort() }
|
||||
|
||||
@available(*, unavailable, renamed="pendingPromise")
|
||||
public class func defer_() -> (promise: Promise, fulfill: (T) -> Void, reject: (ErrorType) -> Void) { abort() }
|
||||
|
||||
@available(*, deprecated, renamed="error")
|
||||
public func report(policy policy: ErrorPolicy = .AllErrorsExceptCancellation, _ body: (ErrorType) -> Void) { error(policy: policy, body) }
|
||||
|
||||
@available(*, deprecated, renamed="always")
|
||||
public func ensure(on q: dispatch_queue_t = dispatch_get_main_queue(), _ body: () -> Void) -> Promise { return always(on: q, body) }
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
Zalgo is dangerous.
|
||||
|
||||
Pass as the `on` parameter for a `then`. Causes the handler to be executed
|
||||
as soon as it is resolved. That means it will be executed on the queue it
|
||||
is resolved. This means you cannot predict the queue.
|
||||
|
||||
In the case that the promise is already resolved the handler will be
|
||||
executed immediately.
|
||||
|
||||
zalgo is provided for libraries providing promises that have good tests
|
||||
that prove unleashing zalgo is safe. You can also use it in your
|
||||
application code in situations where performance is critical, but be
|
||||
careful: read the essay at the provided link to understand the risks.
|
||||
|
||||
- SeeAlso: http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony
|
||||
*/
|
||||
public let zalgo: dispatch_queue_t = dispatch_queue_create("Zalgo", nil)
|
||||
|
||||
/**
|
||||
Waldo is dangerous.
|
||||
|
||||
Waldo is zalgo, unless the current queue is the main thread, in which case
|
||||
we dispatch to the default background queue.
|
||||
|
||||
If your block is likely to take more than a few milliseconds to execute,
|
||||
then you should use waldo: 60fps means the main thread cannot hang longer
|
||||
than 17 milliseconds. Don’t contribute to UI lag.
|
||||
|
||||
Conversely if your then block is trivial, use zalgo: GCD is not free and
|
||||
for whatever reason you may already be on the main thread so just do what
|
||||
you are doing quickly and pass on execution.
|
||||
|
||||
It is considered good practice for asynchronous APIs to complete onto the
|
||||
main thread. Apple do not always honor this, nor do other developers.
|
||||
However, they *should*. In that respect waldo is a good choice if your
|
||||
then is going to take a while and doesn’t interact with the UI.
|
||||
|
||||
Please note (again) that generally you should not use zalgo or waldo. The
|
||||
performance gains are neglible and we provide these functions only out of
|
||||
a misguided sense that library code should be as optimized as possible.
|
||||
If you use zalgo or waldo without tests proving their correctness you may
|
||||
unwillingly introduce horrendous, near-impossible-to-trace bugs.
|
||||
|
||||
- SeeAlso: zalgo
|
||||
*/
|
||||
public let waldo: dispatch_queue_t = dispatch_queue_create("Waldo", nil)
|
||||
|
||||
func contain_zalgo(q: dispatch_queue_t, block: () -> Void) {
|
||||
if q === zalgo {
|
||||
block()
|
||||
} else if q === waldo {
|
||||
if NSThread.isMainThread() {
|
||||
dispatch_async(dispatch_get_global_queue(0, 0), block)
|
||||
} else {
|
||||
block()
|
||||
}
|
||||
} else {
|
||||
dispatch_async(q, block)
|
||||
}
|
||||
}
|
||||
|
||||
func contain_zalgo<T>(q: dispatch_queue_t, rejecter resolve: (Resolution<T>) -> Void, block: () throws -> Void) {
|
||||
contain_zalgo(q) {
|
||||
do {
|
||||
try block()
|
||||
} catch {
|
||||
resolve(.Rejected(error, ErrorConsumptionToken(error)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
extension Promise {
|
||||
/**
|
||||
Void promises are less prone to generics-of-doom scenarios.
|
||||
- SeeAlso: when.swift contains enlightening examples of using `Promise<Void>` to simplify your code.
|
||||
*/
|
||||
public func asVoid() -> Promise<Void> {
|
||||
return then(on: zalgo) { _ in return }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
extension Promise: CustomStringConvertible {
|
||||
public var description: String {
|
||||
return "Promise: \(state)"
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
`firstly` can make chains more readable.
|
||||
|
||||
Compare:
|
||||
|
||||
NSURLConnection.GET(url1).then {
|
||||
NSURLConnection.GET(url2)
|
||||
}.then {
|
||||
NSURLConnection.GET(url3)
|
||||
}
|
||||
|
||||
With:
|
||||
|
||||
firstly {
|
||||
NSURLConnection.GET(url1)
|
||||
}.then {
|
||||
NSURLConnection.GET(url2)
|
||||
}.then {
|
||||
NSURLConnection.GET(url3)
|
||||
}
|
||||
*/
|
||||
public func firstly<T>(@noescape promise: () throws -> Promise<T>) -> Promise<T> {
|
||||
do {
|
||||
return try promise()
|
||||
} catch {
|
||||
return Promise(error: error)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
`firstly` can make chains more readable.
|
||||
|
||||
Compare:
|
||||
|
||||
SCNetworkReachability().then {
|
||||
NSURLSession.GET(url2)
|
||||
}.then {
|
||||
NSURLSession.GET(url3)
|
||||
}
|
||||
|
||||
With:
|
||||
|
||||
firstly {
|
||||
SCNetworkReachability()
|
||||
}.then {
|
||||
NSURLSession.GET(url2)
|
||||
}.then {
|
||||
NSURLSession.GET(url3)
|
||||
}
|
||||
*/
|
||||
public func firstly(@noescape promise: () throws -> AnyPromise) -> Promise<AnyObject?> {
|
||||
return Promise { resolve in
|
||||
try promise().pipe(resolve)
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, unavailable, message="Instead, throw")
|
||||
public func firstly<T: ErrorType>(@noescape promise: () throws -> Promise<T>) -> Promise<T> {
|
||||
fatalError("Unavailable function")
|
||||
}
|
||||
|
||||
|
||||
public enum ErrorPolicy {
|
||||
case AllErrors
|
||||
case AllErrorsExceptCancellation
|
||||
}
|
||||
|
||||
|
||||
extension AnyPromise {
|
||||
private func pipe(resolve: (Resolution<AnyObject?>) -> Void) -> Void {
|
||||
pipe { (obj: AnyObject?) in
|
||||
if let error = obj as? NSError {
|
||||
resolve(.Rejected(error, ErrorConsumptionToken(error)))
|
||||
} else {
|
||||
// possibly the value of this promise is a PMKManifold, if so
|
||||
// calling the objc `value` method will return the first item.
|
||||
resolve(.Fulfilled(self.valueForKey("value")))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
extension Promise {
|
||||
@available(*, unavailable, message="T cannot conform to ErrorType")
|
||||
public convenience init<T: ErrorType>(@noescape resolvers: (fulfill: (T) -> Void, reject: (ErrorType) -> Void) throws -> Void) { abort() }
|
||||
|
||||
@available(*, unavailable, message="T cannot conform to ErrorType")
|
||||
public convenience init<T: ErrorType>(@noescape resolver: ((T?, NSError?) -> Void) throws -> Void) { abort() }
|
||||
|
||||
@available(*, unavailable, message="T cannot conform to ErrorType")
|
||||
public convenience init<T: ErrorType>(@noescape resolver: ((T, NSError?) -> Void) throws -> Void) { abort() }
|
||||
|
||||
@available(*, unavailable, message="T cannot conform to ErrorType")
|
||||
public class func pendingPromise<T: ErrorType>() -> (promise: Promise, fulfill: (T) -> Void, reject: (ErrorType) -> Void) { abort() }
|
||||
|
||||
@available (*, unavailable, message="U cannot conform to ErrorType")
|
||||
public func then<U: ErrorType>(on: dispatch_queue_t = dispatch_get_main_queue(), _ body: (T) throws -> U) -> Promise<U> { abort() }
|
||||
|
||||
@available (*, unavailable, message="U cannot conform to ErrorType")
|
||||
public func then<U: ErrorType>(on: dispatch_queue_t = dispatch_get_main_queue(), _ body: (T) throws -> Promise<U>) -> Promise<U> { abort() }
|
||||
|
||||
@available(*, unavailable, message="U cannot conform to ErrorType")
|
||||
public func thenInBackground<U: ErrorType>(body: (T) throws -> U) -> Promise<U> { abort() }
|
||||
|
||||
@available(*, unavailable, message="U cannot conform to ErrorType")
|
||||
public func thenInBackground<U: ErrorType>(body: (T) throws -> Promise<U>) -> Promise<U> { abort() }
|
||||
}
|
248
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/PromiseKit.h
generated
Normal file
248
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/PromiseKit.h
generated
Normal file
@ -0,0 +1,248 @@
|
||||
#import <dispatch/queue.h>
|
||||
#import <Foundation/NSDate.h>
|
||||
#import <Foundation/NSObject.h>
|
||||
#import <PromiseKit/AnyPromise.h>
|
||||
#import <PromiseKit/NSError+Cancellation.h>
|
||||
#import <PromiseKit/Umbrella.h>
|
||||
|
||||
|
||||
|
||||
/**
|
||||
@return A new promise that resolves after the specified duration.
|
||||
|
||||
@parameter duration The duration in seconds to wait before this promise is resolve.
|
||||
|
||||
For example:
|
||||
|
||||
PMKAfter(1).then(^{
|
||||
//…
|
||||
});
|
||||
*/
|
||||
extern AnyPromise * __nonnull PMKAfter(NSTimeInterval duration);
|
||||
|
||||
|
||||
|
||||
/**
|
||||
`when` is a mechanism for waiting more than one asynchronous task and responding when they are all complete.
|
||||
|
||||
`PMKWhen` accepts varied input. If an array is passed then when those promises fulfill, when’s promise fulfills with an array of fulfillment values. If a dictionary is passed then the same occurs, but when’s promise fulfills with a dictionary of fulfillments keyed as per the input.
|
||||
|
||||
Interestingly, if a single promise is passed then when waits on that single promise, and if a single non-promise object is passed then when fulfills immediately with that object. If the array or dictionary that is passed contains objects that are not promises, then these objects are considered fulfilled promises. The reason we do this is to allow a pattern know as "abstracting away asynchronicity".
|
||||
|
||||
If *any* of the provided promises reject, the returned promise is immediately rejected with that promise’s rejection. The error’s `userInfo` object is supplemented with `PMKFailingPromiseIndexKey`.
|
||||
|
||||
For example:
|
||||
|
||||
PMKWhen(@[promise1, promise2]).then(^(NSArray *results){
|
||||
//…
|
||||
});
|
||||
|
||||
@warning *Important* In the event of rejection the other promises will continue to resolve and as per any other promise will eithe fulfill or reject. This is the right pattern for `getter` style asynchronous tasks, but often for `setter` tasks (eg. storing data on a server), you most likely will need to wait on all tasks and then act based on which have succeeded and which have failed. In such situations use `PMKJoin`.
|
||||
|
||||
@param input The input upon which to wait before resolving this promise.
|
||||
|
||||
@return A promise that is resolved with either:
|
||||
|
||||
1. An array of values from the provided array of promises.
|
||||
2. The value from the provided promise.
|
||||
3. The provided non-promise object.
|
||||
|
||||
@see PMKJoin
|
||||
|
||||
*/
|
||||
extern AnyPromise * __nonnull PMKWhen(id __nonnull input);
|
||||
|
||||
|
||||
|
||||
/**
|
||||
Creates a new promise that resolves only when all provided promises have resolved.
|
||||
|
||||
Typically, you should use `PMKWhen`.
|
||||
|
||||
For example:
|
||||
|
||||
PMKJoin(@[promise1, promise2]).then(^(NSArray *resultingValues){
|
||||
//…
|
||||
}).catch(^(NSError *error){
|
||||
assert(error.domain == PMKErrorDomain);
|
||||
assert(error.code == PMKJoinError);
|
||||
|
||||
NSArray *promises = error.userInfo[PMKJoinPromisesKey];
|
||||
for (AnyPromise *promise in promises) {
|
||||
if (promise.rejected) {
|
||||
//…
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@param promises An array of promises.
|
||||
|
||||
@return A promise that thens three parameters:
|
||||
|
||||
1) An array of mixed values and errors from the resolved input.
|
||||
2) An array of values from the promises that fulfilled.
|
||||
3) An array of errors from the promises that rejected or nil if all promises fulfilled.
|
||||
|
||||
@see when
|
||||
*/
|
||||
AnyPromise *__nonnull PMKJoin(NSArray * __nonnull promises);
|
||||
|
||||
|
||||
|
||||
/**
|
||||
Literally hangs this thread until the promise has resolved.
|
||||
|
||||
Do not use hang… unless you are testing, playing or debugging.
|
||||
|
||||
If you use it in production code I will literally and honestly cry like a child.
|
||||
|
||||
@return The resolved value of the promise.
|
||||
|
||||
@warning T SAFE. IT IS NOT SAFE. IT IS NOT SAFE. IT IS NOT SAFE. IT IS NO
|
||||
*/
|
||||
extern id __nullable PMKHang(AnyPromise * __nonnull promise);
|
||||
|
||||
|
||||
|
||||
/**
|
||||
Sets the unhandled exception handler.
|
||||
|
||||
If an exception is thrown inside an AnyPromise handler it is caught and
|
||||
this handler is executed to determine if the promise is rejected.
|
||||
|
||||
The default handler rejects the promise if an NSError or an NSString is
|
||||
thrown.
|
||||
|
||||
The default handler in PromiseKit 1.x would reject whatever object was
|
||||
thrown (including nil).
|
||||
|
||||
@warning *Important* This handler is provided to allow you to customize
|
||||
which exceptions cause rejection and which abort. You should either
|
||||
return a fully-formed NSError object or nil. Returning nil causes the
|
||||
exception to be re-thrown.
|
||||
|
||||
@warning *Important* The handler is executed on an undefined queue.
|
||||
|
||||
@warning *Important* This function is thread-safe, but to facilitate this
|
||||
it can only be called once per application lifetime and it must be called
|
||||
before any promise in the app throws an exception. Subsequent calls will
|
||||
silently fail.
|
||||
*/
|
||||
extern void PMKSetUnhandledExceptionHandler(NSError * __nullable (^__nonnull handler)(id __nullable));
|
||||
|
||||
|
||||
|
||||
/**
|
||||
Executes the provided block on a background queue.
|
||||
|
||||
dispatch_promise is a convenient way to start a promise chain where the
|
||||
first step needs to run synchronously on a background queue.
|
||||
|
||||
dispatch_promise(^{
|
||||
return md5(input);
|
||||
}).then(^(NSString *md5){
|
||||
NSLog(@"md5: %@", md5);
|
||||
});
|
||||
|
||||
@param block The block to be executed in the background. Returning an `NSError` will reject the promise, everything else (including void) fulfills the promise.
|
||||
|
||||
@return A promise resolved with the return value of the provided block.
|
||||
|
||||
@see dispatch_async
|
||||
*/
|
||||
extern AnyPromise * __nonnull dispatch_promise(id __nonnull block);
|
||||
|
||||
|
||||
|
||||
/**
|
||||
Executes the provided block on the specified background queue.
|
||||
|
||||
dispatch_promise_on(myDispatchQueue, ^{
|
||||
return md5(input);
|
||||
}).then(^(NSString *md5){
|
||||
NSLog(@"md5: %@", md5);
|
||||
});
|
||||
|
||||
@param block The block to be executed in the background. Returning an `NSError` will reject the promise, everything else (including void) fulfills the promise.
|
||||
|
||||
@return A promise resolved with the return value of the provided block.
|
||||
|
||||
@see dispatch_promise
|
||||
*/
|
||||
extern AnyPromise * __nonnull dispatch_promise_on(dispatch_queue_t __nonnull queue, id __nonnull block);
|
||||
|
||||
|
||||
|
||||
#define PMKJSONDeserializationOptions ((NSJSONReadingOptions)(NSJSONReadingAllowFragments | NSJSONReadingMutableContainers))
|
||||
|
||||
/**
|
||||
Really we shouldn’t assume JSON for (application|text)/(x-)javascript,
|
||||
really we should return a String of Javascript. However in practice
|
||||
for the apps we write it *will be* JSON. Thus if you actually want
|
||||
a Javascript String, use the promise variant of our category functions.
|
||||
*/
|
||||
#define PMKHTTPURLResponseIsJSON(rsp) [@[@"application/json", @"text/json", @"text/javascript", @"application/x-javascript", @"application/javascript"] containsObject:[rsp MIMEType]]
|
||||
#define PMKHTTPURLResponseIsImage(rsp) [@[@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap"] containsObject:[rsp MIMEType]]
|
||||
#define PMKHTTPURLResponseIsText(rsp) [[rsp MIMEType] hasPrefix:@"text/"]
|
||||
|
||||
|
||||
|
||||
#if defined(__has_include)
|
||||
#if __has_include(<PromiseKit/ACAccountStore+AnyPromise.h>)
|
||||
#import <PromiseKit/ACAccountStore+AnyPromise.h>
|
||||
#endif
|
||||
#if __has_include(<PromiseKit/AVAudioSession+AnyPromise.h>)
|
||||
#import <PromiseKit/AVAudioSession+AnyPromise.h>
|
||||
#endif
|
||||
#if __has_include(<PromiseKit/CKContainer+AnyPromise.h>)
|
||||
#import <PromiseKit/CKContainer+AnyPromise.h>
|
||||
#endif
|
||||
#if __has_include(<PromiseKit/CKDatabase+AnyPromise.h>)
|
||||
#import <PromiseKit/CKDatabase+AnyPromise.h>
|
||||
#endif
|
||||
#if __has_include(<PromiseKit/CLGeocoder+AnyPromise.h>)
|
||||
#import <PromiseKit/CLGeocoder+AnyPromise.h>
|
||||
#endif
|
||||
#if __has_include(<PromiseKit/CLLocationManager+AnyPromise.h>)
|
||||
#import <PromiseKit/CLLocationManager+AnyPromise.h>
|
||||
#endif
|
||||
#if __has_include(<PromiseKit/NSNotificationCenter+AnyPromise.h>)
|
||||
#import <PromiseKit/NSNotificationCenter+AnyPromise.h>
|
||||
#endif
|
||||
#if __has_include(<PromiseKit/NSTask+AnyPromise.h>)
|
||||
#import <PromiseKit/NSTask+AnyPromise.h>
|
||||
#endif
|
||||
#if __has_include(<PromiseKit/NSURLConnection+AnyPromise.h>)
|
||||
#import <PromiseKit/NSURLConnection+AnyPromise.h>
|
||||
#endif
|
||||
#if __has_include(<PromiseKit/MKDirections+AnyPromise.h>)
|
||||
#import <PromiseKit/MKDirections+AnyPromise.h>
|
||||
#endif
|
||||
#if __has_include(<PromiseKit/MKMapSnapshotter+AnyPromise.h>)
|
||||
#import <PromiseKit/MKMapSnapshotter+AnyPromise.h>
|
||||
#endif
|
||||
#if __has_include(<PromiseKit/CALayer+AnyPromise.h>)
|
||||
#import <PromiseKit/CALayer+AnyPromise.h>
|
||||
#endif
|
||||
#if __has_include(<PromiseKit/SLRequest+AnyPromise.h>)
|
||||
#import <PromiseKit/SLRequest+AnyPromise.h>
|
||||
#endif
|
||||
#if __has_include(<PromiseKit/SKRequest+AnyPromise.h>)
|
||||
#import <PromiseKit/SKRequest+AnyPromise.h>
|
||||
#endif
|
||||
#if __has_include(<PromiseKit/SCNetworkReachability+AnyPromise.h>)
|
||||
#import <PromiseKit/SCNetworkReachability+AnyPromise.h>
|
||||
#endif
|
||||
#if __has_include(<PromiseKit/UIActionSheet+AnyPromise.h>)
|
||||
#import <PromiseKit/UIActionSheet+AnyPromise.h>
|
||||
#endif
|
||||
#if __has_include(<PromiseKit/UIAlertView+AnyPromise.h>)
|
||||
#import <PromiseKit/UIAlertView+AnyPromise.h>
|
||||
#endif
|
||||
#if __has_include(<PromiseKit/UIView+AnyPromise.h>)
|
||||
#import <PromiseKit/UIView+AnyPromise.h>
|
||||
#endif
|
||||
#if __has_include(<PromiseKit/UIViewController+AnyPromise.h>)
|
||||
#import <PromiseKit/UIViewController+AnyPromise.h>
|
||||
#endif
|
||||
#endif
|
156
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/State.swift
generated
Normal file
156
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/State.swift
generated
Normal file
@ -0,0 +1,156 @@
|
||||
import Dispatch
|
||||
import Foundation // NSLog
|
||||
|
||||
enum Seal<R> {
|
||||
case Pending(Handlers<R>)
|
||||
case Resolved(R)
|
||||
}
|
||||
|
||||
enum Resolution<T> {
|
||||
case Fulfilled(T)
|
||||
case Rejected(ErrorType, ErrorConsumptionToken)
|
||||
}
|
||||
|
||||
// would be a protocol, but you can't have typed variables of “generic”
|
||||
// protocols in Swift 2. That is, I couldn’t do var state: State<R> when
|
||||
// it was a protocol. There is no work around.
|
||||
class State<R> {
|
||||
func get() -> R? { fatalError("Abstract Base Class") }
|
||||
func get(body: (Seal<R>) -> Void) { fatalError("Abstract Base Class") }
|
||||
}
|
||||
|
||||
class UnsealedState<R>: State<R> {
|
||||
private let barrier = dispatch_queue_create("org.promisekit.barrier", DISPATCH_QUEUE_CONCURRENT)
|
||||
private var seal: Seal<R>
|
||||
|
||||
/**
|
||||
Quick return, but will not provide the handlers array because
|
||||
it could be modified while you are using it by another thread.
|
||||
If you need the handlers, use the second `get` variant.
|
||||
*/
|
||||
override func get() -> R? {
|
||||
var result: R?
|
||||
dispatch_sync(barrier) {
|
||||
if case .Resolved(let resolution) = self.seal {
|
||||
result = resolution
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
override func get(body: (Seal<R>) -> Void) {
|
||||
var sealed = false
|
||||
dispatch_sync(barrier) {
|
||||
switch self.seal {
|
||||
case .Resolved:
|
||||
sealed = true
|
||||
case .Pending:
|
||||
sealed = false
|
||||
}
|
||||
}
|
||||
if !sealed {
|
||||
dispatch_barrier_sync(barrier) {
|
||||
switch (self.seal) {
|
||||
case .Pending:
|
||||
body(self.seal)
|
||||
case .Resolved:
|
||||
sealed = true // welcome to race conditions
|
||||
}
|
||||
}
|
||||
}
|
||||
if sealed {
|
||||
body(seal)
|
||||
}
|
||||
}
|
||||
|
||||
required init(inout resolver: ((R) -> Void)!) {
|
||||
seal = .Pending(Handlers<R>())
|
||||
super.init()
|
||||
resolver = { resolution in
|
||||
var handlers: Handlers<R>?
|
||||
dispatch_barrier_sync(self.barrier) {
|
||||
if case .Pending(let hh) = self.seal {
|
||||
self.seal = .Resolved(resolution)
|
||||
handlers = hh
|
||||
}
|
||||
}
|
||||
if let handlers = handlers {
|
||||
for handler in handlers {
|
||||
handler(resolution)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
if case .Pending = seal {
|
||||
NSLog("PromiseKit: Pending Promise deallocated! This is usually a bug")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class SealedState<R>: State<R> {
|
||||
private let resolution: R
|
||||
|
||||
init(resolution: R) {
|
||||
self.resolution = resolution
|
||||
}
|
||||
|
||||
override func get() -> R? {
|
||||
return resolution
|
||||
}
|
||||
|
||||
override func get(body: (Seal<R>) -> Void) {
|
||||
body(.Resolved(resolution))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class Handlers<R>: SequenceType {
|
||||
var bodies: [(R)->Void] = []
|
||||
|
||||
func append(body: (R)->Void) {
|
||||
bodies.append(body)
|
||||
}
|
||||
|
||||
func generate() -> IndexingGenerator<[(R)->Void]> {
|
||||
return bodies.generate()
|
||||
}
|
||||
|
||||
var count: Int {
|
||||
return bodies.count
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
extension Resolution: CustomStringConvertible {
|
||||
var description: String {
|
||||
switch self {
|
||||
case .Fulfilled(let value):
|
||||
return "Fulfilled with value: \(value)"
|
||||
case .Rejected(let error):
|
||||
return "Rejected with error: \(error)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension UnsealedState: CustomStringConvertible {
|
||||
var description: String {
|
||||
var rv: String!
|
||||
get { seal in
|
||||
switch seal {
|
||||
case .Pending(let handlers):
|
||||
rv = "Pending with \(handlers.count) handlers"
|
||||
case .Resolved(let resolution):
|
||||
rv = "\(resolution)"
|
||||
}
|
||||
}
|
||||
return "UnsealedState: \(rv)"
|
||||
}
|
||||
}
|
||||
|
||||
extension SealedState: CustomStringConvertible {
|
||||
var description: String {
|
||||
return "SealedState: \(resolution)"
|
||||
}
|
||||
}
|
106
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/URLDataPromise.swift
generated
Normal file
106
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/URLDataPromise.swift
generated
Normal file
@ -0,0 +1,106 @@
|
||||
import Foundation
|
||||
|
||||
public enum Encoding {
|
||||
case JSON(NSJSONReadingOptions)
|
||||
}
|
||||
|
||||
public class URLDataPromise: Promise<NSData> {
|
||||
public func asDataAndResponse() -> Promise<(NSData, NSURLResponse)> {
|
||||
return then(on: zalgo) { ($0, self.URLResponse) }
|
||||
}
|
||||
|
||||
public func asString() -> Promise<String> {
|
||||
return then(on: waldo) { data -> String in
|
||||
guard let str = NSString(data: data, encoding: self.URLResponse.stringEncoding ?? NSUTF8StringEncoding) else {
|
||||
throw URLError.StringEncoding(self.URLRequest, data, self.URLResponse)
|
||||
}
|
||||
return str as String
|
||||
}
|
||||
}
|
||||
|
||||
public func asArray(encoding: Encoding = .JSON(.AllowFragments)) -> Promise<NSArray> {
|
||||
return then(on: waldo) { data -> NSArray in
|
||||
switch encoding {
|
||||
case .JSON(let options):
|
||||
guard !data.b0rkedEmptyRailsResponse else { return NSArray() }
|
||||
let json = try NSJSONSerialization.JSONObjectWithData(data, options: options)
|
||||
guard let array = json as? NSArray else { throw JSONError.UnexpectedRootNode(json) }
|
||||
return array
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func asDictionary(encoding: Encoding = .JSON(.AllowFragments)) -> Promise<NSDictionary> {
|
||||
return then(on: waldo) { data -> NSDictionary in
|
||||
switch encoding {
|
||||
case .JSON(let options):
|
||||
guard !data.b0rkedEmptyRailsResponse else { return NSDictionary() }
|
||||
let json = try NSJSONSerialization.JSONObjectWithData(data, options: options)
|
||||
guard let dict = json as? NSDictionary else { throw JSONError.UnexpectedRootNode(json) }
|
||||
return dict
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private override init(@noescape resolvers: (fulfill: (NSData) -> Void, reject: (ErrorType) -> Void) throws -> Void) {
|
||||
super.init(resolvers: resolvers)
|
||||
}
|
||||
|
||||
public override init(error: ErrorType) {
|
||||
super.init(error: error)
|
||||
}
|
||||
|
||||
private var URLRequest: NSURLRequest!
|
||||
private var URLResponse: NSURLResponse!
|
||||
|
||||
public class func go(request: NSURLRequest, @noescape body: ((NSData?, NSURLResponse?, NSError?) -> Void) -> Void) -> URLDataPromise {
|
||||
var promise: URLDataPromise!
|
||||
promise = URLDataPromise { fulfill, reject in
|
||||
body { data, rsp, error in
|
||||
promise.URLRequest = request
|
||||
promise.URLResponse = rsp
|
||||
|
||||
if let error = error {
|
||||
reject(URLError.UnderlyingCocoaError(request, data, rsp, error))
|
||||
} else if let data = data, rsp = rsp as? NSHTTPURLResponse where rsp.statusCode >= 200 && rsp.statusCode < 300 {
|
||||
fulfill(data)
|
||||
} else if let data = data where !(rsp is NSHTTPURLResponse) {
|
||||
fulfill(data)
|
||||
} else {
|
||||
reject(URLError.BadResponse(request, data, rsp))
|
||||
}
|
||||
}
|
||||
}
|
||||
return promise
|
||||
}
|
||||
}
|
||||
|
||||
#if os(iOS)
|
||||
import UIKit.UIImage
|
||||
|
||||
extension URLDataPromise {
|
||||
public func asImage() -> Promise<UIImage> {
|
||||
return then(on: waldo) { data -> UIImage in
|
||||
guard let img = UIImage(data: data), cgimg = img.CGImage else {
|
||||
throw URLError.InvalidImageData(self.URLRequest, data)
|
||||
}
|
||||
return UIImage(CGImage: cgimg, scale: img.scale, orientation: img.imageOrientation)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
extension NSURLResponse {
|
||||
private var stringEncoding: UInt? {
|
||||
guard let encodingName = textEncodingName else { return nil }
|
||||
let encoding = CFStringConvertIANACharSetNameToEncoding(encodingName)
|
||||
guard encoding != kCFStringEncodingInvalidId else { return nil }
|
||||
return CFStringConvertEncodingToNSStringEncoding(encoding)
|
||||
}
|
||||
}
|
||||
|
||||
extension NSData {
|
||||
private var b0rkedEmptyRailsResponse: Bool {
|
||||
return self == NSData(bytes: " ", length: 1)
|
||||
}
|
||||
}
|
59
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/Umbrella.h
generated
Normal file
59
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/Umbrella.h
generated
Normal file
@ -0,0 +1,59 @@
|
||||
#import <Foundation/NSObjCRuntime.h>
|
||||
#import <Foundation/NSString.h>
|
||||
|
||||
FOUNDATION_EXPORT double PromiseKitVersionNumber;
|
||||
FOUNDATION_EXPORT const unsigned char PromiseKitVersionString[];
|
||||
|
||||
extern NSString * const PMKErrorDomain;
|
||||
|
||||
#define PMKFailingPromiseIndexKey @"PMKFailingPromiseIndexKey"
|
||||
#define PMKURLErrorFailingURLResponseKey @"PMKURLErrorFailingURLResponseKey"
|
||||
#define PMKURLErrorFailingDataKey @"PMKURLErrorFailingDataKey"
|
||||
#define PMKURLErrorFailingStringKey @"PMKURLErrorFailingStringKey"
|
||||
#define PMKJSONErrorJSONObjectKey @"PMKJSONErrorJSONObjectKey"
|
||||
#define PMKJoinPromisesKey @"PMKJoinPromisesKey"
|
||||
|
||||
#define PMKUnexpectedError 1l
|
||||
#define PMKUnknownError 2l
|
||||
#define PMKInvalidUsageError 3l
|
||||
#define PMKAccessDeniedError 4l
|
||||
#define PMKOperationCancelled 5l
|
||||
#define PMKNotFoundError 6l
|
||||
#define PMKJSONError 7l
|
||||
#define PMKOperationFailed 8l
|
||||
#define PMKTaskError 9l
|
||||
#define PMKJoinError 10l
|
||||
|
||||
#if !(defined(PMKEZBake) && defined(SWIFT_CLASS))
|
||||
#if !defined(SWIFT_PASTE)
|
||||
# define SWIFT_PASTE_HELPER(x, y) x##y
|
||||
# define SWIFT_PASTE(x, y) SWIFT_PASTE_HELPER(x, y)
|
||||
#endif
|
||||
#if !defined(SWIFT_METATYPE)
|
||||
# define SWIFT_METATYPE(X) Class
|
||||
#endif
|
||||
|
||||
#if defined(__has_attribute) && __has_attribute(objc_runtime_name)
|
||||
# define SWIFT_RUNTIME_NAME(X) __attribute__((objc_runtime_name(X)))
|
||||
#else
|
||||
# define SWIFT_RUNTIME_NAME(X)
|
||||
#endif
|
||||
#if !defined(SWIFT_CLASS_EXTRA)
|
||||
# define SWIFT_CLASS_EXTRA
|
||||
#endif
|
||||
#if !defined(SWIFT_CLASS)
|
||||
# if defined(__has_attribute) && __has_attribute(objc_subclassing_restricted)
|
||||
# define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_CLASS_EXTRA
|
||||
# else
|
||||
# define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA
|
||||
# endif
|
||||
#endif
|
||||
|
||||
SWIFT_CLASS("AnyPromise")
|
||||
@interface AnyPromise : NSObject
|
||||
@property (nonatomic, readonly) BOOL pending;
|
||||
@property (nonatomic, readonly) BOOL resolved;
|
||||
@property (nonatomic, readonly) BOOL fulfilled;
|
||||
@property (nonatomic, readonly) BOOL rejected;
|
||||
@end
|
||||
#endif
|
13
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/after.m
generated
Normal file
13
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/after.m
generated
Normal file
@ -0,0 +1,13 @@
|
||||
#import "AnyPromise.h"
|
||||
@import Dispatch;
|
||||
@import Foundation.NSDate;
|
||||
@import Foundation.NSValue;
|
||||
|
||||
AnyPromise *PMKAfter(NSTimeInterval duration) {
|
||||
return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) {
|
||||
dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC));
|
||||
dispatch_after(time, dispatch_get_global_queue(0, 0), ^{
|
||||
resolve(@(duration));
|
||||
});
|
||||
}];
|
||||
}
|
20
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/after.swift
generated
Normal file
20
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/after.swift
generated
Normal file
@ -0,0 +1,20 @@
|
||||
import Dispatch
|
||||
import Foundation.NSDate
|
||||
|
||||
/**
|
||||
```
|
||||
after(1).then {
|
||||
//…
|
||||
}
|
||||
```
|
||||
|
||||
- Returns: A new promise that resolves after the specified duration.
|
||||
- Parameter duration: The duration in seconds to wait before this promise is resolve.
|
||||
*/
|
||||
public func after(delay: NSTimeInterval) -> Promise<Void> {
|
||||
return Promise { fulfill, _ in
|
||||
let delta = delay * NSTimeInterval(NSEC_PER_SEC)
|
||||
let when = dispatch_time(DISPATCH_TIME_NOW, Int64(delta))
|
||||
dispatch_after(when, dispatch_get_global_queue(0, 0), fulfill)
|
||||
}
|
||||
}
|
10
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/dispatch_promise.m
generated
Normal file
10
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/dispatch_promise.m
generated
Normal file
@ -0,0 +1,10 @@
|
||||
@import Dispatch;
|
||||
#import "PromiseKit.h"
|
||||
|
||||
AnyPromise *dispatch_promise(id block) {
|
||||
return dispatch_promise_on(dispatch_get_global_queue(0, 0), block);
|
||||
}
|
||||
|
||||
AnyPromise *dispatch_promise_on(dispatch_queue_t queue, id block) {
|
||||
return [AnyPromise promiseWithValue:nil].thenOn(queue, block);
|
||||
}
|
23
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/dispatch_promise.swift
generated
Normal file
23
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/dispatch_promise.swift
generated
Normal file
@ -0,0 +1,23 @@
|
||||
import Dispatch
|
||||
import Foundation.NSError
|
||||
|
||||
/**
|
||||
```
|
||||
dispatch_promise {
|
||||
try md5(input)
|
||||
}.then { md5 in
|
||||
//…
|
||||
}
|
||||
```
|
||||
|
||||
- Parameter on: The queue on which to dispatch `body`.
|
||||
- Parameter body: The closure that resolves this promise.
|
||||
- Returns: A new promise resolved by the provided closure.
|
||||
*/
|
||||
public func dispatch_promise<T>(on queue: dispatch_queue_t = dispatch_get_global_queue(0, 0), body: () throws -> T) -> Promise<T> {
|
||||
return Promise(sealant: { resolve in
|
||||
contain_zalgo(queue, rejecter: resolve) {
|
||||
resolve(.Fulfilled(try body()))
|
||||
}
|
||||
})
|
||||
}
|
24
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/hang.m
generated
Normal file
24
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/hang.m
generated
Normal file
@ -0,0 +1,24 @@
|
||||
#import "AnyPromise.h"
|
||||
#import "AnyPromise+Private.h"
|
||||
@import CoreFoundation.CFRunLoop;
|
||||
|
||||
id PMKHang(AnyPromise *promise) {
|
||||
if (promise.pending) {
|
||||
static CFRunLoopSourceContext context;
|
||||
|
||||
CFRunLoopRef runLoop = CFRunLoopGetCurrent();
|
||||
CFRunLoopSourceRef runLoopSource = CFRunLoopSourceCreate(NULL, 0, &context);
|
||||
CFRunLoopAddSource(runLoop, runLoopSource, kCFRunLoopDefaultMode);
|
||||
|
||||
promise.finally(^{
|
||||
CFRunLoopStop(runLoop);
|
||||
});
|
||||
while (promise.pending) {
|
||||
CFRunLoopRun();
|
||||
}
|
||||
CFRunLoopRemoveSource(runLoop, runLoopSource, kCFRunLoopDefaultMode);
|
||||
CFRelease(runLoopSource);
|
||||
}
|
||||
|
||||
return promise.value;
|
||||
}
|
47
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/join.m
generated
Normal file
47
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/join.m
generated
Normal file
@ -0,0 +1,47 @@
|
||||
#import "AnyPromise.h"
|
||||
#import "AnyPromise+Private.h"
|
||||
@import Foundation.NSDictionary;
|
||||
@import Foundation.NSError;
|
||||
@import Foundation.NSNull;
|
||||
#import <libkern/OSAtomic.h>
|
||||
#import <PromiseKit/Umbrella.h>
|
||||
|
||||
@implementation AnyPromise (join)
|
||||
|
||||
AnyPromise *PMKJoin(NSArray *promises) {
|
||||
if (promises == nil)
|
||||
return [AnyPromise promiseWithValue:[NSError errorWithDomain:PMKErrorDomain code:PMKInvalidUsageError userInfo:@{NSLocalizedDescriptionKey: @"PMKJoin(nil)"}]];
|
||||
|
||||
if (promises.count == 0)
|
||||
return [AnyPromise promiseWithValue:promises];
|
||||
|
||||
return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) {
|
||||
NSPointerArray *results = NSPointerArrayMake(promises.count);
|
||||
__block int32_t countdown = (int32_t)promises.count;
|
||||
__block BOOL rejected = NO;
|
||||
|
||||
[promises enumerateObjectsUsingBlock:^(AnyPromise *promise, NSUInteger ii, BOOL *stop) {
|
||||
[promise pipe:^(id value) {
|
||||
|
||||
if (IsError(value)) {
|
||||
[value pmk_consume];
|
||||
rejected = YES;
|
||||
}
|
||||
|
||||
[results replacePointerAtIndex:ii withPointer:(__bridge void *)(value ?: [NSNull null])];
|
||||
|
||||
if (OSAtomicDecrement32(&countdown) == 0) {
|
||||
if (!rejected) {
|
||||
resolve(results.allObjects);
|
||||
} else {
|
||||
id userInfo = @{PMKJoinPromisesKey: promises};
|
||||
id err = [NSError errorWithDomain:PMKErrorDomain code:PMKJoinError userInfo:userInfo];
|
||||
resolve(err);
|
||||
}
|
||||
}
|
||||
}];
|
||||
}];
|
||||
}];
|
||||
}
|
||||
|
||||
@end
|
44
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/join.swift
generated
Normal file
44
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/join.swift
generated
Normal file
@ -0,0 +1,44 @@
|
||||
import Dispatch
|
||||
|
||||
/**
|
||||
Waits on all provided promises.
|
||||
|
||||
`when` rejects as soon as one of the provided promises rejects. `join` waits on all provided promises, then rejects if any of those promises rejected, otherwise it fulfills with values from the provided promises.
|
||||
|
||||
join(promise1, promise2, promise3).then { results in
|
||||
//…
|
||||
}.error { error in
|
||||
switch error {
|
||||
case Error.Join(let promises):
|
||||
//…
|
||||
}
|
||||
}
|
||||
|
||||
- Returns: A new promise that resolves once all the provided promises resolve.
|
||||
*/
|
||||
public func join<T>(promises: Promise<T>...) -> Promise<[T]> {
|
||||
var countdown = promises.count
|
||||
let barrier = dispatch_queue_create("org.promisekit.barrier.join", DISPATCH_QUEUE_CONCURRENT)
|
||||
var rejected = false
|
||||
|
||||
return Promise { fulfill, reject in
|
||||
for promise in promises {
|
||||
promise.pipe { resolution in
|
||||
dispatch_barrier_sync(barrier) {
|
||||
if case .Rejected(_, let token) = resolution {
|
||||
token.consumed = true // the parent Error.Join consumes all
|
||||
rejected = true
|
||||
}
|
||||
|
||||
if --countdown == 0 {
|
||||
if rejected {
|
||||
reject(Error.Join(promises))
|
||||
} else {
|
||||
fulfill(promises.map{ $0.value! })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
20
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/race.swift
generated
Normal file
20
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/race.swift
generated
Normal file
@ -0,0 +1,20 @@
|
||||
|
||||
/**
|
||||
Resolves with the first resolving promise from a set of promises.
|
||||
|
||||
```
|
||||
race(promise1, promise2, promise3).then { winner in
|
||||
//…
|
||||
}
|
||||
```
|
||||
|
||||
- Returns: A new promise that resolves when the first promise in the provided promises resolves.
|
||||
- Warning: If any of the provided promises reject, the returned promise is rejected.
|
||||
*/
|
||||
public func race<T>(promises: Promise<T>...) -> Promise<T> {
|
||||
return Promise(sealant: { resolve in
|
||||
for promise in promises {
|
||||
promise.pipe(resolve)
|
||||
}
|
||||
})
|
||||
}
|
86
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/when.m
generated
Normal file
86
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/when.m
generated
Normal file
@ -0,0 +1,86 @@
|
||||
#import "AnyPromise.h"
|
||||
#import "AnyPromise+Private.h"
|
||||
@import Foundation.NSDictionary;
|
||||
@import Foundation.NSError;
|
||||
@import Foundation.NSProgress;
|
||||
@import Foundation.NSNull;
|
||||
#import <libkern/OSAtomic.h>
|
||||
#import "Umbrella.h"
|
||||
|
||||
// NSProgress resources:
|
||||
// * https://robots.thoughtbot.com/asynchronous-nsprogress
|
||||
// * http://oleb.net/blog/2014/03/nsprogress/
|
||||
// NSProgress! Beware!
|
||||
// * https://github.com/AFNetworking/AFNetworking/issues/2261
|
||||
|
||||
AnyPromise *PMKWhen(id promises) {
|
||||
if (promises == nil)
|
||||
return [AnyPromise promiseWithValue:[NSError errorWithDomain:PMKErrorDomain code:PMKInvalidUsageError userInfo:@{NSLocalizedDescriptionKey: @"PMKWhen(nil)"}]];
|
||||
|
||||
if ([promises isKindOfClass:[NSArray class]] || [promises isKindOfClass:[NSDictionary class]]) {
|
||||
if ([promises count] == 0)
|
||||
return [AnyPromise promiseWithValue:promises];
|
||||
} else if ([promises isKindOfClass:[AnyPromise class]]) {
|
||||
promises = @[promises];
|
||||
} else {
|
||||
return [AnyPromise promiseWithValue:promises];
|
||||
}
|
||||
|
||||
#ifndef PMKDisableProgress
|
||||
NSProgress *progress = [NSProgress progressWithTotalUnitCount:[promises count]];
|
||||
progress.pausable = NO;
|
||||
progress.cancellable = NO;
|
||||
#else
|
||||
struct PMKProgress {
|
||||
int completedUnitCount;
|
||||
int totalUnitCount;
|
||||
};
|
||||
__block struct PMKProgress progress;
|
||||
#endif
|
||||
|
||||
__block int32_t countdown = (int32_t)[promises count];
|
||||
BOOL const isdict = [promises isKindOfClass:[NSDictionary class]];
|
||||
|
||||
return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) {
|
||||
NSInteger index = 0;
|
||||
|
||||
for (__strong id key in promises) {
|
||||
AnyPromise *promise = isdict ? promises[key] : key;
|
||||
if (!isdict) key = @(index);
|
||||
|
||||
if (![promise isKindOfClass:[AnyPromise class]])
|
||||
promise = [AnyPromise promiseWithValue:promise];
|
||||
|
||||
[promise pipe:^(id value){
|
||||
if (progress.fractionCompleted >= 1)
|
||||
return;
|
||||
|
||||
if (IsError(value)) {
|
||||
progress.completedUnitCount = progress.totalUnitCount;
|
||||
resolve(NSErrorSupplement(value, @{PMKFailingPromiseIndexKey: key}));
|
||||
}
|
||||
else if (OSAtomicDecrement32(&countdown) == 0) {
|
||||
progress.completedUnitCount = progress.totalUnitCount;
|
||||
|
||||
id results;
|
||||
if (isdict) {
|
||||
results = [NSMutableDictionary new];
|
||||
for (id key in promises) {
|
||||
id promise = promises[key];
|
||||
results[key] = IsPromise(promise) ? ((AnyPromise *)promise).value : promise;
|
||||
}
|
||||
} else {
|
||||
results = [NSMutableArray new];
|
||||
for (AnyPromise *promise in promises) {
|
||||
id value = IsPromise(promise) ? (promise.value ?: [NSNull null]) : promise;
|
||||
[results addObject:value];
|
||||
}
|
||||
}
|
||||
resolve(results);
|
||||
} else {
|
||||
progress.completedUnitCount++;
|
||||
}
|
||||
}];
|
||||
}
|
||||
}];
|
||||
}
|
87
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/when.swift
generated
Normal file
87
samples/client/petstore/swift/SwaggerClientTests/Pods/PromiseKit/Sources/when.swift
generated
Normal file
@ -0,0 +1,87 @@
|
||||
import Foundation.NSProgress
|
||||
|
||||
private func _when<T>(promises: [Promise<T>]) -> Promise<Void> {
|
||||
let (rootPromise, fulfill, reject) = Promise<Void>.pendingPromise()
|
||||
#if !PMKDisableProgress
|
||||
let progress = NSProgress(totalUnitCount: Int64(promises.count))
|
||||
progress.cancellable = false
|
||||
progress.pausable = false
|
||||
#else
|
||||
var progress: (completedUnitCount: Int, totalUnitCount: Int) = (0, 0)
|
||||
#endif
|
||||
var countdown = promises.count
|
||||
if countdown == 0 {
|
||||
fulfill()
|
||||
return rootPromise
|
||||
}
|
||||
let barrier = dispatch_queue_create("org.promisekit.barrier.when", DISPATCH_QUEUE_CONCURRENT)
|
||||
|
||||
for (index, promise) in promises.enumerate() {
|
||||
promise.pipe { resolution in
|
||||
dispatch_barrier_sync(barrier) {
|
||||
switch resolution {
|
||||
case .Rejected(let error, let token):
|
||||
token.consumed = true // all errors are consumed by the parent Error.When
|
||||
if rootPromise.pending {
|
||||
progress.completedUnitCount = progress.totalUnitCount
|
||||
reject(Error.When(index, error))
|
||||
}
|
||||
case .Fulfilled:
|
||||
guard rootPromise.pending else { return }
|
||||
progress.completedUnitCount++
|
||||
if --countdown == 0 {
|
||||
fulfill()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return rootPromise
|
||||
}
|
||||
|
||||
/**
|
||||
Wait for all promises in a set to resolve.
|
||||
|
||||
For example:
|
||||
|
||||
when(promise1, promise2).then { results in
|
||||
//…
|
||||
}.error { error in
|
||||
switch error {
|
||||
case Error.When(let index, NSURLError.NoConnection):
|
||||
//…
|
||||
case Error.When(let index, CLError.NotAuthorized):
|
||||
//…
|
||||
}
|
||||
}
|
||||
|
||||
- Warning: If *any* of the provided promises reject, the returned promise is immediately rejected with that promise’s rejection. The error’s `userInfo` object is supplemented with `PMKFailingPromiseIndexKey`.
|
||||
- Warning: In the event of rejection the other promises will continue to resolve and, as per any other promise, will either fulfill or reject. This is the right pattern for `getter` style asynchronous tasks, but often for `setter` tasks (eg. storing data on a server), you most likely will need to wait on all tasks and then act based on which have succeeded and which have failed, in such situations use `join`.
|
||||
- Parameter promises: The promises upon which to wait before the returned promise resolves.
|
||||
- Returns: A new promise that resolves when all the provided promises fulfill or one of the provided promises rejects.
|
||||
- SeeAlso: `join()`
|
||||
*/
|
||||
public func when<T>(promises: [Promise<T>]) -> Promise<[T]> {
|
||||
return _when(promises).then(on: zalgo) { promises.map{ $0.value! } }
|
||||
}
|
||||
|
||||
public func when<T>(promises: Promise<T>...) -> Promise<[T]> {
|
||||
return when(promises)
|
||||
}
|
||||
|
||||
public func when(promises: Promise<Void>...) -> Promise<Void> {
|
||||
return _when(promises)
|
||||
}
|
||||
|
||||
public func when(promises: [Promise<Void>]) -> Promise<Void> {
|
||||
return _when(promises)
|
||||
}
|
||||
|
||||
public func when<U, V>(pu: Promise<U>, _ pv: Promise<V>) -> Promise<(U, V)> {
|
||||
return _when([pu.asVoid(), pv.asVoid()]).then(on: zalgo) { (pu.value!, pv.value!) }
|
||||
}
|
||||
|
||||
public func when<U, V, X>(pu: Promise<U>, _ pv: Promise<V>, _ px: Promise<X>) -> Promise<(U, V, X)> {
|
||||
return _when([pu.asVoid(), pv.asVoid(), px.asVoid()]).then(on: zalgo) { (pu.value!, pv.value!, px.value!) }
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
@interface PodsDummy_Alamofire : NSObject
|
||||
@end
|
||||
@implementation PodsDummy_Alamofire
|
||||
@end
|
@ -0,0 +1,4 @@
|
||||
#ifdef __OBJC__
|
||||
#import <UIKit/UIKit.h>
|
||||
#endif
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user