mirror of
https://github.com/valitydev/openapi-generator.git
synced 2024-11-06 10:35:25 +00:00
* fix #3477, add RxSwift support for Swift * make the SwaggerClient scheme shared
This commit is contained in:
parent
8c2267cd3d
commit
beaf1fc7aa
@ -34,3 +34,7 @@ java $JAVA_OPTS -jar $executable $ags
|
||||
ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l swift -c ./bin/swift-petstore-promisekit.json -o samples/client/petstore/swift/promisekit"
|
||||
echo "#### Petstore Swift API client (promisekit) ####"
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
||||
ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l swift -c ./bin/swift-petstore-rxswift.json -o samples/client/petstore/swift/rxswift"
|
||||
echo "#### Petstore Swift API client (rxswift) ####"
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
7
bin/swift-petstore-rxswift.json
Normal file
7
bin/swift-petstore-rxswift.json
Normal file
@ -0,0 +1,7 @@
|
||||
{
|
||||
"podSummary": "PetstoreClient",
|
||||
"podHomepage": "https://github.com/swagger-api/swagger-codegen",
|
||||
"podAuthors": "",
|
||||
"projectName": "PetstoreClient",
|
||||
"responseAs": "RxSwift"
|
||||
}
|
31
bin/swift-petstore-rxswift.sh
Executable file
31
bin/swift-petstore-rxswift.sh
Executable file
@ -0,0 +1,31 @@
|
||||
#!/bin/sh
|
||||
|
||||
SCRIPT="$0"
|
||||
|
||||
while [ -h "$SCRIPT" ] ; do
|
||||
ls=`ls -ld "$SCRIPT"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
SCRIPT="$link"
|
||||
else
|
||||
SCRIPT=`dirname "$SCRIPT"`/"$link"
|
||||
fi
|
||||
done
|
||||
|
||||
if [ ! -d "${APP_DIR}" ]; then
|
||||
APP_DIR=`dirname "$SCRIPT"`/..
|
||||
APP_DIR=`cd "${APP_DIR}"; pwd`
|
||||
fi
|
||||
|
||||
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
|
||||
|
||||
if [ ! -f "$executable" ]
|
||||
then
|
||||
mvn clean package
|
||||
fi
|
||||
|
||||
# if you've executed sbt assembly previously it will use that instead.
|
||||
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
|
||||
ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l swift -c ./bin/swift-petstore-rxswift.json -o samples/client/petstore/swift/rxswift"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
@ -40,7 +40,8 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
public static final String SWIFT_USE_API_NAMESPACE = "swiftUseApiNamespace";
|
||||
public static final String DEFAULT_POD_AUTHORS = "Swagger Codegen";
|
||||
protected static final String LIBRARY_PROMISE_KIT = "PromiseKit";
|
||||
protected static final String[] RESPONSE_LIBRARIES = { LIBRARY_PROMISE_KIT };
|
||||
protected static final String LIBRARY_RX_SWIFT = "RxSwift";
|
||||
protected static final String[] RESPONSE_LIBRARIES = { LIBRARY_PROMISE_KIT, LIBRARY_RX_SWIFT };
|
||||
protected String projectName = "SwaggerClient";
|
||||
protected boolean unwrapRequired;
|
||||
protected boolean swiftUseApiNamespace;
|
||||
@ -186,6 +187,9 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
if (ArrayUtils.contains(responseAs, LIBRARY_PROMISE_KIT)) {
|
||||
additionalProperties.put("usePromiseKit", true);
|
||||
}
|
||||
if (ArrayUtils.contains(responseAs, LIBRARY_RX_SWIFT)) {
|
||||
additionalProperties.put("useRxSwift", true);
|
||||
}
|
||||
|
||||
// Setup swiftUseApiNamespace option, which makes all the API classes inner-class of {{projectName}}API
|
||||
if (additionalProperties.containsKey(SWIFT_USE_API_NAMESPACE)) {
|
||||
|
@ -1,2 +1,3 @@
|
||||
github "Alamofire/Alamofire" >= 3.1.0{{#usePromiseKit}}
|
||||
github "mxcl/PromiseKit" >=1.5.3{{/usePromiseKit}}
|
||||
github "mxcl/PromiseKit" >=1.5.3{{/usePromiseKit}}{{#useRxSwift}}
|
||||
github "ReactiveX/RxSwift" ~> 2.0{{/useRxSwift}}
|
||||
|
@ -15,6 +15,7 @@ Pod::Spec.new do |s|
|
||||
s.screenshots = {{& podScreenshots}}{{/podScreenshots}}{{#podDocumentationURL}}
|
||||
s.documentation_url = '{{podDocumentationURL}}'{{/podDocumentationURL}}
|
||||
s.source_files = '{{projectName}}/Classes/Swaggers/**/*.swift'{{#usePromiseKit}}
|
||||
s.dependency 'PromiseKit', '~> 3.1.1'{{/usePromiseKit}}
|
||||
s.dependency 'PromiseKit', '~> 3.1.1'{{/usePromiseKit}}{{#useRxSwift}}
|
||||
s.dependency 'RxSwift', '~> 2.0'{{/useRxSwift}}
|
||||
s.dependency 'Alamofire', '~> 3.4.1'
|
||||
end
|
||||
|
@ -6,7 +6,8 @@
|
||||
//
|
||||
|
||||
import Alamofire{{#usePromiseKit}}
|
||||
import PromiseKit{{/usePromiseKit}}
|
||||
import PromiseKit{{/usePromiseKit}}{{#useRxSwift}}
|
||||
import RxSwift{{/useRxSwift}}
|
||||
|
||||
{{#swiftUseApiNamespace}}
|
||||
extension {{projectName}}API {
|
||||
@ -62,6 +63,28 @@ public class {{classname}}: APIBase {
|
||||
return deferred.promise
|
||||
}
|
||||
{{/usePromiseKit}}
|
||||
{{#useRxSwift}}
|
||||
/**
|
||||
{{#summary}}
|
||||
{{{summary}}}
|
||||
{{/summary}}{{#allParams}}
|
||||
- parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
|
||||
- returns: Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>
|
||||
*/
|
||||
public class func {{operationId}}({{#allParams}}{{^secondaryParam}}{{paramName}} {{/secondaryParam}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {
|
||||
return Observable.create { observer -> Disposable in
|
||||
{{operationId}}({{#allParams}}{{paramName}}: {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { {{#returnType}}data, {{/returnType}}error in
|
||||
if let error = error {
|
||||
observer.on(.Error(error as ErrorType))
|
||||
} else {
|
||||
observer.on(.Next({{#returnType}}data!{{/returnType}}))
|
||||
}
|
||||
observer.on(.Completed)
|
||||
}
|
||||
return NopDisposable.instance
|
||||
}
|
||||
}
|
||||
{{/useRxSwift}}
|
||||
|
||||
/**
|
||||
{{#summary}}
|
||||
|
63
samples/client/petstore/swift/rxswift/.gitignore
vendored
Normal file
63
samples/client/petstore/swift/rxswift/.gitignore
vendored
Normal file
@ -0,0 +1,63 @@
|
||||
# Xcode
|
||||
#
|
||||
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
|
||||
|
||||
## Build generated
|
||||
build/
|
||||
DerivedData
|
||||
|
||||
## Various settings
|
||||
*.pbxuser
|
||||
!default.pbxuser
|
||||
*.mode1v3
|
||||
!default.mode1v3
|
||||
*.mode2v3
|
||||
!default.mode2v3
|
||||
*.perspectivev3
|
||||
!default.perspectivev3
|
||||
xcuserdata
|
||||
|
||||
## Other
|
||||
*.xccheckout
|
||||
*.moved-aside
|
||||
*.xcuserstate
|
||||
*.xcscmblueprint
|
||||
|
||||
## Obj-C/Swift specific
|
||||
*.hmap
|
||||
*.ipa
|
||||
|
||||
## Playgrounds
|
||||
timeline.xctimeline
|
||||
playground.xcworkspace
|
||||
|
||||
# Swift Package Manager
|
||||
#
|
||||
# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.
|
||||
# Packages/
|
||||
.build/
|
||||
|
||||
# CocoaPods
|
||||
#
|
||||
# We recommend against adding the Pods directory to your .gitignore. However
|
||||
# you should judge for yourself, the pros and cons are mentioned at:
|
||||
# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
|
||||
#
|
||||
# Pods/
|
||||
|
||||
# Carthage
|
||||
#
|
||||
# Add this line if you want to avoid checking in source code from Carthage dependencies.
|
||||
# Carthage/Checkouts
|
||||
|
||||
Carthage/Build
|
||||
|
||||
# fastlane
|
||||
#
|
||||
# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the
|
||||
# screenshots whenever they are needed.
|
||||
# For more information about the recommended setup visit:
|
||||
# https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md
|
||||
|
||||
fastlane/report.xml
|
||||
fastlane/screenshots
|
@ -0,0 +1,23 @@
|
||||
# Swagger Codegen Ignore
|
||||
# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen
|
||||
|
||||
# Use this file to prevent files from being overwritten by the generator.
|
||||
# The patterns follow closely to .gitignore or .dockerignore.
|
||||
|
||||
# As an example, the C# client generator defines ApiClient.cs.
|
||||
# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line:
|
||||
#ApiClient.cs
|
||||
|
||||
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
|
||||
#foo/*/qux
|
||||
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
|
||||
|
||||
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
|
||||
#foo/**/qux
|
||||
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
|
||||
|
||||
# You can also negate patterns with an exclamation (!).
|
||||
# For example, you can ignore all files in a docs folder with the file extension .md:
|
||||
#docs/*.md
|
||||
# Then explicitly reverse the ignore rule for a single file:
|
||||
#!docs/README.md
|
2
samples/client/petstore/swift/rxswift/Cartfile
Normal file
2
samples/client/petstore/swift/rxswift/Cartfile
Normal file
@ -0,0 +1,2 @@
|
||||
github "Alamofire/Alamofire" >= 3.1.0
|
||||
github "ReactiveX/RxSwift" ~> 2.0
|
201
samples/client/petstore/swift/rxswift/LICENSE
Normal file
201
samples/client/petstore/swift/rxswift/LICENSE
Normal file
@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright {yyyy} {name of copyright owner}
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
14
samples/client/petstore/swift/rxswift/PetstoreClient.podspec
Normal file
14
samples/client/petstore/swift/rxswift/PetstoreClient.podspec
Normal file
@ -0,0 +1,14 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'PetstoreClient'
|
||||
s.ios.deployment_target = '8.0'
|
||||
s.osx.deployment_target = '10.9'
|
||||
s.version = '0.0.1'
|
||||
s.source = { :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' }
|
||||
s.authors = ''
|
||||
s.license = 'Apache License, Version 2.0'
|
||||
s.homepage = 'https://github.com/swagger-api/swagger-codegen'
|
||||
s.summary = 'PetstoreClient'
|
||||
s.source_files = 'PetstoreClient/Classes/Swaggers/**/*.swift'
|
||||
s.dependency 'RxSwift', '~> 2.0'
|
||||
s.dependency 'Alamofire', '~> 3.1.5'
|
||||
end
|
@ -0,0 +1,40 @@
|
||||
// APIHelper.swift
|
||||
//
|
||||
// Generated by swagger-codegen
|
||||
// https://github.com/swagger-api/swagger-codegen
|
||||
//
|
||||
|
||||
class APIHelper {
|
||||
static func rejectNil(source: [String:AnyObject?]) -> [String:AnyObject]? {
|
||||
var destination = [String:AnyObject]()
|
||||
for (key, nillableValue) in source {
|
||||
if let value: AnyObject = nillableValue {
|
||||
destination[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
if destination.isEmpty {
|
||||
return nil
|
||||
}
|
||||
return destination
|
||||
}
|
||||
|
||||
static func convertBoolToString(source: [String: AnyObject]?) -> [String:AnyObject]? {
|
||||
guard let source = source else {
|
||||
return nil
|
||||
}
|
||||
var destination = [String:AnyObject]()
|
||||
let theTrue = NSNumber(bool: true)
|
||||
let theFalse = NSNumber(bool: false)
|
||||
for (key, value) in source {
|
||||
switch value {
|
||||
case let x where x === theTrue || x === theFalse:
|
||||
destination[key] = "\(value as! Bool)"
|
||||
default:
|
||||
destination[key] = value
|
||||
}
|
||||
}
|
||||
return destination
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,75 @@
|
||||
// APIs.swift
|
||||
//
|
||||
// Generated by swagger-codegen
|
||||
// https://github.com/swagger-api/swagger-codegen
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
public class PetstoreClientAPI {
|
||||
public static var basePath = "http://petstore.swagger.io/v2"
|
||||
public static var credential: NSURLCredential?
|
||||
public static var customHeaders: [String:String] = [:]
|
||||
static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory()
|
||||
}
|
||||
|
||||
public class APIBase {
|
||||
func toParameters(encodable: JSONEncodable?) -> [String: AnyObject]? {
|
||||
let encoded: AnyObject? = encodable?.encodeToJSON()
|
||||
|
||||
if encoded! is [AnyObject] {
|
||||
var dictionary = [String:AnyObject]()
|
||||
for (index, item) in (encoded as! [AnyObject]).enumerate() {
|
||||
dictionary["\(index)"] = item
|
||||
}
|
||||
return dictionary
|
||||
} else {
|
||||
return encoded as? [String:AnyObject]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class RequestBuilder<T> {
|
||||
var credential: NSURLCredential?
|
||||
var headers: [String:String] = [:]
|
||||
let parameters: [String:AnyObject]?
|
||||
let isBody: Bool
|
||||
let method: String
|
||||
let URLString: String
|
||||
|
||||
/// Optional block to obtain a reference to the request's progress instance when available.
|
||||
public var onProgressReady: ((NSProgress) -> ())?
|
||||
|
||||
required public init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool) {
|
||||
self.method = method
|
||||
self.URLString = URLString
|
||||
self.parameters = parameters
|
||||
self.isBody = isBody
|
||||
|
||||
addHeaders(PetstoreClientAPI.customHeaders)
|
||||
}
|
||||
|
||||
public func addHeaders(aHeaders:[String:String]) {
|
||||
for (header, value) in aHeaders {
|
||||
headers[header] = value
|
||||
}
|
||||
}
|
||||
|
||||
public func execute(completion: (response: Response<T>?, error: ErrorType?) -> Void) { }
|
||||
|
||||
public func addHeader(name name: String, value: String) -> Self {
|
||||
if !value.isEmpty {
|
||||
headers[name] = value
|
||||
}
|
||||
return self
|
||||
}
|
||||
|
||||
public func addCredential() -> Self {
|
||||
self.credential = PetstoreClientAPI.credential
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
protocol RequestBuilderFactory {
|
||||
func getBuilder<T>() -> RequestBuilder<T>.Type
|
||||
}
|
@ -0,0 +1,608 @@
|
||||
//
|
||||
// PetAPI.swift
|
||||
//
|
||||
// Generated by swagger-codegen
|
||||
// https://github.com/swagger-api/swagger-codegen
|
||||
//
|
||||
|
||||
import Alamofire
|
||||
import RxSwift
|
||||
|
||||
|
||||
|
||||
public class PetAPI: APIBase {
|
||||
/**
|
||||
Add a new pet to the store
|
||||
|
||||
- parameter body: (body) Pet object that needs to be added to the store (optional)
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func addPet(body body: Pet? = nil, completion: ((error: ErrorType?) -> Void)) {
|
||||
addPetWithRequestBuilder(body: body).execute { (response, error) -> Void in
|
||||
completion(error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Add a new pet to the store
|
||||
|
||||
- parameter body: (body) Pet object that needs to be added to the store (optional)
|
||||
- returns: Observable<Void>
|
||||
*/
|
||||
public class func addPet(body body: Pet? = nil) -> Observable<Void> {
|
||||
return Observable.create { observer -> Disposable in
|
||||
addPet(body: body) { error in
|
||||
if let error = error {
|
||||
observer.on(.Error(error as ErrorType))
|
||||
} else {
|
||||
observer.on(.Next())
|
||||
}
|
||||
observer.on(.Completed)
|
||||
}
|
||||
return NopDisposable.instance
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Add a new pet to the store
|
||||
- POST /pet
|
||||
-
|
||||
- OAuth:
|
||||
- type: oauth2
|
||||
- name: petstore_auth
|
||||
|
||||
- parameter body: (body) Pet object that needs to be added to the store (optional)
|
||||
|
||||
- returns: RequestBuilder<Void>
|
||||
*/
|
||||
public class func addPetWithRequestBuilder(body body: Pet? = nil) -> RequestBuilder<Void> {
|
||||
let path = "/pet"
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
let parameters = body?.encodeToJSON() as? [String:AnyObject]
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Deletes a pet
|
||||
|
||||
- parameter petId: (path) Pet id to delete
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func deletePet(petId petId: Int64, completion: ((error: ErrorType?) -> Void)) {
|
||||
deletePetWithRequestBuilder(petId: petId).execute { (response, error) -> Void in
|
||||
completion(error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Deletes a pet
|
||||
|
||||
- parameter petId: (path) Pet id to delete
|
||||
- returns: Observable<Void>
|
||||
*/
|
||||
public class func deletePet(petId petId: Int64) -> Observable<Void> {
|
||||
return Observable.create { observer -> Disposable in
|
||||
deletePet(petId: petId) { error in
|
||||
if let error = error {
|
||||
observer.on(.Error(error as ErrorType))
|
||||
} else {
|
||||
observer.on(.Next())
|
||||
}
|
||||
observer.on(.Completed)
|
||||
}
|
||||
return NopDisposable.instance
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Deletes a pet
|
||||
- DELETE /pet/{petId}
|
||||
-
|
||||
- OAuth:
|
||||
- type: oauth2
|
||||
- name: petstore_auth
|
||||
|
||||
- parameter petId: (path) Pet id to delete
|
||||
|
||||
- returns: RequestBuilder<Void>
|
||||
*/
|
||||
public class func deletePetWithRequestBuilder(petId petId: Int64) -> RequestBuilder<Void> {
|
||||
var path = "/pet/{petId}"
|
||||
path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil)
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
|
||||
let nillableParameters: [String:AnyObject?] = [:]
|
||||
|
||||
let parameters = APIHelper.rejectNil(nillableParameters)
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Finds Pets by status
|
||||
|
||||
- parameter status: (query) Status values that need to be considered for filter (optional, default to available)
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func findPetsByStatus(status status: [String]? = nil, completion: ((data: [Pet]?, error: ErrorType?) -> Void)) {
|
||||
findPetsByStatusWithRequestBuilder(status: status).execute { (response, error) -> Void in
|
||||
completion(data: response?.body, error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Finds Pets by status
|
||||
|
||||
- parameter status: (query) Status values that need to be considered for filter (optional, default to available)
|
||||
- returns: Observable<[Pet]>
|
||||
*/
|
||||
public class func findPetsByStatus(status status: [String]? = nil) -> Observable<[Pet]> {
|
||||
return Observable.create { observer -> Disposable in
|
||||
findPetsByStatus(status: status) { data, error in
|
||||
if let error = error {
|
||||
observer.on(.Error(error as ErrorType))
|
||||
} else {
|
||||
observer.on(.Next(data!))
|
||||
}
|
||||
observer.on(.Completed)
|
||||
}
|
||||
return NopDisposable.instance
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Finds Pets by status
|
||||
- GET /pet/findByStatus
|
||||
- Multiple status values can be provided with comma seperated strings
|
||||
- OAuth:
|
||||
- type: oauth2
|
||||
- name: petstore_auth
|
||||
- examples: [{example={
|
||||
"name" : "Puma",
|
||||
"type" : "Dog",
|
||||
"color" : "Black",
|
||||
"gender" : "Female",
|
||||
"breed" : "Mixed"
|
||||
}, contentType=application/json}]
|
||||
|
||||
- parameter status: (query) Status values that need to be considered for filter (optional, default to available)
|
||||
|
||||
- returns: RequestBuilder<[Pet]>
|
||||
*/
|
||||
public class func findPetsByStatusWithRequestBuilder(status status: [String]? = nil) -> RequestBuilder<[Pet]> {
|
||||
let path = "/pet/findByStatus"
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
|
||||
let nillableParameters: [String:AnyObject?] = [
|
||||
"status": status
|
||||
]
|
||||
|
||||
let parameters = APIHelper.rejectNil(nillableParameters)
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
|
||||
}
|
||||
|
||||
/**
|
||||
Finds Pets by tags
|
||||
|
||||
- parameter tags: (query) Tags to filter by (optional)
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func findPetsByTags(tags tags: [String]? = nil, completion: ((data: [Pet]?, error: ErrorType?) -> Void)) {
|
||||
findPetsByTagsWithRequestBuilder(tags: tags).execute { (response, error) -> Void in
|
||||
completion(data: response?.body, error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Finds Pets by tags
|
||||
|
||||
- parameter tags: (query) Tags to filter by (optional)
|
||||
- returns: Observable<[Pet]>
|
||||
*/
|
||||
public class func findPetsByTags(tags tags: [String]? = nil) -> Observable<[Pet]> {
|
||||
return Observable.create { observer -> Disposable in
|
||||
findPetsByTags(tags: tags) { data, error in
|
||||
if let error = error {
|
||||
observer.on(.Error(error as ErrorType))
|
||||
} else {
|
||||
observer.on(.Next(data!))
|
||||
}
|
||||
observer.on(.Completed)
|
||||
}
|
||||
return NopDisposable.instance
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Finds Pets by tags
|
||||
- GET /pet/findByTags
|
||||
- Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
|
||||
- OAuth:
|
||||
- type: oauth2
|
||||
- name: petstore_auth
|
||||
- examples: [{example=[ {
|
||||
"tags" : [ {
|
||||
"id" : 123456789,
|
||||
"name" : "aeiou"
|
||||
} ],
|
||||
"id" : 123456789,
|
||||
"category" : {
|
||||
"id" : 123456789,
|
||||
"name" : "aeiou"
|
||||
},
|
||||
"status" : "aeiou",
|
||||
"name" : "doggie",
|
||||
"photoUrls" : [ "aeiou" ]
|
||||
} ], contentType=application/json}, {example=<Pet>
|
||||
<id>123456</id>
|
||||
<name>doggie</name>
|
||||
<photoUrls>
|
||||
<photoUrls>string</photoUrls>
|
||||
</photoUrls>
|
||||
<tags>
|
||||
</tags>
|
||||
<status>string</status>
|
||||
</Pet>, contentType=application/xml}]
|
||||
- examples: [{example=[ {
|
||||
"tags" : [ {
|
||||
"id" : 123456789,
|
||||
"name" : "aeiou"
|
||||
} ],
|
||||
"id" : 123456789,
|
||||
"category" : {
|
||||
"id" : 123456789,
|
||||
"name" : "aeiou"
|
||||
},
|
||||
"status" : "aeiou",
|
||||
"name" : "doggie",
|
||||
"photoUrls" : [ "aeiou" ]
|
||||
} ], contentType=application/json}, {example=<Pet>
|
||||
<id>123456</id>
|
||||
<name>doggie</name>
|
||||
<photoUrls>
|
||||
<photoUrls>string</photoUrls>
|
||||
</photoUrls>
|
||||
<tags>
|
||||
</tags>
|
||||
<status>string</status>
|
||||
</Pet>, contentType=application/xml}]
|
||||
|
||||
- parameter tags: (query) Tags to filter by (optional)
|
||||
|
||||
- returns: RequestBuilder<[Pet]>
|
||||
*/
|
||||
public class func findPetsByTagsWithRequestBuilder(tags tags: [String]? = nil) -> RequestBuilder<[Pet]> {
|
||||
let path = "/pet/findByTags"
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
|
||||
let nillableParameters: [String:AnyObject?] = [
|
||||
"tags": tags
|
||||
]
|
||||
|
||||
let parameters = APIHelper.rejectNil(nillableParameters)
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
|
||||
}
|
||||
|
||||
/**
|
||||
Find pet by ID
|
||||
|
||||
- parameter petId: (path) ID of pet that needs to be fetched
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func getPetById(petId petId: Int64, completion: ((data: Pet?, error: ErrorType?) -> Void)) {
|
||||
getPetByIdWithRequestBuilder(petId: petId).execute { (response, error) -> Void in
|
||||
completion(data: response?.body, error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Find pet by ID
|
||||
|
||||
- parameter petId: (path) ID of pet that needs to be fetched
|
||||
- returns: Observable<Pet>
|
||||
*/
|
||||
public class func getPetById(petId petId: Int64) -> Observable<Pet> {
|
||||
return Observable.create { observer -> Disposable in
|
||||
getPetById(petId: petId) { data, error in
|
||||
if let error = error {
|
||||
observer.on(.Error(error as ErrorType))
|
||||
} else {
|
||||
observer.on(.Next(data!))
|
||||
}
|
||||
observer.on(.Completed)
|
||||
}
|
||||
return NopDisposable.instance
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Find pet by ID
|
||||
- GET /pet/{petId}
|
||||
- Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions
|
||||
- API Key:
|
||||
- type: apiKey api_key
|
||||
- name: api_key
|
||||
- OAuth:
|
||||
- type: oauth2
|
||||
- name: petstore_auth
|
||||
- examples: [{example={
|
||||
"tags" : [ {
|
||||
"id" : 123456789,
|
||||
"name" : "aeiou"
|
||||
} ],
|
||||
"id" : 123456789,
|
||||
"category" : {
|
||||
"id" : 123456789,
|
||||
"name" : "aeiou"
|
||||
},
|
||||
"status" : "aeiou",
|
||||
"name" : "doggie",
|
||||
"photoUrls" : [ "aeiou" ]
|
||||
}, contentType=application/json}, {example=<Pet>
|
||||
<id>123456</id>
|
||||
<name>doggie</name>
|
||||
<photoUrls>
|
||||
<photoUrls>string</photoUrls>
|
||||
</photoUrls>
|
||||
<tags>
|
||||
</tags>
|
||||
<status>string</status>
|
||||
</Pet>, contentType=application/xml}]
|
||||
- examples: [{example={
|
||||
"tags" : [ {
|
||||
"id" : 123456789,
|
||||
"name" : "aeiou"
|
||||
} ],
|
||||
"id" : 123456789,
|
||||
"category" : {
|
||||
"id" : 123456789,
|
||||
"name" : "aeiou"
|
||||
},
|
||||
"status" : "aeiou",
|
||||
"name" : "doggie",
|
||||
"photoUrls" : [ "aeiou" ]
|
||||
}, contentType=application/json}, {example=<Pet>
|
||||
<id>123456</id>
|
||||
<name>doggie</name>
|
||||
<photoUrls>
|
||||
<photoUrls>string</photoUrls>
|
||||
</photoUrls>
|
||||
<tags>
|
||||
</tags>
|
||||
<status>string</status>
|
||||
</Pet>, contentType=application/xml}]
|
||||
|
||||
- parameter petId: (path) ID of pet that needs to be fetched
|
||||
|
||||
- returns: RequestBuilder<Pet>
|
||||
*/
|
||||
public class func getPetByIdWithRequestBuilder(petId petId: Int64) -> RequestBuilder<Pet> {
|
||||
var path = "/pet/{petId}"
|
||||
path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil)
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
|
||||
let nillableParameters: [String:AnyObject?] = [:]
|
||||
|
||||
let parameters = APIHelper.rejectNil(nillableParameters)
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Pet>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Update an existing pet
|
||||
|
||||
- parameter body: (body) Pet object that needs to be added to the store (optional)
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func updatePet(body body: Pet? = nil, completion: ((error: ErrorType?) -> Void)) {
|
||||
updatePetWithRequestBuilder(body: body).execute { (response, error) -> Void in
|
||||
completion(error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Update an existing pet
|
||||
|
||||
- parameter body: (body) Pet object that needs to be added to the store (optional)
|
||||
- returns: Observable<Void>
|
||||
*/
|
||||
public class func updatePet(body body: Pet? = nil) -> Observable<Void> {
|
||||
return Observable.create { observer -> Disposable in
|
||||
updatePet(body: body) { error in
|
||||
if let error = error {
|
||||
observer.on(.Error(error as ErrorType))
|
||||
} else {
|
||||
observer.on(.Next())
|
||||
}
|
||||
observer.on(.Completed)
|
||||
}
|
||||
return NopDisposable.instance
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Update an existing pet
|
||||
- PUT /pet
|
||||
-
|
||||
- OAuth:
|
||||
- type: oauth2
|
||||
- name: petstore_auth
|
||||
|
||||
- parameter body: (body) Pet object that needs to be added to the store (optional)
|
||||
|
||||
- returns: RequestBuilder<Void>
|
||||
*/
|
||||
public class func updatePetWithRequestBuilder(body body: Pet? = nil) -> RequestBuilder<Void> {
|
||||
let path = "/pet"
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
let parameters = body?.encodeToJSON() as? [String:AnyObject]
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Updates a pet in the store with form data
|
||||
|
||||
- parameter petId: (path) ID of pet that needs to be updated
|
||||
- parameter name: (form) Updated name of the pet (optional)
|
||||
- parameter status: (form) Updated status of the pet (optional)
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func updatePetWithForm(petId petId: String, name: String? = nil, status: String? = nil, completion: ((error: ErrorType?) -> Void)) {
|
||||
updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (response, error) -> Void in
|
||||
completion(error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Updates a pet in the store with form data
|
||||
|
||||
- parameter petId: (path) ID of pet that needs to be updated
|
||||
- parameter name: (form) Updated name of the pet (optional)
|
||||
- parameter status: (form) Updated status of the pet (optional)
|
||||
- returns: Observable<Void>
|
||||
*/
|
||||
public class func updatePetWithForm(petId petId: String, name: String? = nil, status: String? = nil) -> Observable<Void> {
|
||||
return Observable.create { observer -> Disposable in
|
||||
updatePetWithForm(petId: petId, name: name, status: status) { error in
|
||||
if let error = error {
|
||||
observer.on(.Error(error as ErrorType))
|
||||
} else {
|
||||
observer.on(.Next())
|
||||
}
|
||||
observer.on(.Completed)
|
||||
}
|
||||
return NopDisposable.instance
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Updates a pet in the store with form data
|
||||
- POST /pet/{petId}
|
||||
-
|
||||
- OAuth:
|
||||
- type: oauth2
|
||||
- name: petstore_auth
|
||||
|
||||
- parameter petId: (path) ID of pet that needs to be updated
|
||||
- parameter name: (form) Updated name of the pet (optional)
|
||||
- parameter status: (form) Updated status of the pet (optional)
|
||||
|
||||
- returns: RequestBuilder<Void>
|
||||
*/
|
||||
public class func updatePetWithFormWithRequestBuilder(petId petId: String, name: String? = nil, status: String? = nil) -> RequestBuilder<Void> {
|
||||
var path = "/pet/{petId}"
|
||||
path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil)
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
|
||||
let nillableParameters: [String:AnyObject?] = [
|
||||
"name": name,
|
||||
"status": status
|
||||
]
|
||||
|
||||
let parameters = APIHelper.rejectNil(nillableParameters)
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false)
|
||||
}
|
||||
|
||||
/**
|
||||
uploads an image
|
||||
|
||||
- parameter petId: (path) ID of pet to update
|
||||
- parameter additionalMetadata: (form) Additional data to pass to server (optional)
|
||||
- parameter file: (form) file to upload (optional)
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func uploadFile(petId petId: Int64, additionalMetadata: String? = nil, file: NSURL? = nil, completion: ((error: ErrorType?) -> Void)) {
|
||||
uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute { (response, error) -> Void in
|
||||
completion(error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
uploads an image
|
||||
|
||||
- parameter petId: (path) ID of pet to update
|
||||
- parameter additionalMetadata: (form) Additional data to pass to server (optional)
|
||||
- parameter file: (form) file to upload (optional)
|
||||
- returns: Observable<Void>
|
||||
*/
|
||||
public class func uploadFile(petId petId: Int64, additionalMetadata: String? = nil, file: NSURL? = nil) -> Observable<Void> {
|
||||
return Observable.create { observer -> Disposable in
|
||||
uploadFile(petId: petId, additionalMetadata: additionalMetadata, file: file) { error in
|
||||
if let error = error {
|
||||
observer.on(.Error(error as ErrorType))
|
||||
} else {
|
||||
observer.on(.Next())
|
||||
}
|
||||
observer.on(.Completed)
|
||||
}
|
||||
return NopDisposable.instance
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
uploads an image
|
||||
- POST /pet/{petId}/uploadImage
|
||||
-
|
||||
- OAuth:
|
||||
- type: oauth2
|
||||
- name: petstore_auth
|
||||
|
||||
- parameter petId: (path) ID of pet to update
|
||||
- parameter additionalMetadata: (form) Additional data to pass to server (optional)
|
||||
- parameter file: (form) file to upload (optional)
|
||||
|
||||
- returns: RequestBuilder<Void>
|
||||
*/
|
||||
public class func uploadFileWithRequestBuilder(petId petId: Int64, additionalMetadata: String? = nil, file: NSURL? = nil) -> RequestBuilder<Void> {
|
||||
var path = "/pet/{petId}/uploadImage"
|
||||
path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil)
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
|
||||
let nillableParameters: [String:AnyObject?] = [
|
||||
"additionalMetadata": additionalMetadata,
|
||||
"file": file
|
||||
]
|
||||
|
||||
let parameters = APIHelper.rejectNil(nillableParameters)
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false)
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,302 @@
|
||||
//
|
||||
// StoreAPI.swift
|
||||
//
|
||||
// Generated by swagger-codegen
|
||||
// https://github.com/swagger-api/swagger-codegen
|
||||
//
|
||||
|
||||
import Alamofire
|
||||
import RxSwift
|
||||
|
||||
|
||||
|
||||
public class StoreAPI: APIBase {
|
||||
/**
|
||||
Delete purchase order by ID
|
||||
|
||||
- parameter orderId: (path) ID of the order that needs to be deleted
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func deleteOrder(orderId orderId: String, completion: ((error: ErrorType?) -> Void)) {
|
||||
deleteOrderWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in
|
||||
completion(error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Delete purchase order by ID
|
||||
|
||||
- parameter orderId: (path) ID of the order that needs to be deleted
|
||||
- returns: Observable<Void>
|
||||
*/
|
||||
public class func deleteOrder(orderId orderId: String) -> Observable<Void> {
|
||||
return Observable.create { observer -> Disposable in
|
||||
deleteOrder(orderId: orderId) { error in
|
||||
if let error = error {
|
||||
observer.on(.Error(error as ErrorType))
|
||||
} else {
|
||||
observer.on(.Next())
|
||||
}
|
||||
observer.on(.Completed)
|
||||
}
|
||||
return NopDisposable.instance
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Delete purchase order by ID
|
||||
- DELETE /store/order/{orderId}
|
||||
- For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
|
||||
|
||||
- parameter orderId: (path) ID of the order that needs to be deleted
|
||||
|
||||
- returns: RequestBuilder<Void>
|
||||
*/
|
||||
public class func deleteOrderWithRequestBuilder(orderId orderId: String) -> RequestBuilder<Void> {
|
||||
var path = "/store/order/{orderId}"
|
||||
path = path.stringByReplacingOccurrencesOfString("{orderId}", withString: "\(orderId)", options: .LiteralSearch, range: nil)
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
|
||||
let nillableParameters: [String:AnyObject?] = [:]
|
||||
|
||||
let parameters = APIHelper.rejectNil(nillableParameters)
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Returns pet inventories by status
|
||||
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func getInventory(completion: ((data: [String:Int32]?, error: ErrorType?) -> Void)) {
|
||||
getInventoryWithRequestBuilder().execute { (response, error) -> Void in
|
||||
completion(data: response?.body, error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Returns pet inventories by status
|
||||
|
||||
- returns: Observable<[String:Int32]>
|
||||
*/
|
||||
public class func getInventory() -> Observable<[String:Int32]> {
|
||||
return Observable.create { observer -> Disposable in
|
||||
getInventory() { data, error in
|
||||
if let error = error {
|
||||
observer.on(.Error(error as ErrorType))
|
||||
} else {
|
||||
observer.on(.Next(data!))
|
||||
}
|
||||
observer.on(.Completed)
|
||||
}
|
||||
return NopDisposable.instance
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Returns pet inventories by status
|
||||
- GET /store/inventory
|
||||
- Returns a map of status codes to quantities
|
||||
- API Key:
|
||||
- type: apiKey api_key
|
||||
- name: api_key
|
||||
- examples: [{example={
|
||||
"key" : 123
|
||||
}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}]
|
||||
- examples: [{example={
|
||||
"key" : 123
|
||||
}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}]
|
||||
|
||||
- returns: RequestBuilder<[String:Int32]>
|
||||
*/
|
||||
public class func getInventoryWithRequestBuilder() -> RequestBuilder<[String:Int32]> {
|
||||
let path = "/store/inventory"
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
|
||||
let nillableParameters: [String:AnyObject?] = [:]
|
||||
|
||||
let parameters = APIHelper.rejectNil(nillableParameters)
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<[String:Int32]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Find purchase order by ID
|
||||
|
||||
- parameter orderId: (path) ID of pet that needs to be fetched
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func getOrderById(orderId orderId: String, completion: ((data: Order?, error: ErrorType?) -> Void)) {
|
||||
getOrderByIdWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in
|
||||
completion(data: response?.body, error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Find purchase order by ID
|
||||
|
||||
- parameter orderId: (path) ID of pet that needs to be fetched
|
||||
- returns: Observable<Order>
|
||||
*/
|
||||
public class func getOrderById(orderId orderId: String) -> Observable<Order> {
|
||||
return Observable.create { observer -> Disposable in
|
||||
getOrderById(orderId: orderId) { data, error in
|
||||
if let error = error {
|
||||
observer.on(.Error(error as ErrorType))
|
||||
} else {
|
||||
observer.on(.Next(data!))
|
||||
}
|
||||
observer.on(.Completed)
|
||||
}
|
||||
return NopDisposable.instance
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Find purchase order by ID
|
||||
- GET /store/order/{orderId}
|
||||
- For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
|
||||
- examples: [{example={
|
||||
"id" : 123456789,
|
||||
"petId" : 123456789,
|
||||
"complete" : true,
|
||||
"status" : "aeiou",
|
||||
"quantity" : 123,
|
||||
"shipDate" : "2000-01-23T04:56:07.000+00:00"
|
||||
}, contentType=application/json}, {example=<Order>
|
||||
<id>123456</id>
|
||||
<petId>123456</petId>
|
||||
<quantity>0</quantity>
|
||||
<shipDate>2000-01-23T04:56:07.000Z</shipDate>
|
||||
<status>string</status>
|
||||
<complete>true</complete>
|
||||
</Order>, contentType=application/xml}]
|
||||
- examples: [{example={
|
||||
"id" : 123456789,
|
||||
"petId" : 123456789,
|
||||
"complete" : true,
|
||||
"status" : "aeiou",
|
||||
"quantity" : 123,
|
||||
"shipDate" : "2000-01-23T04:56:07.000+00:00"
|
||||
}, contentType=application/json}, {example=<Order>
|
||||
<id>123456</id>
|
||||
<petId>123456</petId>
|
||||
<quantity>0</quantity>
|
||||
<shipDate>2000-01-23T04:56:07.000Z</shipDate>
|
||||
<status>string</status>
|
||||
<complete>true</complete>
|
||||
</Order>, contentType=application/xml}]
|
||||
|
||||
- parameter orderId: (path) ID of pet that needs to be fetched
|
||||
|
||||
- returns: RequestBuilder<Order>
|
||||
*/
|
||||
public class func getOrderByIdWithRequestBuilder(orderId orderId: String) -> RequestBuilder<Order> {
|
||||
var path = "/store/order/{orderId}"
|
||||
path = path.stringByReplacingOccurrencesOfString("{orderId}", withString: "\(orderId)", options: .LiteralSearch, range: nil)
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
|
||||
let nillableParameters: [String:AnyObject?] = [:]
|
||||
|
||||
let parameters = APIHelper.rejectNil(nillableParameters)
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Order>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Place an order for a pet
|
||||
|
||||
- parameter body: (body) order placed for purchasing the pet (optional)
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func placeOrder(body body: Order? = nil, completion: ((data: Order?, error: ErrorType?) -> Void)) {
|
||||
placeOrderWithRequestBuilder(body: body).execute { (response, error) -> Void in
|
||||
completion(data: response?.body, error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Place an order for a pet
|
||||
|
||||
- parameter body: (body) order placed for purchasing the pet (optional)
|
||||
- returns: Observable<Order>
|
||||
*/
|
||||
public class func placeOrder(body body: Order? = nil) -> Observable<Order> {
|
||||
return Observable.create { observer -> Disposable in
|
||||
placeOrder(body: body) { data, error in
|
||||
if let error = error {
|
||||
observer.on(.Error(error as ErrorType))
|
||||
} else {
|
||||
observer.on(.Next(data!))
|
||||
}
|
||||
observer.on(.Completed)
|
||||
}
|
||||
return NopDisposable.instance
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Place an order for a pet
|
||||
- POST /store/order
|
||||
-
|
||||
- examples: [{example={
|
||||
"id" : 123456789,
|
||||
"petId" : 123456789,
|
||||
"complete" : true,
|
||||
"status" : "aeiou",
|
||||
"quantity" : 123,
|
||||
"shipDate" : "2000-01-23T04:56:07.000+00:00"
|
||||
}, contentType=application/json}, {example=<Order>
|
||||
<id>123456</id>
|
||||
<petId>123456</petId>
|
||||
<quantity>0</quantity>
|
||||
<shipDate>2000-01-23T04:56:07.000Z</shipDate>
|
||||
<status>string</status>
|
||||
<complete>true</complete>
|
||||
</Order>, contentType=application/xml}]
|
||||
- examples: [{example={
|
||||
"id" : 123456789,
|
||||
"petId" : 123456789,
|
||||
"complete" : true,
|
||||
"status" : "aeiou",
|
||||
"quantity" : 123,
|
||||
"shipDate" : "2000-01-23T04:56:07.000+00:00"
|
||||
}, contentType=application/json}, {example=<Order>
|
||||
<id>123456</id>
|
||||
<petId>123456</petId>
|
||||
<quantity>0</quantity>
|
||||
<shipDate>2000-01-23T04:56:07.000Z</shipDate>
|
||||
<status>string</status>
|
||||
<complete>true</complete>
|
||||
</Order>, contentType=application/xml}]
|
||||
|
||||
- parameter body: (body) order placed for purchasing the pet (optional)
|
||||
|
||||
- returns: RequestBuilder<Order>
|
||||
*/
|
||||
public class func placeOrderWithRequestBuilder(body body: Order? = nil) -> RequestBuilder<Order> {
|
||||
let path = "/store/order"
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
let parameters = body?.encodeToJSON() as? [String:AnyObject]
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Order>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,498 @@
|
||||
//
|
||||
// UserAPI.swift
|
||||
//
|
||||
// Generated by swagger-codegen
|
||||
// https://github.com/swagger-api/swagger-codegen
|
||||
//
|
||||
|
||||
import Alamofire
|
||||
import RxSwift
|
||||
|
||||
|
||||
|
||||
public class UserAPI: APIBase {
|
||||
/**
|
||||
Create user
|
||||
|
||||
- parameter body: (body) Created user object (optional)
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func createUser(body body: User? = nil, completion: ((error: ErrorType?) -> Void)) {
|
||||
createUserWithRequestBuilder(body: body).execute { (response, error) -> Void in
|
||||
completion(error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Create user
|
||||
|
||||
- parameter body: (body) Created user object (optional)
|
||||
- returns: Observable<Void>
|
||||
*/
|
||||
public class func createUser(body body: User? = nil) -> Observable<Void> {
|
||||
return Observable.create { observer -> Disposable in
|
||||
createUser(body: body) { error in
|
||||
if let error = error {
|
||||
observer.on(.Error(error as ErrorType))
|
||||
} else {
|
||||
observer.on(.Next())
|
||||
}
|
||||
observer.on(.Completed)
|
||||
}
|
||||
return NopDisposable.instance
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Create user
|
||||
- POST /user
|
||||
- This can only be done by the logged in user.
|
||||
|
||||
- parameter body: (body) Created user object (optional)
|
||||
|
||||
- returns: RequestBuilder<Void>
|
||||
*/
|
||||
public class func createUserWithRequestBuilder(body body: User? = nil) -> RequestBuilder<Void> {
|
||||
let path = "/user"
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
let parameters = body?.encodeToJSON() as? [String:AnyObject]
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates list of users with given input array
|
||||
|
||||
- parameter body: (body) List of user object (optional)
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func createUsersWithArrayInput(body body: [User]? = nil, completion: ((error: ErrorType?) -> Void)) {
|
||||
createUsersWithArrayInputWithRequestBuilder(body: body).execute { (response, error) -> Void in
|
||||
completion(error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Creates list of users with given input array
|
||||
|
||||
- parameter body: (body) List of user object (optional)
|
||||
- returns: Observable<Void>
|
||||
*/
|
||||
public class func createUsersWithArrayInput(body body: [User]? = nil) -> Observable<Void> {
|
||||
return Observable.create { observer -> Disposable in
|
||||
createUsersWithArrayInput(body: body) { error in
|
||||
if let error = error {
|
||||
observer.on(.Error(error as ErrorType))
|
||||
} else {
|
||||
observer.on(.Next())
|
||||
}
|
||||
observer.on(.Completed)
|
||||
}
|
||||
return NopDisposable.instance
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Creates list of users with given input array
|
||||
- POST /user/createWithArray
|
||||
-
|
||||
|
||||
- parameter body: (body) List of user object (optional)
|
||||
|
||||
- returns: RequestBuilder<Void>
|
||||
*/
|
||||
public class func createUsersWithArrayInputWithRequestBuilder(body body: [User]? = nil) -> RequestBuilder<Void> {
|
||||
let path = "/user/createWithArray"
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
let parameters = body?.encodeToJSON() as? [String:AnyObject]
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Creates list of users with given input array
|
||||
|
||||
- parameter body: (body) List of user object (optional)
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func createUsersWithListInput(body body: [User]? = nil, completion: ((error: ErrorType?) -> Void)) {
|
||||
createUsersWithListInputWithRequestBuilder(body: body).execute { (response, error) -> Void in
|
||||
completion(error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Creates list of users with given input array
|
||||
|
||||
- parameter body: (body) List of user object (optional)
|
||||
- returns: Observable<Void>
|
||||
*/
|
||||
public class func createUsersWithListInput(body body: [User]? = nil) -> Observable<Void> {
|
||||
return Observable.create { observer -> Disposable in
|
||||
createUsersWithListInput(body: body) { error in
|
||||
if let error = error {
|
||||
observer.on(.Error(error as ErrorType))
|
||||
} else {
|
||||
observer.on(.Next())
|
||||
}
|
||||
observer.on(.Completed)
|
||||
}
|
||||
return NopDisposable.instance
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Creates list of users with given input array
|
||||
- POST /user/createWithList
|
||||
-
|
||||
|
||||
- parameter body: (body) List of user object (optional)
|
||||
|
||||
- returns: RequestBuilder<Void>
|
||||
*/
|
||||
public class func createUsersWithListInputWithRequestBuilder(body body: [User]? = nil) -> RequestBuilder<Void> {
|
||||
let path = "/user/createWithList"
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
let parameters = body?.encodeToJSON() as? [String:AnyObject]
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Delete user
|
||||
|
||||
- parameter username: (path) The name that needs to be deleted
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func deleteUser(username username: String, completion: ((error: ErrorType?) -> Void)) {
|
||||
deleteUserWithRequestBuilder(username: username).execute { (response, error) -> Void in
|
||||
completion(error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Delete user
|
||||
|
||||
- parameter username: (path) The name that needs to be deleted
|
||||
- returns: Observable<Void>
|
||||
*/
|
||||
public class func deleteUser(username username: String) -> Observable<Void> {
|
||||
return Observable.create { observer -> Disposable in
|
||||
deleteUser(username: username) { error in
|
||||
if let error = error {
|
||||
observer.on(.Error(error as ErrorType))
|
||||
} else {
|
||||
observer.on(.Next())
|
||||
}
|
||||
observer.on(.Completed)
|
||||
}
|
||||
return NopDisposable.instance
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Delete user
|
||||
- DELETE /user/{username}
|
||||
- This can only be done by the logged in user.
|
||||
|
||||
- parameter username: (path) The name that needs to be deleted
|
||||
|
||||
- returns: RequestBuilder<Void>
|
||||
*/
|
||||
public class func deleteUserWithRequestBuilder(username username: String) -> RequestBuilder<Void> {
|
||||
var path = "/user/{username}"
|
||||
path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil)
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
|
||||
let nillableParameters: [String:AnyObject?] = [:]
|
||||
|
||||
let parameters = APIHelper.rejectNil(nillableParameters)
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Get user by user name
|
||||
|
||||
- parameter username: (path) The name that needs to be fetched. Use user1 for testing.
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func getUserByName(username username: String, completion: ((data: User?, error: ErrorType?) -> Void)) {
|
||||
getUserByNameWithRequestBuilder(username: username).execute { (response, error) -> Void in
|
||||
completion(data: response?.body, error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Get user by user name
|
||||
|
||||
- parameter username: (path) The name that needs to be fetched. Use user1 for testing.
|
||||
- returns: Observable<User>
|
||||
*/
|
||||
public class func getUserByName(username username: String) -> Observable<User> {
|
||||
return Observable.create { observer -> Disposable in
|
||||
getUserByName(username: username) { data, error in
|
||||
if let error = error {
|
||||
observer.on(.Error(error as ErrorType))
|
||||
} else {
|
||||
observer.on(.Next(data!))
|
||||
}
|
||||
observer.on(.Completed)
|
||||
}
|
||||
return NopDisposable.instance
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Get user by user name
|
||||
- GET /user/{username}
|
||||
-
|
||||
- examples: [{example={
|
||||
"id" : 123456789,
|
||||
"lastName" : "aeiou",
|
||||
"phone" : "aeiou",
|
||||
"username" : "aeiou",
|
||||
"email" : "aeiou",
|
||||
"userStatus" : 123,
|
||||
"firstName" : "aeiou",
|
||||
"password" : "aeiou"
|
||||
}, contentType=application/json}, {example=<User>
|
||||
<id>123456</id>
|
||||
<username>string</username>
|
||||
<firstName>string</firstName>
|
||||
<lastName>string</lastName>
|
||||
<email>string</email>
|
||||
<password>string</password>
|
||||
<phone>string</phone>
|
||||
<userStatus>0</userStatus>
|
||||
</User>, contentType=application/xml}]
|
||||
- examples: [{example={
|
||||
"id" : 123456789,
|
||||
"lastName" : "aeiou",
|
||||
"phone" : "aeiou",
|
||||
"username" : "aeiou",
|
||||
"email" : "aeiou",
|
||||
"userStatus" : 123,
|
||||
"firstName" : "aeiou",
|
||||
"password" : "aeiou"
|
||||
}, contentType=application/json}, {example=<User>
|
||||
<id>123456</id>
|
||||
<username>string</username>
|
||||
<firstName>string</firstName>
|
||||
<lastName>string</lastName>
|
||||
<email>string</email>
|
||||
<password>string</password>
|
||||
<phone>string</phone>
|
||||
<userStatus>0</userStatus>
|
||||
</User>, contentType=application/xml}]
|
||||
|
||||
- parameter username: (path) The name that needs to be fetched. Use user1 for testing.
|
||||
|
||||
- returns: RequestBuilder<User>
|
||||
*/
|
||||
public class func getUserByNameWithRequestBuilder(username username: String) -> RequestBuilder<User> {
|
||||
var path = "/user/{username}"
|
||||
path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil)
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
|
||||
let nillableParameters: [String:AnyObject?] = [:]
|
||||
|
||||
let parameters = APIHelper.rejectNil(nillableParameters)
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<User>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Logs user into the system
|
||||
|
||||
- parameter username: (query) The user name for login (optional)
|
||||
- parameter password: (query) The password for login in clear text (optional)
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func loginUser(username username: String? = nil, password: String? = nil, completion: ((data: String?, error: ErrorType?) -> Void)) {
|
||||
loginUserWithRequestBuilder(username: username, password: password).execute { (response, error) -> Void in
|
||||
completion(data: response?.body, error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Logs user into the system
|
||||
|
||||
- parameter username: (query) The user name for login (optional)
|
||||
- parameter password: (query) The password for login in clear text (optional)
|
||||
- returns: Observable<String>
|
||||
*/
|
||||
public class func loginUser(username username: String? = nil, password: String? = nil) -> Observable<String> {
|
||||
return Observable.create { observer -> Disposable in
|
||||
loginUser(username: username, password: password) { data, error in
|
||||
if let error = error {
|
||||
observer.on(.Error(error as ErrorType))
|
||||
} else {
|
||||
observer.on(.Next(data!))
|
||||
}
|
||||
observer.on(.Completed)
|
||||
}
|
||||
return NopDisposable.instance
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Logs user into the system
|
||||
- GET /user/login
|
||||
-
|
||||
- examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}]
|
||||
- examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}]
|
||||
|
||||
- parameter username: (query) The user name for login (optional)
|
||||
- parameter password: (query) The password for login in clear text (optional)
|
||||
|
||||
- returns: RequestBuilder<String>
|
||||
*/
|
||||
public class func loginUserWithRequestBuilder(username username: String? = nil, password: String? = nil) -> RequestBuilder<String> {
|
||||
let path = "/user/login"
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
|
||||
let nillableParameters: [String:AnyObject?] = [
|
||||
"username": username,
|
||||
"password": password
|
||||
]
|
||||
|
||||
let parameters = APIHelper.rejectNil(nillableParameters)
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<String>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
|
||||
}
|
||||
|
||||
/**
|
||||
Logs out current logged in user session
|
||||
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func logoutUser(completion: ((error: ErrorType?) -> Void)) {
|
||||
logoutUserWithRequestBuilder().execute { (response, error) -> Void in
|
||||
completion(error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Logs out current logged in user session
|
||||
|
||||
- returns: Observable<Void>
|
||||
*/
|
||||
public class func logoutUser() -> Observable<Void> {
|
||||
return Observable.create { observer -> Disposable in
|
||||
logoutUser() { error in
|
||||
if let error = error {
|
||||
observer.on(.Error(error as ErrorType))
|
||||
} else {
|
||||
observer.on(.Next())
|
||||
}
|
||||
observer.on(.Completed)
|
||||
}
|
||||
return NopDisposable.instance
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Logs out current logged in user session
|
||||
- GET /user/logout
|
||||
-
|
||||
|
||||
- returns: RequestBuilder<Void>
|
||||
*/
|
||||
public class func logoutUserWithRequestBuilder() -> RequestBuilder<Void> {
|
||||
let path = "/user/logout"
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
|
||||
let nillableParameters: [String:AnyObject?] = [:]
|
||||
|
||||
let parameters = APIHelper.rejectNil(nillableParameters)
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
/**
|
||||
Updated user
|
||||
|
||||
- parameter username: (path) name that need to be deleted
|
||||
- parameter body: (body) Updated user object (optional)
|
||||
- parameter completion: completion handler to receive the data and the error objects
|
||||
*/
|
||||
public class func updateUser(username username: String, body: User? = nil, completion: ((error: ErrorType?) -> Void)) {
|
||||
updateUserWithRequestBuilder(username: username, body: body).execute { (response, error) -> Void in
|
||||
completion(error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Updated user
|
||||
|
||||
- parameter username: (path) name that need to be deleted
|
||||
- parameter body: (body) Updated user object (optional)
|
||||
- returns: Observable<Void>
|
||||
*/
|
||||
public class func updateUser(username username: String, body: User? = nil) -> Observable<Void> {
|
||||
return Observable.create { observer -> Disposable in
|
||||
updateUser(username: username, body: body) { error in
|
||||
if let error = error {
|
||||
observer.on(.Error(error as ErrorType))
|
||||
} else {
|
||||
observer.on(.Next())
|
||||
}
|
||||
observer.on(.Completed)
|
||||
}
|
||||
return NopDisposable.instance
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Updated user
|
||||
- PUT /user/{username}
|
||||
- This can only be done by the logged in user.
|
||||
|
||||
- parameter username: (path) name that need to be deleted
|
||||
- parameter body: (body) Updated user object (optional)
|
||||
|
||||
- returns: RequestBuilder<Void>
|
||||
*/
|
||||
public class func updateUserWithRequestBuilder(username username: String, body: User? = nil) -> RequestBuilder<Void> {
|
||||
var path = "/user/{username}"
|
||||
path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil)
|
||||
let URLString = PetstoreClientAPI.basePath + path
|
||||
let parameters = body?.encodeToJSON() as? [String:AnyObject]
|
||||
|
||||
let convertedParameters = APIHelper.convertBoolToString(parameters)
|
||||
|
||||
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
|
||||
|
||||
return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true)
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,148 @@
|
||||
// AlamofireImplementations.swift
|
||||
//
|
||||
// Generated by swagger-codegen
|
||||
// https://github.com/swagger-api/swagger-codegen
|
||||
//
|
||||
|
||||
import Alamofire
|
||||
|
||||
class AlamofireRequestBuilderFactory: RequestBuilderFactory {
|
||||
func getBuilder<T>() -> RequestBuilder<T>.Type {
|
||||
return AlamofireRequestBuilder<T>.self
|
||||
}
|
||||
}
|
||||
|
||||
// Store manager to retain its reference
|
||||
private var managerStore: [String: Alamofire.Manager] = [:]
|
||||
|
||||
class AlamofireRequestBuilder<T>: RequestBuilder<T> {
|
||||
required init(method: String, URLString: String, parameters: [String : AnyObject]?, isBody: Bool) {
|
||||
super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody)
|
||||
}
|
||||
|
||||
override func execute(completion: (response: Response<T>?, error: ErrorType?) -> Void) {
|
||||
let managerId = NSUUID().UUIDString
|
||||
// Create a new manager for each request to customize its request header
|
||||
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
|
||||
configuration.HTTPAdditionalHeaders = buildHeaders()
|
||||
let manager = Alamofire.Manager(configuration: configuration)
|
||||
managerStore[managerId] = manager
|
||||
|
||||
let encoding = isBody ? Alamofire.ParameterEncoding.JSON : Alamofire.ParameterEncoding.URL
|
||||
let xMethod = Alamofire.Method(rawValue: method)
|
||||
let fileKeys = parameters == nil ? [] : parameters!.filter { $1.isKindOfClass(NSURL) }
|
||||
.map { $0.0 }
|
||||
|
||||
if fileKeys.count > 0 {
|
||||
manager.upload(
|
||||
xMethod!, URLString, headers: nil,
|
||||
multipartFormData: { mpForm in
|
||||
for (k, v) in self.parameters! {
|
||||
switch v {
|
||||
case let fileURL as NSURL:
|
||||
mpForm.appendBodyPart(fileURL: fileURL, name: k)
|
||||
break
|
||||
case let string as NSString:
|
||||
mpForm.appendBodyPart(data: string.dataUsingEncoding(NSUTF8StringEncoding)!, name: k)
|
||||
break
|
||||
case let number as NSNumber:
|
||||
mpForm.appendBodyPart(data: number.stringValue.dataUsingEncoding(NSUTF8StringEncoding)!, name: k)
|
||||
break
|
||||
default:
|
||||
fatalError("Unprocessable value \(v) with key \(k)")
|
||||
break
|
||||
}
|
||||
}
|
||||
},
|
||||
encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold,
|
||||
encodingCompletion: { encodingResult in
|
||||
switch encodingResult {
|
||||
case .Success(let uploadRequest, _, _):
|
||||
if let onProgressReady = self.onProgressReady {
|
||||
onProgressReady(uploadRequest.progress)
|
||||
}
|
||||
self.processRequest(uploadRequest, managerId, completion)
|
||||
case .Failure(let encodingError):
|
||||
completion(response: nil, error: encodingError)
|
||||
}
|
||||
}
|
||||
)
|
||||
} else {
|
||||
let request = manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding)
|
||||
if let onProgressReady = self.onProgressReady {
|
||||
onProgressReady(request.progress)
|
||||
}
|
||||
processRequest(request, managerId, completion)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private func processRequest(request: Request, _ managerId: String, _ completion: (response: Response<T>?, error: ErrorType?) -> Void) {
|
||||
if let credential = self.credential {
|
||||
request.authenticate(usingCredential: credential)
|
||||
}
|
||||
|
||||
let cleanupRequest = {
|
||||
managerStore.removeValueForKey(managerId)
|
||||
}
|
||||
|
||||
let validatedRequest = request.validate()
|
||||
|
||||
switch T.self {
|
||||
case is NSData.Type:
|
||||
validatedRequest.responseData({ (dataResponse) in
|
||||
cleanupRequest()
|
||||
|
||||
if (dataResponse.result.isFailure) {
|
||||
completion(
|
||||
response: nil,
|
||||
error: dataResponse.result.error
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
completion(
|
||||
response: Response(
|
||||
response: dataResponse.response!,
|
||||
body: dataResponse.data as! T
|
||||
),
|
||||
error: nil
|
||||
)
|
||||
})
|
||||
default:
|
||||
validatedRequest.responseJSON(options: .AllowFragments) { response in
|
||||
cleanupRequest()
|
||||
|
||||
if response.result.isFailure {
|
||||
completion(response: nil, error: response.result.error)
|
||||
return
|
||||
}
|
||||
|
||||
if () is T {
|
||||
completion(response: Response(response: response.response!, body: () as! T), error: nil)
|
||||
return
|
||||
}
|
||||
if let json: AnyObject = response.result.value {
|
||||
let body = Decoders.decode(clazz: T.self, source: json)
|
||||
completion(response: Response(response: response.response!, body: body), error: nil)
|
||||
return
|
||||
} else if "" is T {
|
||||
// swagger-parser currently doesn't support void, which will be fixed in future swagger-parser release
|
||||
// https://github.com/swagger-api/swagger-parser/pull/34
|
||||
completion(response: Response(response: response.response!, body: "" as! T), error: nil)
|
||||
return
|
||||
}
|
||||
|
||||
completion(response: nil, error: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"]))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func buildHeaders() -> [String: AnyObject] {
|
||||
var httpHeaders = Manager.defaultHTTPHeaders
|
||||
for (key, value) in self.headers {
|
||||
httpHeaders[key] = value
|
||||
}
|
||||
return httpHeaders
|
||||
}
|
||||
}
|
@ -0,0 +1,84 @@
|
||||
// Extensions.swift
|
||||
//
|
||||
// Generated by swagger-codegen
|
||||
// https://github.com/swagger-api/swagger-codegen
|
||||
//
|
||||
|
||||
import Alamofire
|
||||
|
||||
extension Bool: JSONEncodable {
|
||||
func encodeToJSON() -> AnyObject { return self }
|
||||
}
|
||||
|
||||
extension Float: JSONEncodable {
|
||||
func encodeToJSON() -> AnyObject { return self }
|
||||
}
|
||||
|
||||
extension Int: JSONEncodable {
|
||||
func encodeToJSON() -> AnyObject { return self }
|
||||
}
|
||||
|
||||
extension Int32: JSONEncodable {
|
||||
func encodeToJSON() -> AnyObject { return NSNumber(int: self) }
|
||||
}
|
||||
|
||||
extension Int64: JSONEncodable {
|
||||
func encodeToJSON() -> AnyObject { return NSNumber(longLong: self) }
|
||||
}
|
||||
|
||||
extension Double: JSONEncodable {
|
||||
func encodeToJSON() -> AnyObject { return self }
|
||||
}
|
||||
|
||||
extension String: JSONEncodable {
|
||||
func encodeToJSON() -> AnyObject { return self }
|
||||
}
|
||||
|
||||
private func encodeIfPossible<T>(object: T) -> AnyObject {
|
||||
if object is JSONEncodable {
|
||||
return (object as! JSONEncodable).encodeToJSON()
|
||||
} else {
|
||||
return object as! AnyObject
|
||||
}
|
||||
}
|
||||
|
||||
extension Array: JSONEncodable {
|
||||
func encodeToJSON() -> AnyObject {
|
||||
return self.map(encodeIfPossible)
|
||||
}
|
||||
}
|
||||
|
||||
extension Dictionary: JSONEncodable {
|
||||
func encodeToJSON() -> AnyObject {
|
||||
var dictionary = [NSObject:AnyObject]()
|
||||
for (key, value) in self {
|
||||
dictionary[key as! NSObject] = encodeIfPossible(value)
|
||||
}
|
||||
return dictionary
|
||||
}
|
||||
}
|
||||
|
||||
extension NSData: JSONEncodable {
|
||||
func encodeToJSON() -> AnyObject {
|
||||
return self.base64EncodedStringWithOptions(NSDataBase64EncodingOptions())
|
||||
}
|
||||
}
|
||||
|
||||
private let dateFormatter: NSDateFormatter = {
|
||||
let fmt = NSDateFormatter()
|
||||
fmt.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
|
||||
fmt.locale = NSLocale(localeIdentifier: "en_US_POSIX")
|
||||
return fmt
|
||||
}()
|
||||
|
||||
extension NSDate: JSONEncodable {
|
||||
func encodeToJSON() -> AnyObject {
|
||||
return dateFormatter.stringFromDate(self)
|
||||
}
|
||||
}
|
||||
|
||||
extension NSUUID: JSONEncodable {
|
||||
func encodeToJSON() -> AnyObject {
|
||||
return self.UUIDString
|
||||
}
|
||||
}
|
@ -0,0 +1,224 @@
|
||||
// Models.swift
|
||||
//
|
||||
// Generated by swagger-codegen
|
||||
// https://github.com/swagger-api/swagger-codegen
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol JSONEncodable {
|
||||
func encodeToJSON() -> AnyObject
|
||||
}
|
||||
|
||||
public class Response<T> {
|
||||
public let statusCode: Int
|
||||
public let header: [String: String]
|
||||
public let body: T
|
||||
|
||||
public init(statusCode: Int, header: [String: String], body: T) {
|
||||
self.statusCode = statusCode
|
||||
self.header = header
|
||||
self.body = body
|
||||
}
|
||||
|
||||
public convenience init(response: NSHTTPURLResponse, body: T) {
|
||||
let rawHeader = response.allHeaderFields
|
||||
var header = [String:String]()
|
||||
for (key, value) in rawHeader {
|
||||
header[key as! String] = value as? String
|
||||
}
|
||||
self.init(statusCode: response.statusCode, header: header, body: body)
|
||||
}
|
||||
}
|
||||
|
||||
private var once = dispatch_once_t()
|
||||
class Decoders {
|
||||
static private var decoders = Dictionary<String, ((AnyObject) -> AnyObject)>()
|
||||
|
||||
static func addDecoder<T>(clazz clazz: T.Type, decoder: ((AnyObject) -> T)) {
|
||||
let key = "\(T.self)"
|
||||
decoders[key] = { decoder($0) as! AnyObject }
|
||||
}
|
||||
|
||||
static func decode<T>(clazz clazz: [T].Type, source: AnyObject) -> [T] {
|
||||
let array = source as! [AnyObject]
|
||||
return array.map { Decoders.decode(clazz: T.self, source: $0) }
|
||||
}
|
||||
|
||||
static func decode<T, Key: Hashable>(clazz clazz: [Key:T].Type, source: AnyObject) -> [Key:T] {
|
||||
let sourceDictionary = source as! [Key: AnyObject]
|
||||
var dictionary = [Key:T]()
|
||||
for (key, value) in sourceDictionary {
|
||||
dictionary[key] = Decoders.decode(clazz: T.self, source: value)
|
||||
}
|
||||
return dictionary
|
||||
}
|
||||
|
||||
static func decode<T>(clazz clazz: T.Type, source: AnyObject) -> T {
|
||||
initialize()
|
||||
if T.self is Int32.Type && source is NSNumber {
|
||||
return source.intValue as! T;
|
||||
}
|
||||
if T.self is Int64.Type && source is NSNumber {
|
||||
return source.longLongValue as! T;
|
||||
}
|
||||
if T.self is NSUUID.Type && source is String {
|
||||
return NSUUID(UUIDString: source as! String) as! T
|
||||
}
|
||||
if source is T {
|
||||
return source as! T
|
||||
}
|
||||
if T.self is NSData.Type && source is String {
|
||||
return NSData(base64EncodedString: source as! String, options: NSDataBase64DecodingOptions()) as! T
|
||||
}
|
||||
|
||||
let key = "\(T.self)"
|
||||
if let decoder = decoders[key] {
|
||||
return decoder(source) as! T
|
||||
} else {
|
||||
fatalError("Source \(source) is not convertible to type \(clazz): Maybe swagger file is insufficient")
|
||||
}
|
||||
}
|
||||
|
||||
static func decodeOptional<T>(clazz clazz: T.Type, source: AnyObject?) -> T? {
|
||||
if source is NSNull {
|
||||
return nil
|
||||
}
|
||||
return source.map { (source: AnyObject) -> T in
|
||||
Decoders.decode(clazz: clazz, source: source)
|
||||
}
|
||||
}
|
||||
|
||||
static func decodeOptional<T>(clazz clazz: [T].Type, source: AnyObject?) -> [T]? {
|
||||
if source is NSNull {
|
||||
return nil
|
||||
}
|
||||
return source.map { (someSource: AnyObject) -> [T] in
|
||||
Decoders.decode(clazz: clazz, source: someSource)
|
||||
}
|
||||
}
|
||||
|
||||
static func decodeOptional<T, Key: Hashable>(clazz clazz: [Key:T].Type, source: AnyObject?) -> [Key:T]? {
|
||||
if source is NSNull {
|
||||
return nil
|
||||
}
|
||||
return source.map { (someSource: AnyObject) -> [Key:T] in
|
||||
Decoders.decode(clazz: clazz, source: someSource)
|
||||
}
|
||||
}
|
||||
|
||||
static private func initialize() {
|
||||
dispatch_once(&once) {
|
||||
let formatters = [
|
||||
"yyyy-MM-dd",
|
||||
"yyyy-MM-dd'T'HH:mm:ssZZZZZ",
|
||||
"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ",
|
||||
"yyyy-MM-dd'T'HH:mm:ss'Z'",
|
||||
"yyyy-MM-dd'T'HH:mm:ss.SSS"
|
||||
].map { (format: String) -> NSDateFormatter in
|
||||
let formatter = NSDateFormatter()
|
||||
formatter.dateFormat = format
|
||||
return formatter
|
||||
}
|
||||
// Decoder for NSDate
|
||||
Decoders.addDecoder(clazz: NSDate.self) { (source: AnyObject) -> NSDate in
|
||||
if let sourceString = source as? String {
|
||||
for formatter in formatters {
|
||||
if let date = formatter.dateFromString(sourceString) {
|
||||
return date
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
if let sourceInt = source as? Int {
|
||||
// treat as a java date
|
||||
return NSDate(timeIntervalSince1970: Double(sourceInt / 1000) )
|
||||
}
|
||||
fatalError("formatter failed to parse \(source)")
|
||||
}
|
||||
|
||||
// Decoder for [Category]
|
||||
Decoders.addDecoder(clazz: [Category].self) { (source: AnyObject) -> [Category] in
|
||||
return Decoders.decode(clazz: [Category].self, source: source)
|
||||
}
|
||||
// Decoder for Category
|
||||
Decoders.addDecoder(clazz: Category.self) { (source: AnyObject) -> Category in
|
||||
let sourceDictionary = source as! [NSObject:AnyObject]
|
||||
let instance = Category()
|
||||
instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"])
|
||||
instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"])
|
||||
return instance
|
||||
}
|
||||
|
||||
|
||||
// Decoder for [Order]
|
||||
Decoders.addDecoder(clazz: [Order].self) { (source: AnyObject) -> [Order] in
|
||||
return Decoders.decode(clazz: [Order].self, source: source)
|
||||
}
|
||||
// Decoder for Order
|
||||
Decoders.addDecoder(clazz: Order.self) { (source: AnyObject) -> Order in
|
||||
let sourceDictionary = source as! [NSObject:AnyObject]
|
||||
let instance = Order()
|
||||
instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"])
|
||||
instance.petId = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["petId"])
|
||||
instance.quantity = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["quantity"])
|
||||
instance.shipDate = Decoders.decodeOptional(clazz: NSDate.self, source: sourceDictionary["shipDate"])
|
||||
instance.status = Order.Status(rawValue: (sourceDictionary["status"] as? String) ?? "")
|
||||
instance.complete = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["complete"])
|
||||
return instance
|
||||
}
|
||||
|
||||
|
||||
// Decoder for [Pet]
|
||||
Decoders.addDecoder(clazz: [Pet].self) { (source: AnyObject) -> [Pet] in
|
||||
return Decoders.decode(clazz: [Pet].self, source: source)
|
||||
}
|
||||
// Decoder for Pet
|
||||
Decoders.addDecoder(clazz: Pet.self) { (source: AnyObject) -> Pet in
|
||||
let sourceDictionary = source as! [NSObject:AnyObject]
|
||||
let instance = Pet()
|
||||
instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"])
|
||||
instance.category = Decoders.decodeOptional(clazz: Category.self, source: sourceDictionary["category"])
|
||||
instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"])
|
||||
instance.photoUrls = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["photoUrls"])
|
||||
instance.tags = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["tags"])
|
||||
instance.status = Pet.Status(rawValue: (sourceDictionary["status"] as? String) ?? "")
|
||||
return instance
|
||||
}
|
||||
|
||||
|
||||
// Decoder for [Tag]
|
||||
Decoders.addDecoder(clazz: [Tag].self) { (source: AnyObject) -> [Tag] in
|
||||
return Decoders.decode(clazz: [Tag].self, source: source)
|
||||
}
|
||||
// Decoder for Tag
|
||||
Decoders.addDecoder(clazz: Tag.self) { (source: AnyObject) -> Tag in
|
||||
let sourceDictionary = source as! [NSObject:AnyObject]
|
||||
let instance = Tag()
|
||||
instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"])
|
||||
instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"])
|
||||
return instance
|
||||
}
|
||||
|
||||
|
||||
// Decoder for [User]
|
||||
Decoders.addDecoder(clazz: [User].self) { (source: AnyObject) -> [User] in
|
||||
return Decoders.decode(clazz: [User].self, source: source)
|
||||
}
|
||||
// Decoder for User
|
||||
Decoders.addDecoder(clazz: User.self) { (source: AnyObject) -> User in
|
||||
let sourceDictionary = source as! [NSObject:AnyObject]
|
||||
let instance = User()
|
||||
instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"])
|
||||
instance.username = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["username"])
|
||||
instance.firstName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["firstName"])
|
||||
instance.lastName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["lastName"])
|
||||
instance.email = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["email"])
|
||||
instance.password = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["password"])
|
||||
instance.phone = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["phone"])
|
||||
instance.userStatus = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["userStatus"])
|
||||
return instance
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
//
|
||||
// Category.swift
|
||||
//
|
||||
// Generated by swagger-codegen
|
||||
// https://github.com/swagger-api/swagger-codegen
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
|
||||
public class Category: JSONEncodable {
|
||||
public var id: Int64?
|
||||
public var name: String?
|
||||
|
||||
public init() {}
|
||||
|
||||
// MARK: JSONEncodable
|
||||
func encodeToJSON() -> AnyObject {
|
||||
var nillableDictionary = [String:AnyObject?]()
|
||||
nillableDictionary["id"] = self.id?.encodeToJSON()
|
||||
nillableDictionary["name"] = self.name
|
||||
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
|
||||
return dictionary
|
||||
}
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
//
|
||||
// Order.swift
|
||||
//
|
||||
// Generated by swagger-codegen
|
||||
// https://github.com/swagger-api/swagger-codegen
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
|
||||
public class Order: JSONEncodable {
|
||||
public enum Status: String {
|
||||
case Placed = "placed"
|
||||
case Approved = "approved"
|
||||
case Delivered = "delivered"
|
||||
}
|
||||
public var id: Int64?
|
||||
public var petId: Int64?
|
||||
public var quantity: Int32?
|
||||
public var shipDate: NSDate?
|
||||
/** Order Status */
|
||||
public var status: Status?
|
||||
public var complete: Bool?
|
||||
|
||||
public init() {}
|
||||
|
||||
// MARK: JSONEncodable
|
||||
func encodeToJSON() -> AnyObject {
|
||||
var nillableDictionary = [String:AnyObject?]()
|
||||
nillableDictionary["id"] = self.id?.encodeToJSON()
|
||||
nillableDictionary["petId"] = self.petId?.encodeToJSON()
|
||||
nillableDictionary["quantity"] = self.quantity?.encodeToJSON()
|
||||
nillableDictionary["shipDate"] = self.shipDate?.encodeToJSON()
|
||||
nillableDictionary["status"] = self.status?.rawValue
|
||||
nillableDictionary["complete"] = self.complete
|
||||
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
|
||||
return dictionary
|
||||
}
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
//
|
||||
// Pet.swift
|
||||
//
|
||||
// Generated by swagger-codegen
|
||||
// https://github.com/swagger-api/swagger-codegen
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
|
||||
public class Pet: JSONEncodable {
|
||||
public enum Status: String {
|
||||
case Available = "available"
|
||||
case Pending = "pending"
|
||||
case Sold = "sold"
|
||||
}
|
||||
public var id: Int64?
|
||||
public var category: Category?
|
||||
public var name: String?
|
||||
public var photoUrls: [String]?
|
||||
public var tags: [Tag]?
|
||||
/** pet status in the store */
|
||||
public var status: Status?
|
||||
|
||||
public init() {}
|
||||
|
||||
// MARK: JSONEncodable
|
||||
func encodeToJSON() -> AnyObject {
|
||||
var nillableDictionary = [String:AnyObject?]()
|
||||
nillableDictionary["id"] = self.id?.encodeToJSON()
|
||||
nillableDictionary["category"] = self.category?.encodeToJSON()
|
||||
nillableDictionary["name"] = self.name
|
||||
nillableDictionary["photoUrls"] = self.photoUrls?.encodeToJSON()
|
||||
nillableDictionary["tags"] = self.tags?.encodeToJSON()
|
||||
nillableDictionary["status"] = self.status?.rawValue
|
||||
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
|
||||
return dictionary
|
||||
}
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
//
|
||||
// Tag.swift
|
||||
//
|
||||
// Generated by swagger-codegen
|
||||
// https://github.com/swagger-api/swagger-codegen
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
|
||||
public class Tag: JSONEncodable {
|
||||
public var id: Int64?
|
||||
public var name: String?
|
||||
|
||||
public init() {}
|
||||
|
||||
// MARK: JSONEncodable
|
||||
func encodeToJSON() -> AnyObject {
|
||||
var nillableDictionary = [String:AnyObject?]()
|
||||
nillableDictionary["id"] = self.id?.encodeToJSON()
|
||||
nillableDictionary["name"] = self.name
|
||||
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
|
||||
return dictionary
|
||||
}
|
||||
}
|
@ -0,0 +1,38 @@
|
||||
//
|
||||
// User.swift
|
||||
//
|
||||
// Generated by swagger-codegen
|
||||
// https://github.com/swagger-api/swagger-codegen
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
|
||||
public class User: JSONEncodable {
|
||||
public var id: Int64?
|
||||
public var username: String?
|
||||
public var firstName: String?
|
||||
public var lastName: String?
|
||||
public var email: String?
|
||||
public var password: String?
|
||||
public var phone: String?
|
||||
/** User Status */
|
||||
public var userStatus: Int32?
|
||||
|
||||
public init() {}
|
||||
|
||||
// MARK: JSONEncodable
|
||||
func encodeToJSON() -> AnyObject {
|
||||
var nillableDictionary = [String:AnyObject?]()
|
||||
nillableDictionary["id"] = self.id?.encodeToJSON()
|
||||
nillableDictionary["username"] = self.username
|
||||
nillableDictionary["firstName"] = self.firstName
|
||||
nillableDictionary["lastName"] = self.lastName
|
||||
nillableDictionary["email"] = self.email
|
||||
nillableDictionary["password"] = self.password
|
||||
nillableDictionary["phone"] = self.phone
|
||||
nillableDictionary["userStatus"] = self.userStatus?.encodeToJSON()
|
||||
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
|
||||
return dictionary
|
||||
}
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
use_frameworks!
|
||||
source 'https://github.com/CocoaPods/Specs.git'
|
||||
|
||||
target 'SwaggerClient' do
|
||||
pod "PetstoreClient", :path => "../"
|
||||
|
||||
target 'SwaggerClientTests' do
|
||||
inherit! :search_paths
|
||||
end
|
||||
end
|
19
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/LICENSE
generated
Normal file
19
samples/client/petstore/swift/rxswift/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/rxswift/SwaggerClientTests/Pods/Alamofire/README.md
generated
Normal file
1149
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/README.md
generated
Normal file
File diff suppressed because it is too large
Load Diff
368
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift
generated
Normal file
368
samples/client/petstore/swift/rxswift/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/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Download.swift
generated
Normal file
244
samples/client/petstore/swift/rxswift/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/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Error.swift
generated
Normal file
66
samples/client/petstore/swift/rxswift/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/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift
generated
Normal file
693
samples/client/petstore/swift/rxswift/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/rxswift/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift
generated
Normal file
669
samples/client/petstore/swift/rxswift/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/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift
generated
Normal file
251
samples/client/petstore/swift/rxswift/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/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Request.swift
generated
Normal file
538
samples/client/petstore/swift/rxswift/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/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Response.swift
generated
Normal file
83
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Response.swift
generated
Normal file
@ -0,0 +1,83 @@
|
||||
// Response.swift
|
||||
//
|
||||
// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Used to store all response data returned from a completed `Request`.
|
||||
public struct Response<Value, Error: ErrorType> {
|
||||
/// The URL request sent to the server.
|
||||
public let request: NSURLRequest?
|
||||
|
||||
/// The server's response to the URL request.
|
||||
public let response: NSHTTPURLResponse?
|
||||
|
||||
/// The data returned by the server.
|
||||
public let data: NSData?
|
||||
|
||||
/// The result of response serialization.
|
||||
public let result: Result<Value, Error>
|
||||
|
||||
/**
|
||||
Initializes the `Response` instance with the specified URL request, URL response, server data and response
|
||||
serialization result.
|
||||
|
||||
- parameter request: The URL request sent to the server.
|
||||
- parameter response: The server's response to the URL request.
|
||||
- parameter data: The data returned by the server.
|
||||
- parameter result: The result of response serialization.
|
||||
|
||||
- returns: the new `Response` instance.
|
||||
*/
|
||||
public init(request: NSURLRequest?, response: NSHTTPURLResponse?, data: NSData?, result: Result<Value, Error>) {
|
||||
self.request = request
|
||||
self.response = response
|
||||
self.data = data
|
||||
self.result = result
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
extension Response: CustomStringConvertible {
|
||||
/// The textual representation used when written to an output stream, which includes whether the result was a
|
||||
/// success or failure.
|
||||
public var description: String {
|
||||
return result.debugDescription
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomDebugStringConvertible
|
||||
|
||||
extension Response: CustomDebugStringConvertible {
|
||||
/// The debug textual representation used when written to an output stream, which includes the URL request, the URL
|
||||
/// response, the server data and the response serialization result.
|
||||
public var debugDescription: String {
|
||||
var output: [String] = []
|
||||
|
||||
output.append(request != nil ? "[Request]: \(request!)" : "[Request]: nil")
|
||||
output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil")
|
||||
output.append("[Data]: \(data?.length ?? 0) bytes")
|
||||
output.append("[Result]: \(result.debugDescription)")
|
||||
|
||||
return output.joinWithSeparator("\n")
|
||||
}
|
||||
}
|
@ -0,0 +1,355 @@
|
||||
// ResponseSerialization.swift
|
||||
//
|
||||
// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
// MARK: ResponseSerializer
|
||||
|
||||
/**
|
||||
The type in which all response serializers must conform to in order to serialize a response.
|
||||
*/
|
||||
public protocol ResponseSerializerType {
|
||||
/// The type of serialized object to be created by this `ResponseSerializerType`.
|
||||
typealias SerializedObject
|
||||
|
||||
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
|
||||
typealias ErrorObject: ErrorType
|
||||
|
||||
/**
|
||||
A closure used by response handlers that takes a request, response, data and error and returns a result.
|
||||
*/
|
||||
var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<SerializedObject, ErrorObject> { get }
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
/**
|
||||
A generic `ResponseSerializerType` used to serialize a request, response, and data into a serialized object.
|
||||
*/
|
||||
public struct ResponseSerializer<Value, Error: ErrorType>: ResponseSerializerType {
|
||||
/// The type of serialized object to be created by this `ResponseSerializer`.
|
||||
public typealias SerializedObject = Value
|
||||
|
||||
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
|
||||
public typealias ErrorObject = Error
|
||||
|
||||
/**
|
||||
A closure used by response handlers that takes a request, response, data and error and returns a result.
|
||||
*/
|
||||
public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>
|
||||
|
||||
/**
|
||||
Initializes the `ResponseSerializer` instance with the given serialize response closure.
|
||||
|
||||
- parameter serializeResponse: The closure used to serialize the response.
|
||||
|
||||
- returns: The new generic response serializer instance.
|
||||
*/
|
||||
public init(serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>) {
|
||||
self.serializeResponse = serializeResponse
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Default
|
||||
|
||||
extension Request {
|
||||
|
||||
/**
|
||||
Adds a handler to be called once the request has finished.
|
||||
|
||||
- parameter queue: The queue on which the completion handler is dispatched.
|
||||
- parameter completionHandler: The code to be executed once the request has finished.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func response(
|
||||
queue queue: dispatch_queue_t? = nil,
|
||||
completionHandler: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Void)
|
||||
-> Self
|
||||
{
|
||||
delegate.queue.addOperationWithBlock {
|
||||
dispatch_async(queue ?? dispatch_get_main_queue()) {
|
||||
completionHandler(self.request, self.response, self.delegate.data, self.delegate.error)
|
||||
}
|
||||
}
|
||||
|
||||
return self
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler to be called once the request has finished.
|
||||
|
||||
- parameter queue: The queue on which the completion handler is dispatched.
|
||||
- parameter responseSerializer: The response serializer responsible for serializing the request, response,
|
||||
and data.
|
||||
- parameter completionHandler: The code to be executed once the request has finished.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func response<T: ResponseSerializerType>(
|
||||
queue queue: dispatch_queue_t? = nil,
|
||||
responseSerializer: T,
|
||||
completionHandler: Response<T.SerializedObject, T.ErrorObject> -> Void)
|
||||
-> Self
|
||||
{
|
||||
delegate.queue.addOperationWithBlock {
|
||||
let result = responseSerializer.serializeResponse(
|
||||
self.request,
|
||||
self.response,
|
||||
self.delegate.data,
|
||||
self.delegate.error
|
||||
)
|
||||
|
||||
dispatch_async(queue ?? dispatch_get_main_queue()) {
|
||||
let response = Response<T.SerializedObject, T.ErrorObject>(
|
||||
request: self.request,
|
||||
response: self.response,
|
||||
data: self.delegate.data,
|
||||
result: result
|
||||
)
|
||||
|
||||
completionHandler(response)
|
||||
}
|
||||
}
|
||||
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Data
|
||||
|
||||
extension Request {
|
||||
|
||||
/**
|
||||
Creates a response serializer that returns the associated data as-is.
|
||||
|
||||
- returns: A data response serializer.
|
||||
*/
|
||||
public static func dataResponseSerializer() -> ResponseSerializer<NSData, NSError> {
|
||||
return ResponseSerializer { _, response, data, error in
|
||||
guard error == nil else { return .Failure(error!) }
|
||||
|
||||
if let response = response where response.statusCode == 204 { return .Success(NSData()) }
|
||||
|
||||
guard let validData = data else {
|
||||
let failureReason = "Data could not be serialized. Input data was nil."
|
||||
let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
|
||||
return .Failure(error)
|
||||
}
|
||||
|
||||
return .Success(validData)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler to be called once the request has finished.
|
||||
|
||||
- parameter completionHandler: The code to be executed once the request has finished.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func responseData(completionHandler: Response<NSData, NSError> -> Void) -> Self {
|
||||
return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - String
|
||||
|
||||
extension Request {
|
||||
|
||||
/**
|
||||
Creates a response serializer that returns a string initialized from the response data with the specified
|
||||
string encoding.
|
||||
|
||||
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
|
||||
response, falling back to the default HTTP default character set, ISO-8859-1.
|
||||
|
||||
- returns: A string response serializer.
|
||||
*/
|
||||
public static func stringResponseSerializer(
|
||||
var encoding encoding: NSStringEncoding? = nil)
|
||||
-> ResponseSerializer<String, NSError>
|
||||
{
|
||||
return ResponseSerializer { _, response, data, error in
|
||||
guard error == nil else { return .Failure(error!) }
|
||||
|
||||
if let response = response where response.statusCode == 204 { return .Success("") }
|
||||
|
||||
guard let validData = data else {
|
||||
let failureReason = "String could not be serialized. Input data was nil."
|
||||
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
|
||||
return .Failure(error)
|
||||
}
|
||||
|
||||
if let encodingName = response?.textEncodingName where encoding == nil {
|
||||
encoding = CFStringConvertEncodingToNSStringEncoding(
|
||||
CFStringConvertIANACharSetNameToEncoding(encodingName)
|
||||
)
|
||||
}
|
||||
|
||||
let actualEncoding = encoding ?? NSISOLatin1StringEncoding
|
||||
|
||||
if let string = String(data: validData, encoding: actualEncoding) {
|
||||
return .Success(string)
|
||||
} else {
|
||||
let failureReason = "String could not be serialized with encoding: \(actualEncoding)"
|
||||
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
|
||||
return .Failure(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler to be called once the request has finished.
|
||||
|
||||
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
|
||||
server response, falling back to the default HTTP default character set,
|
||||
ISO-8859-1.
|
||||
- parameter completionHandler: A closure to be executed once the request has finished.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func responseString(
|
||||
encoding encoding: NSStringEncoding? = nil,
|
||||
completionHandler: Response<String, NSError> -> Void)
|
||||
-> Self
|
||||
{
|
||||
return response(
|
||||
responseSerializer: Request.stringResponseSerializer(encoding: encoding),
|
||||
completionHandler: completionHandler
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - JSON
|
||||
|
||||
extension Request {
|
||||
|
||||
/**
|
||||
Creates a response serializer that returns a JSON object constructed from the response data using
|
||||
`NSJSONSerialization` with the specified reading options.
|
||||
|
||||
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
|
||||
|
||||
- returns: A JSON object response serializer.
|
||||
*/
|
||||
public static func JSONResponseSerializer(
|
||||
options options: NSJSONReadingOptions = .AllowFragments)
|
||||
-> ResponseSerializer<AnyObject, NSError>
|
||||
{
|
||||
return ResponseSerializer { _, response, data, error in
|
||||
guard error == nil else { return .Failure(error!) }
|
||||
|
||||
if let response = response where response.statusCode == 204 { return .Success(NSNull()) }
|
||||
|
||||
guard let validData = data where validData.length > 0 else {
|
||||
let failureReason = "JSON could not be serialized. Input data was nil or zero length."
|
||||
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
|
||||
return .Failure(error)
|
||||
}
|
||||
|
||||
do {
|
||||
let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: options)
|
||||
return .Success(JSON)
|
||||
} catch {
|
||||
return .Failure(error as NSError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler to be called once the request has finished.
|
||||
|
||||
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
|
||||
- parameter completionHandler: A closure to be executed once the request has finished.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func responseJSON(
|
||||
options options: NSJSONReadingOptions = .AllowFragments,
|
||||
completionHandler: Response<AnyObject, NSError> -> Void)
|
||||
-> Self
|
||||
{
|
||||
return response(
|
||||
responseSerializer: Request.JSONResponseSerializer(options: options),
|
||||
completionHandler: completionHandler
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Property List
|
||||
|
||||
extension Request {
|
||||
|
||||
/**
|
||||
Creates a response serializer that returns an object constructed from the response data using
|
||||
`NSPropertyListSerialization` with the specified reading options.
|
||||
|
||||
- parameter options: The property list reading options. `NSPropertyListReadOptions()` by default.
|
||||
|
||||
- returns: A property list object response serializer.
|
||||
*/
|
||||
public static func propertyListResponseSerializer(
|
||||
options options: NSPropertyListReadOptions = NSPropertyListReadOptions())
|
||||
-> ResponseSerializer<AnyObject, NSError>
|
||||
{
|
||||
return ResponseSerializer { _, response, data, error in
|
||||
guard error == nil else { return .Failure(error!) }
|
||||
|
||||
if let response = response where response.statusCode == 204 { return .Success(NSNull()) }
|
||||
|
||||
guard let validData = data where validData.length > 0 else {
|
||||
let failureReason = "Property list could not be serialized. Input data was nil or zero length."
|
||||
let error = Error.errorWithCode(.PropertyListSerializationFailed, failureReason: failureReason)
|
||||
return .Failure(error)
|
||||
}
|
||||
|
||||
do {
|
||||
let plist = try NSPropertyListSerialization.propertyListWithData(validData, options: options, format: nil)
|
||||
return .Success(plist)
|
||||
} catch {
|
||||
return .Failure(error as NSError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a handler to be called once the request has finished.
|
||||
|
||||
- parameter options: The property list reading options. `0` by default.
|
||||
- parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3
|
||||
arguments: the URL request, the URL response, the server data and the result
|
||||
produced while creating the property list.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func responsePropertyList(
|
||||
options options: NSPropertyListReadOptions = NSPropertyListReadOptions(),
|
||||
completionHandler: Response<AnyObject, NSError> -> Void)
|
||||
-> Self
|
||||
{
|
||||
return response(
|
||||
responseSerializer: Request.propertyListResponseSerializer(options: options),
|
||||
completionHandler: completionHandler
|
||||
)
|
||||
}
|
||||
}
|
101
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Result.swift
generated
Normal file
101
samples/client/petstore/swift/rxswift/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/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift
generated
Normal file
302
samples/client/petstore/swift/rxswift/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/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift
generated
Normal file
180
samples/client/petstore/swift/rxswift/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/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift
generated
Normal file
372
samples/client/petstore/swift/rxswift/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/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift
generated
Normal file
189
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift
generated
Normal file
@ -0,0 +1,189 @@
|
||||
// Validation.swift
|
||||
//
|
||||
// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
import Foundation
|
||||
|
||||
extension Request {
|
||||
|
||||
/**
|
||||
Used to represent whether validation was successful or encountered an error resulting in a failure.
|
||||
|
||||
- Success: The validation was successful.
|
||||
- Failure: The validation failed encountering the provided error.
|
||||
*/
|
||||
public enum ValidationResult {
|
||||
case Success
|
||||
case Failure(NSError)
|
||||
}
|
||||
|
||||
/**
|
||||
A closure used to validate a request that takes a URL request and URL response, and returns whether the
|
||||
request was valid.
|
||||
*/
|
||||
public typealias Validation = (NSURLRequest?, NSHTTPURLResponse) -> ValidationResult
|
||||
|
||||
/**
|
||||
Validates the request, using the specified closure.
|
||||
|
||||
If validation fails, subsequent calls to response handlers will have an associated error.
|
||||
|
||||
- parameter validation: A closure to validate the request.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func validate(validation: Validation) -> Self {
|
||||
delegate.queue.addOperationWithBlock {
|
||||
if let
|
||||
response = self.response where self.delegate.error == nil,
|
||||
case let .Failure(error) = validation(self.request, response)
|
||||
{
|
||||
self.delegate.error = error
|
||||
}
|
||||
}
|
||||
|
||||
return self
|
||||
}
|
||||
|
||||
// MARK: - Status Code
|
||||
|
||||
/**
|
||||
Validates that the response has a status code in the specified range.
|
||||
|
||||
If validation fails, subsequent calls to response handlers will have an associated error.
|
||||
|
||||
- parameter range: The range of acceptable status codes.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func validate<S: SequenceType where S.Generator.Element == Int>(statusCode acceptableStatusCode: S) -> Self {
|
||||
return validate { _, response in
|
||||
if acceptableStatusCode.contains(response.statusCode) {
|
||||
return .Success
|
||||
} else {
|
||||
let failureReason = "Response status code was unacceptable: \(response.statusCode)"
|
||||
return .Failure(Error.errorWithCode(.StatusCodeValidationFailed, failureReason: failureReason))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Content-Type
|
||||
|
||||
private struct MIMEType {
|
||||
let type: String
|
||||
let subtype: String
|
||||
|
||||
init?(_ string: String) {
|
||||
let components: [String] = {
|
||||
let stripped = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
|
||||
let split = stripped.substringToIndex(stripped.rangeOfString(";")?.startIndex ?? stripped.endIndex)
|
||||
return split.componentsSeparatedByString("/")
|
||||
}()
|
||||
|
||||
if let
|
||||
type = components.first,
|
||||
subtype = components.last
|
||||
{
|
||||
self.type = type
|
||||
self.subtype = subtype
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func matches(MIME: MIMEType) -> Bool {
|
||||
switch (type, subtype) {
|
||||
case (MIME.type, MIME.subtype), (MIME.type, "*"), ("*", MIME.subtype), ("*", "*"):
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Validates that the response has a content type in the specified array.
|
||||
|
||||
If validation fails, subsequent calls to response handlers will have an associated error.
|
||||
|
||||
- parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func validate<S : SequenceType where S.Generator.Element == String>(contentType acceptableContentTypes: S) -> Self {
|
||||
return validate { _, response in
|
||||
guard let validData = self.delegate.data where validData.length > 0 else { return .Success }
|
||||
|
||||
if let
|
||||
responseContentType = response.MIMEType,
|
||||
responseMIMEType = MIMEType(responseContentType)
|
||||
{
|
||||
for contentType in acceptableContentTypes {
|
||||
if let acceptableMIMEType = MIMEType(contentType) where acceptableMIMEType.matches(responseMIMEType) {
|
||||
return .Success
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for contentType in acceptableContentTypes {
|
||||
if let MIMEType = MIMEType(contentType) where MIMEType.type == "*" && MIMEType.subtype == "*" {
|
||||
return .Success
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let failureReason: String
|
||||
|
||||
if let responseContentType = response.MIMEType {
|
||||
failureReason = (
|
||||
"Response content type \"\(responseContentType)\" does not match any acceptable " +
|
||||
"content types: \(acceptableContentTypes)"
|
||||
)
|
||||
} else {
|
||||
failureReason = "Response content type was missing and acceptable content type does not match \"*/*\""
|
||||
}
|
||||
|
||||
return .Failure(Error.errorWithCode(.ContentTypeValidationFailed, failureReason: failureReason))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Automatic
|
||||
|
||||
/**
|
||||
Validates that the response has a status code in the default acceptable range of 200...299, and that the content
|
||||
type matches any specified in the Accept HTTP header field.
|
||||
|
||||
If validation fails, subsequent calls to response handlers will have an associated error.
|
||||
|
||||
- returns: The request.
|
||||
*/
|
||||
public func validate() -> Self {
|
||||
let acceptableStatusCodes: Range<Int> = 200..<300
|
||||
let acceptableContentTypes: [String] = {
|
||||
if let accept = request?.valueForHTTPHeaderField("Accept") {
|
||||
return accept.componentsSeparatedByString(",")
|
||||
}
|
||||
|
||||
return ["*/*"]
|
||||
}()
|
||||
|
||||
return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes)
|
||||
}
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
{
|
||||
"name": "PetstoreClient",
|
||||
"platforms": {
|
||||
"ios": "8.0",
|
||||
"osx": "10.9"
|
||||
},
|
||||
"version": "0.0.1",
|
||||
"source": {
|
||||
"git": "git@github.com:swagger-api/swagger-mustache.git",
|
||||
"tag": "v1.0.0"
|
||||
},
|
||||
"authors": "",
|
||||
"license": "Apache License, Version 2.0",
|
||||
"homepage": "https://github.com/swagger-api/swagger-codegen",
|
||||
"summary": "PetstoreClient",
|
||||
"source_files": "PetstoreClient/Classes/Swaggers/**/*.swift",
|
||||
"dependencies": {
|
||||
"RxSwift": [
|
||||
"~> 2.0"
|
||||
],
|
||||
"Alamofire": [
|
||||
"~> 3.1.5"
|
||||
]
|
||||
}
|
||||
}
|
22
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Manifest.lock
generated
Normal file
22
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Manifest.lock
generated
Normal file
@ -0,0 +1,22 @@
|
||||
PODS:
|
||||
- Alamofire (3.1.5)
|
||||
- PetstoreClient (0.0.1):
|
||||
- Alamofire (~> 3.1.5)
|
||||
- RxSwift (~> 2.0)
|
||||
- RxSwift (2.6.0)
|
||||
|
||||
DEPENDENCIES:
|
||||
- PetstoreClient (from `../`)
|
||||
|
||||
EXTERNAL SOURCES:
|
||||
PetstoreClient:
|
||||
:path: "../"
|
||||
|
||||
SPEC CHECKSUMS:
|
||||
Alamofire: 5f730ba29fd113b7ddd71c1e65d0c630acf5d7b0
|
||||
PetstoreClient: 0baad893079f270b6bcf2e868ba68d8b9ce36812
|
||||
RxSwift: 77f3a0b15324baa7a1c9bfa9f199648a82424e26
|
||||
|
||||
PODFILE CHECKSUM: cedb3058b02f4776d7c31f6d92ae2f674fdf424d
|
||||
|
||||
COCOAPODS: 1.0.1
|
1731
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj
generated
Normal file
1731
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj
generated
Normal file
File diff suppressed because it is too large
Load Diff
9
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/LICENSE.md
generated
Normal file
9
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/LICENSE.md
generated
Normal file
@ -0,0 +1,9 @@
|
||||
**The MIT License**
|
||||
**Copyright © 2015 Krunoslav Zaher**
|
||||
**All rights reserved.**
|
||||
|
||||
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.
|
180
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/README.md
generated
Normal file
180
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/README.md
generated
Normal file
@ -0,0 +1,180 @@
|
||||
<img src="assets/Rx_Logo_M.png" alt="Miss Electric Eel 2016" width="36" height="36"> RxSwift: ReactiveX for Swift
|
||||
======================================
|
||||
|
||||
[![Travis CI](https://travis-ci.org/ReactiveX/RxSwift.svg?branch=master)](https://travis-ci.org/ReactiveX/RxSwift) ![platforms](https://img.shields.io/badge/platforms-iOS%20%7C%20OSX%20%7C%20tvOS%20%7C%20watchOS%20%7C%20Linux%28experimental%29-333333.svg) ![pod](https://img.shields.io/cocoapods/v/RxSwift.svg) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)
|
||||
|
||||
Xcode 7.3 Swift 2.2 required
|
||||
|
||||
## About Rx
|
||||
|
||||
Rx is a [generic abstraction of computation](https://youtu.be/looJcaeboBY) expressed through `Observable<Element>` interface.
|
||||
|
||||
This is a Swift version of [Rx](https://github.com/Reactive-Extensions/Rx.NET).
|
||||
|
||||
It tries to port as many concepts from the original version as possible, but some concepts were adapted for more pleasant and performant integration with iOS/OSX environment.
|
||||
|
||||
Cross platform documentation can be found on [ReactiveX.io](http://reactivex.io/).
|
||||
|
||||
Like the original Rx, its intention is to enable easy composition of asynchronous operations and event/data streams.
|
||||
|
||||
KVO observing, async operations and streams are all unified under [abstraction of sequence](Documentation/GettingStarted.md#observables-aka-sequences). This is the reason why Rx is so simple, elegant and powerful.
|
||||
|
||||
## I came here because I want to ...
|
||||
|
||||
###### ... understand
|
||||
|
||||
* [why use rx?](Documentation/Why.md)
|
||||
* [the basics, getting started with RxSwift](Documentation/GettingStarted.md)
|
||||
* [units](Documentation/Units.md) - what is `Driver`, `ControlProperty`, and `Variable` ... and why do they exist?
|
||||
* [testing](Documentation/UnitTests.md)
|
||||
* [tips and common errors](Documentation/Tips.md)
|
||||
* [debugging](Documentation/GettingStarted.md#debugging)
|
||||
* [the math behind Rx](Documentation/MathBehindRx.md)
|
||||
* [what are hot and cold observable sequences?](Documentation/HotAndColdObservables.md)
|
||||
* [what does the the public API look like?](Documentation/API.md)
|
||||
|
||||
###### ... install
|
||||
|
||||
* Integrate RxSwift/RxCocoa with my app. [Installation Guide](Documentation/Installation.md)
|
||||
|
||||
###### ... hack around
|
||||
|
||||
* with the example app. [Running Example App](Documentation/ExampleApp.md)
|
||||
* with operators in playgrounds. [Playgrounds](Documentation/Playgrounds.md)
|
||||
|
||||
###### ... interact
|
||||
|
||||
* All of this is great, but it would be nice to talk with other people using RxSwift and exchange experiences. <br />[![Slack channel](http://slack.rxswift.org/badge.svg)](http://slack.rxswift.org) [Join Slack Channel](http://slack.rxswift.org/)
|
||||
* Report a problem using the library. [Open an Issue With Bug Template](ISSUE_TEMPLATE.md)
|
||||
* Request a new feature. [Open an Issue With Feature Request Template](Documentation/NewFeatureRequestTemplate.md)
|
||||
|
||||
|
||||
###### ... compare
|
||||
|
||||
* [with other libraries](Documentation/ComparisonWithOtherLibraries.md).
|
||||
|
||||
|
||||
###### ... find compatible
|
||||
|
||||
* libraries from [RxSwiftCommunity](https://github.com/RxSwiftCommunity).
|
||||
* [Pods using RxSwift](https://cocoapods.org/?q=uses%3Arxswift).
|
||||
|
||||
###### ... see the broader vision
|
||||
|
||||
* Does this exist for Android? [RxJava](https://github.com/ReactiveX/RxJava)
|
||||
* Where is all of this going, what is the future, what about reactive architectures, how do you design entire apps this way? [Cycle.js](https://github.com/cyclejs/cycle-core) - this is javascript, but [RxJS](https://github.com/Reactive-Extensions/RxJS) is javascript version of Rx.
|
||||
|
||||
## Usage
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th width="30%">Here's an example</th>
|
||||
<th width="30%">In Action</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Define search for GitHub repositories ...</td>
|
||||
<th rowspan="9"><img src="https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/GithubSearch.gif"></th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><div class="highlight highlight-source-swift"><pre>
|
||||
let searchResults = searchBar.rx_text
|
||||
.throttle(0.3, scheduler: MainScheduler.instance)
|
||||
.distinctUntilChanged()
|
||||
.flatMapLatest { query -> Observable<[Repository]> in
|
||||
if query.isEmpty {
|
||||
return Observable.just([])
|
||||
}
|
||||
|
||||
return searchGitHub(query)
|
||||
.catchErrorJustReturn([])
|
||||
}
|
||||
.observeOn(MainScheduler.instance)</pre></div></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>... then bind the results to your tableview</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="30%"><div class="highlight highlight-source-swift"><pre>
|
||||
searchResults
|
||||
.bindTo(tableView.rx_itemsWithCellIdentifier("Cell")) {
|
||||
(index, repository: Repository, cell) in
|
||||
cell.textLabel?.text = repository.name
|
||||
cell.detailTextLabel?.text = repository.url
|
||||
}
|
||||
.addDisposableTo(disposeBag)</pre></div></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
|
||||
## Installation
|
||||
|
||||
Rx doesn't contain any external dependencies.
|
||||
|
||||
These are currently the supported options:
|
||||
|
||||
### Manual
|
||||
|
||||
Open Rx.xcworkspace, choose `RxExample` and hit run. This method will build everything and run the sample app
|
||||
|
||||
### [CocoaPods](https://guides.cocoapods.org/using/using-cocoapods.html)
|
||||
|
||||
**:warning: IMPORTANT! For tvOS support, CocoaPods `0.39` is required. :warning:**
|
||||
|
||||
```
|
||||
# Podfile
|
||||
use_frameworks!
|
||||
|
||||
target 'YOUR_TARGET_NAME' do
|
||||
pod 'RxSwift', '~> 2.0'
|
||||
pod 'RxCocoa', '~> 2.0'
|
||||
end
|
||||
|
||||
# RxTests and RxBlocking make the most sense in the context of unit/integration tests
|
||||
target 'YOUR_TESTING_TARGET' do
|
||||
pod 'RxBlocking', '~> 2.0'
|
||||
pod 'RxTests', '~> 2.0'
|
||||
end
|
||||
```
|
||||
|
||||
Replace `YOUR_TARGET_NAME` and then, in the `Podfile` directory, type:
|
||||
|
||||
```
|
||||
$ pod install
|
||||
```
|
||||
|
||||
### [Carthage](https://github.com/Carthage/Carthage)
|
||||
|
||||
**Xcode 7.1 required**
|
||||
|
||||
Add this to `Cartfile`
|
||||
|
||||
```
|
||||
github "ReactiveX/RxSwift" ~> 2.0
|
||||
```
|
||||
|
||||
```
|
||||
$ carthage update
|
||||
```
|
||||
|
||||
### Manually using git submodules
|
||||
|
||||
* Add RxSwift as a submodule
|
||||
|
||||
```
|
||||
$ git submodule add git@github.com:ReactiveX/RxSwift.git
|
||||
```
|
||||
|
||||
* Drag `Rx.xcodeproj` into Project Navigator
|
||||
* Go to `Project > Targets > Build Phases > Link Binary With Libraries`, click `+` and select `RxSwift-[Platform]` and `RxCocoa-[Platform]` targets
|
||||
|
||||
|
||||
## References
|
||||
|
||||
* [http://reactivex.io/](http://reactivex.io/)
|
||||
* [Reactive Extensions GitHub (GitHub)](https://github.com/Reactive-Extensions)
|
||||
* [Erik Meijer (Wikipedia)](http://en.wikipedia.org/wiki/Erik_Meijer_%28computer_scientist%29)
|
||||
* [Expert to Expert: Brian Beckman and Erik Meijer - Inside the .NET Reactive Framework (Rx) (video)](https://youtu.be/looJcaeboBY)
|
||||
* [Reactive Programming Overview (Jafar Husain from Netflix)](https://www.youtube.com/watch?v=dwP1TNXE6fc)
|
||||
* [Subject/Observer is Dual to Iterator (paper)](http://csl.stanford.edu/~christos/pldi2010.fit/meijer.duality.pdf)
|
||||
* [Rx standard sequence operators visualized (visualization tool)](http://rxmarbles.com/)
|
||||
* [Haskell](https://www.haskell.org/)
|
75
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/AnyObserver.swift
generated
Normal file
75
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/AnyObserver.swift
generated
Normal file
@ -0,0 +1,75 @@
|
||||
//
|
||||
// AnyObserver.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 2/28/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
A type-erased `ObserverType`.
|
||||
|
||||
Forwards operations to an arbitrary underlying observer with the same `Element` type, hiding the specifics of the underlying observer type.
|
||||
*/
|
||||
public struct AnyObserver<Element> : ObserverType {
|
||||
/**
|
||||
The type of elements in sequence that observer can observe.
|
||||
*/
|
||||
public typealias E = Element
|
||||
|
||||
/**
|
||||
Anonymous event handler type.
|
||||
*/
|
||||
public typealias EventHandler = (Event<Element>) -> Void
|
||||
|
||||
public let observer: EventHandler
|
||||
|
||||
/**
|
||||
Construct an instance whose `on(event)` calls `eventHandler(event)`
|
||||
|
||||
- parameter eventHandler: Event handler that observes sequences events.
|
||||
*/
|
||||
public init(eventHandler: EventHandler) {
|
||||
self.observer = eventHandler
|
||||
}
|
||||
|
||||
/**
|
||||
Construct an instance whose `on(event)` calls `observer.on(event)`
|
||||
|
||||
- parameter observer: Observer that receives sequence events.
|
||||
*/
|
||||
public init<O : ObserverType where O.E == Element>(_ observer: O) {
|
||||
self.observer = observer.on
|
||||
}
|
||||
|
||||
/**
|
||||
Send `event` to this observer.
|
||||
|
||||
- parameter event: Event instance.
|
||||
*/
|
||||
public func on(event: Event<Element>) {
|
||||
return self.observer(event)
|
||||
}
|
||||
|
||||
/**
|
||||
Erases type of observer and returns canonical observer.
|
||||
|
||||
- returns: type erased observer.
|
||||
*/
|
||||
public func asObserver() -> AnyObserver<E> {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
extension ObserverType {
|
||||
/**
|
||||
Erases type of observer and returns canonical observer.
|
||||
|
||||
- returns: type erased observer.
|
||||
*/
|
||||
public func asObserver() -> AnyObserver<E> {
|
||||
return AnyObserver(self)
|
||||
}
|
||||
}
|
19
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Cancelable.swift
generated
Normal file
19
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Cancelable.swift
generated
Normal file
@ -0,0 +1,19 @@
|
||||
//
|
||||
// Cancelable.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 3/12/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Represents disposable resource with state tracking.
|
||||
*/
|
||||
public protocol Cancelable : Disposable {
|
||||
/**
|
||||
- returns: Was resource disposed.
|
||||
*/
|
||||
var disposed: Bool { get }
|
||||
}
|
@ -0,0 +1,104 @@
|
||||
//
|
||||
// AsyncLock.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 3/21/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
In case nobody holds this lock, the work will be queued and executed immediately
|
||||
on thread that is requesting lock.
|
||||
|
||||
In case there is somebody currently holding that lock, action will be enqueued.
|
||||
When owned of the lock finishes with it's processing, it will also execute
|
||||
and pending work.
|
||||
|
||||
That means that enqueued work could possibly be executed later on a different thread.
|
||||
*/
|
||||
class AsyncLock<I: InvocableType>
|
||||
: Disposable
|
||||
, Lock
|
||||
, SynchronizedDisposeType {
|
||||
typealias Action = () -> Void
|
||||
|
||||
var _lock = SpinLock()
|
||||
|
||||
private var _queue: Queue<I> = Queue(capacity: 0)
|
||||
|
||||
private var _isExecuting: Bool = false
|
||||
private var _hasFaulted: Bool = false
|
||||
|
||||
// lock {
|
||||
func lock() {
|
||||
_lock.lock()
|
||||
}
|
||||
|
||||
func unlock() {
|
||||
_lock.unlock()
|
||||
}
|
||||
// }
|
||||
|
||||
private func enqueue(action: I) -> I? {
|
||||
_lock.lock(); defer { _lock.unlock() } // {
|
||||
if _hasFaulted {
|
||||
return nil
|
||||
}
|
||||
|
||||
if _isExecuting {
|
||||
_queue.enqueue(action)
|
||||
return nil
|
||||
}
|
||||
|
||||
_isExecuting = true
|
||||
|
||||
return action
|
||||
// }
|
||||
}
|
||||
|
||||
private func dequeue() -> I? {
|
||||
_lock.lock(); defer { _lock.unlock() } // {
|
||||
if _queue.count > 0 {
|
||||
return _queue.dequeue()
|
||||
}
|
||||
else {
|
||||
_isExecuting = false
|
||||
return nil
|
||||
}
|
||||
// }
|
||||
}
|
||||
|
||||
func invoke(action: I) {
|
||||
let firstEnqueuedAction = enqueue(action)
|
||||
|
||||
if let firstEnqueuedAction = firstEnqueuedAction {
|
||||
firstEnqueuedAction.invoke()
|
||||
}
|
||||
else {
|
||||
// action is enqueued, it's somebody else's concern now
|
||||
return
|
||||
}
|
||||
|
||||
while true {
|
||||
let nextAction = dequeue()
|
||||
|
||||
if let nextAction = nextAction {
|
||||
nextAction.invoke()
|
||||
}
|
||||
else {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func dispose() {
|
||||
synchronizedDispose()
|
||||
}
|
||||
|
||||
func _synchronized_dispose() {
|
||||
_queue = Queue(capacity: 0)
|
||||
_hasFaulted = true
|
||||
}
|
||||
}
|
107
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/Lock.swift
generated
Normal file
107
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/Lock.swift
generated
Normal file
@ -0,0 +1,107 @@
|
||||
//
|
||||
// Lock.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 3/31/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol Lock {
|
||||
func lock()
|
||||
func unlock()
|
||||
}
|
||||
|
||||
#if os(Linux)
|
||||
import Glibc
|
||||
|
||||
/**
|
||||
Simple wrapper for spin lock.
|
||||
*/
|
||||
class SpinLock {
|
||||
private var _lock: pthread_spinlock_t = 0
|
||||
|
||||
init() {
|
||||
if (pthread_spin_init(&_lock, 0) != 0) {
|
||||
fatalError("Spin lock initialization failed")
|
||||
}
|
||||
}
|
||||
|
||||
func lock() {
|
||||
pthread_spin_lock(&_lock)
|
||||
}
|
||||
|
||||
func unlock() {
|
||||
pthread_spin_unlock(&_lock)
|
||||
}
|
||||
|
||||
func performLocked(@noescape action: () -> Void) {
|
||||
lock(); defer { unlock() }
|
||||
action()
|
||||
}
|
||||
|
||||
func calculateLocked<T>(@noescape action: () -> T) -> T {
|
||||
lock(); defer { unlock() }
|
||||
return action()
|
||||
}
|
||||
|
||||
func calculateLockedOrFail<T>(@noescape action: () throws -> T) throws -> T {
|
||||
lock(); defer { unlock() }
|
||||
let result = try action()
|
||||
return result
|
||||
}
|
||||
|
||||
deinit {
|
||||
pthread_spin_destroy(&_lock)
|
||||
}
|
||||
}
|
||||
#else
|
||||
|
||||
// https://lists.swift.org/pipermail/swift-dev/Week-of-Mon-20151214/000321.html
|
||||
typealias SpinLock = NSRecursiveLock
|
||||
#endif
|
||||
|
||||
extension NSRecursiveLock : Lock {
|
||||
func performLocked(@noescape action: () -> Void) {
|
||||
lock(); defer { unlock() }
|
||||
action()
|
||||
}
|
||||
|
||||
func calculateLocked<T>(@noescape action: () -> T) -> T {
|
||||
lock(); defer { unlock() }
|
||||
return action()
|
||||
}
|
||||
|
||||
func calculateLockedOrFail<T>(@noescape action: () throws -> T) throws -> T {
|
||||
lock(); defer { unlock() }
|
||||
let result = try action()
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
let RECURSIVE_MUTEX = _initializeRecursiveMutex()
|
||||
|
||||
func _initializeRecursiveMutex() -> pthread_mutex_t {
|
||||
var mutex: pthread_mutex_t = pthread_mutex_t()
|
||||
var mta: pthread_mutexattr_t = pthread_mutexattr_t()
|
||||
|
||||
pthread_mutex_init(&mutex, nil)
|
||||
pthread_mutexattr_init(&mta)
|
||||
pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_RECURSIVE)
|
||||
pthread_mutex_init(&mutex, &mta)
|
||||
|
||||
return mutex
|
||||
}
|
||||
|
||||
extension pthread_mutex_t {
|
||||
mutating func lock() {
|
||||
pthread_mutex_lock(&self)
|
||||
}
|
||||
|
||||
mutating func unlock() {
|
||||
pthread_mutex_unlock(&self)
|
||||
}
|
||||
}
|
||||
*/
|
@ -0,0 +1,23 @@
|
||||
//
|
||||
// LockOwnerType.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 10/25/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol LockOwnerType : class, Lock {
|
||||
var _lock: NSRecursiveLock { get }
|
||||
}
|
||||
|
||||
extension LockOwnerType {
|
||||
func lock() {
|
||||
_lock.lock()
|
||||
}
|
||||
|
||||
func unlock() {
|
||||
_lock.unlock()
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
//
|
||||
// SynchronizedDisposeType.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 10/25/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol SynchronizedDisposeType : class, Disposable, Lock {
|
||||
func _synchronized_dispose()
|
||||
}
|
||||
|
||||
extension SynchronizedDisposeType {
|
||||
func synchronizedDispose() {
|
||||
lock(); defer { unlock() }
|
||||
_synchronized_dispose()
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
//
|
||||
// SynchronizedOnType.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 10/25/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol SynchronizedOnType : class, ObserverType, Lock {
|
||||
func _synchronized_on(event: Event<E>)
|
||||
}
|
||||
|
||||
extension SynchronizedOnType {
|
||||
func synchronizedOn(event: Event<E>) {
|
||||
lock(); defer { unlock() }
|
||||
_synchronized_on(event)
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
//
|
||||
// SynchronizedSubscribeType.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 10/25/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol SynchronizedSubscribeType : class, ObservableType, Lock {
|
||||
func _synchronized_subscribe<O: ObserverType where O.E == E>(observer: O) -> Disposable
|
||||
}
|
||||
|
||||
extension SynchronizedSubscribeType {
|
||||
func synchronizedSubscribe<O: ObserverType where O.E == E>(observer: O) -> Disposable {
|
||||
lock(); defer { unlock() }
|
||||
return _synchronized_subscribe(observer)
|
||||
}
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
//
|
||||
// SynchronizedUnsubscribeType.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 10/25/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol SynchronizedUnsubscribeType : class {
|
||||
associatedtype DisposeKey
|
||||
|
||||
func synchronizedUnsubscribe(disposeKey: DisposeKey)
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
//
|
||||
// ConnectableObservableType.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 3/1/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Represents an observable sequence wrapper that can be connected and disconnected from its underlying observable sequence.
|
||||
*/
|
||||
public protocol ConnectableObservableType : ObservableType {
|
||||
/**
|
||||
Connects the observable wrapper to its source. All subscribed observers will receive values from the underlying observable sequence as long as the connection is established.
|
||||
|
||||
- returns: Disposable used to disconnect the observable wrapper from its source, causing subscribed observer to stop receiving values from the underlying observable sequence.
|
||||
*/
|
||||
func connect() -> Disposable
|
||||
}
|
328
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/Bag.swift
generated
Normal file
328
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/Bag.swift
generated
Normal file
@ -0,0 +1,328 @@
|
||||
//
|
||||
// Bag.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 2/28/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Swift
|
||||
|
||||
let arrayDictionaryMaxSize = 30
|
||||
|
||||
/**
|
||||
Class that enables using memory allocations as a means to uniquely identify objects.
|
||||
*/
|
||||
class Identity {
|
||||
// weird things have known to happen with Swift
|
||||
var _forceAllocation: Int32 = 0
|
||||
}
|
||||
|
||||
func hash(_x: Int) -> Int {
|
||||
var x = _x
|
||||
x = ((x >> 16) ^ x) &* 0x45d9f3b
|
||||
x = ((x >> 16) ^ x) &* 0x45d9f3b
|
||||
x = ((x >> 16) ^ x)
|
||||
return x;
|
||||
}
|
||||
|
||||
/**
|
||||
Unique identifier for object added to `Bag`.
|
||||
*/
|
||||
public struct BagKey : Hashable {
|
||||
let uniqueIdentity: Identity?
|
||||
let key: Int
|
||||
|
||||
public var hashValue: Int {
|
||||
if let uniqueIdentity = uniqueIdentity {
|
||||
return hash(key) ^ (unsafeAddressOf(uniqueIdentity).hashValue)
|
||||
}
|
||||
else {
|
||||
return hash(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Compares two `BagKey`s.
|
||||
*/
|
||||
public func == (lhs: BagKey, rhs: BagKey) -> Bool {
|
||||
return lhs.key == rhs.key && lhs.uniqueIdentity === rhs.uniqueIdentity
|
||||
}
|
||||
|
||||
/**
|
||||
Data structure that represents a bag of elements typed `T`.
|
||||
|
||||
Single element can be stored multiple times.
|
||||
|
||||
Time and space complexity of insertion an deletion is O(n).
|
||||
|
||||
It is suitable for storing small number of elements.
|
||||
*/
|
||||
public struct Bag<T> : CustomDebugStringConvertible {
|
||||
/**
|
||||
Type of identifier for inserted elements.
|
||||
*/
|
||||
public typealias KeyType = BagKey
|
||||
|
||||
private typealias ScopeUniqueTokenType = Int
|
||||
|
||||
typealias Entry = (key: BagKey, value: T)
|
||||
|
||||
private var _uniqueIdentity: Identity?
|
||||
private var _nextKey: ScopeUniqueTokenType = 0
|
||||
|
||||
// data
|
||||
|
||||
// first fill inline variables
|
||||
private var _key0: BagKey? = nil
|
||||
private var _value0: T? = nil
|
||||
|
||||
private var _key1: BagKey? = nil
|
||||
private var _value1: T? = nil
|
||||
|
||||
// then fill "array dictionary"
|
||||
private var _pairs = ContiguousArray<Entry>()
|
||||
|
||||
// last is sparse dictionary
|
||||
private var _dictionary: [BagKey : T]? = nil
|
||||
|
||||
private var _onlyFastPath = true
|
||||
|
||||
/**
|
||||
Creates new empty `Bag`.
|
||||
*/
|
||||
public init() {
|
||||
}
|
||||
|
||||
/**
|
||||
Inserts `value` into bag.
|
||||
|
||||
- parameter element: Element to insert.
|
||||
- returns: Key that can be used to remove element from bag.
|
||||
*/
|
||||
public mutating func insert(element: T) -> BagKey {
|
||||
_nextKey = _nextKey &+ 1
|
||||
|
||||
#if DEBUG
|
||||
_nextKey = _nextKey % 20
|
||||
#endif
|
||||
|
||||
if _nextKey == 0 {
|
||||
_uniqueIdentity = Identity()
|
||||
}
|
||||
|
||||
let key = BagKey(uniqueIdentity: _uniqueIdentity, key: _nextKey)
|
||||
|
||||
if _key0 == nil {
|
||||
_key0 = key
|
||||
_value0 = element
|
||||
return key
|
||||
}
|
||||
|
||||
_onlyFastPath = false
|
||||
|
||||
if _key1 == nil {
|
||||
_key1 = key
|
||||
_value1 = element
|
||||
return key
|
||||
}
|
||||
|
||||
if _dictionary != nil {
|
||||
_dictionary![key] = element
|
||||
return key
|
||||
}
|
||||
|
||||
if _pairs.count < arrayDictionaryMaxSize {
|
||||
_pairs.append(key: key, value: element)
|
||||
return key
|
||||
}
|
||||
|
||||
if _dictionary == nil {
|
||||
_dictionary = [:]
|
||||
}
|
||||
|
||||
_dictionary![key] = element
|
||||
|
||||
return key
|
||||
}
|
||||
|
||||
/**
|
||||
- returns: Number of elements in bag.
|
||||
*/
|
||||
public var count: Int {
|
||||
let dictionaryCount: Int = _dictionary?.count ?? 0
|
||||
return _pairs.count + (_value0 != nil ? 1 : 0) + (_value1 != nil ? 1 : 0) + dictionaryCount
|
||||
}
|
||||
|
||||
/**
|
||||
Removes all elements from bag and clears capacity.
|
||||
*/
|
||||
public mutating func removeAll() {
|
||||
_key0 = nil
|
||||
_value0 = nil
|
||||
_key1 = nil
|
||||
_value1 = nil
|
||||
|
||||
_pairs.removeAll(keepCapacity: false)
|
||||
_dictionary?.removeAll(keepCapacity: false)
|
||||
}
|
||||
|
||||
/**
|
||||
Removes element with a specific `key` from bag.
|
||||
|
||||
- parameter key: Key that identifies element to remove from bag.
|
||||
- returns: Element that bag contained, or nil in case element was already removed.
|
||||
*/
|
||||
public mutating func removeKey(key: BagKey) -> T? {
|
||||
if _key0 == key {
|
||||
_key0 = nil
|
||||
let value = _value0!
|
||||
_value0 = nil
|
||||
return value
|
||||
}
|
||||
|
||||
if _key1 == key {
|
||||
_key1 = nil
|
||||
let value = _value1!
|
||||
_value1 = nil
|
||||
return value
|
||||
}
|
||||
|
||||
if let existingObject = _dictionary?.removeValueForKey(key) {
|
||||
return existingObject
|
||||
}
|
||||
|
||||
for i in 0 ..< _pairs.count {
|
||||
if _pairs[i].key == key {
|
||||
let value = _pairs[i].value
|
||||
_pairs.removeAtIndex(i)
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
extension Bag {
|
||||
/**
|
||||
A textual representation of `self`, suitable for debugging.
|
||||
*/
|
||||
public var debugDescription : String {
|
||||
return "\(self.count) elements in Bag"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: forEach
|
||||
|
||||
extension Bag {
|
||||
/**
|
||||
Enumerates elements inside the bag.
|
||||
|
||||
- parameter action: Enumeration closure.
|
||||
*/
|
||||
public func forEach(@noescape action: (T) -> Void) {
|
||||
if _onlyFastPath {
|
||||
if let value0 = _value0 {
|
||||
action(value0)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
let pairs = _pairs
|
||||
let value0 = _value0
|
||||
let value1 = _value1
|
||||
let dictionary = _dictionary
|
||||
|
||||
if let value0 = value0 {
|
||||
action(value0)
|
||||
}
|
||||
|
||||
if let value1 = value1 {
|
||||
action(value1)
|
||||
}
|
||||
|
||||
for i in 0 ..< pairs.count {
|
||||
action(pairs[i].value)
|
||||
}
|
||||
|
||||
if dictionary?.count ?? 0 > 0 {
|
||||
for element in dictionary!.values {
|
||||
action(element)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Bag where T: ObserverType {
|
||||
/**
|
||||
Dispatches `event` to app observers contained inside bag.
|
||||
|
||||
- parameter action: Enumeration closure.
|
||||
*/
|
||||
public func on(event: Event<T.E>) {
|
||||
if _onlyFastPath {
|
||||
_value0?.on(event)
|
||||
return
|
||||
}
|
||||
|
||||
let pairs = _pairs
|
||||
let value0 = _value0
|
||||
let value1 = _value1
|
||||
let dictionary = _dictionary
|
||||
|
||||
if let value0 = value0 {
|
||||
value0.on(event)
|
||||
}
|
||||
|
||||
if let value1 = value1 {
|
||||
value1.on(event)
|
||||
}
|
||||
|
||||
for i in 0 ..< pairs.count {
|
||||
pairs[i].value.on(event)
|
||||
}
|
||||
|
||||
if dictionary?.count ?? 0 > 0 {
|
||||
for element in dictionary!.values {
|
||||
element.on(event)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Dispatches `dispose` to all disposables contained inside bag.
|
||||
*/
|
||||
public func disposeAllIn(bag: Bag<Disposable>) {
|
||||
if bag._onlyFastPath {
|
||||
bag._value0?.dispose()
|
||||
return
|
||||
}
|
||||
|
||||
let pairs = bag._pairs
|
||||
let value0 = bag._value0
|
||||
let value1 = bag._value1
|
||||
let dictionary = bag._dictionary
|
||||
|
||||
if let value0 = value0 {
|
||||
value0.dispose()
|
||||
}
|
||||
|
||||
if let value1 = value1 {
|
||||
value1.dispose()
|
||||
}
|
||||
|
||||
for i in 0 ..< pairs.count {
|
||||
pairs[i].value.dispose()
|
||||
}
|
||||
|
||||
if dictionary?.count ?? 0 > 0 {
|
||||
for element in dictionary!.values {
|
||||
element.dispose()
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
//
|
||||
// InfiniteSequence.swift
|
||||
// RxSwift
|
||||
//
|
||||
// Created by Krunoslav Zaher on 6/13/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Sequence that repeats `repeatedValue` infinite number of times.
|
||||
*/
|
||||
struct InfiniteSequence<E> : SequenceType {
|
||||
typealias Element = E
|
||||
typealias Generator = AnyGenerator<E>
|
||||
|
||||
private let _repeatedValue: E
|
||||
|
||||
init(repeatedValue: E) {
|
||||
_repeatedValue = repeatedValue
|
||||
}
|
||||
|
||||
func generate() -> Generator {
|
||||
let repeatedValue = _repeatedValue
|
||||
return AnyGenerator {
|
||||
return repeatedValue
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,120 @@
|
||||
//
|
||||
// PriorityQueue.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 12/27/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
struct PriorityQueue<Element: AnyObject> {
|
||||
private let _hasHigherPriority: (Element, Element) -> Bool
|
||||
private var _elements = [Element]()
|
||||
|
||||
init(hasHigherPriority: (Element, Element) -> Bool) {
|
||||
_hasHigherPriority = hasHigherPriority
|
||||
}
|
||||
|
||||
mutating func enqueue(element: Element) {
|
||||
_elements.append(element)
|
||||
bubbleToHigherPriority(_elements.count - 1)
|
||||
}
|
||||
|
||||
func peek() -> Element? {
|
||||
return _elements.first
|
||||
}
|
||||
|
||||
var isEmpty: Bool {
|
||||
return _elements.count == 0
|
||||
}
|
||||
|
||||
mutating func dequeue() -> Element? {
|
||||
guard let front = peek() else {
|
||||
return nil
|
||||
}
|
||||
|
||||
removeAt(0)
|
||||
|
||||
return front
|
||||
}
|
||||
|
||||
mutating func remove(element: Element) {
|
||||
for i in 0 ..< _elements.count {
|
||||
if _elements[i] === element {
|
||||
removeAt(i)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func removeAt(index: Int) {
|
||||
let removingLast = index == _elements.count - 1
|
||||
if !removingLast {
|
||||
swap(&_elements[index], &_elements[_elements.count - 1])
|
||||
}
|
||||
|
||||
_elements.popLast()
|
||||
|
||||
if !removingLast {
|
||||
bubbleToHigherPriority(index)
|
||||
bubbleToLowerPriority(index)
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func bubbleToHigherPriority(initialUnbalancedIndex: Int) {
|
||||
precondition(initialUnbalancedIndex >= 0)
|
||||
precondition(initialUnbalancedIndex < _elements.count)
|
||||
|
||||
var unbalancedIndex = initialUnbalancedIndex
|
||||
|
||||
while unbalancedIndex > 0 {
|
||||
let parentIndex = (unbalancedIndex - 1) / 2
|
||||
|
||||
if _hasHigherPriority(_elements[unbalancedIndex], _elements[parentIndex]) {
|
||||
swap(&_elements[unbalancedIndex], &_elements[parentIndex])
|
||||
|
||||
unbalancedIndex = parentIndex
|
||||
}
|
||||
else {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func bubbleToLowerPriority(initialUnbalancedIndex: Int) {
|
||||
precondition(initialUnbalancedIndex >= 0)
|
||||
precondition(initialUnbalancedIndex < _elements.count)
|
||||
|
||||
var unbalancedIndex = initialUnbalancedIndex
|
||||
repeat {
|
||||
let leftChildIndex = unbalancedIndex * 2 + 1
|
||||
let rightChildIndex = unbalancedIndex * 2 + 2
|
||||
|
||||
var highestPriorityIndex = unbalancedIndex
|
||||
|
||||
if leftChildIndex < _elements.count && _hasHigherPriority(_elements[leftChildIndex], _elements[highestPriorityIndex]) {
|
||||
highestPriorityIndex = leftChildIndex
|
||||
}
|
||||
|
||||
if rightChildIndex < _elements.count && _hasHigherPriority(_elements[rightChildIndex], _elements[highestPriorityIndex]) {
|
||||
highestPriorityIndex = rightChildIndex
|
||||
}
|
||||
|
||||
if highestPriorityIndex != unbalancedIndex {
|
||||
swap(&_elements[highestPriorityIndex], &_elements[unbalancedIndex])
|
||||
|
||||
unbalancedIndex = highestPriorityIndex
|
||||
}
|
||||
else {
|
||||
break
|
||||
}
|
||||
} while true
|
||||
}
|
||||
}
|
||||
|
||||
extension PriorityQueue : CustomDebugStringConvertible {
|
||||
var debugDescription: String {
|
||||
return _elements.debugDescription
|
||||
}
|
||||
}
|
168
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/Queue.swift
generated
Normal file
168
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/Queue.swift
generated
Normal file
@ -0,0 +1,168 @@
|
||||
//
|
||||
// Queue.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 3/21/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Data structure that represents queue.
|
||||
|
||||
Complexity of `enqueue`, `dequeue` is O(1) when number of operations is
|
||||
averaged over N operations.
|
||||
|
||||
Complexity of `peek` is O(1).
|
||||
*/
|
||||
public struct Queue<T>: SequenceType {
|
||||
/**
|
||||
Type of generator.
|
||||
*/
|
||||
public typealias Generator = AnyGenerator<T>
|
||||
|
||||
private let _resizeFactor = 2
|
||||
|
||||
private var _storage: ContiguousArray<T?>
|
||||
private var _count = 0
|
||||
private var _pushNextIndex = 0
|
||||
private var _initialCapacity: Int
|
||||
|
||||
/**
|
||||
Creates new queue.
|
||||
|
||||
- parameter capacity: Capacity of newly created queue.
|
||||
*/
|
||||
public init(capacity: Int) {
|
||||
_initialCapacity = capacity
|
||||
|
||||
_storage = ContiguousArray<T?>(count: capacity, repeatedValue: nil)
|
||||
}
|
||||
|
||||
private var dequeueIndex: Int {
|
||||
let index = _pushNextIndex - count
|
||||
return index < 0 ? index + _storage.count : index
|
||||
}
|
||||
|
||||
/**
|
||||
- returns: Is queue empty.
|
||||
*/
|
||||
public var isEmpty: Bool {
|
||||
return count == 0
|
||||
}
|
||||
|
||||
/**
|
||||
- returns: Number of elements inside queue.
|
||||
*/
|
||||
public var count: Int {
|
||||
return _count
|
||||
}
|
||||
|
||||
/**
|
||||
- returns: Element in front of a list of elements to `dequeue`.
|
||||
*/
|
||||
public func peek() -> T {
|
||||
precondition(count > 0)
|
||||
|
||||
return _storage[dequeueIndex]!
|
||||
}
|
||||
|
||||
mutating private func resizeTo(size: Int) {
|
||||
var newStorage = ContiguousArray<T?>(count: size, repeatedValue: nil)
|
||||
|
||||
let count = _count
|
||||
|
||||
let dequeueIndex = self.dequeueIndex
|
||||
let spaceToEndOfQueue = _storage.count - dequeueIndex
|
||||
|
||||
// first batch is from dequeue index to end of array
|
||||
let countElementsInFirstBatch = min(count, spaceToEndOfQueue)
|
||||
// second batch is wrapped from start of array to end of queue
|
||||
let numberOfElementsInSecondBatch = count - countElementsInFirstBatch
|
||||
|
||||
newStorage[0 ..< countElementsInFirstBatch] = _storage[dequeueIndex ..< (dequeueIndex + countElementsInFirstBatch)]
|
||||
newStorage[countElementsInFirstBatch ..< (countElementsInFirstBatch + numberOfElementsInSecondBatch)] = _storage[0 ..< numberOfElementsInSecondBatch]
|
||||
|
||||
_count = count
|
||||
_pushNextIndex = count
|
||||
_storage = newStorage
|
||||
}
|
||||
|
||||
/**
|
||||
Enqueues `element`.
|
||||
|
||||
- parameter element: Element to enqueue.
|
||||
*/
|
||||
public mutating func enqueue(element: T) {
|
||||
if count == _storage.count {
|
||||
resizeTo(max(_storage.count, 1) * _resizeFactor)
|
||||
}
|
||||
|
||||
_storage[_pushNextIndex] = element
|
||||
_pushNextIndex += 1
|
||||
_count += 1
|
||||
|
||||
if _pushNextIndex >= _storage.count {
|
||||
_pushNextIndex -= _storage.count
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func dequeueElementOnly() -> T {
|
||||
precondition(count > 0)
|
||||
|
||||
let index = dequeueIndex
|
||||
|
||||
defer {
|
||||
_storage[index] = nil
|
||||
_count -= 1
|
||||
}
|
||||
|
||||
return _storage[index]!
|
||||
}
|
||||
|
||||
/**
|
||||
Dequeues element or throws an exception in case queue is empty.
|
||||
|
||||
- returns: Dequeued element.
|
||||
*/
|
||||
public mutating func dequeue() -> T? {
|
||||
if self.count == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
defer {
|
||||
let downsizeLimit = _storage.count / (_resizeFactor * _resizeFactor)
|
||||
if _count < downsizeLimit && downsizeLimit >= _initialCapacity {
|
||||
resizeTo(_storage.count / _resizeFactor)
|
||||
}
|
||||
}
|
||||
|
||||
return dequeueElementOnly()
|
||||
}
|
||||
|
||||
/**
|
||||
- returns: Generator of contained elements.
|
||||
*/
|
||||
public func generate() -> Generator {
|
||||
var i = dequeueIndex
|
||||
var count = _count
|
||||
|
||||
return AnyGenerator {
|
||||
if count == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
defer {
|
||||
count -= 1
|
||||
i += 1
|
||||
}
|
||||
|
||||
if i >= self._storage.count {
|
||||
i -= self._storage.count
|
||||
}
|
||||
|
||||
return self._storage[i]
|
||||
}
|
||||
}
|
||||
}
|
15
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposable.swift
generated
Normal file
15
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposable.swift
generated
Normal file
@ -0,0 +1,15 @@
|
||||
//
|
||||
// Disposable.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 2/8/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Respresents a disposable resource.
|
||||
public protocol Disposable {
|
||||
/// Dispose resource.
|
||||
func dispose()
|
||||
}
|
@ -0,0 +1,54 @@
|
||||
//
|
||||
// AnonymousDisposable.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 2/15/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Represents an Action-based disposable.
|
||||
|
||||
When dispose method is called, disposal action will be dereferenced.
|
||||
*/
|
||||
public final class AnonymousDisposable : DisposeBase, Cancelable {
|
||||
public typealias DisposeAction = () -> Void
|
||||
|
||||
private var _disposed: AtomicInt = 0
|
||||
private var _disposeAction: DisposeAction?
|
||||
|
||||
/**
|
||||
- returns: Was resource disposed.
|
||||
*/
|
||||
public var disposed: Bool {
|
||||
return _disposed == 1
|
||||
}
|
||||
|
||||
/**
|
||||
Constructs a new disposable with the given action used for disposal.
|
||||
|
||||
- parameter disposeAction: Disposal action which will be run upon calling `dispose`.
|
||||
*/
|
||||
public init(_ disposeAction: DisposeAction) {
|
||||
_disposeAction = disposeAction
|
||||
super.init()
|
||||
}
|
||||
|
||||
/**
|
||||
Calls the disposal action if and only if the current instance hasn't been disposed yet.
|
||||
|
||||
After invoking disposal action, disposal action will be dereferenced.
|
||||
*/
|
||||
public func dispose() {
|
||||
if AtomicCompareAndSwap(0, 1, &_disposed) {
|
||||
assert(_disposed == 1)
|
||||
|
||||
if let action = _disposeAction {
|
||||
_disposeAction = nil
|
||||
action()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,54 @@
|
||||
//
|
||||
// BinaryDisposable.swift
|
||||
// RxSwift
|
||||
//
|
||||
// Created by Krunoslav Zaher on 6/12/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Represents two disposable resources that are disposed together.
|
||||
*/
|
||||
public final class BinaryDisposable : DisposeBase, Cancelable {
|
||||
|
||||
private var _disposed: AtomicInt = 0
|
||||
|
||||
// state
|
||||
private var _disposable1: Disposable?
|
||||
private var _disposable2: Disposable?
|
||||
|
||||
/**
|
||||
- returns: Was resource disposed.
|
||||
*/
|
||||
public var disposed: Bool {
|
||||
return _disposed > 0
|
||||
}
|
||||
|
||||
/**
|
||||
Constructs new binary disposable from two disposables.
|
||||
|
||||
- parameter disposable1: First disposable
|
||||
- parameter disposable2: Second disposable
|
||||
*/
|
||||
init(_ disposable1: Disposable, _ disposable2: Disposable) {
|
||||
_disposable1 = disposable1
|
||||
_disposable2 = disposable2
|
||||
super.init()
|
||||
}
|
||||
|
||||
/**
|
||||
Calls the disposal action if and only if the current instance hasn't been disposed yet.
|
||||
|
||||
After invoking disposal action, disposal action will be dereferenced.
|
||||
*/
|
||||
public func dispose() {
|
||||
if AtomicCompareAndSwap(0, 1, &_disposed) {
|
||||
_disposable1?.dispose()
|
||||
_disposable2?.dispose()
|
||||
_disposable1 = nil
|
||||
_disposable2 = nil
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,45 @@
|
||||
//
|
||||
// BooleanDisposable.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Junior B. on 10/29/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Represents a disposable resource that can be checked for disposal status.
|
||||
*/
|
||||
public class BooleanDisposable : Disposable, Cancelable {
|
||||
|
||||
internal static let BooleanDisposableTrue = BooleanDisposable(disposed: true)
|
||||
private var _disposed = false
|
||||
|
||||
/**
|
||||
Initializes a new instance of the `BooleanDisposable` class
|
||||
*/
|
||||
public init() {
|
||||
}
|
||||
|
||||
/**
|
||||
Initializes a new instance of the `BooleanDisposable` class with given value
|
||||
*/
|
||||
public init(disposed: Bool) {
|
||||
self._disposed = disposed
|
||||
}
|
||||
|
||||
/**
|
||||
- returns: Was resource disposed.
|
||||
*/
|
||||
public var disposed: Bool {
|
||||
return _disposed
|
||||
}
|
||||
|
||||
/**
|
||||
Sets the status to disposed, which can be observer through the `disposed` property.
|
||||
*/
|
||||
public func dispose() {
|
||||
_disposed = true
|
||||
}
|
||||
}
|
@ -0,0 +1,135 @@
|
||||
//
|
||||
// CompositeDisposable.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 2/20/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Represents a group of disposable resources that are disposed together.
|
||||
*/
|
||||
public class CompositeDisposable : DisposeBase, Disposable, Cancelable {
|
||||
public typealias DisposeKey = Bag<Disposable>.KeyType
|
||||
|
||||
private var _lock = SpinLock()
|
||||
|
||||
// state
|
||||
private var _disposables: Bag<Disposable>? = Bag()
|
||||
|
||||
public var disposed: Bool {
|
||||
_lock.lock(); defer { _lock.unlock() }
|
||||
return _disposables == nil
|
||||
}
|
||||
|
||||
public override init() {
|
||||
}
|
||||
|
||||
/**
|
||||
Initializes a new instance of composite disposable with the specified number of disposables.
|
||||
*/
|
||||
public init(_ disposable1: Disposable, _ disposable2: Disposable) {
|
||||
// This overload is here to make sure we are using optimized version up to 4 arguments.
|
||||
_disposables!.insert(disposable1)
|
||||
_disposables!.insert(disposable2)
|
||||
}
|
||||
|
||||
/**
|
||||
Initializes a new instance of composite disposable with the specified number of disposables.
|
||||
*/
|
||||
public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable) {
|
||||
// This overload is here to make sure we are using optimized version up to 4 arguments.
|
||||
_disposables!.insert(disposable1)
|
||||
_disposables!.insert(disposable2)
|
||||
_disposables!.insert(disposable3)
|
||||
}
|
||||
|
||||
/**
|
||||
Initializes a new instance of composite disposable with the specified number of disposables.
|
||||
*/
|
||||
public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable, _ disposable4: Disposable, _ disposables: Disposable...) {
|
||||
// This overload is here to make sure we are using optimized version up to 4 arguments.
|
||||
_disposables!.insert(disposable1)
|
||||
_disposables!.insert(disposable2)
|
||||
_disposables!.insert(disposable3)
|
||||
_disposables!.insert(disposable4)
|
||||
|
||||
for disposable in disposables {
|
||||
_disposables!.insert(disposable)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Initializes a new instance of composite disposable with the specified number of disposables.
|
||||
*/
|
||||
public init(disposables: [Disposable]) {
|
||||
for disposable in disposables {
|
||||
_disposables!.insert(disposable)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
|
||||
|
||||
- parameter disposable: Disposable to add.
|
||||
- returns: Key that can be used to remove disposable from composite disposable. In case dispose bag was already
|
||||
disposed `nil` will be returned.
|
||||
*/
|
||||
public func addDisposable(disposable: Disposable) -> DisposeKey? {
|
||||
let key = _addDisposable(disposable)
|
||||
|
||||
if key == nil {
|
||||
disposable.dispose()
|
||||
}
|
||||
|
||||
return key
|
||||
}
|
||||
|
||||
private func _addDisposable(disposable: Disposable) -> DisposeKey? {
|
||||
_lock.lock(); defer { _lock.unlock() }
|
||||
|
||||
return _disposables?.insert(disposable)
|
||||
}
|
||||
|
||||
/**
|
||||
- returns: Gets the number of disposables contained in the `CompositeDisposable`.
|
||||
*/
|
||||
public var count: Int {
|
||||
_lock.lock(); defer { _lock.unlock() }
|
||||
return _disposables?.count ?? 0
|
||||
}
|
||||
|
||||
/**
|
||||
Removes and disposes the disposable identified by `disposeKey` from the CompositeDisposable.
|
||||
|
||||
- parameter disposeKey: Key used to identify disposable to be removed.
|
||||
*/
|
||||
public func removeDisposable(disposeKey: DisposeKey) {
|
||||
_removeDisposable(disposeKey)?.dispose()
|
||||
}
|
||||
|
||||
private func _removeDisposable(disposeKey: DisposeKey) -> Disposable? {
|
||||
_lock.lock(); defer { _lock.unlock() }
|
||||
return _disposables?.removeKey(disposeKey)
|
||||
}
|
||||
|
||||
/**
|
||||
Disposes all disposables in the group and removes them from the group.
|
||||
*/
|
||||
public func dispose() {
|
||||
if let disposables = _dispose() {
|
||||
disposeAllIn(disposables)
|
||||
}
|
||||
}
|
||||
|
||||
private func _dispose() -> Bag<Disposable>? {
|
||||
_lock.lock(); defer { _lock.unlock() }
|
||||
|
||||
let disposeBag = _disposables
|
||||
_disposables = nil
|
||||
|
||||
return disposeBag
|
||||
}
|
||||
}
|
@ -0,0 +1,94 @@
|
||||
//
|
||||
// DisposeBag.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 3/25/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
extension Disposable {
|
||||
/**
|
||||
Adds `self` to `bag`.
|
||||
|
||||
- parameter bag: `DisposeBag` to add `self` to.
|
||||
*/
|
||||
public func addDisposableTo(bag: DisposeBag) {
|
||||
bag.addDisposable(self)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Thread safe bag that disposes added disposables on `deinit`.
|
||||
|
||||
This returns ARC (RAII) like resource management to `RxSwift`.
|
||||
|
||||
In case contained disposables need to be disposed, just put a different dispose bag
|
||||
or create a new one in its place.
|
||||
|
||||
self.existingDisposeBag = DisposeBag()
|
||||
|
||||
In case explicit disposal is necessary, there is also `CompositeDisposable`.
|
||||
*/
|
||||
public class DisposeBag: DisposeBase {
|
||||
|
||||
private var _lock = SpinLock()
|
||||
|
||||
// state
|
||||
private var _disposables = [Disposable]()
|
||||
private var _disposed = false
|
||||
|
||||
/**
|
||||
Constructs new empty dispose bag.
|
||||
*/
|
||||
public override init() {
|
||||
super.init()
|
||||
}
|
||||
|
||||
/**
|
||||
Adds `disposable` to be disposed when dispose bag is being deinited.
|
||||
|
||||
- parameter disposable: Disposable to add.
|
||||
*/
|
||||
public func addDisposable(disposable: Disposable) {
|
||||
_addDisposable(disposable)?.dispose()
|
||||
}
|
||||
|
||||
private func _addDisposable(disposable: Disposable) -> Disposable? {
|
||||
_lock.lock(); defer { _lock.unlock() }
|
||||
if _disposed {
|
||||
return disposable
|
||||
}
|
||||
|
||||
_disposables.append(disposable)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
/**
|
||||
This is internal on purpose, take a look at `CompositeDisposable` instead.
|
||||
*/
|
||||
private func dispose() {
|
||||
let oldDisposables = _dispose()
|
||||
|
||||
for disposable in oldDisposables {
|
||||
disposable.dispose()
|
||||
}
|
||||
}
|
||||
|
||||
private func _dispose() -> [Disposable] {
|
||||
_lock.lock(); defer { _lock.unlock() }
|
||||
|
||||
let disposables = _disposables
|
||||
|
||||
_disposables.removeAll(keepCapacity: false)
|
||||
_disposed = true
|
||||
|
||||
return disposables
|
||||
}
|
||||
|
||||
deinit {
|
||||
dispose()
|
||||
}
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
//
|
||||
// DisposeBase.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 4/4/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Base class for all disposables.
|
||||
*/
|
||||
public class DisposeBase {
|
||||
init() {
|
||||
#if TRACE_RESOURCES
|
||||
AtomicIncrement(&resourceCount)
|
||||
#endif
|
||||
}
|
||||
|
||||
deinit {
|
||||
#if TRACE_RESOURCES
|
||||
AtomicDecrement(&resourceCount)
|
||||
#endif
|
||||
}
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
// This file is autogenerated. Take a look at `Preprocessor` target in RxSwift project
|
||||
//
|
||||
// NAryDisposable.swift
|
||||
// RxSwift
|
||||
//
|
||||
// Created by Krunoslav Zaher on 8/20/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
@ -0,0 +1,32 @@
|
||||
//
|
||||
// NopDisposable.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 2/15/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Represents a disposable that does nothing on disposal.
|
||||
|
||||
Nop = No Operation
|
||||
*/
|
||||
public struct NopDisposable : Disposable {
|
||||
|
||||
/**
|
||||
Singleton instance of `NopDisposable`.
|
||||
*/
|
||||
public static let instance: Disposable = NopDisposable()
|
||||
|
||||
init() {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
Does nothing.
|
||||
*/
|
||||
public func dispose() {
|
||||
}
|
||||
}
|
@ -0,0 +1,127 @@
|
||||
//
|
||||
// RefCountDisposable.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Junior B. on 10/29/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
|
||||
*/
|
||||
public class RefCountDisposable : DisposeBase, Cancelable {
|
||||
private var _lock = SpinLock()
|
||||
private var _disposable = nil as Disposable?
|
||||
private var _primaryDisposed = false
|
||||
private var _count = 0
|
||||
|
||||
/**
|
||||
- returns: Was resource disposed.
|
||||
*/
|
||||
public var disposed: Bool {
|
||||
_lock.lock(); defer { _lock.unlock() }
|
||||
return _disposable == nil
|
||||
}
|
||||
|
||||
/**
|
||||
Initializes a new instance of the `RefCountDisposable`.
|
||||
*/
|
||||
public init(disposable: Disposable) {
|
||||
_disposable = disposable
|
||||
super.init()
|
||||
}
|
||||
|
||||
/**
|
||||
Holds a dependent disposable that when disposed decreases the refcount on the underlying disposable.
|
||||
|
||||
When getter is called, a dependent disposable contributing to the reference count that manages the underlying disposable's lifetime is returned.
|
||||
*/
|
||||
public func retain() -> Disposable {
|
||||
return _lock.calculateLocked {
|
||||
if let _ = _disposable {
|
||||
|
||||
do {
|
||||
try incrementChecked(&_count)
|
||||
} catch (_) {
|
||||
rxFatalError("RefCountDisposable increment failed")
|
||||
}
|
||||
|
||||
return RefCountInnerDisposable(self)
|
||||
} else {
|
||||
return NopDisposable.instance
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Disposes the underlying disposable only when all dependent disposables have been disposed.
|
||||
*/
|
||||
public func dispose() {
|
||||
let oldDisposable: Disposable? = _lock.calculateLocked {
|
||||
if let oldDisposable = _disposable where !_primaryDisposed
|
||||
{
|
||||
_primaryDisposed = true
|
||||
|
||||
if (_count == 0)
|
||||
{
|
||||
_disposable = nil
|
||||
return oldDisposable
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
if let disposable = oldDisposable {
|
||||
disposable.dispose()
|
||||
}
|
||||
}
|
||||
|
||||
private func release() {
|
||||
let oldDisposable: Disposable? = _lock.calculateLocked {
|
||||
if let oldDisposable = _disposable {
|
||||
do {
|
||||
try decrementChecked(&_count)
|
||||
} catch (_) {
|
||||
rxFatalError("RefCountDisposable decrement on release failed")
|
||||
}
|
||||
|
||||
guard _count >= 0 else {
|
||||
rxFatalError("RefCountDisposable counter is lower than 0")
|
||||
}
|
||||
|
||||
if _primaryDisposed && _count == 0 {
|
||||
_disposable = nil
|
||||
return oldDisposable
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
if let disposable = oldDisposable {
|
||||
disposable.dispose()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal final class RefCountInnerDisposable: DisposeBase, Disposable
|
||||
{
|
||||
private let _parent: RefCountDisposable
|
||||
private var _disposed: AtomicInt = 0
|
||||
|
||||
init(_ parent: RefCountDisposable)
|
||||
{
|
||||
_parent = parent
|
||||
super.init()
|
||||
}
|
||||
|
||||
internal func dispose()
|
||||
{
|
||||
if AtomicCompareAndSwap(0, 1, &_disposed) {
|
||||
_parent.release()
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,58 @@
|
||||
//
|
||||
// ScheduledDisposable.swift
|
||||
// RxSwift
|
||||
//
|
||||
// Created by Krunoslav Zaher on 6/13/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
private let disposeScheduledDisposable: ScheduledDisposable -> Disposable = { sd in
|
||||
sd.disposeInner()
|
||||
return NopDisposable.instance
|
||||
}
|
||||
|
||||
/**
|
||||
Represents a disposable resource whose disposal invocation will be scheduled on the specified scheduler.
|
||||
*/
|
||||
public class ScheduledDisposable : Cancelable {
|
||||
public let scheduler: ImmediateSchedulerType
|
||||
|
||||
private var _disposed: AtomicInt = 0
|
||||
|
||||
// state
|
||||
private var _disposable: Disposable?
|
||||
|
||||
/**
|
||||
- returns: Was resource disposed.
|
||||
*/
|
||||
public var disposed: Bool {
|
||||
return _disposed == 1
|
||||
}
|
||||
|
||||
/**
|
||||
Initializes a new instance of the `ScheduledDisposable` that uses a `scheduler` on which to dispose the `disposable`.
|
||||
|
||||
- parameter scheduler: Scheduler where the disposable resource will be disposed on.
|
||||
- parameter disposable: Disposable resource to dispose on the given scheduler.
|
||||
*/
|
||||
public init(scheduler: ImmediateSchedulerType, disposable: Disposable) {
|
||||
self.scheduler = scheduler
|
||||
_disposable = disposable
|
||||
}
|
||||
|
||||
/**
|
||||
Disposes the wrapped disposable on the provided scheduler.
|
||||
*/
|
||||
public func dispose() {
|
||||
scheduler.schedule(self, action: disposeScheduledDisposable)
|
||||
}
|
||||
|
||||
func disposeInner() {
|
||||
if AtomicCompareAndSwap(0, 1, &_disposed) {
|
||||
_disposable!.dispose()
|
||||
_disposable = nil
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,85 @@
|
||||
//
|
||||
// SerialDisposable.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 3/12/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource.
|
||||
*/
|
||||
public class SerialDisposable : DisposeBase, Cancelable {
|
||||
private var _lock = SpinLock()
|
||||
|
||||
// state
|
||||
private var _current = nil as Disposable?
|
||||
private var _disposed = false
|
||||
|
||||
/**
|
||||
- returns: Was resource disposed.
|
||||
*/
|
||||
public var disposed: Bool {
|
||||
return _disposed
|
||||
}
|
||||
|
||||
/**
|
||||
Initializes a new instance of the `SerialDisposable`.
|
||||
*/
|
||||
override public init() {
|
||||
super.init()
|
||||
}
|
||||
|
||||
/**
|
||||
Gets or sets the underlying disposable.
|
||||
|
||||
Assigning this property disposes the previous disposable object.
|
||||
|
||||
If the `SerialDisposable` has already been disposed, assignment to this property causes immediate disposal of the given disposable object.
|
||||
*/
|
||||
public var disposable: Disposable {
|
||||
get {
|
||||
return _lock.calculateLocked {
|
||||
return self.disposable
|
||||
}
|
||||
}
|
||||
set (newDisposable) {
|
||||
let disposable: Disposable? = _lock.calculateLocked {
|
||||
if _disposed {
|
||||
return newDisposable
|
||||
}
|
||||
else {
|
||||
let toDispose = _current
|
||||
_current = newDisposable
|
||||
return toDispose
|
||||
}
|
||||
}
|
||||
|
||||
if let disposable = disposable {
|
||||
disposable.dispose()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Disposes the underlying disposable as well as all future replacements.
|
||||
*/
|
||||
public func dispose() {
|
||||
_dispose()?.dispose()
|
||||
}
|
||||
|
||||
private func _dispose() -> Disposable? {
|
||||
_lock.lock(); defer { _lock.unlock() }
|
||||
if _disposed {
|
||||
return nil
|
||||
}
|
||||
else {
|
||||
_disposed = true
|
||||
let current = _current
|
||||
_current = nil
|
||||
return current
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,89 @@
|
||||
//
|
||||
// SingleAssignmentDisposable.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 2/15/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Represents a disposable resource which only allows a single assignment of its underlying disposable resource.
|
||||
|
||||
If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an exception.
|
||||
*/
|
||||
public class SingleAssignmentDisposable : DisposeBase, Disposable, Cancelable {
|
||||
private var _lock = SpinLock()
|
||||
|
||||
// state
|
||||
private var _disposed = false
|
||||
private var _disposableSet = false
|
||||
private var _disposable = nil as Disposable?
|
||||
|
||||
/**
|
||||
- returns: A value that indicates whether the object is disposed.
|
||||
*/
|
||||
public var disposed: Bool {
|
||||
return _disposed
|
||||
}
|
||||
|
||||
/**
|
||||
Initializes a new instance of the `SingleAssignmentDisposable`.
|
||||
*/
|
||||
public override init() {
|
||||
super.init()
|
||||
}
|
||||
|
||||
/**
|
||||
Gets or sets the underlying disposable. After disposal, the result of getting this property is undefined.
|
||||
|
||||
**Throws exception if the `SingleAssignmentDisposable` has already been assigned to.**
|
||||
*/
|
||||
public var disposable: Disposable {
|
||||
get {
|
||||
_lock.lock(); defer { _lock.unlock() }
|
||||
return _disposable ?? NopDisposable.instance
|
||||
}
|
||||
set {
|
||||
_setDisposable(newValue)?.dispose()
|
||||
}
|
||||
}
|
||||
|
||||
private func _setDisposable(newValue: Disposable) -> Disposable? {
|
||||
_lock.lock(); defer { _lock.unlock() }
|
||||
if _disposableSet {
|
||||
rxFatalError("oldState.disposable != nil")
|
||||
}
|
||||
|
||||
_disposableSet = true
|
||||
|
||||
if _disposed {
|
||||
return newValue
|
||||
}
|
||||
|
||||
_disposable = newValue
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
/**
|
||||
Disposes the underlying disposable.
|
||||
*/
|
||||
public func dispose() {
|
||||
if _disposed {
|
||||
return
|
||||
}
|
||||
_dispose()?.dispose()
|
||||
}
|
||||
|
||||
private func _dispose() -> Disposable? {
|
||||
_lock.lock(); defer { _lock.unlock() }
|
||||
|
||||
_disposed = true
|
||||
let disposable = _disposable
|
||||
_disposable = nil
|
||||
|
||||
return disposable
|
||||
}
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
//
|
||||
// StableCompositeDisposable.swift
|
||||
// RxSwift
|
||||
//
|
||||
// Created by Krunoslav Zaher on 6/12/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
public final class StableCompositeDisposable {
|
||||
public static func create(disposable1: Disposable, _ disposable2: Disposable) -> Disposable {
|
||||
return BinaryDisposable(disposable1, disposable2)
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
//
|
||||
// SubscriptionDisposable.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 10/25/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
struct SubscriptionDisposable<T: SynchronizedUnsubscribeType> : Disposable {
|
||||
private let _key: T.DisposeKey
|
||||
private weak var _owner: T?
|
||||
|
||||
init(owner: T, key: T.DisposeKey) {
|
||||
_owner = owner
|
||||
_key = key
|
||||
}
|
||||
|
||||
func dispose() {
|
||||
_owner?.synchronizedUnsubscribe(_key)
|
||||
}
|
||||
}
|
72
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Errors.swift
generated
Normal file
72
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Errors.swift
generated
Normal file
@ -0,0 +1,72 @@
|
||||
//
|
||||
// Errors.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 3/28/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
let RxErrorDomain = "RxErrorDomain"
|
||||
let RxCompositeFailures = "RxCompositeFailures"
|
||||
|
||||
/**
|
||||
Generic Rx error codes.
|
||||
*/
|
||||
public enum RxError
|
||||
: ErrorType
|
||||
, CustomDebugStringConvertible {
|
||||
/**
|
||||
Unknown error occured.
|
||||
*/
|
||||
case Unknown
|
||||
/**
|
||||
Performing an action on disposed object.
|
||||
*/
|
||||
case Disposed(object: AnyObject)
|
||||
/**
|
||||
Aritmetic overflow error.
|
||||
*/
|
||||
case Overflow
|
||||
/**
|
||||
Argument out of range error.
|
||||
*/
|
||||
case ArgumentOutOfRange
|
||||
/**
|
||||
Sequence doesn't contain any elements.
|
||||
*/
|
||||
case NoElements
|
||||
/**
|
||||
Sequence contains more than one element.
|
||||
*/
|
||||
case MoreThanOneElement
|
||||
/**
|
||||
Timeout error.
|
||||
*/
|
||||
case Timeout
|
||||
}
|
||||
|
||||
public extension RxError {
|
||||
/**
|
||||
A textual representation of `self`, suitable for debugging.
|
||||
*/
|
||||
public var debugDescription: String {
|
||||
switch self {
|
||||
case .Unknown:
|
||||
return "Unknown error occured."
|
||||
case .Disposed(let object):
|
||||
return "Object `\(object)` was already disposed."
|
||||
case .Overflow:
|
||||
return "Arithmetic overflow occured."
|
||||
case .ArgumentOutOfRange:
|
||||
return "Argument out of range."
|
||||
case .NoElements:
|
||||
return "Sequence doesn't contain any elements."
|
||||
case .MoreThanOneElement:
|
||||
return "Sequence contains more than one element."
|
||||
case .Timeout:
|
||||
return "Sequence timeout."
|
||||
}
|
||||
}
|
||||
}
|
66
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Event.swift
generated
Normal file
66
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Event.swift
generated
Normal file
@ -0,0 +1,66 @@
|
||||
//
|
||||
// Event.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 2/8/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Represents a sequence event.
|
||||
|
||||
Sequence grammar:
|
||||
Next\* (Error | Completed)
|
||||
*/
|
||||
public enum Event<Element> {
|
||||
/// Next element is produced.
|
||||
case Next(Element)
|
||||
|
||||
/// Sequence terminated with an error.
|
||||
case Error(ErrorType)
|
||||
|
||||
/// Sequence completed successfully.
|
||||
case Completed
|
||||
}
|
||||
|
||||
extension Event : CustomDebugStringConvertible {
|
||||
/// - returns: Description of event.
|
||||
public var debugDescription: String {
|
||||
switch self {
|
||||
case .Next(let value):
|
||||
return "Next(\(value))"
|
||||
case .Error(let error):
|
||||
return "Error(\(error))"
|
||||
case .Completed:
|
||||
return "Completed"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Event {
|
||||
/// - returns: Is `Completed` or `Error` event.
|
||||
public var isStopEvent: Bool {
|
||||
switch self {
|
||||
case .Next: return false
|
||||
case .Error, .Completed: return true
|
||||
}
|
||||
}
|
||||
|
||||
/// - returns: If `Next` event, returns element value.
|
||||
public var element: Element? {
|
||||
if case .Next(let value) = self {
|
||||
return value
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/// - returns: If `Error` event, returns error.
|
||||
public var error: ErrorType? {
|
||||
if case .Error(let error) = self {
|
||||
return error
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
//
|
||||
// String+Rx.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 12/25/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
extension String {
|
||||
/**
|
||||
This is needed because on Linux Swift doesn't have `rangeOfString(..., options: .BackwardsSearch)`
|
||||
*/
|
||||
func lastIndexOf(character: Character) -> Index? {
|
||||
var index = endIndex
|
||||
while index > startIndex {
|
||||
index = index.predecessor()
|
||||
if self[index] == character {
|
||||
return index
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
//
|
||||
// ImmediateSchedulerType.swift
|
||||
// RxSwift
|
||||
//
|
||||
// Created by Krunoslav Zaher on 5/31/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Represents an object that immediately schedules units of work.
|
||||
*/
|
||||
public protocol ImmediateSchedulerType {
|
||||
/**
|
||||
Schedules an action to be executed immediatelly.
|
||||
|
||||
- parameter state: State passed to the action to be executed.
|
||||
- parameter action: Action to be executed.
|
||||
- returns: The disposable object used to cancel the scheduled action (best effort).
|
||||
*/
|
||||
func schedule<StateType>(state: StateType, action: (StateType) -> Disposable) -> Disposable
|
||||
}
|
||||
|
||||
extension ImmediateSchedulerType {
|
||||
/**
|
||||
Schedules an action to be executed recursively.
|
||||
|
||||
- parameter state: State passed to the action to be executed.
|
||||
- parameter action: Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
|
||||
- returns: The disposable object used to cancel the scheduled action (best effort).
|
||||
*/
|
||||
public func scheduleRecursive<State>(state: State, action: (state: State, recurse: (State) -> ()) -> ()) -> Disposable {
|
||||
let recursiveScheduler = RecursiveImmediateScheduler(action: action, scheduler: self)
|
||||
|
||||
recursiveScheduler.schedule(state)
|
||||
|
||||
return AnonymousDisposable(recursiveScheduler.dispose)
|
||||
}
|
||||
}
|
@ -0,0 +1,128 @@
|
||||
//
|
||||
// Observable+Extensions.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 2/21/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
extension ObservableType {
|
||||
/**
|
||||
Subscribes an event handler to an observable sequence.
|
||||
|
||||
- parameter on: Action to invoke for each event in the observable sequence.
|
||||
- returns: Subscription object used to unsubscribe from the observable sequence.
|
||||
*/
|
||||
@warn_unused_result(message="http://git.io/rxs.ud")
|
||||
public func subscribe(on: (event: Event<E>) -> Void)
|
||||
-> Disposable {
|
||||
let observer = AnonymousObserver { e in
|
||||
on(event: e)
|
||||
}
|
||||
return self.subscribeSafe(observer)
|
||||
}
|
||||
|
||||
/**
|
||||
Subscribes an element handler, an error handler, a completion handler and disposed handler to an observable sequence.
|
||||
|
||||
- parameter onNext: Action to invoke for each element in the observable sequence.
|
||||
- parameter onError: Action to invoke upon errored termination of the observable sequence.
|
||||
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
|
||||
- parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has
|
||||
gracefully completed, errored, or if the generation is cancelled by disposing subscription).
|
||||
- returns: Subscription object used to unsubscribe from the observable sequence.
|
||||
*/
|
||||
@warn_unused_result(message="http://git.io/rxs.ud")
|
||||
public func subscribe(onNext onNext: (E -> Void)? = nil, onError: (ErrorType -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil)
|
||||
-> Disposable {
|
||||
|
||||
let disposable: Disposable
|
||||
|
||||
if let disposed = onDisposed {
|
||||
disposable = AnonymousDisposable(disposed)
|
||||
}
|
||||
else {
|
||||
disposable = NopDisposable.instance
|
||||
}
|
||||
|
||||
let observer = AnonymousObserver<E> { e in
|
||||
switch e {
|
||||
case .Next(let value):
|
||||
onNext?(value)
|
||||
case .Error(let e):
|
||||
onError?(e)
|
||||
disposable.dispose()
|
||||
case .Completed:
|
||||
onCompleted?()
|
||||
disposable.dispose()
|
||||
}
|
||||
}
|
||||
return BinaryDisposable(
|
||||
self.subscribeSafe(observer),
|
||||
disposable
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
Subscribes an element handler to an observable sequence.
|
||||
|
||||
- parameter onNext: Action to invoke for each element in the observable sequence.
|
||||
- returns: Subscription object used to unsubscribe from the observable sequence.
|
||||
*/
|
||||
@warn_unused_result(message="http://git.io/rxs.ud")
|
||||
public func subscribeNext(onNext: (E) -> Void)
|
||||
-> Disposable {
|
||||
let observer = AnonymousObserver<E> { e in
|
||||
if case .Next(let value) = e {
|
||||
onNext(value)
|
||||
}
|
||||
}
|
||||
return self.subscribeSafe(observer)
|
||||
}
|
||||
|
||||
/**
|
||||
Subscribes an error handler to an observable sequence.
|
||||
|
||||
- parameter onError: Action to invoke upon errored termination of the observable sequence.
|
||||
- returns: Subscription object used to unsubscribe from the observable sequence.
|
||||
*/
|
||||
@warn_unused_result(message="http://git.io/rxs.ud")
|
||||
public func subscribeError(onError: (ErrorType) -> Void)
|
||||
-> Disposable {
|
||||
let observer = AnonymousObserver<E> { e in
|
||||
if case .Error(let error) = e {
|
||||
onError(error)
|
||||
}
|
||||
}
|
||||
return self.subscribeSafe(observer)
|
||||
}
|
||||
|
||||
/**
|
||||
Subscribes a completion handler to an observable sequence.
|
||||
|
||||
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
|
||||
- returns: Subscription object used to unsubscribe from the observable sequence.
|
||||
*/
|
||||
@warn_unused_result(message="http://git.io/rxs.ud")
|
||||
public func subscribeCompleted(onCompleted: () -> Void)
|
||||
-> Disposable {
|
||||
let observer = AnonymousObserver<E> { e in
|
||||
if case .Completed = e {
|
||||
onCompleted()
|
||||
}
|
||||
}
|
||||
return self.subscribeSafe(observer)
|
||||
}
|
||||
}
|
||||
|
||||
public extension ObservableType {
|
||||
/**
|
||||
All internal subscribe calls go through this method.
|
||||
*/
|
||||
@warn_unused_result(message="http://git.io/rxs.ud")
|
||||
func subscribeSafe<O: ObserverType where O.E == E>(observer: O) -> Disposable {
|
||||
return self.asObservable().subscribe(observer)
|
||||
}
|
||||
}
|
51
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observable.swift
generated
Normal file
51
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observable.swift
generated
Normal file
@ -0,0 +1,51 @@
|
||||
//
|
||||
// Observable.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 2/8/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
A type-erased `ObservableType`.
|
||||
|
||||
It represents a push style sequence.
|
||||
*/
|
||||
public class Observable<Element> : ObservableType {
|
||||
/**
|
||||
Type of elements in sequence.
|
||||
*/
|
||||
public typealias E = Element
|
||||
|
||||
init() {
|
||||
#if TRACE_RESOURCES
|
||||
OSAtomicIncrement32(&resourceCount)
|
||||
#endif
|
||||
}
|
||||
|
||||
public func subscribe<O: ObserverType where O.E == E>(observer: O) -> Disposable {
|
||||
abstractMethod()
|
||||
}
|
||||
|
||||
public func asObservable() -> Observable<E> {
|
||||
return self
|
||||
}
|
||||
|
||||
deinit {
|
||||
#if TRACE_RESOURCES
|
||||
AtomicDecrement(&resourceCount)
|
||||
#endif
|
||||
}
|
||||
|
||||
// this is kind of ugly I know :(
|
||||
// Swift compiler reports "Not supported yet" when trying to override protocol extensions, so ¯\_(ツ)_/¯
|
||||
|
||||
/**
|
||||
Optimizations for map operator
|
||||
*/
|
||||
internal func composeMap<R>(selector: Element throws -> R) -> Observable<R> {
|
||||
return Map(source: self, selector: selector)
|
||||
}
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
//
|
||||
// ObservableConvertibleType.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 9/17/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Type that can be converted to observable sequence (`Observer<E>`).
|
||||
*/
|
||||
public protocol ObservableConvertibleType {
|
||||
/**
|
||||
Type of elements in sequence.
|
||||
*/
|
||||
associatedtype E
|
||||
|
||||
/**
|
||||
Converts `self` to `Observable` sequence.
|
||||
|
||||
- returns: Observable sequence that represents `self`.
|
||||
*/
|
||||
func asObservable() -> Observable<E>
|
||||
}
|
57
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObservableType.swift
generated
Normal file
57
samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObservableType.swift
generated
Normal file
@ -0,0 +1,57 @@
|
||||
//
|
||||
// ObservableType.swift
|
||||
// RxSwift
|
||||
//
|
||||
// Created by Krunoslav Zaher on 8/8/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Represents a push style sequence.
|
||||
*/
|
||||
public protocol ObservableType : ObservableConvertibleType {
|
||||
/**
|
||||
Type of elements in sequence.
|
||||
*/
|
||||
associatedtype E
|
||||
|
||||
/**
|
||||
Subscribes `observer` to receive events for this sequence.
|
||||
|
||||
### Grammar
|
||||
|
||||
**Next\* (Error | Completed)?**
|
||||
|
||||
* sequences can produce zero or more elements so zero or more `Next` events can be sent to `observer`
|
||||
* once an `Error` or `Completed` event is sent, the sequence terminates and can't produce any other elements
|
||||
|
||||
It is possible that events are sent from different threads, but no two events can be sent concurrently to
|
||||
`observer`.
|
||||
|
||||
### Resource Management
|
||||
|
||||
When sequence sends `Complete` or `Error` event all internal resources that compute sequence elements
|
||||
will be freed.
|
||||
|
||||
To cancel production of sequence elements and free resources immediatelly, call `dispose` on returned
|
||||
subscription.
|
||||
|
||||
- returns: Subscription for `observer` that can be used to cancel production of sequence elements and free resources.
|
||||
*/
|
||||
@warn_unused_result(message="http://git.io/rxs.ud")
|
||||
func subscribe<O: ObserverType where O.E == E>(observer: O) -> Disposable
|
||||
|
||||
}
|
||||
|
||||
extension ObservableType {
|
||||
|
||||
/**
|
||||
Default implementation of converting `ObservableType` to `Observable`.
|
||||
*/
|
||||
@warn_unused_result(message="http://git.io/rxs.uo")
|
||||
public func asObservable() -> Observable<E> {
|
||||
return Observable.create(self.subscribe)
|
||||
}
|
||||
}
|
@ -0,0 +1,47 @@
|
||||
//
|
||||
// AddRef.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Junior B. on 30/10/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
class AddRefSink<O: ObserverType> : Sink<O>, ObserverType {
|
||||
typealias Element = O.E
|
||||
|
||||
override init(observer: O) {
|
||||
super.init(observer: observer)
|
||||
}
|
||||
|
||||
func on(event: Event<Element>) {
|
||||
switch event {
|
||||
case .Next(_):
|
||||
forwardOn(event)
|
||||
case .Completed, .Error(_):
|
||||
forwardOn(event)
|
||||
dispose()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class AddRef<Element> : Producer<Element> {
|
||||
typealias EventHandler = Event<Element> throws -> Void
|
||||
|
||||
private let _source: Observable<Element>
|
||||
private let _refCount: RefCountDisposable
|
||||
|
||||
init(source: Observable<Element>, refCount: RefCountDisposable) {
|
||||
_source = source
|
||||
_refCount = refCount
|
||||
}
|
||||
|
||||
override func run<O: ObserverType where O.E == Element>(observer: O) -> Disposable {
|
||||
let releaseDisposable = _refCount.retain()
|
||||
let sink = AddRefSink(observer: observer)
|
||||
sink.disposable = StableCompositeDisposable.create(releaseDisposable, _source.subscribeSafe(sink))
|
||||
|
||||
return sink
|
||||
}
|
||||
}
|
@ -0,0 +1,122 @@
|
||||
//
|
||||
// Amb.swift
|
||||
// RxSwift
|
||||
//
|
||||
// Created by Krunoslav Zaher on 6/14/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
enum AmbState {
|
||||
case Neither
|
||||
case Left
|
||||
case Right
|
||||
}
|
||||
|
||||
class AmbObserver<ElementType, O: ObserverType where O.E == ElementType> : ObserverType {
|
||||
typealias Element = ElementType
|
||||
typealias Parent = AmbSink<ElementType, O>
|
||||
typealias This = AmbObserver<ElementType, O>
|
||||
typealias Sink = (This, Event<Element>) -> Void
|
||||
|
||||
private let _parent: Parent
|
||||
private var _sink: Sink
|
||||
private var _cancel: Disposable
|
||||
|
||||
init(parent: Parent, cancel: Disposable, sink: Sink) {
|
||||
#if TRACE_RESOURCES
|
||||
AtomicIncrement(&resourceCount)
|
||||
#endif
|
||||
|
||||
_parent = parent
|
||||
_sink = sink
|
||||
_cancel = cancel
|
||||
}
|
||||
|
||||
func on(event: Event<Element>) {
|
||||
_sink(self, event)
|
||||
if event.isStopEvent {
|
||||
_cancel.dispose()
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
#if TRACE_RESOURCES
|
||||
AtomicDecrement(&resourceCount)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
class AmbSink<ElementType, O: ObserverType where O.E == ElementType> : Sink<O> {
|
||||
typealias Parent = Amb<ElementType>
|
||||
typealias AmbObserverType = AmbObserver<ElementType, O>
|
||||
|
||||
private let _parent: Parent
|
||||
|
||||
private let _lock = NSRecursiveLock()
|
||||
// state
|
||||
private var _choice = AmbState.Neither
|
||||
|
||||
init(parent: Parent, observer: O) {
|
||||
_parent = parent
|
||||
super.init(observer: observer)
|
||||
}
|
||||
|
||||
func run() -> Disposable {
|
||||
let subscription1 = SingleAssignmentDisposable()
|
||||
let subscription2 = SingleAssignmentDisposable()
|
||||
let disposeAll = StableCompositeDisposable.create(subscription1, subscription2)
|
||||
|
||||
let forwardEvent = { (o: AmbObserverType, event: Event<ElementType>) -> Void in
|
||||
self.forwardOn(event)
|
||||
}
|
||||
|
||||
let decide = { (o: AmbObserverType, event: Event<ElementType>, me: AmbState, otherSubscription: Disposable) in
|
||||
self._lock.performLocked {
|
||||
if self._choice == .Neither {
|
||||
self._choice = me
|
||||
o._sink = forwardEvent
|
||||
o._cancel = disposeAll
|
||||
otherSubscription.dispose()
|
||||
}
|
||||
|
||||
if self._choice == me {
|
||||
self.forwardOn(event)
|
||||
if event.isStopEvent {
|
||||
self.dispose()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let sink1 = AmbObserver(parent: self, cancel: subscription1) { o, e in
|
||||
decide(o, e, .Left, subscription2)
|
||||
}
|
||||
|
||||
let sink2 = AmbObserver(parent: self, cancel: subscription1) { o, e in
|
||||
decide(o, e, .Right, subscription1)
|
||||
}
|
||||
|
||||
subscription1.disposable = _parent._left.subscribe(sink1)
|
||||
subscription2.disposable = _parent._right.subscribe(sink2)
|
||||
|
||||
return disposeAll
|
||||
}
|
||||
}
|
||||
|
||||
class Amb<Element>: Producer<Element> {
|
||||
private let _left: Observable<Element>
|
||||
private let _right: Observable<Element>
|
||||
|
||||
init(left: Observable<Element>, right: Observable<Element>) {
|
||||
_left = left
|
||||
_right = right
|
||||
}
|
||||
|
||||
override func run<O : ObserverType where O.E == Element>(observer: O) -> Disposable {
|
||||
let sink = AmbSink(parent: self, observer: observer)
|
||||
sink.disposable = sink.run()
|
||||
return sink
|
||||
}
|
||||
}
|
@ -0,0 +1,56 @@
|
||||
//
|
||||
// AnonymousObservable.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 2/8/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
class AnonymousObservableSink<O: ObserverType> : Sink<O>, ObserverType {
|
||||
typealias E = O.E
|
||||
typealias Parent = AnonymousObservable<E>
|
||||
|
||||
// state
|
||||
private var _isStopped: AtomicInt = 0
|
||||
|
||||
override init(observer: O) {
|
||||
super.init(observer: observer)
|
||||
}
|
||||
|
||||
func on(event: Event<E>) {
|
||||
switch event {
|
||||
case .Next:
|
||||
if _isStopped == 1 {
|
||||
return
|
||||
}
|
||||
forwardOn(event)
|
||||
case .Error, .Completed:
|
||||
if AtomicCompareAndSwap(0, 1, &_isStopped) {
|
||||
forwardOn(event)
|
||||
dispose()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func run(parent: Parent) -> Disposable {
|
||||
return parent._subscribeHandler(AnyObserver(self))
|
||||
}
|
||||
}
|
||||
|
||||
class AnonymousObservable<Element> : Producer<Element> {
|
||||
typealias SubscribeHandler = (AnyObserver<Element>) -> Disposable
|
||||
|
||||
let _subscribeHandler: SubscribeHandler
|
||||
|
||||
init(_ subscribeHandler: SubscribeHandler) {
|
||||
_subscribeHandler = subscribeHandler
|
||||
}
|
||||
|
||||
override func run<O : ObserverType where O.E == Element>(observer: O) -> Disposable {
|
||||
let sink = AnonymousObservableSink(observer: observer)
|
||||
sink.disposable = sink.run(self)
|
||||
return sink
|
||||
}
|
||||
}
|
@ -0,0 +1,119 @@
|
||||
//
|
||||
// Buffer.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 9/13/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
class BufferTimeCount<Element> : Producer<[Element]> {
|
||||
|
||||
private let _timeSpan: RxTimeInterval
|
||||
private let _count: Int
|
||||
private let _scheduler: SchedulerType
|
||||
private let _source: Observable<Element>
|
||||
|
||||
init(source: Observable<Element>, timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) {
|
||||
_source = source
|
||||
_timeSpan = timeSpan
|
||||
_count = count
|
||||
_scheduler = scheduler
|
||||
}
|
||||
|
||||
override func run<O : ObserverType where O.E == [Element]>(observer: O) -> Disposable {
|
||||
let sink = BufferTimeCountSink(parent: self, observer: observer)
|
||||
sink.disposable = sink.run()
|
||||
return sink
|
||||
}
|
||||
}
|
||||
|
||||
class BufferTimeCountSink<Element, O: ObserverType where O.E == [Element]>
|
||||
: Sink<O>
|
||||
, LockOwnerType
|
||||
, ObserverType
|
||||
, SynchronizedOnType {
|
||||
typealias Parent = BufferTimeCount<Element>
|
||||
typealias E = Element
|
||||
|
||||
private let _parent: Parent
|
||||
|
||||
let _lock = NSRecursiveLock()
|
||||
|
||||
// state
|
||||
private let _timerD = SerialDisposable()
|
||||
private var _buffer = [Element]()
|
||||
private var _windowID = 0
|
||||
|
||||
init(parent: Parent, observer: O) {
|
||||
_parent = parent
|
||||
super.init(observer: observer)
|
||||
}
|
||||
|
||||
func run() -> Disposable {
|
||||
createTimer(_windowID)
|
||||
return StableCompositeDisposable.create(_timerD, _parent._source.subscribe(self))
|
||||
}
|
||||
|
||||
func startNewWindowAndSendCurrentOne() {
|
||||
_windowID = _windowID &+ 1
|
||||
let windowID = _windowID
|
||||
|
||||
let buffer = _buffer
|
||||
_buffer = []
|
||||
forwardOn(.Next(buffer))
|
||||
|
||||
createTimer(windowID)
|
||||
}
|
||||
|
||||
func on(event: Event<E>) {
|
||||
synchronizedOn(event)
|
||||
}
|
||||
|
||||
func _synchronized_on(event: Event<E>) {
|
||||
switch event {
|
||||
case .Next(let element):
|
||||
_buffer.append(element)
|
||||
|
||||
if _buffer.count == _parent._count {
|
||||
startNewWindowAndSendCurrentOne()
|
||||
}
|
||||
|
||||
case .Error(let error):
|
||||
_buffer = []
|
||||
forwardOn(.Error(error))
|
||||
dispose()
|
||||
case .Completed:
|
||||
forwardOn(.Next(_buffer))
|
||||
forwardOn(.Completed)
|
||||
dispose()
|
||||
}
|
||||
}
|
||||
|
||||
func createTimer(windowID: Int) {
|
||||
if _timerD.disposed {
|
||||
return
|
||||
}
|
||||
|
||||
if _windowID != windowID {
|
||||
return
|
||||
}
|
||||
|
||||
let nextTimer = SingleAssignmentDisposable()
|
||||
|
||||
_timerD.disposable = nextTimer
|
||||
|
||||
nextTimer.disposable = _parent._scheduler.scheduleRelative(windowID, dueTime: _parent._timeSpan) { previousWindowID in
|
||||
self._lock.performLocked {
|
||||
if previousWindowID != self._windowID {
|
||||
return
|
||||
}
|
||||
|
||||
self.startNewWindowAndSendCurrentOne()
|
||||
}
|
||||
|
||||
return NopDisposable.instance
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,162 @@
|
||||
//
|
||||
// Catch.swift
|
||||
// RxSwift
|
||||
//
|
||||
// Created by Krunoslav Zaher on 4/19/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
// catch with callback
|
||||
|
||||
class CatchSinkProxy<O: ObserverType> : ObserverType {
|
||||
typealias E = O.E
|
||||
typealias Parent = CatchSink<O>
|
||||
|
||||
private let _parent: Parent
|
||||
|
||||
init(parent: Parent) {
|
||||
_parent = parent
|
||||
}
|
||||
|
||||
func on(event: Event<E>) {
|
||||
_parent.forwardOn(event)
|
||||
|
||||
switch event {
|
||||
case .Next:
|
||||
break
|
||||
case .Error, .Completed:
|
||||
_parent.dispose()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class CatchSink<O: ObserverType> : Sink<O>, ObserverType {
|
||||
typealias E = O.E
|
||||
typealias Parent = Catch<E>
|
||||
|
||||
private let _parent: Parent
|
||||
private let _subscription = SerialDisposable()
|
||||
|
||||
init(parent: Parent, observer: O) {
|
||||
_parent = parent
|
||||
super.init(observer: observer)
|
||||
}
|
||||
|
||||
func run() -> Disposable {
|
||||
let d1 = SingleAssignmentDisposable()
|
||||
_subscription.disposable = d1
|
||||
d1.disposable = _parent._source.subscribe(self)
|
||||
|
||||
return _subscription
|
||||
}
|
||||
|
||||
func on(event: Event<E>) {
|
||||
switch event {
|
||||
case .Next:
|
||||
forwardOn(event)
|
||||
case .Completed:
|
||||
forwardOn(event)
|
||||
dispose()
|
||||
case .Error(let error):
|
||||
do {
|
||||
let catchSequence = try _parent._handler(error)
|
||||
|
||||
let observer = CatchSinkProxy(parent: self)
|
||||
|
||||
_subscription.disposable = catchSequence.subscribe(observer)
|
||||
}
|
||||
catch let e {
|
||||
forwardOn(.Error(e))
|
||||
dispose()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Catch<Element> : Producer<Element> {
|
||||
typealias Handler = (ErrorType) throws -> Observable<Element>
|
||||
|
||||
private let _source: Observable<Element>
|
||||
private let _handler: Handler
|
||||
|
||||
init(source: Observable<Element>, handler: Handler) {
|
||||
_source = source
|
||||
_handler = handler
|
||||
}
|
||||
|
||||
override func run<O: ObserverType where O.E == Element>(observer: O) -> Disposable {
|
||||
let sink = CatchSink(parent: self, observer: observer)
|
||||
sink.disposable = sink.run()
|
||||
return sink
|
||||
}
|
||||
}
|
||||
|
||||
// catch enumerable
|
||||
|
||||
class CatchSequenceSink<S: SequenceType, O: ObserverType where S.Generator.Element : ObservableConvertibleType, S.Generator.Element.E == O.E>
|
||||
: TailRecursiveSink<S, O>
|
||||
, ObserverType {
|
||||
typealias Element = O.E
|
||||
typealias Parent = CatchSequence<S>
|
||||
|
||||
private var _lastError: ErrorType?
|
||||
|
||||
override init(observer: O) {
|
||||
super.init(observer: observer)
|
||||
}
|
||||
|
||||
func on(event: Event<Element>) {
|
||||
switch event {
|
||||
case .Next:
|
||||
forwardOn(event)
|
||||
case .Error(let error):
|
||||
_lastError = error
|
||||
schedule(.MoveNext)
|
||||
case .Completed:
|
||||
forwardOn(event)
|
||||
dispose()
|
||||
}
|
||||
}
|
||||
|
||||
override func subscribeToNext(source: Observable<E>) -> Disposable {
|
||||
return source.subscribe(self)
|
||||
}
|
||||
|
||||
override func done() {
|
||||
if let lastError = _lastError {
|
||||
forwardOn(.Error(lastError))
|
||||
}
|
||||
else {
|
||||
forwardOn(.Completed)
|
||||
}
|
||||
|
||||
self.dispose()
|
||||
}
|
||||
|
||||
override func extract(observable: Observable<Element>) -> SequenceGenerator? {
|
||||
if let onError = observable as? CatchSequence<S> {
|
||||
return (onError.sources.generate(), nil)
|
||||
}
|
||||
else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class CatchSequence<S: SequenceType where S.Generator.Element : ObservableConvertibleType> : Producer<S.Generator.Element.E> {
|
||||
typealias Element = S.Generator.Element.E
|
||||
|
||||
let sources: S
|
||||
|
||||
init(sources: S) {
|
||||
self.sources = sources
|
||||
}
|
||||
|
||||
override func run<O : ObserverType where O.E == Element>(observer: O) -> Disposable {
|
||||
let sink = CatchSequenceSink<S, O>(observer: observer)
|
||||
sink.disposable = sink.run((self.sources.generate(), nil))
|
||||
return sink
|
||||
}
|
||||
}
|
@ -0,0 +1,125 @@
|
||||
//
|
||||
// CombineLatest+CollectionType.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 8/29/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
class CombineLatestCollectionTypeSink<C: CollectionType, R, O: ObserverType where C.Generator.Element : ObservableConvertibleType, O.E == R>
|
||||
: Sink<O> {
|
||||
typealias Parent = CombineLatestCollectionType<C, R>
|
||||
typealias SourceElement = C.Generator.Element.E
|
||||
|
||||
let _parent: Parent
|
||||
|
||||
let _lock = NSRecursiveLock()
|
||||
|
||||
// state
|
||||
var _numberOfValues = 0
|
||||
var _values: [SourceElement?]
|
||||
var _isDone: [Bool]
|
||||
var _numberOfDone = 0
|
||||
var _subscriptions: [SingleAssignmentDisposable]
|
||||
|
||||
init(parent: Parent, observer: O) {
|
||||
_parent = parent
|
||||
_values = [SourceElement?](count: parent._count, repeatedValue: nil)
|
||||
_isDone = [Bool](count: parent._count, repeatedValue: false)
|
||||
_subscriptions = Array<SingleAssignmentDisposable>()
|
||||
_subscriptions.reserveCapacity(parent._count)
|
||||
|
||||
for _ in 0 ..< parent._count {
|
||||
_subscriptions.append(SingleAssignmentDisposable())
|
||||
}
|
||||
|
||||
super.init(observer: observer)
|
||||
}
|
||||
|
||||
func on(event: Event<SourceElement>, atIndex: Int) {
|
||||
_lock.lock(); defer { _lock.unlock() } // {
|
||||
switch event {
|
||||
case .Next(let element):
|
||||
if _values[atIndex] == nil {
|
||||
_numberOfValues += 1
|
||||
}
|
||||
|
||||
_values[atIndex] = element
|
||||
|
||||
if _numberOfValues < _parent._count {
|
||||
let numberOfOthersThatAreDone = self._numberOfDone - (_isDone[atIndex] ? 1 : 0)
|
||||
if numberOfOthersThatAreDone == self._parent._count - 1 {
|
||||
forwardOn(.Completed)
|
||||
dispose()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
do {
|
||||
let result = try _parent._resultSelector(_values.map { $0! })
|
||||
forwardOn(.Next(result))
|
||||
}
|
||||
catch let error {
|
||||
forwardOn(.Error(error))
|
||||
dispose()
|
||||
}
|
||||
|
||||
case .Error(let error):
|
||||
forwardOn(.Error(error))
|
||||
dispose()
|
||||
case .Completed:
|
||||
if _isDone[atIndex] {
|
||||
return
|
||||
}
|
||||
|
||||
_isDone[atIndex] = true
|
||||
_numberOfDone += 1
|
||||
|
||||
if _numberOfDone == self._parent._count {
|
||||
forwardOn(.Completed)
|
||||
dispose()
|
||||
}
|
||||
else {
|
||||
_subscriptions[atIndex].dispose()
|
||||
}
|
||||
}
|
||||
// }
|
||||
}
|
||||
|
||||
func run() -> Disposable {
|
||||
var j = 0
|
||||
for i in _parent._sources.startIndex ..< _parent._sources.endIndex {
|
||||
let index = j
|
||||
let source = _parent._sources[i].asObservable()
|
||||
_subscriptions[j].disposable = source.subscribe(AnyObserver { event in
|
||||
self.on(event, atIndex: index)
|
||||
})
|
||||
|
||||
j += 1
|
||||
}
|
||||
|
||||
return CompositeDisposable(disposables: _subscriptions.map { $0 })
|
||||
}
|
||||
}
|
||||
|
||||
class CombineLatestCollectionType<C: CollectionType, R where C.Generator.Element : ObservableConvertibleType> : Producer<R> {
|
||||
typealias ResultSelector = [C.Generator.Element.E] throws -> R
|
||||
|
||||
let _sources: C
|
||||
let _resultSelector: ResultSelector
|
||||
let _count: Int
|
||||
|
||||
init(sources: C, resultSelector: ResultSelector) {
|
||||
_sources = sources
|
||||
_resultSelector = resultSelector
|
||||
_count = Int(self._sources.count.toIntMax())
|
||||
}
|
||||
|
||||
override func run<O : ObserverType where O.E == R>(observer: O) -> Disposable {
|
||||
let sink = CombineLatestCollectionTypeSink(parent: self, observer: observer)
|
||||
sink.disposable = sink.run()
|
||||
return sink
|
||||
}
|
||||
}
|
@ -0,0 +1,724 @@
|
||||
// This file is autogenerated. Take a look at `Preprocessor` target in RxSwift project
|
||||
//
|
||||
// CombineLatest+arity.swift
|
||||
// RxSwift
|
||||
//
|
||||
// Created by Krunoslav Zaher on 4/22/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
|
||||
|
||||
// 2
|
||||
|
||||
extension Observable {
|
||||
/**
|
||||
Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element.
|
||||
|
||||
- seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html)
|
||||
|
||||
- parameter resultSelector: Function to invoke whenever any of the sources produces an element.
|
||||
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
|
||||
*/
|
||||
@warn_unused_result(message="http://git.io/rxs.uo")
|
||||
public static func combineLatest<O1: ObservableType, O2: ObservableType>
|
||||
(source1: O1, _ source2: O2, resultSelector: (O1.E, O2.E) throws -> E)
|
||||
-> Observable<E> {
|
||||
return CombineLatest2(
|
||||
source1: source1.asObservable(), source2: source2.asObservable(),
|
||||
resultSelector: resultSelector
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
class CombineLatestSink2_<E1, E2, O: ObserverType> : CombineLatestSink<O> {
|
||||
typealias R = O.E
|
||||
typealias Parent = CombineLatest2<E1, E2, R>
|
||||
|
||||
let _parent: Parent
|
||||
|
||||
var _latestElement1: E1! = nil
|
||||
var _latestElement2: E2! = nil
|
||||
|
||||
init(parent: Parent, observer: O) {
|
||||
_parent = parent
|
||||
super.init(arity: 2, observer: observer)
|
||||
}
|
||||
|
||||
func run() -> Disposable {
|
||||
let subscription1 = SingleAssignmentDisposable()
|
||||
let subscription2 = SingleAssignmentDisposable()
|
||||
|
||||
let observer1 = CombineLatestObserver(lock: _lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self._latestElement1 = e }, this: subscription1)
|
||||
let observer2 = CombineLatestObserver(lock: _lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self._latestElement2 = e }, this: subscription2)
|
||||
|
||||
subscription1.disposable = _parent._source1.subscribe(observer1)
|
||||
subscription2.disposable = _parent._source2.subscribe(observer2)
|
||||
|
||||
return CompositeDisposable(disposables: [
|
||||
subscription1,
|
||||
subscription2
|
||||
])
|
||||
}
|
||||
|
||||
override func getResult() throws -> R {
|
||||
return try _parent._resultSelector(_latestElement1, _latestElement2)
|
||||
}
|
||||
}
|
||||
|
||||
class CombineLatest2<E1, E2, R> : Producer<R> {
|
||||
typealias ResultSelector = (E1, E2) throws -> R
|
||||
|
||||
let _source1: Observable<E1>
|
||||
let _source2: Observable<E2>
|
||||
|
||||
let _resultSelector: ResultSelector
|
||||
|
||||
init(source1: Observable<E1>, source2: Observable<E2>, resultSelector: ResultSelector) {
|
||||
_source1 = source1
|
||||
_source2 = source2
|
||||
|
||||
_resultSelector = resultSelector
|
||||
}
|
||||
|
||||
override func run<O: ObserverType where O.E == R>(observer: O) -> Disposable {
|
||||
let sink = CombineLatestSink2_(parent: self, observer: observer)
|
||||
sink.disposable = sink.run()
|
||||
return sink
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// 3
|
||||
|
||||
extension Observable {
|
||||
/**
|
||||
Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element.
|
||||
|
||||
- seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html)
|
||||
|
||||
- parameter resultSelector: Function to invoke whenever any of the sources produces an element.
|
||||
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
|
||||
*/
|
||||
@warn_unused_result(message="http://git.io/rxs.uo")
|
||||
public static func combineLatest<O1: ObservableType, O2: ObservableType, O3: ObservableType>
|
||||
(source1: O1, _ source2: O2, _ source3: O3, resultSelector: (O1.E, O2.E, O3.E) throws -> E)
|
||||
-> Observable<E> {
|
||||
return CombineLatest3(
|
||||
source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(),
|
||||
resultSelector: resultSelector
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
class CombineLatestSink3_<E1, E2, E3, O: ObserverType> : CombineLatestSink<O> {
|
||||
typealias R = O.E
|
||||
typealias Parent = CombineLatest3<E1, E2, E3, R>
|
||||
|
||||
let _parent: Parent
|
||||
|
||||
var _latestElement1: E1! = nil
|
||||
var _latestElement2: E2! = nil
|
||||
var _latestElement3: E3! = nil
|
||||
|
||||
init(parent: Parent, observer: O) {
|
||||
_parent = parent
|
||||
super.init(arity: 3, observer: observer)
|
||||
}
|
||||
|
||||
func run() -> Disposable {
|
||||
let subscription1 = SingleAssignmentDisposable()
|
||||
let subscription2 = SingleAssignmentDisposable()
|
||||
let subscription3 = SingleAssignmentDisposable()
|
||||
|
||||
let observer1 = CombineLatestObserver(lock: _lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self._latestElement1 = e }, this: subscription1)
|
||||
let observer2 = CombineLatestObserver(lock: _lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self._latestElement2 = e }, this: subscription2)
|
||||
let observer3 = CombineLatestObserver(lock: _lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self._latestElement3 = e }, this: subscription3)
|
||||
|
||||
subscription1.disposable = _parent._source1.subscribe(observer1)
|
||||
subscription2.disposable = _parent._source2.subscribe(observer2)
|
||||
subscription3.disposable = _parent._source3.subscribe(observer3)
|
||||
|
||||
return CompositeDisposable(disposables: [
|
||||
subscription1,
|
||||
subscription2,
|
||||
subscription3
|
||||
])
|
||||
}
|
||||
|
||||
override func getResult() throws -> R {
|
||||
return try _parent._resultSelector(_latestElement1, _latestElement2, _latestElement3)
|
||||
}
|
||||
}
|
||||
|
||||
class CombineLatest3<E1, E2, E3, R> : Producer<R> {
|
||||
typealias ResultSelector = (E1, E2, E3) throws -> R
|
||||
|
||||
let _source1: Observable<E1>
|
||||
let _source2: Observable<E2>
|
||||
let _source3: Observable<E3>
|
||||
|
||||
let _resultSelector: ResultSelector
|
||||
|
||||
init(source1: Observable<E1>, source2: Observable<E2>, source3: Observable<E3>, resultSelector: ResultSelector) {
|
||||
_source1 = source1
|
||||
_source2 = source2
|
||||
_source3 = source3
|
||||
|
||||
_resultSelector = resultSelector
|
||||
}
|
||||
|
||||
override func run<O: ObserverType where O.E == R>(observer: O) -> Disposable {
|
||||
let sink = CombineLatestSink3_(parent: self, observer: observer)
|
||||
sink.disposable = sink.run()
|
||||
return sink
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// 4
|
||||
|
||||
extension Observable {
|
||||
/**
|
||||
Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element.
|
||||
|
||||
- seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html)
|
||||
|
||||
- parameter resultSelector: Function to invoke whenever any of the sources produces an element.
|
||||
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
|
||||
*/
|
||||
@warn_unused_result(message="http://git.io/rxs.uo")
|
||||
public static func combineLatest<O1: ObservableType, O2: ObservableType, O3: ObservableType, O4: ObservableType>
|
||||
(source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, resultSelector: (O1.E, O2.E, O3.E, O4.E) throws -> E)
|
||||
-> Observable<E> {
|
||||
return CombineLatest4(
|
||||
source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(),
|
||||
resultSelector: resultSelector
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
class CombineLatestSink4_<E1, E2, E3, E4, O: ObserverType> : CombineLatestSink<O> {
|
||||
typealias R = O.E
|
||||
typealias Parent = CombineLatest4<E1, E2, E3, E4, R>
|
||||
|
||||
let _parent: Parent
|
||||
|
||||
var _latestElement1: E1! = nil
|
||||
var _latestElement2: E2! = nil
|
||||
var _latestElement3: E3! = nil
|
||||
var _latestElement4: E4! = nil
|
||||
|
||||
init(parent: Parent, observer: O) {
|
||||
_parent = parent
|
||||
super.init(arity: 4, observer: observer)
|
||||
}
|
||||
|
||||
func run() -> Disposable {
|
||||
let subscription1 = SingleAssignmentDisposable()
|
||||
let subscription2 = SingleAssignmentDisposable()
|
||||
let subscription3 = SingleAssignmentDisposable()
|
||||
let subscription4 = SingleAssignmentDisposable()
|
||||
|
||||
let observer1 = CombineLatestObserver(lock: _lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self._latestElement1 = e }, this: subscription1)
|
||||
let observer2 = CombineLatestObserver(lock: _lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self._latestElement2 = e }, this: subscription2)
|
||||
let observer3 = CombineLatestObserver(lock: _lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self._latestElement3 = e }, this: subscription3)
|
||||
let observer4 = CombineLatestObserver(lock: _lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self._latestElement4 = e }, this: subscription4)
|
||||
|
||||
subscription1.disposable = _parent._source1.subscribe(observer1)
|
||||
subscription2.disposable = _parent._source2.subscribe(observer2)
|
||||
subscription3.disposable = _parent._source3.subscribe(observer3)
|
||||
subscription4.disposable = _parent._source4.subscribe(observer4)
|
||||
|
||||
return CompositeDisposable(disposables: [
|
||||
subscription1,
|
||||
subscription2,
|
||||
subscription3,
|
||||
subscription4
|
||||
])
|
||||
}
|
||||
|
||||
override func getResult() throws -> R {
|
||||
return try _parent._resultSelector(_latestElement1, _latestElement2, _latestElement3, _latestElement4)
|
||||
}
|
||||
}
|
||||
|
||||
class CombineLatest4<E1, E2, E3, E4, R> : Producer<R> {
|
||||
typealias ResultSelector = (E1, E2, E3, E4) throws -> R
|
||||
|
||||
let _source1: Observable<E1>
|
||||
let _source2: Observable<E2>
|
||||
let _source3: Observable<E3>
|
||||
let _source4: Observable<E4>
|
||||
|
||||
let _resultSelector: ResultSelector
|
||||
|
||||
init(source1: Observable<E1>, source2: Observable<E2>, source3: Observable<E3>, source4: Observable<E4>, resultSelector: ResultSelector) {
|
||||
_source1 = source1
|
||||
_source2 = source2
|
||||
_source3 = source3
|
||||
_source4 = source4
|
||||
|
||||
_resultSelector = resultSelector
|
||||
}
|
||||
|
||||
override func run<O: ObserverType where O.E == R>(observer: O) -> Disposable {
|
||||
let sink = CombineLatestSink4_(parent: self, observer: observer)
|
||||
sink.disposable = sink.run()
|
||||
return sink
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// 5
|
||||
|
||||
extension Observable {
|
||||
/**
|
||||
Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element.
|
||||
|
||||
- seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html)
|
||||
|
||||
- parameter resultSelector: Function to invoke whenever any of the sources produces an element.
|
||||
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
|
||||
*/
|
||||
@warn_unused_result(message="http://git.io/rxs.uo")
|
||||
public static func combineLatest<O1: ObservableType, O2: ObservableType, O3: ObservableType, O4: ObservableType, O5: ObservableType>
|
||||
(source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, resultSelector: (O1.E, O2.E, O3.E, O4.E, O5.E) throws -> E)
|
||||
-> Observable<E> {
|
||||
return CombineLatest5(
|
||||
source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(),
|
||||
resultSelector: resultSelector
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
class CombineLatestSink5_<E1, E2, E3, E4, E5, O: ObserverType> : CombineLatestSink<O> {
|
||||
typealias R = O.E
|
||||
typealias Parent = CombineLatest5<E1, E2, E3, E4, E5, R>
|
||||
|
||||
let _parent: Parent
|
||||
|
||||
var _latestElement1: E1! = nil
|
||||
var _latestElement2: E2! = nil
|
||||
var _latestElement3: E3! = nil
|
||||
var _latestElement4: E4! = nil
|
||||
var _latestElement5: E5! = nil
|
||||
|
||||
init(parent: Parent, observer: O) {
|
||||
_parent = parent
|
||||
super.init(arity: 5, observer: observer)
|
||||
}
|
||||
|
||||
func run() -> Disposable {
|
||||
let subscription1 = SingleAssignmentDisposable()
|
||||
let subscription2 = SingleAssignmentDisposable()
|
||||
let subscription3 = SingleAssignmentDisposable()
|
||||
let subscription4 = SingleAssignmentDisposable()
|
||||
let subscription5 = SingleAssignmentDisposable()
|
||||
|
||||
let observer1 = CombineLatestObserver(lock: _lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self._latestElement1 = e }, this: subscription1)
|
||||
let observer2 = CombineLatestObserver(lock: _lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self._latestElement2 = e }, this: subscription2)
|
||||
let observer3 = CombineLatestObserver(lock: _lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self._latestElement3 = e }, this: subscription3)
|
||||
let observer4 = CombineLatestObserver(lock: _lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self._latestElement4 = e }, this: subscription4)
|
||||
let observer5 = CombineLatestObserver(lock: _lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self._latestElement5 = e }, this: subscription5)
|
||||
|
||||
subscription1.disposable = _parent._source1.subscribe(observer1)
|
||||
subscription2.disposable = _parent._source2.subscribe(observer2)
|
||||
subscription3.disposable = _parent._source3.subscribe(observer3)
|
||||
subscription4.disposable = _parent._source4.subscribe(observer4)
|
||||
subscription5.disposable = _parent._source5.subscribe(observer5)
|
||||
|
||||
return CompositeDisposable(disposables: [
|
||||
subscription1,
|
||||
subscription2,
|
||||
subscription3,
|
||||
subscription4,
|
||||
subscription5
|
||||
])
|
||||
}
|
||||
|
||||
override func getResult() throws -> R {
|
||||
return try _parent._resultSelector(_latestElement1, _latestElement2, _latestElement3, _latestElement4, _latestElement5)
|
||||
}
|
||||
}
|
||||
|
||||
class CombineLatest5<E1, E2, E3, E4, E5, R> : Producer<R> {
|
||||
typealias ResultSelector = (E1, E2, E3, E4, E5) throws -> R
|
||||
|
||||
let _source1: Observable<E1>
|
||||
let _source2: Observable<E2>
|
||||
let _source3: Observable<E3>
|
||||
let _source4: Observable<E4>
|
||||
let _source5: Observable<E5>
|
||||
|
||||
let _resultSelector: ResultSelector
|
||||
|
||||
init(source1: Observable<E1>, source2: Observable<E2>, source3: Observable<E3>, source4: Observable<E4>, source5: Observable<E5>, resultSelector: ResultSelector) {
|
||||
_source1 = source1
|
||||
_source2 = source2
|
||||
_source3 = source3
|
||||
_source4 = source4
|
||||
_source5 = source5
|
||||
|
||||
_resultSelector = resultSelector
|
||||
}
|
||||
|
||||
override func run<O: ObserverType where O.E == R>(observer: O) -> Disposable {
|
||||
let sink = CombineLatestSink5_(parent: self, observer: observer)
|
||||
sink.disposable = sink.run()
|
||||
return sink
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// 6
|
||||
|
||||
extension Observable {
|
||||
/**
|
||||
Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element.
|
||||
|
||||
- seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html)
|
||||
|
||||
- parameter resultSelector: Function to invoke whenever any of the sources produces an element.
|
||||
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
|
||||
*/
|
||||
@warn_unused_result(message="http://git.io/rxs.uo")
|
||||
public static func combineLatest<O1: ObservableType, O2: ObservableType, O3: ObservableType, O4: ObservableType, O5: ObservableType, O6: ObservableType>
|
||||
(source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, resultSelector: (O1.E, O2.E, O3.E, O4.E, O5.E, O6.E) throws -> E)
|
||||
-> Observable<E> {
|
||||
return CombineLatest6(
|
||||
source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(),
|
||||
resultSelector: resultSelector
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
class CombineLatestSink6_<E1, E2, E3, E4, E5, E6, O: ObserverType> : CombineLatestSink<O> {
|
||||
typealias R = O.E
|
||||
typealias Parent = CombineLatest6<E1, E2, E3, E4, E5, E6, R>
|
||||
|
||||
let _parent: Parent
|
||||
|
||||
var _latestElement1: E1! = nil
|
||||
var _latestElement2: E2! = nil
|
||||
var _latestElement3: E3! = nil
|
||||
var _latestElement4: E4! = nil
|
||||
var _latestElement5: E5! = nil
|
||||
var _latestElement6: E6! = nil
|
||||
|
||||
init(parent: Parent, observer: O) {
|
||||
_parent = parent
|
||||
super.init(arity: 6, observer: observer)
|
||||
}
|
||||
|
||||
func run() -> Disposable {
|
||||
let subscription1 = SingleAssignmentDisposable()
|
||||
let subscription2 = SingleAssignmentDisposable()
|
||||
let subscription3 = SingleAssignmentDisposable()
|
||||
let subscription4 = SingleAssignmentDisposable()
|
||||
let subscription5 = SingleAssignmentDisposable()
|
||||
let subscription6 = SingleAssignmentDisposable()
|
||||
|
||||
let observer1 = CombineLatestObserver(lock: _lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self._latestElement1 = e }, this: subscription1)
|
||||
let observer2 = CombineLatestObserver(lock: _lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self._latestElement2 = e }, this: subscription2)
|
||||
let observer3 = CombineLatestObserver(lock: _lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self._latestElement3 = e }, this: subscription3)
|
||||
let observer4 = CombineLatestObserver(lock: _lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self._latestElement4 = e }, this: subscription4)
|
||||
let observer5 = CombineLatestObserver(lock: _lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self._latestElement5 = e }, this: subscription5)
|
||||
let observer6 = CombineLatestObserver(lock: _lock, parent: self, index: 5, setLatestValue: { (e: E6) -> Void in self._latestElement6 = e }, this: subscription6)
|
||||
|
||||
subscription1.disposable = _parent._source1.subscribe(observer1)
|
||||
subscription2.disposable = _parent._source2.subscribe(observer2)
|
||||
subscription3.disposable = _parent._source3.subscribe(observer3)
|
||||
subscription4.disposable = _parent._source4.subscribe(observer4)
|
||||
subscription5.disposable = _parent._source5.subscribe(observer5)
|
||||
subscription6.disposable = _parent._source6.subscribe(observer6)
|
||||
|
||||
return CompositeDisposable(disposables: [
|
||||
subscription1,
|
||||
subscription2,
|
||||
subscription3,
|
||||
subscription4,
|
||||
subscription5,
|
||||
subscription6
|
||||
])
|
||||
}
|
||||
|
||||
override func getResult() throws -> R {
|
||||
return try _parent._resultSelector(_latestElement1, _latestElement2, _latestElement3, _latestElement4, _latestElement5, _latestElement6)
|
||||
}
|
||||
}
|
||||
|
||||
class CombineLatest6<E1, E2, E3, E4, E5, E6, R> : Producer<R> {
|
||||
typealias ResultSelector = (E1, E2, E3, E4, E5, E6) throws -> R
|
||||
|
||||
let _source1: Observable<E1>
|
||||
let _source2: Observable<E2>
|
||||
let _source3: Observable<E3>
|
||||
let _source4: Observable<E4>
|
||||
let _source5: Observable<E5>
|
||||
let _source6: Observable<E6>
|
||||
|
||||
let _resultSelector: ResultSelector
|
||||
|
||||
init(source1: Observable<E1>, source2: Observable<E2>, source3: Observable<E3>, source4: Observable<E4>, source5: Observable<E5>, source6: Observable<E6>, resultSelector: ResultSelector) {
|
||||
_source1 = source1
|
||||
_source2 = source2
|
||||
_source3 = source3
|
||||
_source4 = source4
|
||||
_source5 = source5
|
||||
_source6 = source6
|
||||
|
||||
_resultSelector = resultSelector
|
||||
}
|
||||
|
||||
override func run<O: ObserverType where O.E == R>(observer: O) -> Disposable {
|
||||
let sink = CombineLatestSink6_(parent: self, observer: observer)
|
||||
sink.disposable = sink.run()
|
||||
return sink
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// 7
|
||||
|
||||
extension Observable {
|
||||
/**
|
||||
Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element.
|
||||
|
||||
- seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html)
|
||||
|
||||
- parameter resultSelector: Function to invoke whenever any of the sources produces an element.
|
||||
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
|
||||
*/
|
||||
@warn_unused_result(message="http://git.io/rxs.uo")
|
||||
public static func combineLatest<O1: ObservableType, O2: ObservableType, O3: ObservableType, O4: ObservableType, O5: ObservableType, O6: ObservableType, O7: ObservableType>
|
||||
(source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, resultSelector: (O1.E, O2.E, O3.E, O4.E, O5.E, O6.E, O7.E) throws -> E)
|
||||
-> Observable<E> {
|
||||
return CombineLatest7(
|
||||
source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(),
|
||||
resultSelector: resultSelector
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
class CombineLatestSink7_<E1, E2, E3, E4, E5, E6, E7, O: ObserverType> : CombineLatestSink<O> {
|
||||
typealias R = O.E
|
||||
typealias Parent = CombineLatest7<E1, E2, E3, E4, E5, E6, E7, R>
|
||||
|
||||
let _parent: Parent
|
||||
|
||||
var _latestElement1: E1! = nil
|
||||
var _latestElement2: E2! = nil
|
||||
var _latestElement3: E3! = nil
|
||||
var _latestElement4: E4! = nil
|
||||
var _latestElement5: E5! = nil
|
||||
var _latestElement6: E6! = nil
|
||||
var _latestElement7: E7! = nil
|
||||
|
||||
init(parent: Parent, observer: O) {
|
||||
_parent = parent
|
||||
super.init(arity: 7, observer: observer)
|
||||
}
|
||||
|
||||
func run() -> Disposable {
|
||||
let subscription1 = SingleAssignmentDisposable()
|
||||
let subscription2 = SingleAssignmentDisposable()
|
||||
let subscription3 = SingleAssignmentDisposable()
|
||||
let subscription4 = SingleAssignmentDisposable()
|
||||
let subscription5 = SingleAssignmentDisposable()
|
||||
let subscription6 = SingleAssignmentDisposable()
|
||||
let subscription7 = SingleAssignmentDisposable()
|
||||
|
||||
let observer1 = CombineLatestObserver(lock: _lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self._latestElement1 = e }, this: subscription1)
|
||||
let observer2 = CombineLatestObserver(lock: _lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self._latestElement2 = e }, this: subscription2)
|
||||
let observer3 = CombineLatestObserver(lock: _lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self._latestElement3 = e }, this: subscription3)
|
||||
let observer4 = CombineLatestObserver(lock: _lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self._latestElement4 = e }, this: subscription4)
|
||||
let observer5 = CombineLatestObserver(lock: _lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self._latestElement5 = e }, this: subscription5)
|
||||
let observer6 = CombineLatestObserver(lock: _lock, parent: self, index: 5, setLatestValue: { (e: E6) -> Void in self._latestElement6 = e }, this: subscription6)
|
||||
let observer7 = CombineLatestObserver(lock: _lock, parent: self, index: 6, setLatestValue: { (e: E7) -> Void in self._latestElement7 = e }, this: subscription7)
|
||||
|
||||
subscription1.disposable = _parent._source1.subscribe(observer1)
|
||||
subscription2.disposable = _parent._source2.subscribe(observer2)
|
||||
subscription3.disposable = _parent._source3.subscribe(observer3)
|
||||
subscription4.disposable = _parent._source4.subscribe(observer4)
|
||||
subscription5.disposable = _parent._source5.subscribe(observer5)
|
||||
subscription6.disposable = _parent._source6.subscribe(observer6)
|
||||
subscription7.disposable = _parent._source7.subscribe(observer7)
|
||||
|
||||
return CompositeDisposable(disposables: [
|
||||
subscription1,
|
||||
subscription2,
|
||||
subscription3,
|
||||
subscription4,
|
||||
subscription5,
|
||||
subscription6,
|
||||
subscription7
|
||||
])
|
||||
}
|
||||
|
||||
override func getResult() throws -> R {
|
||||
return try _parent._resultSelector(_latestElement1, _latestElement2, _latestElement3, _latestElement4, _latestElement5, _latestElement6, _latestElement7)
|
||||
}
|
||||
}
|
||||
|
||||
class CombineLatest7<E1, E2, E3, E4, E5, E6, E7, R> : Producer<R> {
|
||||
typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7) throws -> R
|
||||
|
||||
let _source1: Observable<E1>
|
||||
let _source2: Observable<E2>
|
||||
let _source3: Observable<E3>
|
||||
let _source4: Observable<E4>
|
||||
let _source5: Observable<E5>
|
||||
let _source6: Observable<E6>
|
||||
let _source7: Observable<E7>
|
||||
|
||||
let _resultSelector: ResultSelector
|
||||
|
||||
init(source1: Observable<E1>, source2: Observable<E2>, source3: Observable<E3>, source4: Observable<E4>, source5: Observable<E5>, source6: Observable<E6>, source7: Observable<E7>, resultSelector: ResultSelector) {
|
||||
_source1 = source1
|
||||
_source2 = source2
|
||||
_source3 = source3
|
||||
_source4 = source4
|
||||
_source5 = source5
|
||||
_source6 = source6
|
||||
_source7 = source7
|
||||
|
||||
_resultSelector = resultSelector
|
||||
}
|
||||
|
||||
override func run<O: ObserverType where O.E == R>(observer: O) -> Disposable {
|
||||
let sink = CombineLatestSink7_(parent: self, observer: observer)
|
||||
sink.disposable = sink.run()
|
||||
return sink
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// 8
|
||||
|
||||
extension Observable {
|
||||
/**
|
||||
Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element.
|
||||
|
||||
- seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html)
|
||||
|
||||
- parameter resultSelector: Function to invoke whenever any of the sources produces an element.
|
||||
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
|
||||
*/
|
||||
@warn_unused_result(message="http://git.io/rxs.uo")
|
||||
public static func combineLatest<O1: ObservableType, O2: ObservableType, O3: ObservableType, O4: ObservableType, O5: ObservableType, O6: ObservableType, O7: ObservableType, O8: ObservableType>
|
||||
(source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8, resultSelector: (O1.E, O2.E, O3.E, O4.E, O5.E, O6.E, O7.E, O8.E) throws -> E)
|
||||
-> Observable<E> {
|
||||
return CombineLatest8(
|
||||
source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), source8: source8.asObservable(),
|
||||
resultSelector: resultSelector
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
class CombineLatestSink8_<E1, E2, E3, E4, E5, E6, E7, E8, O: ObserverType> : CombineLatestSink<O> {
|
||||
typealias R = O.E
|
||||
typealias Parent = CombineLatest8<E1, E2, E3, E4, E5, E6, E7, E8, R>
|
||||
|
||||
let _parent: Parent
|
||||
|
||||
var _latestElement1: E1! = nil
|
||||
var _latestElement2: E2! = nil
|
||||
var _latestElement3: E3! = nil
|
||||
var _latestElement4: E4! = nil
|
||||
var _latestElement5: E5! = nil
|
||||
var _latestElement6: E6! = nil
|
||||
var _latestElement7: E7! = nil
|
||||
var _latestElement8: E8! = nil
|
||||
|
||||
init(parent: Parent, observer: O) {
|
||||
_parent = parent
|
||||
super.init(arity: 8, observer: observer)
|
||||
}
|
||||
|
||||
func run() -> Disposable {
|
||||
let subscription1 = SingleAssignmentDisposable()
|
||||
let subscription2 = SingleAssignmentDisposable()
|
||||
let subscription3 = SingleAssignmentDisposable()
|
||||
let subscription4 = SingleAssignmentDisposable()
|
||||
let subscription5 = SingleAssignmentDisposable()
|
||||
let subscription6 = SingleAssignmentDisposable()
|
||||
let subscription7 = SingleAssignmentDisposable()
|
||||
let subscription8 = SingleAssignmentDisposable()
|
||||
|
||||
let observer1 = CombineLatestObserver(lock: _lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self._latestElement1 = e }, this: subscription1)
|
||||
let observer2 = CombineLatestObserver(lock: _lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self._latestElement2 = e }, this: subscription2)
|
||||
let observer3 = CombineLatestObserver(lock: _lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self._latestElement3 = e }, this: subscription3)
|
||||
let observer4 = CombineLatestObserver(lock: _lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self._latestElement4 = e }, this: subscription4)
|
||||
let observer5 = CombineLatestObserver(lock: _lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self._latestElement5 = e }, this: subscription5)
|
||||
let observer6 = CombineLatestObserver(lock: _lock, parent: self, index: 5, setLatestValue: { (e: E6) -> Void in self._latestElement6 = e }, this: subscription6)
|
||||
let observer7 = CombineLatestObserver(lock: _lock, parent: self, index: 6, setLatestValue: { (e: E7) -> Void in self._latestElement7 = e }, this: subscription7)
|
||||
let observer8 = CombineLatestObserver(lock: _lock, parent: self, index: 7, setLatestValue: { (e: E8) -> Void in self._latestElement8 = e }, this: subscription8)
|
||||
|
||||
subscription1.disposable = _parent._source1.subscribe(observer1)
|
||||
subscription2.disposable = _parent._source2.subscribe(observer2)
|
||||
subscription3.disposable = _parent._source3.subscribe(observer3)
|
||||
subscription4.disposable = _parent._source4.subscribe(observer4)
|
||||
subscription5.disposable = _parent._source5.subscribe(observer5)
|
||||
subscription6.disposable = _parent._source6.subscribe(observer6)
|
||||
subscription7.disposable = _parent._source7.subscribe(observer7)
|
||||
subscription8.disposable = _parent._source8.subscribe(observer8)
|
||||
|
||||
return CompositeDisposable(disposables: [
|
||||
subscription1,
|
||||
subscription2,
|
||||
subscription3,
|
||||
subscription4,
|
||||
subscription5,
|
||||
subscription6,
|
||||
subscription7,
|
||||
subscription8
|
||||
])
|
||||
}
|
||||
|
||||
override func getResult() throws -> R {
|
||||
return try _parent._resultSelector(_latestElement1, _latestElement2, _latestElement3, _latestElement4, _latestElement5, _latestElement6, _latestElement7, _latestElement8)
|
||||
}
|
||||
}
|
||||
|
||||
class CombineLatest8<E1, E2, E3, E4, E5, E6, E7, E8, R> : Producer<R> {
|
||||
typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7, E8) throws -> R
|
||||
|
||||
let _source1: Observable<E1>
|
||||
let _source2: Observable<E2>
|
||||
let _source3: Observable<E3>
|
||||
let _source4: Observable<E4>
|
||||
let _source5: Observable<E5>
|
||||
let _source6: Observable<E6>
|
||||
let _source7: Observable<E7>
|
||||
let _source8: Observable<E8>
|
||||
|
||||
let _resultSelector: ResultSelector
|
||||
|
||||
init(source1: Observable<E1>, source2: Observable<E2>, source3: Observable<E3>, source4: Observable<E4>, source5: Observable<E5>, source6: Observable<E6>, source7: Observable<E7>, source8: Observable<E8>, resultSelector: ResultSelector) {
|
||||
_source1 = source1
|
||||
_source2 = source2
|
||||
_source3 = source3
|
||||
_source4 = source4
|
||||
_source5 = source5
|
||||
_source6 = source6
|
||||
_source7 = source7
|
||||
_source8 = source8
|
||||
|
||||
_resultSelector = resultSelector
|
||||
}
|
||||
|
||||
override func run<O: ObserverType where O.E == R>(observer: O) -> Disposable {
|
||||
let sink = CombineLatestSink8_(parent: self, observer: observer)
|
||||
sink.disposable = sink.run()
|
||||
return sink
|
||||
}
|
||||
}
|
@ -0,0 +1,134 @@
|
||||
//
|
||||
// CombineLatest.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 3/21/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol CombineLatestProtocol : class {
|
||||
func next(index: Int)
|
||||
func fail(error: ErrorType)
|
||||
func done(index: Int)
|
||||
}
|
||||
|
||||
class CombineLatestSink<O: ObserverType>
|
||||
: Sink<O>
|
||||
, CombineLatestProtocol {
|
||||
typealias Element = O.E
|
||||
|
||||
let _lock = NSRecursiveLock()
|
||||
|
||||
private let _arity: Int
|
||||
private var _numberOfValues = 0
|
||||
private var _numberOfDone = 0
|
||||
private var _hasValue: [Bool]
|
||||
private var _isDone: [Bool]
|
||||
|
||||
init(arity: Int, observer: O) {
|
||||
_arity = arity
|
||||
_hasValue = [Bool](count: arity, repeatedValue: false)
|
||||
_isDone = [Bool](count: arity, repeatedValue: false)
|
||||
|
||||
super.init(observer: observer)
|
||||
}
|
||||
|
||||
func getResult() throws -> Element {
|
||||
abstractMethod()
|
||||
}
|
||||
|
||||
func next(index: Int) {
|
||||
if !_hasValue[index] {
|
||||
_hasValue[index] = true
|
||||
_numberOfValues += 1
|
||||
}
|
||||
|
||||
if _numberOfValues == _arity {
|
||||
do {
|
||||
let result = try getResult()
|
||||
forwardOn(.Next(result))
|
||||
}
|
||||
catch let e {
|
||||
forwardOn(.Error(e))
|
||||
dispose()
|
||||
}
|
||||
}
|
||||
else {
|
||||
var allOthersDone = true
|
||||
|
||||
for i in 0 ..< _arity {
|
||||
if i != index && !_isDone[i] {
|
||||
allOthersDone = false
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if allOthersDone {
|
||||
forwardOn(.Completed)
|
||||
dispose()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func fail(error: ErrorType) {
|
||||
forwardOn(.Error(error))
|
||||
dispose()
|
||||
}
|
||||
|
||||
func done(index: Int) {
|
||||
if _isDone[index] {
|
||||
return
|
||||
}
|
||||
|
||||
_isDone[index] = true
|
||||
_numberOfDone += 1
|
||||
|
||||
if _numberOfDone == _arity {
|
||||
forwardOn(.Completed)
|
||||
dispose()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class CombineLatestObserver<ElementType>
|
||||
: ObserverType
|
||||
, LockOwnerType
|
||||
, SynchronizedOnType {
|
||||
typealias Element = ElementType
|
||||
typealias ValueSetter = (Element) -> Void
|
||||
|
||||
private let _parent: CombineLatestProtocol
|
||||
|
||||
let _lock: NSRecursiveLock
|
||||
private let _index: Int
|
||||
private let _this: Disposable
|
||||
private let _setLatestValue: ValueSetter
|
||||
|
||||
init(lock: NSRecursiveLock, parent: CombineLatestProtocol, index: Int, setLatestValue: ValueSetter, this: Disposable) {
|
||||
_lock = lock
|
||||
_parent = parent
|
||||
_index = index
|
||||
_this = this
|
||||
_setLatestValue = setLatestValue
|
||||
}
|
||||
|
||||
func on(event: Event<Element>) {
|
||||
synchronizedOn(event)
|
||||
}
|
||||
|
||||
func _synchronized_on(event: Event<Element>) {
|
||||
switch event {
|
||||
case .Next(let value):
|
||||
_setLatestValue(value)
|
||||
_parent.next(_index)
|
||||
case .Error(let error):
|
||||
_this.dispose()
|
||||
_parent.fail(error)
|
||||
case .Completed:
|
||||
_this.dispose()
|
||||
_parent.done(_index)
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,63 @@
|
||||
//
|
||||
// Concat.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 3/21/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
|
||||
class ConcatSink<S: SequenceType, O: ObserverType where S.Generator.Element : ObservableConvertibleType, S.Generator.Element.E == O.E>
|
||||
: TailRecursiveSink<S, O>
|
||||
, ObserverType {
|
||||
typealias Element = O.E
|
||||
|
||||
override init(observer: O) {
|
||||
super.init(observer: observer)
|
||||
}
|
||||
|
||||
func on(event: Event<Element>){
|
||||
switch event {
|
||||
case .Next:
|
||||
forwardOn(event)
|
||||
case .Error:
|
||||
forwardOn(event)
|
||||
dispose()
|
||||
case .Completed:
|
||||
schedule(.MoveNext)
|
||||
}
|
||||
}
|
||||
|
||||
override func subscribeToNext(source: Observable<E>) -> Disposable {
|
||||
return source.subscribe(self)
|
||||
}
|
||||
|
||||
override func extract(observable: Observable<E>) -> SequenceGenerator? {
|
||||
if let source = observable as? Concat<S> {
|
||||
return (source._sources.generate(), source._count)
|
||||
}
|
||||
else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Concat<S: SequenceType where S.Generator.Element : ObservableConvertibleType> : Producer<S.Generator.Element.E> {
|
||||
typealias Element = S.Generator.Element.E
|
||||
|
||||
private let _sources: S
|
||||
private let _count: IntMax?
|
||||
|
||||
init(sources: S, count: IntMax?) {
|
||||
_sources = sources
|
||||
_count = count
|
||||
}
|
||||
|
||||
override func run<O: ObserverType where O.E == Element>(observer: O) -> Disposable {
|
||||
let sink = ConcatSink<S, O>(observer: observer)
|
||||
sink.disposable = sink.run((_sources.generate(), _count))
|
||||
return sink
|
||||
}
|
||||
}
|
@ -0,0 +1,96 @@
|
||||
//
|
||||
// ConnectableObservable.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 3/1/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Represents an observable wrapper that can be connected and disconnected from its underlying observable sequence.
|
||||
*/
|
||||
public class ConnectableObservable<Element>
|
||||
: Observable<Element>
|
||||
, ConnectableObservableType {
|
||||
|
||||
/**
|
||||
Connects the observable wrapper to its source. All subscribed observers will receive values from the underlying observable sequence as long as the connection is established.
|
||||
|
||||
- returns: Disposable used to disconnect the observable wrapper from its source, causing subscribed observer to stop receiving values from the underlying observable sequence.
|
||||
*/
|
||||
public func connect() -> Disposable {
|
||||
abstractMethod()
|
||||
}
|
||||
}
|
||||
|
||||
class Connection<S: SubjectType> : Disposable {
|
||||
|
||||
private var _lock: NSRecursiveLock
|
||||
// state
|
||||
private var _parent: ConnectableObservableAdapter<S>?
|
||||
private var _subscription : Disposable?
|
||||
|
||||
init(parent: ConnectableObservableAdapter<S>, lock: NSRecursiveLock, subscription: Disposable) {
|
||||
_parent = parent
|
||||
_subscription = subscription
|
||||
_lock = lock
|
||||
}
|
||||
|
||||
func dispose() {
|
||||
_lock.lock(); defer { _lock.unlock() } // {
|
||||
guard let parent = _parent else {
|
||||
return
|
||||
}
|
||||
|
||||
guard let oldSubscription = _subscription else {
|
||||
return
|
||||
}
|
||||
|
||||
_subscription = nil
|
||||
if parent._connection === self {
|
||||
parent._connection = nil
|
||||
}
|
||||
_parent = nil
|
||||
|
||||
oldSubscription.dispose()
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
class ConnectableObservableAdapter<S: SubjectType>
|
||||
: ConnectableObservable<S.E> {
|
||||
typealias ConnectionType = Connection<S>
|
||||
|
||||
private let _subject: S
|
||||
private let _source: Observable<S.SubjectObserverType.E>
|
||||
|
||||
private let _lock = NSRecursiveLock()
|
||||
|
||||
// state
|
||||
private var _connection: ConnectionType?
|
||||
|
||||
init(source: Observable<S.SubjectObserverType.E>, subject: S) {
|
||||
_source = source
|
||||
_subject = subject
|
||||
_connection = nil
|
||||
}
|
||||
|
||||
override func connect() -> Disposable {
|
||||
return _lock.calculateLocked {
|
||||
if let connection = _connection {
|
||||
return connection
|
||||
}
|
||||
|
||||
let disposable = _source.subscribe(_subject.asObserver())
|
||||
let connection = Connection(parent: self, lock: _lock, subscription: disposable)
|
||||
_connection = connection
|
||||
return connection
|
||||
}
|
||||
}
|
||||
|
||||
override func subscribe<O : ObserverType where O.E == S.E>(observer: O) -> Disposable {
|
||||
return _subject.subscribe(observer)
|
||||
}
|
||||
}
|
@ -0,0 +1,77 @@
|
||||
//
|
||||
// Debug.swift
|
||||
// RxSwift
|
||||
//
|
||||
// Created by Krunoslav Zaher on 5/2/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
let dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
|
||||
|
||||
func logEvent(identifier: String, dateFormat: NSDateFormatter, content: String) {
|
||||
print("\(dateFormat.stringFromDate(NSDate())): \(identifier) -> \(content)")
|
||||
}
|
||||
|
||||
class Debug_<O: ObserverType> : Sink<O>, ObserverType {
|
||||
typealias Element = O.E
|
||||
typealias Parent = Debug<Element>
|
||||
|
||||
private let _parent: Parent
|
||||
private let _timestampFormatter = NSDateFormatter()
|
||||
|
||||
init(parent: Parent, observer: O) {
|
||||
_parent = parent
|
||||
_timestampFormatter.dateFormat = dateFormat
|
||||
|
||||
logEvent(_parent._identifier, dateFormat: _timestampFormatter, content: "subscribed")
|
||||
|
||||
super.init(observer: observer)
|
||||
}
|
||||
|
||||
func on(event: Event<Element>) {
|
||||
let maxEventTextLength = 40
|
||||
let eventText = "\(event)"
|
||||
let eventNormalized = eventText.characters.count > maxEventTextLength
|
||||
? String(eventText.characters.prefix(maxEventTextLength / 2)) + "..." + String(eventText.characters.suffix(maxEventTextLength / 2))
|
||||
: eventText
|
||||
|
||||
logEvent(_parent._identifier, dateFormat: _timestampFormatter, content: "Event \(eventNormalized)")
|
||||
forwardOn(event)
|
||||
}
|
||||
|
||||
override func dispose() {
|
||||
logEvent(_parent._identifier, dateFormat: _timestampFormatter, content: "disposed")
|
||||
super.dispose()
|
||||
}
|
||||
}
|
||||
|
||||
class Debug<Element> : Producer<Element> {
|
||||
private let _identifier: String
|
||||
|
||||
private let _source: Observable<Element>
|
||||
|
||||
init(source: Observable<Element>, identifier: String?, file: String, line: UInt, function: String) {
|
||||
if let identifier = identifier {
|
||||
_identifier = identifier
|
||||
}
|
||||
else {
|
||||
let trimmedFile: String
|
||||
if let lastIndex = file.lastIndexOf("/") {
|
||||
trimmedFile = file[lastIndex.successor() ..< file.endIndex]
|
||||
}
|
||||
else {
|
||||
trimmedFile = file
|
||||
}
|
||||
_identifier = "\(trimmedFile):\(line) (\(function))"
|
||||
}
|
||||
_source = source
|
||||
}
|
||||
|
||||
override func run<O: ObserverType where O.E == Element>(observer: O) -> Disposable {
|
||||
let sink = Debug_(parent: self, observer: observer)
|
||||
sink.disposable = _source.subscribe(sink)
|
||||
return sink
|
||||
}
|
||||
}
|
@ -0,0 +1,61 @@
|
||||
//
|
||||
// Deferred.swift
|
||||
// RxSwift
|
||||
//
|
||||
// Created by Krunoslav Zaher on 4/19/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
class DeferredSink<S: ObservableType, O: ObserverType where S.E == O.E> : Sink<O>, ObserverType {
|
||||
typealias E = O.E
|
||||
|
||||
private let _observableFactory: () throws -> S
|
||||
|
||||
init(observableFactory: () throws -> S, observer: O) {
|
||||
_observableFactory = observableFactory
|
||||
super.init(observer: observer)
|
||||
}
|
||||
|
||||
func run() -> Disposable {
|
||||
do {
|
||||
let result = try _observableFactory()
|
||||
return result.subscribe(self)
|
||||
}
|
||||
catch let e {
|
||||
forwardOn(.Error(e))
|
||||
dispose()
|
||||
return NopDisposable.instance
|
||||
}
|
||||
}
|
||||
|
||||
func on(event: Event<E>) {
|
||||
forwardOn(event)
|
||||
|
||||
switch event {
|
||||
case .Next:
|
||||
break
|
||||
case .Error:
|
||||
dispose()
|
||||
case .Completed:
|
||||
dispose()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Deferred<S: ObservableType> : Producer<S.E> {
|
||||
typealias Factory = () throws -> S
|
||||
|
||||
private let _observableFactory : Factory
|
||||
|
||||
init(observableFactory: Factory) {
|
||||
_observableFactory = observableFactory
|
||||
}
|
||||
|
||||
override func run<O: ObserverType where O.E == S.E>(observer: O) -> Disposable {
|
||||
let sink = DeferredSink(observableFactory: _observableFactory, observer: observer)
|
||||
sink.disposable = sink.run()
|
||||
return sink
|
||||
}
|
||||
}
|
@ -0,0 +1,52 @@
|
||||
//
|
||||
// DelaySubscription.swift
|
||||
// RxSwift
|
||||
//
|
||||
// Created by Krunoslav Zaher on 6/14/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
class DelaySubscriptionSink<ElementType, O: ObserverType where O.E == ElementType>
|
||||
: Sink<O>
|
||||
, ObserverType {
|
||||
typealias Parent = DelaySubscription<ElementType>
|
||||
typealias E = O.E
|
||||
|
||||
private let _parent: Parent
|
||||
|
||||
init(parent: Parent, observer: O) {
|
||||
_parent = parent
|
||||
super.init(observer: observer)
|
||||
}
|
||||
|
||||
func on(event: Event<E>) {
|
||||
forwardOn(event)
|
||||
if event.isStopEvent {
|
||||
dispose()
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class DelaySubscription<Element>: Producer<Element> {
|
||||
private let _source: Observable<Element>
|
||||
private let _dueTime: RxTimeInterval
|
||||
private let _scheduler: SchedulerType
|
||||
|
||||
init(source: Observable<Element>, dueTime: RxTimeInterval, scheduler: SchedulerType) {
|
||||
_source = source
|
||||
_dueTime = dueTime
|
||||
_scheduler = scheduler
|
||||
}
|
||||
|
||||
override func run<O : ObserverType where O.E == Element>(observer: O) -> Disposable {
|
||||
let sink = DelaySubscriptionSink(parent: self, observer: observer)
|
||||
sink.disposable = _scheduler.scheduleRelative((), dueTime: _dueTime) { _ in
|
||||
return self._source.subscribe(sink)
|
||||
}
|
||||
|
||||
return sink
|
||||
}
|
||||
}
|
@ -0,0 +1,70 @@
|
||||
//
|
||||
// DistinctUntilChanged.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 3/15/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
class DistinctUntilChangedSink<O: ObserverType, Key>: Sink<O>, ObserverType {
|
||||
typealias E = O.E
|
||||
|
||||
private let _parent: DistinctUntilChanged<E, Key>
|
||||
private var _currentKey: Key? = nil
|
||||
|
||||
init(parent: DistinctUntilChanged<E, Key>, observer: O) {
|
||||
_parent = parent
|
||||
super.init(observer: observer)
|
||||
}
|
||||
|
||||
func on(event: Event<E>) {
|
||||
switch event {
|
||||
case .Next(let value):
|
||||
do {
|
||||
let key = try _parent._selector(value)
|
||||
var areEqual = false
|
||||
if let currentKey = _currentKey {
|
||||
areEqual = try _parent._comparer(currentKey, key)
|
||||
}
|
||||
|
||||
if areEqual {
|
||||
return
|
||||
}
|
||||
|
||||
_currentKey = key
|
||||
|
||||
forwardOn(event)
|
||||
}
|
||||
catch let error {
|
||||
forwardOn(.Error(error))
|
||||
dispose()
|
||||
}
|
||||
case .Error, .Completed:
|
||||
forwardOn(event)
|
||||
dispose()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class DistinctUntilChanged<Element, Key>: Producer<Element> {
|
||||
typealias KeySelector = (Element) throws -> Key
|
||||
typealias EqualityComparer = (Key, Key) throws -> Bool
|
||||
|
||||
private let _source: Observable<Element>
|
||||
private let _selector: KeySelector
|
||||
private let _comparer: EqualityComparer
|
||||
|
||||
init(source: Observable<Element>, selector: KeySelector, comparer: EqualityComparer) {
|
||||
_source = source
|
||||
_selector = selector
|
||||
_comparer = comparer
|
||||
}
|
||||
|
||||
override func run<O: ObserverType where O.E == Element>(observer: O) -> Disposable {
|
||||
let sink = DistinctUntilChangedSink(parent: self, observer: observer)
|
||||
sink.disposable = _source.subscribe(sink)
|
||||
return sink
|
||||
}
|
||||
}
|
@ -0,0 +1,53 @@
|
||||
//
|
||||
// Do.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Krunoslav Zaher on 2/21/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
class DoSink<O: ObserverType> : Sink<O>, ObserverType {
|
||||
typealias Element = O.E
|
||||
typealias Parent = Do<Element>
|
||||
|
||||
private let _parent: Parent
|
||||
|
||||
init(parent: Parent, observer: O) {
|
||||
_parent = parent
|
||||
super.init(observer: observer)
|
||||
}
|
||||
|
||||
func on(event: Event<Element>) {
|
||||
do {
|
||||
try _parent._eventHandler(event)
|
||||
forwardOn(event)
|
||||
if event.isStopEvent {
|
||||
dispose()
|
||||
}
|
||||
}
|
||||
catch let error {
|
||||
forwardOn(.Error(error))
|
||||
dispose()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Do<Element> : Producer<Element> {
|
||||
typealias EventHandler = Event<Element> throws -> Void
|
||||
|
||||
private let _source: Observable<Element>
|
||||
private let _eventHandler: EventHandler
|
||||
|
||||
init(source: Observable<Element>, eventHandler: EventHandler) {
|
||||
_source = source
|
||||
_eventHandler = eventHandler
|
||||
}
|
||||
|
||||
override func run<O: ObserverType where O.E == Element>(observer: O) -> Disposable {
|
||||
let sink = DoSink(parent: self, observer: observer)
|
||||
sink.disposable = _source.subscribe(sink)
|
||||
return sink
|
||||
}
|
||||
}
|
@ -0,0 +1,79 @@
|
||||
//
|
||||
// ElementAt.swift
|
||||
// Rx
|
||||
//
|
||||
// Created by Junior B. on 21/10/15.
|
||||
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
|
||||
class ElementAtSink<SourceType, O: ObserverType where O.E == SourceType> : Sink<O>, ObserverType {
|
||||
typealias Parent = ElementAt<SourceType>
|
||||
|
||||
let _parent: Parent
|
||||
var _i: Int
|
||||
|
||||
init(parent: Parent, observer: O) {
|
||||
_parent = parent
|
||||
_i = parent._index
|
||||
|
||||
super.init(observer: observer)
|
||||
}
|
||||
|
||||
func on(event: Event<SourceType>) {
|
||||
switch event {
|
||||
case .Next(_):
|
||||
|
||||
if (_i == 0) {
|
||||
forwardOn(event)
|
||||
forwardOn(.Completed)
|
||||
self.dispose()
|
||||
}
|
||||
|
||||
do {
|
||||
try decrementChecked(&_i)
|
||||
} catch(let e) {
|
||||
forwardOn(.Error(e))
|
||||
dispose()
|
||||
return
|
||||
}
|
||||
|
||||
case .Error(let e):
|
||||
forwardOn(.Error(e))
|
||||
self.dispose()
|
||||
case .Completed:
|
||||
if (_parent._throwOnEmpty) {
|
||||
forwardOn(.Error(RxError.ArgumentOutOfRange))
|
||||
} else {
|
||||
forwardOn(.Completed)
|
||||
}
|
||||
|
||||
self.dispose()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class ElementAt<SourceType> : Producer<SourceType> {
|
||||
|
||||
let _source: Observable<SourceType>
|
||||
let _throwOnEmpty: Bool
|
||||
let _index: Int
|
||||
|
||||
init(source: Observable<SourceType>, index: Int, throwOnEmpty: Bool) {
|
||||
if index < 0 {
|
||||
rxFatalError("index can't be negative")
|
||||
}
|
||||
|
||||
self._source = source
|
||||
self._index = index
|
||||
self._throwOnEmpty = throwOnEmpty
|
||||
}
|
||||
|
||||
override func run<O: ObserverType where O.E == SourceType>(observer: O) -> Disposable {
|
||||
let sink = ElementAtSink(parent: self, observer: observer)
|
||||
sink.disposable = _source.subscribeSafe(sink)
|
||||
return sink
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user