diff --git a/README.md b/README.md index 4e51201deb..76855c8c0a 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ ## Overview This is the swagger codegen project, which allows generation of API client libraries (SDK generation), server stubs and documentation automatically given an [OpenAPI Spec](https://github.com/OAI/OpenAPI-Specification). Currently, the following languages/frameworks are supported: -- **API clients**: **ActionScript**, **Apex**, **Bash**, **C#** (.net 2.0, 4.0 or later), **C++** (cpprest, Qt5, Tizen), **Clojure**, **Dart**, **Elixir**, **Go**, **Groovy**, **Haskell**, **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign), **Kotlin**, **Node.js** (ES5, ES6, AngularJS with Google Closure Compiler annotations) **Objective-C**, **Perl**, **PHP**, **PowerShell**, **Python**, **Ruby**, **Scala**, **Swift** (2.x, 3.x), **Typescript** (Angular1.x, Angular2.x, Fetch, jQuery, Node) +- **API clients**: **ActionScript**, **Apex**, **Bash**, **C#** (.net 2.0, 4.0 or later), **C++** (cpprest, Qt5, Tizen), **Clojure**, **Dart**, **Elixir**, **Go**, **Groovy**, **Haskell**, **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy), **Kotlin**, **Node.js** (ES5, ES6, AngularJS with Google Closure Compiler annotations) **Objective-C**, **Perl**, **PHP**, **PowerShell**, **Python**, **Ruby**, **Scala**, **Swift** (2.x, 3.x, 4.x), **Typescript** (Angular1.x, Angular2.x, Fetch, jQuery, Node) - **Server stubs**: **C#** (ASP.NET Core, NancyFx), **C++** (Pistache, Restbed), **Erlang**, **Go**, **Haskell**, **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, RestEasy, Play Framework), **PHP** (Lumen, Slim, Silex, [Symfony](https://symfony.com/), [Zend Expressive](https://github.com/zendframework/zend-expressive)), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Scala** ([Finch](https://github.com/finagle/finch), Scalatra) - **API documentation generators**: **HTML**, **Confluence Wiki** - **Configuration files**: [**Apache2**](https://httpd.apache.org/) @@ -942,6 +942,7 @@ Here is a list of template creators: * PowerShell: @beatcracker * Swift: @tkqubo * Swift 3: @hexelon + * Swift 4: @ehyche * TypeScript (Node): @mhardorf * TypeScript (Angular1): @mhardorf * TypeScript (Fetch): @leonyu diff --git a/bin/swift4-petstore-all.sh b/bin/swift4-petstore-all.sh new file mode 100755 index 0000000000..88d870bb58 --- /dev/null +++ b/bin/swift4-petstore-all.sh @@ -0,0 +1,40 @@ +#!/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/swift4 -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l swift4 -c ./bin/swift4-petstore.json -o samples/client/petstore/swift4/default" + +echo "#### Petstore Swift API client (default) ####" +java $JAVA_OPTS -jar $executable $ags + +ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift4 -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l swift4 -c ./bin/swift4-petstore-promisekit.json -o samples/client/petstore/swift4/promisekit" +echo "#### Petstore Swift API client (promisekit) ####" +java $JAVA_OPTS -jar $executable $ags + +ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift4 -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l swift4 -c ./bin/swift4-petstore-rxswift.json -o samples/client/petstore/swift4/rxswift" +echo "#### Petstore Swift API client (rxswift) ####" +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/swift4-petstore-promisekit.json b/bin/swift4-petstore-promisekit.json new file mode 100644 index 0000000000..1211352cc5 --- /dev/null +++ b/bin/swift4-petstore-promisekit.json @@ -0,0 +1,7 @@ +{ + "podSummary": "PetstoreClient", + "podHomepage": "https://github.com/swagger-api/swagger-codegen", + "podAuthors": "", + "projectName": "PetstoreClient", + "responseAs": "PromiseKit" +} \ No newline at end of file diff --git a/bin/swift4-petstore-promisekit.sh b/bin/swift4-petstore-promisekit.sh new file mode 100755 index 0000000000..fcf2362286 --- /dev/null +++ b/bin/swift4-petstore-promisekit.sh @@ -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/swift4 -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l swift4 -c ./bin/swift4-petstore-promisekit.json -o samples/client/petstore/swift4/promisekit" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/swift4-petstore-rxswift.json b/bin/swift4-petstore-rxswift.json new file mode 100644 index 0000000000..3a81d53dee --- /dev/null +++ b/bin/swift4-petstore-rxswift.json @@ -0,0 +1,7 @@ +{ + "podSummary": "PetstoreClient", + "podHomepage": "https://github.com/swagger-api/swagger-codegen", + "podAuthors": "", + "projectName": "PetstoreClient", + "responseAs": "RxSwift" +} diff --git a/bin/swift4-petstore-rxswift.sh b/bin/swift4-petstore-rxswift.sh new file mode 100755 index 0000000000..f82e86d56c --- /dev/null +++ b/bin/swift4-petstore-rxswift.sh @@ -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/swift4 -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l swift4 -c ./bin/swift4-petstore-rxswift.json -o samples/client/petstore/swift4/rxswift" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/swift4-petstore.json b/bin/swift4-petstore.json new file mode 100644 index 0000000000..3d9ecfd5d0 --- /dev/null +++ b/bin/swift4-petstore.json @@ -0,0 +1,6 @@ +{ + "podSummary": "PetstoreClient", + "podHomepage": "https://github.com/swagger-api/swagger-codegen", + "podAuthors": "", + "projectName": "PetstoreClient" +} \ No newline at end of file diff --git a/bin/swift4-petstore.sh b/bin/swift4-petstore.sh new file mode 100755 index 0000000000..8708fd394e --- /dev/null +++ b/bin/swift4-petstore.sh @@ -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/swift4 -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l swift4 -c ./bin/swift4-petstore.json -o samples/client/petstore/swift4/default" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/windows/swift4-petstore-all.bat b/bin/windows/swift4-petstore-all.bat new file mode 100755 index 0000000000..bf485d27e5 --- /dev/null +++ b/bin/windows/swift4-petstore-all.bat @@ -0,0 +1,3 @@ +call .\bin\windows\swift4-petstore.bat +call .\bin\windows\swift4-petstore-promisekit.bat +call .\bin\windows\swift4-petstore-rxswift.bat diff --git a/bin/windows/swift4-petstore-promisekit.bat b/bin/windows/swift4-petstore-promisekit.bat new file mode 100755 index 0000000000..855bc89434 --- /dev/null +++ b/bin/windows/swift4-petstore-promisekit.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M +set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -l swift4 -c bin\swift4-petstore-promisekit.json -o samples\client\petstore\swift4\promisekit + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/swift4-petstore-rxswift.bat b/bin/windows/swift4-petstore-rxswift.bat new file mode 100755 index 0000000000..63b258a49b --- /dev/null +++ b/bin/windows/swift4-petstore-rxswift.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M +set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -l swift4 -c bin\swift4-petstore-rxswift.json -o samples\client\petstore\swift4\rxswift + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/swift4-petstore.bat b/bin/windows/swift4-petstore.bat new file mode 100755 index 0000000000..deaf755915 --- /dev/null +++ b/bin/windows/swift4-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M +set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -l swift4 -o samples\client\petstore\swift4\default + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift4Codegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift4Codegen.java new file mode 100644 index 0000000000..ed6fc2d123 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift4Codegen.java @@ -0,0 +1,640 @@ +package io.swagger.codegen.languages; + +import com.google.common.base.Predicate; +import com.google.common.collect.Iterators; +import com.google.common.collect.Lists; +import io.swagger.codegen.*; +import io.swagger.models.Model; +import io.swagger.models.ModelImpl; +import io.swagger.models.Operation; +import io.swagger.models.Swagger; +import io.swagger.models.parameters.HeaderParameter; +import io.swagger.models.parameters.Parameter; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.text.WordUtils; + +import javax.annotation.Nullable; +import java.io.File; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class Swift4Codegen extends DefaultCodegen implements CodegenConfig { + public static final String PROJECT_NAME = "projectName"; + public static final String RESPONSE_AS = "responseAs"; + public static final String UNWRAP_REQUIRED = "unwrapRequired"; + public static final String POD_SOURCE = "podSource"; + public static final String POD_AUTHORS = "podAuthors"; + public static final String POD_SOCIAL_MEDIA_URL = "podSocialMediaURL"; + public static final String POD_DOCSET_URL = "podDocsetURL"; + public static final String POD_LICENSE = "podLicense"; + public static final String POD_HOMEPAGE = "podHomepage"; + public static final String POD_SUMMARY = "podSummary"; + public static final String POD_DESCRIPTION = "podDescription"; + public static final String POD_SCREENSHOTS = "podScreenshots"; + public static final String POD_DOCUMENTATION_URL = "podDocumentationURL"; + public static final String SWIFT_USE_API_NAMESPACE = "swiftUseApiNamespace"; + public static final String DEFAULT_POD_AUTHORS = "Swagger Codegen"; + public static final String LENIENT_TYPE_CAST = "lenientTypeCast"; + protected static final String LIBRARY_PROMISE_KIT = "PromiseKit"; + 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 lenientTypeCast = false; + protected boolean swiftUseApiNamespace; + protected String[] responseAs = new String[0]; + protected String sourceFolder = "Classes" + File.separator + "Swaggers"; + + @Override + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + @Override + public String getName() { + return "swift4"; + } + + @Override + public String getHelp() { + return "Generates a swift client library."; + } + + @Override + protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, ModelImpl swaggerModel) { + + final Property additionalProperties = swaggerModel.getAdditionalProperties(); + + if(additionalProperties != null) { + codegenModel.additionalPropertiesType = getSwaggerType(additionalProperties); + } + } + + public Swift4Codegen() { + super(); + outputFolder = "generated-code" + File.separator + "swift"; + modelTemplateFiles.put("model.mustache", ".swift"); + apiTemplateFiles.put("api.mustache", ".swift"); + embeddedTemplateDir = templateDir = "swift4"; + apiPackage = File.separator + "APIs"; + modelPackage = File.separator + "Models"; + + languageSpecificPrimitives = new HashSet<>( + Arrays.asList( + "Int", + "Int32", + "Int64", + "Float", + "Double", + "Bool", + "Void", + "String", + "Character", + "AnyObject", + "Any") + ); + defaultIncludes = new HashSet<>( + Arrays.asList( + "Data", + "Date", + "URL", // for file + "UUID", + "Array", + "Dictionary", + "Set", + "Any", + "Empty", + "AnyObject", + "Any") + ); + reservedWords = new HashSet<>( + Arrays.asList( + // name used by swift client + "ErrorResponse", "Response", + + // swift keywords + "Int", "Int32", "Int64", "Int64", "Float", "Double", "Bool", "Void", "String", "Character", "AnyObject", "Any", "Error", "URL", + "class", "Class", "break", "as", "associativity", "deinit", "case", "dynamicType", "convenience", "enum", "continue", + "false", "dynamic", "extension", "default", "is", "didSet", "func", "do", "nil", "final", "import", "else", + "self", "get", "init", "fallthrough", "Self", "infix", "internal", "for", "super", "inout", "let", "if", + "true", "lazy", "operator", "in", "COLUMN", "left", "private", "return", "FILE", "mutating", "protocol", + "switch", "FUNCTION", "none", "public", "where", "LINE", "nonmutating", "static", "while", "optional", + "struct", "override", "subscript", "postfix", "typealias", "precedence", "var", "prefix", "Protocol", + "required", "right", "set", "Type", "unowned", "weak", "Codable", "Encodable", "Decodable") + ); + + typeMapping = new HashMap<>(); + typeMapping.put("array", "Array"); + typeMapping.put("List", "Array"); + typeMapping.put("map", "Dictionary"); + typeMapping.put("date", "Date"); + typeMapping.put("Date", "Date"); + typeMapping.put("DateTime", "Date"); + typeMapping.put("boolean", "Bool"); + typeMapping.put("string", "String"); + typeMapping.put("char", "Character"); + typeMapping.put("short", "Int"); + typeMapping.put("int", "Int32"); + typeMapping.put("long", "Int64"); + typeMapping.put("integer", "Int32"); + typeMapping.put("Integer", "Int32"); + typeMapping.put("float", "Float"); + typeMapping.put("number", "Double"); + typeMapping.put("double", "Double"); + typeMapping.put("object", "Any"); + typeMapping.put("file", "URL"); + typeMapping.put("binary", "Data"); + typeMapping.put("ByteArray", "Data"); + typeMapping.put("UUID", "UUID"); + + importMapping = new HashMap<>(); + + cliOptions.add(new CliOption(PROJECT_NAME, "Project name in Xcode")); + cliOptions.add(new CliOption(RESPONSE_AS, "Optionally use libraries to manage response. Currently " + + StringUtils.join(RESPONSE_LIBRARIES, ", ") + " are available.")); + cliOptions.add(new CliOption(UNWRAP_REQUIRED, "Treat 'required' properties in response as non-optional " + + "(which would crash the app if api returns null as opposed to required option specified in json schema")); + cliOptions.add(new CliOption(POD_SOURCE, "Source information used for Podspec")); + cliOptions.add(new CliOption(CodegenConstants.POD_VERSION, "Version used for Podspec")); + cliOptions.add(new CliOption(POD_AUTHORS, "Authors used for Podspec")); + cliOptions.add(new CliOption(POD_SOCIAL_MEDIA_URL, "Social Media URL used for Podspec")); + cliOptions.add(new CliOption(POD_DOCSET_URL, "Docset URL used for Podspec")); + cliOptions.add(new CliOption(POD_LICENSE, "License used for Podspec")); + cliOptions.add(new CliOption(POD_HOMEPAGE, "Homepage used for Podspec")); + cliOptions.add(new CliOption(POD_SUMMARY, "Summary used for Podspec")); + cliOptions.add(new CliOption(POD_DESCRIPTION, "Description used for Podspec")); + cliOptions.add(new CliOption(POD_SCREENSHOTS, "Screenshots used for Podspec")); + cliOptions.add(new CliOption(POD_DOCUMENTATION_URL, "Documentation URL used for Podspec")); + cliOptions.add(new CliOption(SWIFT_USE_API_NAMESPACE, "Flag to make all the API classes inner-class of {{projectName}}API")); + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") + .defaultValue(Boolean.TRUE.toString())); + cliOptions.add(new CliOption(LENIENT_TYPE_CAST, "Accept and cast values for simple types (string->bool, string->int, int->string)") + .defaultValue(Boolean.FALSE.toString())); + } + + @Override + public void processOpts() { + super.processOpts(); + + // default HIDE_GENERATION_TIMESTAMP to true + if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); + } else { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + } + + // Setup project name + if (additionalProperties.containsKey(PROJECT_NAME)) { + setProjectName((String) additionalProperties.get(PROJECT_NAME)); + } else { + additionalProperties.put(PROJECT_NAME, projectName); + } + sourceFolder = projectName + File.separator + sourceFolder; + + // Setup unwrapRequired option, which makes all the properties with "required" non-optional + if (additionalProperties.containsKey(UNWRAP_REQUIRED)) { + setUnwrapRequired(convertPropertyToBooleanAndWriteBack(UNWRAP_REQUIRED)); + } + additionalProperties.put(UNWRAP_REQUIRED, unwrapRequired); + + // Setup unwrapRequired option, which makes all the properties with "required" non-optional + if (additionalProperties.containsKey(RESPONSE_AS)) { + Object responseAsObject = additionalProperties.get(RESPONSE_AS); + if (responseAsObject instanceof String) { + setResponseAs(((String) responseAsObject).split(",")); + } else { + setResponseAs((String[]) responseAsObject); + } + } + additionalProperties.put(RESPONSE_AS, responseAs); + 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)) { + setSwiftUseApiNamespace(convertPropertyToBooleanAndWriteBack(SWIFT_USE_API_NAMESPACE)); + } + + if (!additionalProperties.containsKey(POD_AUTHORS)) { + additionalProperties.put(POD_AUTHORS, DEFAULT_POD_AUTHORS); + } + + setLenientTypeCast(convertPropertyToBooleanAndWriteBack(LENIENT_TYPE_CAST)); + + supportingFiles.add(new SupportingFile("Podspec.mustache", "", projectName + ".podspec")); + supportingFiles.add(new SupportingFile("Cartfile.mustache", "", "Cartfile")); + supportingFiles.add(new SupportingFile("APIHelper.mustache", sourceFolder, "APIHelper.swift")); + supportingFiles.add(new SupportingFile("AlamofireImplementations.mustache", sourceFolder, + "AlamofireImplementations.swift")); + supportingFiles.add(new SupportingFile("Configuration.mustache", sourceFolder, "Configuration.swift")); + supportingFiles.add(new SupportingFile("Extensions.mustache", sourceFolder, "Extensions.swift")); + supportingFiles.add(new SupportingFile("Models.mustache", sourceFolder, "Models.swift")); + supportingFiles.add(new SupportingFile("APIs.mustache", sourceFolder, "APIs.swift")); + supportingFiles.add(new SupportingFile("CodableHelper.mustache", sourceFolder, "CodableHelper.swift")); + supportingFiles.add(new SupportingFile("JSONEncodableEncoding.mustache", sourceFolder, "JSONEncodableEncoding.swift")); + supportingFiles.add(new SupportingFile("JSONEncodingHelper.mustache", sourceFolder, "JSONEncodingHelper.swift")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + + } + + @Override + protected boolean isReservedWord(String word) { + return word != null && reservedWords.contains(word); //don't lowercase as super does + } + + @Override + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return "_" + name; // add an underscore to the name + } + + @Override + public String modelFileFolder() { + return outputFolder + File.separator + sourceFolder + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separator + sourceFolder + apiPackage().replace('.', File.separatorChar); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return "[String:" + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type) || defaultIncludes.contains(type)) + return type; + } else + type = swaggerType; + return toModelName(type); + } + + @Override + public boolean isDataTypeFile(String dataType) { + return dataType != null && dataType.equals("URL"); + } + + @Override + public boolean isDataTypeBinary(final String dataType) { + return dataType != null && dataType.equals("Data"); + } + + /** + * Output the proper model name (capitalized) + * + * @param name the name of the model + * @return capitalized model name + */ + @Override + public String toModelName(String name) { + name = sanitizeName(name); // FIXME parameter should not be assigned. Also declare it as "final" + + if (!StringUtils.isEmpty(modelNameSuffix)) { // set model suffix + name = name + "_" + modelNameSuffix; + } + + if (!StringUtils.isEmpty(modelNamePrefix)) { // set model prefix + name = modelNamePrefix + "_" + name; + } + + // camelize the model name + // phone_number => PhoneNumber + name = camelize(name); + + // model name cannot use reserved keyword, e.g. return + if (isReservedWord(name)) { + String modelName = "Model" + name; + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName); + return modelName; + } + + // model name starts with number + if (name.matches("^\\d.*")) { + String modelName = "Model" + name; // e.g. 200Response => Model200Response (after camelize) + LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); + return modelName; + } + + return name; + } + + /** + * Return the capitalized file name of the model + * + * @param name the model name + * @return the file name of the model + */ + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); + } + + @Override + public String toDefaultValue(Property p) { + // nil + return null; + } + + @Override + public String toInstantiationType(Property p) { + if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return inner; + } else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return "[" + inner + "]"; + } + return null; + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) + return "DefaultAPI"; + return initialCaps(name) + "API"; + } + + @Override + public String toOperationId(String operationId) { + operationId = camelize(sanitizeName(operationId), true); + + // throw exception if method name is empty. This should not happen but keep the check just in case + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method name (operationId) not allowed"); + } + + // method name cannot use reserved keyword, e.g. return + if (isReservedWord(operationId)) { + String newOperationId = camelize(("call_" + operationId), true); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); + return newOperationId; + } + + return operationId; + } + + @Override + public String toVarName(String name) { + // sanitize name + name = sanitizeName(name); + + // if it's all uppper case, do nothing + if (name.matches("^[A-Z_]*$")) { + return name; + } + + // camelize the variable name + // pet_id => petId + name = camelize(name, true); + + // for reserved word or word starting with number, append _ + if (isReservedWord(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } + + return name; + } + + @Override + public String toParamName(String name) { + // sanitize name + name = sanitizeName(name); + + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); + + // if it's all uppper case, do nothing + if (name.matches("^[A-Z_]*$")) { + return name; + } + + // camelize(lower) the variable name + // pet_id => petId + name = camelize(name, true); + + // for reserved word or word starting with number, append _ + if (isReservedWord(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } + + return name; + } + + @Override + public CodegenModel fromModel(String name, Model model, Map allDefinitions) { + CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); + if(codegenModel.description != null) { + codegenModel.imports.add("ApiModel"); + } + if (allDefinitions != null) { + String parentSchema = codegenModel.parentSchema; + + // multilevel inheritance: reconcile properties of all the parents + while (parentSchema != null) { + final Model parentModel = allDefinitions.get(parentSchema); + final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel, allDefinitions); + codegenModel = Swift4Codegen.reconcileProperties(codegenModel, parentCodegenModel); + + // get the next parent + parentSchema = parentCodegenModel.parentSchema; + } + } + + return codegenModel; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + public void setUnwrapRequired(boolean unwrapRequired) { + this.unwrapRequired = unwrapRequired; + } + + public void setLenientTypeCast(boolean lenientTypeCast) { + this.lenientTypeCast = lenientTypeCast; + } + + public void setResponseAs(String[] responseAs) { + this.responseAs = responseAs; + } + + public void setSwiftUseApiNamespace(boolean swiftUseApiNamespace) { + this.swiftUseApiNamespace = swiftUseApiNamespace; + } + + @Override + public String toEnumValue(String value, String datatype) { + return String.valueOf(value); + } + + @Override + public String toEnumDefaultValue(String value, String datatype) { + return datatype + "_" + value; + } + + @Override + public String toEnumVarName(String name, String datatype) { + if (name.length() == 0) { + return "empty"; + } + + Pattern startWithNumberPattern = Pattern.compile("^\\d+"); + Matcher startWithNumberMatcher = startWithNumberPattern.matcher(name); + if (startWithNumberMatcher.find()) { + String startingNumbers = startWithNumberMatcher.group(0); + String nameWithoutStartingNumbers = name.substring(startingNumbers.length()); + + return "_" + startingNumbers + camelize(nameWithoutStartingNumbers, true); + } + + // for symbol, e.g. $, # + if (getSymbolName(name) != null) { + return camelize(WordUtils.capitalizeFully(getSymbolName(name).toUpperCase()), true); + } + + // Camelize only when we have a structure defined below + Boolean camelized = false; + if (name.matches("[A-Z][a-z0-9]+[a-zA-Z0-9]*")) { + name = camelize(name, true); + camelized = true; + } + + // Reserved Name + String nameLowercase = StringUtils.lowerCase(name); + if (isReservedWord(nameLowercase)) { + return escapeReservedWord(nameLowercase); + } + + // Check for numerical conversions + if ("Int".equals(datatype) || "Int32".equals(datatype) || "Int64".equals(datatype) || + "Float".equals(datatype) || "Double".equals(datatype)) { + String varName = "number" + camelize(name); + varName = varName.replaceAll("-", "minus"); + varName = varName.replaceAll("\\+", "plus"); + varName = varName.replaceAll("\\.", "dot"); + return varName; + } + + // If we have already camelized the word, don't progress + // any further + if (camelized) { + return name; + } + + char[] separators = {'-', '_', ' ', ':', '(', ')'}; + return camelize(WordUtils.capitalizeFully(StringUtils.lowerCase(name), separators).replaceAll("[-_ :\\(\\)]", ""), true); + } + + @Override + public String toEnumName(CodegenProperty property) { + String enumName = toModelName(property.name); + + // Ensure that the enum type doesn't match a reserved word or + // the variable name doesn't match the generated enum type or the + // Swift compiler will generate an error + if (isReservedWord(property.datatypeWithEnum) || toVarName(property.name).equals(property.datatypeWithEnum)) { + enumName = property.datatypeWithEnum + "Enum"; + } + + // TODO: toModelName already does something for names starting with number, so this code is probably never called + if (enumName.matches("\\d.*")) { // starts with number + return "_" + enumName; + } else { + return enumName; + } + } + + @Override + public Map postProcessModels(Map objs) { + // process enum in models + return postProcessModelsEnum(objs); + } + + @Override + public String escapeQuotationMark(String input) { + // remove " to avoid code injection + return input.replace("\"", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + return input.replace("*/", "*_/").replace("/*", "/_*"); + } + + private static CodegenModel reconcileProperties(CodegenModel codegenModel, CodegenModel parentCodegenModel) { + // To support inheritance in this generator, we will analyze + // the parent and child models, look for properties that match, and remove + // them from the child models and leave them in the parent. + // Because the child models extend the parents, the properties will be available via the parent. + + // Get the properties for the parent and child models + final List parentModelCodegenProperties = parentCodegenModel.vars; + List codegenProperties = codegenModel.vars; + codegenModel.allVars = new ArrayList(codegenProperties); + codegenModel.parentVars = parentCodegenModel.allVars; + + // Iterate over all of the parent model properties + boolean removedChildProperty = false; + + for (CodegenProperty parentModelCodegenProperty : parentModelCodegenProperties) { + // Now that we have found a prop in the parent class, + // and search the child class for the same prop. + Iterator iterator = codegenProperties.iterator(); + while (iterator.hasNext()) { + CodegenProperty codegenProperty = iterator.next(); + if (codegenProperty.baseName == parentModelCodegenProperty.baseName) { + // We found a property in the child class that is + // a duplicate of the one in the parent, so remove it. + iterator.remove(); + removedChildProperty = true; + } + } + } + + if(removedChildProperty) { + // If we removed an entry from this model's vars, we need to ensure hasMore is updated + int count = 0, numVars = codegenProperties.size(); + for(CodegenProperty codegenProperty : codegenProperties) { + count += 1; + codegenProperty.hasMore = (count < numVars) ? true : false; + } + codegenModel.vars = codegenProperties; + } + + + return codegenModel; + } +} diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig index 7b008720a9..522e4bbaf7 100644 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -61,6 +61,7 @@ io.swagger.codegen.languages.StaticHtml2Generator io.swagger.codegen.languages.StaticHtmlGenerator io.swagger.codegen.languages.SwaggerGenerator io.swagger.codegen.languages.SwaggerYamlGenerator +io.swagger.codegen.languages.Swift4Codegen io.swagger.codegen.languages.Swift3Codegen io.swagger.codegen.languages.SwiftCodegen io.swagger.codegen.languages.TizenClientCodegen diff --git a/modules/swagger-codegen/src/main/resources/swift4/APIHelper.mustache b/modules/swagger-codegen/src/main/resources/swift4/APIHelper.mustache new file mode 100644 index 0000000000..b612ff9092 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift4/APIHelper.mustache @@ -0,0 +1,65 @@ +// APIHelper.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +class APIHelper { + static func rejectNil(_ source: [String:Any?]) -> [String:Any]? { + var destination = [String:Any]() + for (key, nillableValue) in source { + if let value: Any = nillableValue { + destination[key] = value + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] { + var destination = [String:String]() + for (key, nillableValue) in source { + if let value: Any = nillableValue { + destination[key] = "\(value)" + } + } + return destination + } + + static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? { + guard let source = source else { + return nil + } + var destination = [String:Any]() + let theTrue = NSNumber(value: true as Bool) + let theFalse = NSNumber(value: false as Bool) + for (key, value) in source { + switch value { + case let x where x as? NSNumber === theTrue || x as? NSNumber === theFalse: + destination[key] = "\(value as! Bool)" as Any? + default: + destination[key] = value + } + } + return destination + } + + + static func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem]? { + let returnValues = values + .filter { $0.1 != nil } + .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in + URLQueryItem(name: item._key, value:"\(item._value!)") + } + if returnValues.count == 0 { + return nil + } + return returnValues + } + +} diff --git a/modules/swagger-codegen/src/main/resources/swift4/APIs.mustache b/modules/swagger-codegen/src/main/resources/swift4/APIs.mustache new file mode 100644 index 0000000000..4337e40cff --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift4/APIs.mustache @@ -0,0 +1,61 @@ +// APIs.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +open class {{projectName}}API { + open static var basePath = "{{{basePath}}}" + open static var credential: URLCredential? + open static var customHeaders: [String:String] = [:] + open static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() +} + +open class RequestBuilder { + var credential: URLCredential? + var headers: [String:String] + let parameters: [String:Any]? + 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: ((Progress) -> ())? + + required public init(method: String, URLString: String, parameters: [String:Any]?, isBody: Bool, headers: [String:String] = [:]) { + self.method = method + self.URLString = URLString + self.parameters = parameters + self.isBody = isBody + self.headers = headers + + addHeaders({{projectName}}API.customHeaders) + } + + open func addHeaders(_ aHeaders:[String:String]) { + for (header, value) in aHeaders { + headers[header] = value + } + } + + open func execute(_ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { } + + public func addHeader(name: String, value: String) -> Self { + if !value.isEmpty { + headers[name] = value + } + return self + } + + open func addCredential() -> Self { + self.credential = {{projectName}}API.credential + return self + } +} + +public protocol RequestBuilderFactory { + func getNonDecodableBuilder() -> RequestBuilder.Type + func getBuilder() -> RequestBuilder.Type +} diff --git a/modules/swagger-codegen/src/main/resources/swift4/AlamofireImplementations.mustache b/modules/swagger-codegen/src/main/resources/swift4/AlamofireImplementations.mustache new file mode 100644 index 0000000000..b9d2a2727d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift4/AlamofireImplementations.mustache @@ -0,0 +1,307 @@ +// AlamofireImplementations.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire + +class AlamofireRequestBuilderFactory: RequestBuilderFactory { + func getNonDecodableBuilder() -> RequestBuilder.Type { + return AlamofireRequestBuilder.self + } + + func getBuilder() -> RequestBuilder.Type { + return AlamofireDecodableRequestBuilder.self + } +} + +// Store manager to retain its reference +private var managerStore: [String: Alamofire.SessionManager] = [:] + +open class AlamofireRequestBuilder: RequestBuilder { + required public init(method: String, URLString: String, parameters: [String : Any]?, isBody: Bool, headers: [String : String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody, headers: headers) + } + + /** + May be overridden by a subclass if you want to control the session + configuration. + */ + open func createSessionManager() -> Alamofire.SessionManager { + let configuration = URLSessionConfiguration.default + configuration.httpAdditionalHeaders = buildHeaders() + return Alamofire.SessionManager(configuration: configuration) + } + + /** + May be overridden by a subclass if you want to control the Content-Type + that is given to an uploaded form part. + + Return nil to use the default behavior (inferring the Content-Type from + the file extension). Return the desired Content-Type otherwise. + */ + open func contentTypeForFormPart(fileURL: URL) -> String? { + return nil + } + + /** + May be overridden by a subclass if you want to control the request + configuration (e.g. to override the cache policy). + */ + open func makeRequest(manager: SessionManager, method: HTTPMethod, encoding: ParameterEncoding, headers: [String:String]) -> DataRequest { + return manager.request(URLString, method: method, parameters: parameters, encoding: encoding, headers: headers) + } + + override open func execute(_ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { + let managerId:String = UUID().uuidString + // Create a new manager for each request to customize its request header + let manager = createSessionManager() + managerStore[managerId] = manager + + let encoding:ParameterEncoding = isBody ? JSONDataEncoding() : URLEncoding() + + let xMethod = Alamofire.HTTPMethod(rawValue: method) + let fileKeys = parameters == nil ? [] : parameters!.filter { $1 is NSURL } + .map { $0.0 } + + if fileKeys.count > 0 { + manager.upload(multipartFormData: { mpForm in + for (k, v) in self.parameters! { + switch v { + case let fileURL as URL: + if let mimeType = self.contentTypeForFormPart(fileURL: fileURL) { + mpForm.append(fileURL, withName: k, fileName: fileURL.lastPathComponent, mimeType: mimeType) + } + else { + mpForm.append(fileURL, withName: k) + } + break + case let string as String: + mpForm.append(string.data(using: String.Encoding.utf8)!, withName: k) + break + case let number as NSNumber: + mpForm.append(number.stringValue.data(using: String.Encoding.utf8)!, withName: k) + break + default: + fatalError("Unprocessable value \(v) with key \(k)") + break + } + } + }, to: URLString, method: xMethod!, headers: nil, encodingCompletion: { encodingResult in + switch encodingResult { + case .success(let upload, _, _): + if let onProgressReady = self.onProgressReady { + onProgressReady(upload.uploadProgress) + } + self.processRequest(request: upload, managerId, completion) + case .failure(let encodingError): + completion(nil, ErrorResponse.Error(415, nil, encodingError)) + } + }) + } else { + let request = makeRequest(manager: manager, method: xMethod!, encoding: encoding, headers: headers) + if let onProgressReady = self.onProgressReady { + onProgressReady(request.progress) + } + processRequest(request: request, managerId, completion) + } + + } + + fileprivate func processRequest(request: DataRequest, _ managerId: String, _ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { + if let credential = self.credential { + request.authenticate(usingCredential: credential) + } + + let cleanupRequest = { + _ = managerStore.removeValue(forKey: managerId) + } + + let validatedRequest = request.validate() + + switch T.self { + case is String.Type: + validatedRequest.responseString(completionHandler: { (stringResponse) in + cleanupRequest() + + if stringResponse.result.isFailure { + completion( + nil, + ErrorResponse.Error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.result.error as Error!) + ) + return + } + + completion( + Response( + response: stringResponse.response!, + body: ((stringResponse.result.value ?? "") as! T) + ), + nil + ) + }) + case is Void.Type: + validatedRequest.responseData(completionHandler: { (voidResponse) in + cleanupRequest() + + if voidResponse.result.isFailure { + completion( + nil, + ErrorResponse.Error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.result.error!) + ) + return + } + + completion( + Response( + response: voidResponse.response!, + body: nil), + nil + ) + }) + default: + validatedRequest.responseData(completionHandler: { (dataResponse) in + cleanupRequest() + + if (dataResponse.result.isFailure) { + completion( + nil, + ErrorResponse.Error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!) + ) + return + } + + completion( + Response( + response: dataResponse.response!, + body: (dataResponse.data as! T) + ), + nil + ) + }) + } + } + + open func buildHeaders() -> [String: String] { + var httpHeaders = SessionManager.defaultHTTPHeaders + for (key, value) in self.headers { + httpHeaders[key] = value + } + return httpHeaders + } +} + +public enum AlamofireDecodableRequestBuilderError: Error { + case emptyDataResponse + case nilHTTPResponse + case jsonDecoding(DecodingError) + case generalError(Error) +} + +open class AlamofireDecodableRequestBuilder: AlamofireRequestBuilder { + + override fileprivate func processRequest(request: DataRequest, _ managerId: String, _ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { + if let credential = self.credential { + request.authenticate(usingCredential: credential) + } + + let cleanupRequest = { + _ = managerStore.removeValue(forKey: managerId) + } + + let validatedRequest = request.validate() + + switch T.self { + case is String.Type: + validatedRequest.responseString(completionHandler: { (stringResponse) in + cleanupRequest() + + if stringResponse.result.isFailure { + completion( + nil, + ErrorResponse.Error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.result.error as Error!) + ) + return + } + + completion( + Response( + response: stringResponse.response!, + body: ((stringResponse.result.value ?? "") as! T) + ), + nil + ) + }) + case is Void.Type: + validatedRequest.responseData(completionHandler: { (voidResponse) in + cleanupRequest() + + if voidResponse.result.isFailure { + completion( + nil, + ErrorResponse.Error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.result.error!) + ) + return + } + + completion( + Response( + response: voidResponse.response!, + body: nil), + nil + ) + }) + case is Data.Type: + validatedRequest.responseData(completionHandler: { (dataResponse) in + cleanupRequest() + + if (dataResponse.result.isFailure) { + completion( + nil, + ErrorResponse.Error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!) + ) + return + } + + completion( + Response( + response: dataResponse.response!, + body: (dataResponse.data as! T) + ), + nil + ) + }) + default: + validatedRequest.responseData(completionHandler: { (dataResponse: DataResponse) in + cleanupRequest() + + guard dataResponse.result.isSuccess else { + completion(nil, ErrorResponse.Error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!)) + return + } + + guard let data = dataResponse.data, !data.isEmpty else { + completion(nil, ErrorResponse.Error(-1, nil, AlamofireDecodableRequestBuilderError.emptyDataResponse)) + return + } + + guard let httpResponse = dataResponse.response else { + completion(nil, ErrorResponse.Error(-2, nil, AlamofireDecodableRequestBuilderError.nilHTTPResponse)) + return + } + + var responseObj: Response? = nil + + let decodeResult: (decodableObj: T?, error: Error?) = CodableHelper.decode(T.self, from: data) + if decodeResult.error == nil { + responseObj = Response(response: httpResponse, body: decodeResult.decodableObj) + } + + completion(responseObj, decodeResult.error) + }) + } + } + +} diff --git a/modules/swagger-codegen/src/main/resources/swift4/Cartfile.mustache b/modules/swagger-codegen/src/main/resources/swift4/Cartfile.mustache new file mode 100644 index 0000000000..101df9a7e0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift4/Cartfile.mustache @@ -0,0 +1,3 @@ +github "Alamofire/Alamofire" >= 3.1.0{{#usePromiseKit}} +github "mxcl/PromiseKit" >=1.5.3{{/usePromiseKit}}{{#useRxSwift}} +github "ReactiveX/RxSwift" ~> 2.0{{/useRxSwift}} diff --git a/modules/swagger-codegen/src/main/resources/swift4/CodableHelper.mustache b/modules/swagger-codegen/src/main/resources/swift4/CodableHelper.mustache new file mode 100644 index 0000000000..7603003824 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift4/CodableHelper.mustache @@ -0,0 +1,53 @@ +// +// CodableHelper.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +public typealias EncodeResult = (data: Data?, error: Error?) + +open class CodableHelper { + + open class func decode(_ type: T.Type, from data: Data) -> (decodableObj: T?, error: Error?) where T : Decodable { + var returnedDecodable: T? = nil + var returnedError: Error? = nil + + let decoder = JSONDecoder() + decoder.dataDecodingStrategy = .base64Decode + if #available(iOS 10.0, *) { + decoder.dateDecodingStrategy = .iso8601 + } + + do { + returnedDecodable = try decoder.decode(type, from: data) + } catch { + returnedError = error + } + + return (returnedDecodable, returnedError) + } + + open class func encode(_ value: T, prettyPrint: Bool = false) -> EncodeResult where T : Encodable { + var returnedData: Data? + var returnedError: Error? = nil + + let encoder = JSONEncoder() + encoder.outputFormatting = (prettyPrint ? .prettyPrinted : .compact) + encoder.dataEncodingStrategy = .base64Encode + if #available(iOS 10.0, *) { + encoder.dateEncodingStrategy = .iso8601 + } + + do { + returnedData = try encoder.encode(value) + } catch { + returnedError = error + } + + return (returnedData, returnedError) + } + +} diff --git a/modules/swagger-codegen/src/main/resources/swift4/Configuration.mustache b/modules/swagger-codegen/src/main/resources/swift4/Configuration.mustache new file mode 100644 index 0000000000..c03a10b930 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift4/Configuration.mustache @@ -0,0 +1,15 @@ +// Configuration.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +open class Configuration { + + // This value is used to configure the date formatter that is used to serialize dates into JSON format. + // You must set it prior to encoding any dates, and it will only be read once. + open static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/swift4/Extensions.mustache b/modules/swagger-codegen/src/main/resources/swift4/Extensions.mustache new file mode 100644 index 0000000000..19a3dd7364 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift4/Extensions.mustache @@ -0,0 +1,100 @@ +// Extensions.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire{{#usePromiseKit}} +import PromiseKit{{/usePromiseKit}} + +extension Bool: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension Float: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension Int: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension Int32: JSONEncodable { + func encodeToJSON() -> Any { return NSNumber(value: self as Int32) } +} + +extension Int64: JSONEncodable { + func encodeToJSON() -> Any { return NSNumber(value: self as Int64) } +} + +extension Double: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension String: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +private func encodeIfPossible(_ object: T) -> Any { + if let encodableObject = object as? JSONEncodable { + return encodableObject.encodeToJSON() + } else { + return object as Any + } +} + +extension Array: JSONEncodable { + func encodeToJSON() -> Any { + return self.map(encodeIfPossible) + } +} + +extension Dictionary: JSONEncodable { + func encodeToJSON() -> Any { + var dictionary = [AnyHashable: Any]() + for (key, value) in self { + dictionary[key as! NSObject] = encodeIfPossible(value) + } + return dictionary as Any + } +} + +extension Data: JSONEncodable { + func encodeToJSON() -> Any { + return self.base64EncodedString(options: Data.Base64EncodingOptions()) + } +} + +private let dateFormatter: DateFormatter = { + let fmt = DateFormatter() + fmt.dateFormat = Configuration.dateFormat + fmt.locale = Locale(identifier: "en_US_POSIX") + return fmt +}() + +extension Date: JSONEncodable { + func encodeToJSON() -> Any { + return dateFormatter.string(from: self) as Any + } +} + +extension UUID: JSONEncodable { + func encodeToJSON() -> Any { + return self.uuidString + } +} + +{{#usePromiseKit}}extension RequestBuilder { + public func execute() -> Promise> { + let deferred = Promise>.pending() + self.execute { (response: Response?, error: Error?) in + if let response = response { + deferred.fulfill(response) + } else { + deferred.reject(error!) + } + } + return deferred.promise + } +}{{/usePromiseKit}} diff --git a/modules/swagger-codegen/src/main/resources/swift4/JSONEncodableEncoding.mustache b/modules/swagger-codegen/src/main/resources/swift4/JSONEncodableEncoding.mustache new file mode 100644 index 0000000000..472e955ee8 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift4/JSONEncodableEncoding.mustache @@ -0,0 +1,54 @@ +// +// JSONDataEncoding.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire + +public struct JSONDataEncoding: ParameterEncoding { + + // MARK: Properties + + private static let jsonDataKey = "jsonData" + + // MARK: Encoding + + /// 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. This should have a single key/value + /// pair with "jsonData" as the key and a Data object as the value. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let jsonData = parameters?[JSONDataEncoding.jsonDataKey] as? Data, !jsonData.isEmpty else { + return urlRequest + } + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = jsonData + + return urlRequest + } + + public static func encodingParameters(jsonData: Data?) -> Parameters? { + var returnedParams: Parameters? = nil + if let jsonData = jsonData, !jsonData.isEmpty { + var params = Parameters() + params[jsonDataKey] = jsonData + returnedParams = params + } + return returnedParams + } + +} diff --git a/modules/swagger-codegen/src/main/resources/swift4/JSONEncodingHelper.mustache b/modules/swagger-codegen/src/main/resources/swift4/JSONEncodingHelper.mustache new file mode 100644 index 0000000000..4cf4ac206a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift4/JSONEncodingHelper.mustache @@ -0,0 +1,27 @@ +// +// JSONEncodingHelper.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire + +open class JSONEncodingHelper { + + open class func encodingParameters(forEncodableObject encodableObj: T?) -> Parameters? { + var params: Parameters? = nil + + // Encode the Encodable object + if let encodableObj = encodableObj { + let encodeResult = CodableHelper.encode(encodableObj, prettyPrint: true) + if encodeResult.error == nil { + params = JSONDataEncoding.encodingParameters(jsonData: encodeResult.data) + } + } + + return params + } + +} diff --git a/modules/swagger-codegen/src/main/resources/swift4/Models.mustache b/modules/swagger-codegen/src/main/resources/swift4/Models.mustache new file mode 100644 index 0000000000..2c19b32158 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift4/Models.mustache @@ -0,0 +1,36 @@ +// Models.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +protocol JSONEncodable { + func encodeToJSON() -> Any +} + +public enum ErrorResponse : Error { + case Error(Int, Data?, Error) +} + +open class Response { + open let statusCode: Int + open let header: [String: String] + open 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: HTTPURLResponse, 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) + } +} diff --git a/modules/swagger-codegen/src/main/resources/swift4/Podspec.mustache b/modules/swagger-codegen/src/main/resources/swift4/Podspec.mustache new file mode 100644 index 0000000000..173be12b43 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift4/Podspec.mustache @@ -0,0 +1,21 @@ +Pod::Spec.new do |s| + s.name = '{{projectName}}'{{#projectDescription}} + s.summary = '{{projectDescription}}'{{/projectDescription}} + s.ios.deployment_target = '9.0' + s.osx.deployment_target = '10.11' + s.version = '{{#podVersion}}{{podVersion}}{{/podVersion}}{{^podVersion}}0.0.1{{/podVersion}}' + s.source = {{#podSource}}{{& podSource}}{{/podSource}}{{^podSource}}{ :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' }{{/podSource}}{{#podAuthors}} + s.authors = '{{podAuthors}}'{{/podAuthors}}{{#podSocialMediaURL}} + s.social_media_url = '{{podSocialMediaURL}}'{{/podSocialMediaURL}}{{#podDocsetURL}} + s.docset_url = '{{podDocsetURL}}'{{/podDocsetURL}} + s.license = {{#podLicense}}{{& podLicense}}{{/podLicense}}{{^podLicense}}'Proprietary'{{/podLicense}}{{#podHomepage}} + s.homepage = '{{podHomepage}}'{{/podHomepage}}{{#podSummary}} + s.summary = '{{podSummary}}'{{/podSummary}}{{#podDescription}} + s.description = '{{podDescription}}'{{/podDescription}}{{#podScreenshots}} + s.screenshots = {{& podScreenshots}}{{/podScreenshots}}{{#podDocumentationURL}} + s.documentation_url = '{{podDocumentationURL}}'{{/podDocumentationURL}} + s.source_files = '{{projectName}}/Classes/Swaggers/**/*.swift'{{#usePromiseKit}} + s.dependency 'PromiseKit', '~> 4.2.2'{{/usePromiseKit}}{{#useRxSwift}} + s.dependency 'RxSwift', '~> 3.4.1'{{/useRxSwift}} + s.dependency 'Alamofire', '~> 4.5' +end diff --git a/modules/swagger-codegen/src/main/resources/swift4/README.mustache b/modules/swagger-codegen/src/main/resources/swift4/README.mustache new file mode 100644 index 0000000000..933e46039a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift4/README.mustache @@ -0,0 +1,65 @@ +# Swift4 API client for {{packageName}} + +{{#appDescription}} +{{{appDescription}}} +{{/appDescription}} + +## Overview +This API client was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [swagger-spec](https://github.com/swagger-api/swagger-spec) from a remote server, you can easily generate an API client. + +- API version: {{appVersion}} +- Package version: {{packageVersion}} +{{^hideGenerationTimestamp}} +- Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} +- Build package: {{generatorClass}} +{{#infoUrl}} +For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + +## Installation +Put the package under your project folder and add the following in import: +``` + "./{{packageName}}" +``` + +## Documentation for API Endpoints + +All URIs are relative to *{{basePath}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + +## Documentation For Models + +{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) +{{/model}}{{/models}} + +## Documentation For Authorization + +{{^authMethods}} All endpoints do not require authorization. +{{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}} +{{#authMethods}}## {{{name}}} + +{{#isApiKey}}- **Type**: API key +- **API key parameter name**: {{{keyParamName}}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasic}}- **Type**: HTTP basic authentication +{{/isBasic}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{{flow}}} +- **Authorization URL**: {{{authorizationUrl}}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - **{{{scope}}}**: {{{description}}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} + +## Author + +{{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}} +{{/hasMore}}{{/apis}}{{/apiInfo}} diff --git a/modules/swagger-codegen/src/main/resources/swift4/_param.mustache b/modules/swagger-codegen/src/main/resources/swift4/_param.mustache new file mode 100644 index 0000000000..5caacbc600 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift4/_param.mustache @@ -0,0 +1 @@ +"{{baseName}}": {{paramName}}{{^isEnum}}{{#isInteger}}{{^required}}?{{/required}}.encodeToJSON(){{/isInteger}}{{#isLong}}{{^required}}?{{/required}}.encodeToJSON(){{/isLong}}{{/isEnum}}{{#isEnum}}{{^isContainer}}{{^required}}?{{/required}}.rawValue{{/isContainer}}{{/isEnum}}{{#isDate}}{{^required}}?{{/required}}.encodeToJSON(){{/isDate}}{{#isDateTime}}{{^required}}?{{/required}}.encodeToJSON(){{/isDateTime}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/swift4/api.mustache b/modules/swagger-codegen/src/main/resources/swift4/api.mustache new file mode 100644 index 0000000000..fbce8ed748 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift4/api.mustache @@ -0,0 +1,153 @@ +{{#operations}}// +// {{classname}}.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire{{#usePromiseKit}} +import PromiseKit{{/usePromiseKit}}{{#useRxSwift}} +import RxSwift{{/useRxSwift}} + +{{#swiftUseApiNamespace}} +extension {{projectName}}API { +{{/swiftUseApiNamespace}} + +{{#description}} +/** {{description}} */{{/description}} +open class {{classname}} { +{{#operation}} + {{#allParams}} + {{#isEnum}} + /** + * enum for parameter {{paramName}} + */ + public enum {{enumName}}_{{operationId}}: {{^isContainer}}{{{dataType}}}{{/isContainer}}{{#isContainer}}String{{/isContainer}} { {{#allowableValues}}{{#enumVars}} + case {{name}} = {{#isContainer}}"{{/isContainer}}{{#isString}}"{{/isString}}{{{value}}}{{#isString}}"{{/isString}}{{#isContainer}}"{{/isContainer}}{{/enumVars}}{{/allowableValues}} + } + + {{/isEnum}} + {{/allParams}} + /** + {{#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}} + - parameter completion: completion handler to receive the data and the error objects + */ + open class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}completion: @escaping ((_ {{#returnType}}data: {{{returnType}}}?,_ {{/returnType}}error: Error?) -> Void)) { + {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}).execute { (response, error) -> Void in + completion({{#returnType}}response?.body, {{/returnType}}error); + } + } + +{{#usePromiseKit}} + /** + {{#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: Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> + */ + open class func {{operationId}}({{#allParams}} {{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { + let deferred = Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.pending() + {{operationId}}({{#allParams}}{{paramName}}: {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { {{#returnType}}data, {{/returnType}}error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill({{#returnType}}data!{{/returnType}}) + } + } + 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}}> + */ + open class func {{operationId}}({{#allParams}}{{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 Error)) + } else { + observer.on(.next({{#returnType}}data!{{/returnType}})) + } + observer.on(.completed) + } + return Disposables.create() + } + } +{{/useRxSwift}} + + /** + {{#summary}} + {{{summary}}} + {{/summary}} + - {{httpMethod}} {{{path}}}{{#notes}} + - {{{notes}}}{{/notes}}{{#subresourceOperation}} + - subresourceOperation: {{subresourceOperation}}{{/subresourceOperation}}{{#defaultResponse}} + - defaultResponse: {{defaultResponse}}{{/defaultResponse}}{{#authMethods}} + - {{#isBasic}}BASIC{{/isBasic}}{{#isOAuth}}OAuth{{/isOAuth}}{{#isApiKey}}API Key{{/isApiKey}}: + - type: {{type}}{{#keyParamName}} {{keyParamName}} {{#isKeyInQuery}}(QUERY){{/isKeyInQuery}}{{#isKeyInHeaer}}(HEADER){{/isKeyInHeaer}}{{/keyParamName}} + - name: {{name}}{{/authMethods}}{{#responseHeaders}} + - responseHeaders: {{responseHeaders}}{{/responseHeaders}}{{#examples}} + - examples: {{{examples}}}{{/examples}}{{#externalDocs}} + - externalDocs: {{externalDocs}}{{/externalDocs}}{{#hasParams}} + {{/hasParams}}{{#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: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{description}} + */ + open class func {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { + {{^pathParams}}let{{/pathParams}}{{#pathParams}}{{^secondaryParam}}var{{/secondaryParam}}{{/pathParams}} path = "{{{path}}}"{{#pathParams}} + path = path.replacingOccurrences(of: "{{=<% %>=}}{<%baseName%>}<%={{ }}=%>", with: "\({{paramName}}{{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}.rawValue{{/isContainer}}{{/isEnum}})", options: .literal, range: nil){{/pathParams}} + let URLString = {{projectName}}API.basePath + path + {{#bodyParam}} + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: {{paramName}}) + {{/bodyParam}} + {{^bodyParam}} + {{#hasFormParams}} + let formParams: [String:Any?] = [ + {{#formParams}} + {{> _param}}{{#hasMore}},{{/hasMore}} + {{/formParams}} + ] + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + {{/hasFormParams}} + {{^hasFormParams}} + let parameters: [String:Any]? = nil + {{/hasFormParams}} + {{/bodyParam}} + + let url = NSURLComponents(string: URLString) + {{#hasQueryParams}} + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + {{#queryParams}} + {{> _param}}{{#hasMore}}, {{/hasMore}} + {{/queryParams}} + ]) + {{/hasQueryParams}}{{#headerParams}}{{^secondaryParam}} + let nillableHeaders: [String: Any?] = [{{/secondaryParam}} + {{> _param}}{{#hasMore}},{{/hasMore}}{{^hasMore}} + ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders){{/hasMore}}{{/headerParams}} + + let requestBuilder: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.Type = {{projectName}}API.requestBuilderFactory.{{#returnType}}getBuilder(){{/returnType}}{{^returnType}}getNonDecodableBuilder(){{/returnType}} + + return requestBuilder.init(method: "{{httpMethod}}", URLString: (url?.string ?? URLString), parameters: parameters, isBody: {{hasBodyParam}}{{#headerParams}}{{^secondaryParam}}, headers: headerParameters{{/secondaryParam}}{{/headerParams}}) + } + +{{/operation}} +} +{{#swiftUseApiNamespace}} +} +{{/swiftUseApiNamespace}} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/swift4/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/swift4/git_push.sh.mustache new file mode 100755 index 0000000000..e153ce23ec --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift4/git_push.sh.mustache @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/modules/swagger-codegen/src/main/resources/swift4/gitignore.mustache b/modules/swagger-codegen/src/main/resources/swift4/gitignore.mustache new file mode 100644 index 0000000000..5e5d5cebcf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift4/gitignore.mustache @@ -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 diff --git a/modules/swagger-codegen/src/main/resources/swift4/model.mustache b/modules/swagger-codegen/src/main/resources/swift4/model.mustache new file mode 100644 index 0000000000..12bc82a54d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift4/model.mustache @@ -0,0 +1,79 @@ +{{#models}}{{#model}}// +// {{classname}}.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +{{#description}} + +/** {{description}} */{{/description}} +{{#isArrayModel}} +public typealias {{classname}} = [{{arrayModelType}}] +{{/isArrayModel}} +{{^isArrayModel}} +{{#isEnum}} +public enum {{classname}}: {{dataType}}, Codable { +{{#allowableValues}}{{#enumVars}} case {{name}} = "{{{value}}}" +{{/enumVars}}{{/allowableValues}} +} +{{/isEnum}} +{{^isEnum}} +{{#vars.isEmpty}} +public typealias {{classname}} = {{dataType}} +{{/vars.isEmpty}} +{{^vars.isEmpty}} +open class {{classname}}: {{#parent}}{{{parent}}}{{/parent}}{{^parent}}Codable{{/parent}} { + +{{#vars}} +{{#isEnum}} + public enum {{enumName}}: {{^isContainer}}{{datatype}}{{/isContainer}}{{#isContainer}}String{{/isContainer}}, Codable { {{#allowableValues}}{{#enumVars}} + case {{name}} = {{#isContainer}}"{{/isContainer}}{{#isString}}"{{/isString}}{{{value}}}{{#isString}}"{{/isString}}{{#isContainer}}"{{/isContainer}}{{/enumVars}}{{/allowableValues}} + } +{{/isEnum}} +{{/vars}} +{{#vars}} +{{#isEnum}} + {{#description}}/** {{description}} */ + {{/description}}public var {{name}}: {{{datatypeWithEnum}}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}} +{{/isEnum}} +{{^isEnum}} + {{#description}}/** {{description}} */ + {{/description}}public var {{name}}: {{{datatype}}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}} +{{/isEnum}} +{{/vars}} + +{{#additionalPropertiesType}} + public var additionalProperties: [AnyHashable:{{{additionalPropertiesType}}}] = [:] + +{{/additionalPropertiesType}} +{{^unwrapRequired}} + {{^parent}}public init() {}{{/parent}}{{/unwrapRequired}} +{{#unwrapRequired}} + public init({{#allVars}}{{^-first}}, {{/-first}}{{name}}: {{#isEnum}}{{datatypeWithEnum}}{{/isEnum}}{{^isEnum}}{{datatype}}{{/isEnum}}{{^required}}?=nil{{/required}}{{/allVars}}) { + {{#vars}} + self.{{name}} = {{name}} + {{/vars}} + }{{/unwrapRequired}} +{{#additionalPropertiesType}} + public subscript(key: AnyHashable) -> {{{additionalPropertiesType}}}? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } +{{/additionalPropertiesType}} +} +{{/vars.isEmpty}} +{{/isEnum}} +{{/isArrayModel}} +{{/model}} +{{/models}} diff --git a/samples/client/petstore/swift4/.gitignore b/samples/client/petstore/swift4/.gitignore new file mode 100644 index 0000000000..5e5d5cebcf --- /dev/null +++ b/samples/client/petstore/swift4/.gitignore @@ -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 diff --git a/samples/client/petstore/swift4/.swagger-codegen-ignore b/samples/client/petstore/swift4/.swagger-codegen-ignore new file mode 100644 index 0000000000..c5fa491b4c --- /dev/null +++ b/samples/client/petstore/swift4/.swagger-codegen-ignore @@ -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 diff --git a/samples/client/petstore/swift4/default/.gitignore b/samples/client/petstore/swift4/default/.gitignore new file mode 100644 index 0000000000..5e5d5cebcf --- /dev/null +++ b/samples/client/petstore/swift4/default/.gitignore @@ -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 diff --git a/samples/client/petstore/swift4/default/.swagger-codegen-ignore b/samples/client/petstore/swift4/default/.swagger-codegen-ignore new file mode 100644 index 0000000000..c5fa491b4c --- /dev/null +++ b/samples/client/petstore/swift4/default/.swagger-codegen-ignore @@ -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 diff --git a/samples/client/petstore/swift4/default/.swagger-codegen/VERSION b/samples/client/petstore/swift4/default/.swagger-codegen/VERSION new file mode 100644 index 0000000000..7fea99011a --- /dev/null +++ b/samples/client/petstore/swift4/default/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.2.3-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift4/default/Cartfile b/samples/client/petstore/swift4/default/Cartfile new file mode 100644 index 0000000000..3d90db1689 --- /dev/null +++ b/samples/client/petstore/swift4/default/Cartfile @@ -0,0 +1 @@ +github "Alamofire/Alamofire" >= 3.1.0 diff --git a/samples/client/petstore/swift4/default/PetstoreClient.podspec b/samples/client/petstore/swift4/default/PetstoreClient.podspec new file mode 100644 index 0000000000..c1e940bdb8 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient.podspec @@ -0,0 +1,13 @@ +Pod::Spec.new do |s| + s.name = 'PetstoreClient' + s.ios.deployment_target = '9.0' + s.osx.deployment_target = '10.11' + s.version = '0.0.1' + s.source = { :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' } + s.authors = '' + s.license = 'Proprietary' + s.homepage = 'https://github.com/swagger-api/swagger-codegen' + s.summary = 'PetstoreClient' + s.source_files = 'PetstoreClient/Classes/Swaggers/**/*.swift' + s.dependency 'Alamofire', '~> 4.5' +end diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIHelper.swift new file mode 100644 index 0000000000..b612ff9092 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIHelper.swift @@ -0,0 +1,65 @@ +// APIHelper.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +class APIHelper { + static func rejectNil(_ source: [String:Any?]) -> [String:Any]? { + var destination = [String:Any]() + for (key, nillableValue) in source { + if let value: Any = nillableValue { + destination[key] = value + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] { + var destination = [String:String]() + for (key, nillableValue) in source { + if let value: Any = nillableValue { + destination[key] = "\(value)" + } + } + return destination + } + + static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? { + guard let source = source else { + return nil + } + var destination = [String:Any]() + let theTrue = NSNumber(value: true as Bool) + let theFalse = NSNumber(value: false as Bool) + for (key, value) in source { + switch value { + case let x where x as? NSNumber === theTrue || x as? NSNumber === theFalse: + destination[key] = "\(value as! Bool)" as Any? + default: + destination[key] = value + } + } + return destination + } + + + static func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem]? { + let returnValues = values + .filter { $0.1 != nil } + .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in + URLQueryItem(name: item._key, value:"\(item._value!)") + } + if returnValues.count == 0 { + return nil + } + return returnValues + } + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs.swift new file mode 100644 index 0000000000..745d640ec1 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs.swift @@ -0,0 +1,61 @@ +// APIs.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +open class PetstoreClientAPI { + open static var basePath = "http://petstore.swagger.io:80/v2" + open static var credential: URLCredential? + open static var customHeaders: [String:String] = [:] + open static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() +} + +open class RequestBuilder { + var credential: URLCredential? + var headers: [String:String] + let parameters: [String:Any]? + 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: ((Progress) -> ())? + + required public init(method: String, URLString: String, parameters: [String:Any]?, isBody: Bool, headers: [String:String] = [:]) { + self.method = method + self.URLString = URLString + self.parameters = parameters + self.isBody = isBody + self.headers = headers + + addHeaders(PetstoreClientAPI.customHeaders) + } + + open func addHeaders(_ aHeaders:[String:String]) { + for (header, value) in aHeaders { + headers[header] = value + } + } + + open func execute(_ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { } + + public func addHeader(name: String, value: String) -> Self { + if !value.isEmpty { + headers[name] = value + } + return self + } + + open func addCredential() -> Self { + self.credential = PetstoreClientAPI.credential + return self + } +} + +public protocol RequestBuilderFactory { + func getNonDecodableBuilder() -> RequestBuilder.Type + func getBuilder() -> RequestBuilder.Type +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift new file mode 100644 index 0000000000..070bd8af1e --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift @@ -0,0 +1,407 @@ +// +// FakeAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire + + + +open class FakeAPI { + /** + + - parameter body: (body) Input boolean as post body (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + open class func fakeOuterBooleanSerialize(body: OuterBoolean? = nil, completion: @escaping ((_ data: OuterBoolean?,_ error: Error?) -> Void)) { + fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + + /** + - POST /fake/outer/boolean + - Test serialization of outer boolean types + - examples: [{contentType=application/json, example={ }}] + + - parameter body: (body) Input boolean as post body (optional) + + - returns: RequestBuilder + */ + open class func fakeOuterBooleanSerializeWithRequestBuilder(body: OuterBoolean? = nil) -> RequestBuilder { + let path = "/fake/outer/boolean" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + + - parameter body: (body) Input composite as post body (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, completion: @escaping ((_ data: OuterComposite?,_ error: Error?) -> Void)) { + fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + + /** + - POST /fake/outer/composite + - Test serialization of object with outer number type + - examples: [{contentType=application/json, example={ + "my_string" : { }, + "my_number" : { }, + "my_boolean" : { } +}}] + + - parameter body: (body) Input composite as post body (optional) + + - returns: RequestBuilder + */ + open class func fakeOuterCompositeSerializeWithRequestBuilder(body: OuterComposite? = nil) -> RequestBuilder { + let path = "/fake/outer/composite" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + + - parameter body: (body) Input number as post body (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + open class func fakeOuterNumberSerialize(body: OuterNumber? = nil, completion: @escaping ((_ data: OuterNumber?,_ error: Error?) -> Void)) { + fakeOuterNumberSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + + /** + - POST /fake/outer/number + - Test serialization of outer number types + - examples: [{contentType=application/json, example={ }}] + + - parameter body: (body) Input number as post body (optional) + + - returns: RequestBuilder + */ + open class func fakeOuterNumberSerializeWithRequestBuilder(body: OuterNumber? = nil) -> RequestBuilder { + let path = "/fake/outer/number" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + + - parameter body: (body) Input string as post body (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + open class func fakeOuterStringSerialize(body: OuterString? = nil, completion: @escaping ((_ data: OuterString?,_ error: Error?) -> Void)) { + fakeOuterStringSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + + /** + - POST /fake/outer/string + - Test serialization of outer string types + - examples: [{contentType=application/json, example={ }}] + + - parameter body: (body) Input string as post body (optional) + + - returns: RequestBuilder + */ + open class func fakeOuterStringSerializeWithRequestBuilder(body: OuterString? = nil) -> RequestBuilder { + let path = "/fake/outer/string" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + To test \"client\" model + + - parameter body: (body) client model + - parameter completion: completion handler to receive the data and the error objects + */ + open class func testClientModel(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { + testClientModelWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + + /** + To test \"client\" model + - PATCH /fake + - To test \"client\" model + - examples: [{contentType=application/json, example={ + "client" : "aeiou" +}}] + + - parameter body: (body) client model + + - returns: RequestBuilder + */ + open class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder { + let path = "/fake" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + + - parameter number: (form) None + - parameter double: (form) None + - parameter patternWithoutDelimiter: (form) None + - parameter byte: (form) None + - parameter integer: (form) None (optional) + - parameter int32: (form) None (optional) + - parameter int64: (form) None (optional) + - parameter float: (form) None (optional) + - parameter string: (form) None (optional) + - parameter binary: (form) None (optional) + - parameter date: (form) None (optional) + - parameter dateTime: (form) None (optional) + - parameter password: (form) None (optional) + - parameter callback: (form) None (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int32? = nil, int32: Int32? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: Data? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute { (response, error) -> Void in + completion(error); + } + } + + + /** + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + - POST /fake + - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + - BASIC: + - type: basic + - name: http_basic_test + + - parameter number: (form) None + - parameter double: (form) None + - parameter patternWithoutDelimiter: (form) None + - parameter byte: (form) None + - parameter integer: (form) None (optional) + - parameter int32: (form) None (optional) + - parameter int64: (form) None (optional) + - parameter float: (form) None (optional) + - parameter string: (form) None (optional) + - parameter binary: (form) None (optional) + - parameter date: (form) None (optional) + - parameter dateTime: (form) None (optional) + - parameter password: (form) None (optional) + - parameter callback: (form) None (optional) + + - returns: RequestBuilder + */ + open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int32? = nil, int32: Int32? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: Data? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { + let path = "/fake" + let URLString = PetstoreClientAPI.basePath + path + let formParams: [String:Any?] = [ + "integer": integer?.encodeToJSON(), + "int32": int32?.encodeToJSON(), + "int64": int64?.encodeToJSON(), + "number": number, + "float": float, + "double": double, + "string": string, + "pattern_without_delimiter": patternWithoutDelimiter, + "byte": byte, + "binary": binary, + "date": date?.encodeToJSON(), + "dateTime": dateTime?.encodeToJSON(), + "password": password, + "callback": callback + ] + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + * enum for parameter enumFormStringArray + */ + public enum EnumFormStringArray_testEnumParameters: String { + case greaterThan = ">" + case dollar = "$" + } + + /** + * enum for parameter enumFormString + */ + public enum EnumFormString_testEnumParameters: String { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + } + + /** + * enum for parameter enumHeaderStringArray + */ + public enum EnumHeaderStringArray_testEnumParameters: String { + case greaterThan = ">" + case dollar = "$" + } + + /** + * enum for parameter enumHeaderString + */ + public enum EnumHeaderString_testEnumParameters: String { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + } + + /** + * enum for parameter enumQueryStringArray + */ + public enum EnumQueryStringArray_testEnumParameters: String { + case greaterThan = ">" + case dollar = "$" + } + + /** + * enum for parameter enumQueryString + */ + public enum EnumQueryString_testEnumParameters: String { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + } + + /** + * enum for parameter enumQueryInteger + */ + public enum EnumQueryInteger_testEnumParameters: Int32 { + case _1 = 1 + case numberminus2 = -2 + } + + /** + * enum for parameter enumQueryDouble + */ + public enum EnumQueryDouble_testEnumParameters: Double { + case _11 = 1.1 + case numberminus12 = -1.2 + } + + /** + To test enum parameters + + - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional) + - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to -efg) + - parameter enumHeaderStringArray: (header) Header parameter enum test (string array) (optional) + - parameter enumHeaderString: (header) Header parameter enum test (string) (optional, default to -efg) + - parameter enumQueryStringArray: (query) Query parameter enum test (string array) (optional) + - parameter enumQueryString: (query) Query parameter enum test (string) (optional, default to -efg) + - parameter enumQueryInteger: (query) Query parameter enum test (double) (optional) + - parameter enumQueryDouble: (form) Query parameter enum test (double) (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + testEnumParametersWithRequestBuilder(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble).execute { (response, error) -> Void in + completion(error); + } + } + + + /** + To test enum parameters + - GET /fake + - To test enum parameters + + - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional) + - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to -efg) + - parameter enumHeaderStringArray: (header) Header parameter enum test (string array) (optional) + - parameter enumHeaderString: (header) Header parameter enum test (string) (optional, default to -efg) + - parameter enumQueryStringArray: (query) Query parameter enum test (string array) (optional) + - parameter enumQueryString: (query) Query parameter enum test (string) (optional, default to -efg) + - parameter enumQueryInteger: (query) Query parameter enum test (double) (optional) + - parameter enumQueryDouble: (form) Query parameter enum test (double) (optional) + + - returns: RequestBuilder + */ + open class func testEnumParametersWithRequestBuilder(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil) -> RequestBuilder { + let path = "/fake" + let URLString = PetstoreClientAPI.basePath + path + let formParams: [String:Any?] = [ + "enum_form_string_array": enumFormStringArray, + "enum_form_string": enumFormString?.rawValue, + "enum_query_double": enumQueryDouble?.rawValue + ] + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + "enum_query_string_array": enumQueryStringArray, + "enum_query_string": enumQueryString?.rawValue, + "enum_query_integer": enumQueryInteger?.rawValue + ]) + + let nillableHeaders: [String: Any?] = [ + "enum_header_string_array": enumHeaderStringArray, + "enum_header_string": enumHeaderString?.rawValue + ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + } + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/FakeclassnametagsAPI.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/FakeclassnametagsAPI.swift new file mode 100644 index 0000000000..19ab8370d4 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/FakeclassnametagsAPI.swift @@ -0,0 +1,49 @@ +// +// FakeclassnametagsAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire + + + +open class FakeclassnametagsAPI { + /** + To test class name in snake case + + - parameter body: (body) client model + - parameter completion: completion handler to receive the data and the error objects + */ + open class func testClassname(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { + testClassnameWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + + /** + To test class name in snake case + - PATCH /fake_classname_test + - examples: [{contentType=application/json, example={ + "client" : "aeiou" +}}] + + - parameter body: (body) client model + + - returns: RequestBuilder + */ + open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { + let path = "/fake_classname_test" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "PATCH", URLString: URLString, parameters: convertedParameters, isBody: true) + } + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift new file mode 100644 index 0000000000..71c66fc9f5 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -0,0 +1,506 @@ +// +// PetAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire + + + +open class PetAPI { + /** + Add a new pet to the store + + - parameter body: (body) Pet object that needs to be added to the store + - parameter completion: completion handler to receive the data and the error objects + */ + open class func addPet(body: Pet, completion: @escaping ((_ error: Error?) -> Void)) { + addPetWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error); + } + } + + + /** + 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 + + - returns: RequestBuilder + */ + open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder { + let path = "/pet" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + Deletes a pet + + - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + open class func deletePet(petId: Int64, apiKey: String? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (response, error) -> Void in + completion(error); + } + } + + + /** + Deletes a pet + - DELETE /pet/{petId} + - + - OAuth: + - type: oauth2 + - name: petstore_auth + + - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) + + - returns: RequestBuilder + */ + open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder { + var path = "/pet/{petId}" + path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + "api_key": apiKey + ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + } + + /** + * enum for parameter status + */ + public enum Status_findPetsByStatus: String { + case available = "available" + case pending = "pending" + case sold = "sold" + } + + /** + Finds Pets by status + + - parameter status: (query) Status values that need to be considered for filter + - parameter completion: completion handler to receive the data and the error objects + */ + open class func findPetsByStatus(status: [String], completion: @escaping ((_ data: [Pet]?,_ error: Error?) -> Void)) { + findPetsByStatusWithRequestBuilder(status: status).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + + /** + Finds Pets by status + - GET /pet/findByStatus + - Multiple status values can be provided with comma separated strings + - OAuth: + - type: oauth2 + - name: petstore_auth + - examples: [{contentType=application/xml, example= + 123456789 + doggie + + aeiou + + + + aeiou +}, {contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "aeiou", + "id" : 6 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 1 + } ], + "status" : "available" +} ]}] + - examples: [{contentType=application/xml, example= + 123456789 + doggie + + aeiou + + + + aeiou +}, {contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "aeiou", + "id" : 6 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 1 + } ], + "status" : "available" +} ]}] + + - parameter status: (query) Status values that need to be considered for filter + + - returns: RequestBuilder<[Pet]> + */ + open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + let path = "/pet/findByStatus" + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + "status": status + ]) + + + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Finds Pets by tags + + - parameter tags: (query) Tags to filter by + - parameter completion: completion handler to receive the data and the error objects + */ + open class func findPetsByTags(tags: [String], completion: @escaping ((_ data: [Pet]?,_ error: Error?) -> Void)) { + findPetsByTagsWithRequestBuilder(tags: tags).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + + /** + Finds Pets by tags + - GET /pet/findByTags + - Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + - OAuth: + - type: oauth2 + - name: petstore_auth + - examples: [{contentType=application/xml, example= + 123456789 + doggie + + aeiou + + + + aeiou +}, {contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "aeiou", + "id" : 6 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 1 + } ], + "status" : "available" +} ]}] + - examples: [{contentType=application/xml, example= + 123456789 + doggie + + aeiou + + + + aeiou +}, {contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "aeiou", + "id" : 6 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 1 + } ], + "status" : "available" +} ]}] + + - parameter tags: (query) Tags to filter by + + - returns: RequestBuilder<[Pet]> + */ + open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { + let path = "/pet/findByTags" + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + "tags": tags + ]) + + + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Find pet by ID + + - parameter petId: (path) ID of pet to return + - parameter completion: completion handler to receive the data and the error objects + */ + open class func getPetById(petId: Int64, completion: @escaping ((_ data: Pet?,_ error: Error?) -> Void)) { + getPetByIdWithRequestBuilder(petId: petId).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + + /** + Find pet by ID + - GET /pet/{petId} + - Returns a single pet + - API Key: + - type: apiKey api_key + - name: api_key + - examples: [{contentType=application/xml, example= + 123456789 + doggie + + aeiou + + + + aeiou +}, {contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "aeiou", + "id" : 6 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 1 + } ], + "status" : "available" +}}] + - examples: [{contentType=application/xml, example= + 123456789 + doggie + + aeiou + + + + aeiou +}, {contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "aeiou", + "id" : 6 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 1 + } ], + "status" : "available" +}}] + + - parameter petId: (path) ID of pet to return + + - returns: RequestBuilder + */ + open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder { + var path = "/pet/{petId}" + path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Update an existing pet + + - parameter body: (body) Pet object that needs to be added to the store + - parameter completion: completion handler to receive the data and the error objects + */ + open class func updatePet(body: Pet, completion: @escaping ((_ error: Error?) -> Void)) { + updatePetWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error); + } + } + + + /** + 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 + + - returns: RequestBuilder + */ + open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder { + let path = "/pet" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, 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 + */ + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (response, error) -> Void in + completion(error); + } + } + + + /** + 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 + */ + open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder { + var path = "/pet/{petId}" + path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let formParams: [String:Any?] = [ + "name": name, + "status": status + ] + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, 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 + */ + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, completion: @escaping ((_ data: ApiResponse?,_ error: Error?) -> Void)) { + uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + + /** + uploads an image + - POST /pet/{petId}/uploadImage + - + - OAuth: + - type: oauth2 + - name: petstore_auth + - examples: [{contentType=application/json, example={ + "code" : 0, + "type" : "aeiou", + "message" : "aeiou" +}}] + + - 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 + */ + open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder { + var path = "/pet/{petId}/uploadImage" + path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let formParams: [String:Any?] = [ + "additionalMetadata": additionalMetadata, + "file": file + ] + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift new file mode 100644 index 0000000000..8ba921a9b8 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -0,0 +1,219 @@ +// +// StoreAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire + + + +open class StoreAPI { + /** + 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 + */ + open class func deleteOrder(orderId: String, completion: @escaping ((_ error: Error?) -> Void)) { + deleteOrderWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in + completion(error); + } + } + + + /** + Delete purchase order by ID + - DELETE /store/order/{order_id} + - 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 + */ + open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder { + var path = "/store/order/{order_id}" + path = path.replacingOccurrences(of: "{order_id}", with: "\(orderId)", options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Returns pet inventories by status + + - parameter completion: completion handler to receive the data and the error objects + */ + open class func getInventory(completion: @escaping ((_ data: [String:Int32]?,_ error: Error?) -> Void)) { + getInventoryWithRequestBuilder().execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + + /** + Returns pet inventories by status + - GET /store/inventory + - Returns a map of status codes to quantities + - API Key: + - type: apiKey api_key + - name: api_key + - examples: [{contentType=application/json, example={ + "key" : 0 +}}] + + - returns: RequestBuilder<[String:Int32]> + */ + open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String:Int32]> { + let path = "/store/inventory" + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder<[String:Int32]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + 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 + */ + open class func getOrderById(orderId: Int64, completion: @escaping ((_ data: Order?,_ error: Error?) -> Void)) { + getOrderByIdWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + + /** + Find purchase order by ID + - GET /store/order/{order_id} + - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + - examples: [{contentType=application/xml, example= + 123456789 + 123456789 + 123 + 2000-01-23T04:56:07.000Z + aeiou + true +}, {contentType=application/json, example={ + "petId" : 6, + "quantity" : 1, + "id" : 0, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : false, + "status" : "placed" +}}] + - examples: [{contentType=application/xml, example= + 123456789 + 123456789 + 123 + 2000-01-23T04:56:07.000Z + aeiou + true +}, {contentType=application/json, example={ + "petId" : 6, + "quantity" : 1, + "id" : 0, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : false, + "status" : "placed" +}}] + + - parameter orderId: (path) ID of pet that needs to be fetched + + - returns: RequestBuilder + */ + open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder { + var path = "/store/order/{order_id}" + path = path.replacingOccurrences(of: "{order_id}", with: "\(orderId)", options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Place an order for a pet + + - parameter body: (body) order placed for purchasing the pet + - parameter completion: completion handler to receive the data and the error objects + */ + open class func placeOrder(body: Order, completion: @escaping ((_ data: Order?,_ error: Error?) -> Void)) { + placeOrderWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + + /** + Place an order for a pet + - POST /store/order + - + - examples: [{contentType=application/xml, example= + 123456789 + 123456789 + 123 + 2000-01-23T04:56:07.000Z + aeiou + true +}, {contentType=application/json, example={ + "petId" : 6, + "quantity" : 1, + "id" : 0, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : false, + "status" : "placed" +}}] + - examples: [{contentType=application/xml, example= + 123456789 + 123456789 + 123 + 2000-01-23T04:56:07.000Z + aeiou + true +}, {contentType=application/json, example={ + "petId" : 6, + "quantity" : 1, + "id" : 0, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : false, + "status" : "placed" +}}] + + - parameter body: (body) order placed for purchasing the pet + + - returns: RequestBuilder + */ + open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder { + let path = "/store/order" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift new file mode 100644 index 0000000000..f98a0343f5 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -0,0 +1,344 @@ +// +// UserAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire + + + +open class UserAPI { + /** + Create user + + - parameter body: (body) Created user object + - parameter completion: completion handler to receive the data and the error objects + */ + open class func createUser(body: User, completion: @escaping ((_ error: Error?) -> Void)) { + createUserWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error); + } + } + + + /** + Create user + - POST /user + - This can only be done by the logged in user. + + - parameter body: (body) Created user object + + - returns: RequestBuilder + */ + open class func createUserWithRequestBuilder(body: User) -> RequestBuilder { + let path = "/user" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + Creates list of users with given input array + + - parameter body: (body) List of user object + - parameter completion: completion handler to receive the data and the error objects + */ + open class func createUsersWithArrayInput(body: [User], completion: @escaping ((_ error: Error?) -> Void)) { + createUsersWithArrayInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error); + } + } + + + /** + Creates list of users with given input array + - POST /user/createWithArray + - + + - parameter body: (body) List of user object + + - returns: RequestBuilder + */ + open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder { + let path = "/user/createWithArray" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + Creates list of users with given input array + + - parameter body: (body) List of user object + - parameter completion: completion handler to receive the data and the error objects + */ + open class func createUsersWithListInput(body: [User], completion: @escaping ((_ error: Error?) -> Void)) { + createUsersWithListInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error); + } + } + + + /** + Creates list of users with given input array + - POST /user/createWithList + - + + - parameter body: (body) List of user object + + - returns: RequestBuilder + */ + open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder { + let path = "/user/createWithList" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, 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 + */ + open class func deleteUser(username: String, completion: @escaping ((_ error: Error?) -> Void)) { + deleteUserWithRequestBuilder(username: username).execute { (response, error) -> Void in + completion(error); + } + } + + + /** + 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 + */ + open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder { + var path = "/user/{username}" + path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + 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 + */ + open class func getUserByName(username: String, completion: @escaping ((_ data: User?,_ error: Error?) -> Void)) { + getUserByNameWithRequestBuilder(username: username).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + + /** + Get user by user name + - GET /user/{username} + - + - examples: [{contentType=application/xml, example= + 123456789 + aeiou + aeiou + aeiou + aeiou + aeiou + aeiou + 123 +}, {contentType=application/json, example={ + "firstName" : "aeiou", + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 6, + "phone" : "aeiou", + "id" : 0, + "email" : "aeiou", + "username" : "aeiou" +}}] + - examples: [{contentType=application/xml, example= + 123456789 + aeiou + aeiou + aeiou + aeiou + aeiou + aeiou + 123 +}, {contentType=application/json, example={ + "firstName" : "aeiou", + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 6, + "phone" : "aeiou", + "id" : 0, + "email" : "aeiou", + "username" : "aeiou" +}}] + + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + + - returns: RequestBuilder + */ + open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder { + var path = "/user/{username}" + path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Logs user into the system + + - parameter username: (query) The user name for login + - parameter password: (query) The password for login in clear text + - parameter completion: completion handler to receive the data and the error objects + */ + open class func loginUser(username: String, password: String, completion: @escaping ((_ data: String?,_ error: Error?) -> Void)) { + loginUserWithRequestBuilder(username: username, password: password).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + + /** + Logs user into the system + - GET /user/login + - + - responseHeaders: [X-Rate-Limit(Int32), X-Expires-After(Date)] + - responseHeaders: [X-Rate-Limit(Int32), X-Expires-After(Date)] + - examples: [{contentType=application/xml, example=aeiou}, {contentType=application/json, example="aeiou"}] + - examples: [{contentType=application/xml, example=aeiou}, {contentType=application/json, example="aeiou"}] + + - parameter username: (query) The user name for login + - parameter password: (query) The password for login in clear text + + - returns: RequestBuilder + */ + open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { + let path = "/user/login" + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + "username": username, + "password": password + ]) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Logs out current logged in user session + + - parameter completion: completion handler to receive the data and the error objects + */ + open class func logoutUser(completion: @escaping ((_ error: Error?) -> Void)) { + logoutUserWithRequestBuilder().execute { (response, error) -> Void in + completion(error); + } + } + + + /** + Logs out current logged in user session + - GET /user/logout + - + + - returns: RequestBuilder + */ + open class func logoutUserWithRequestBuilder() -> RequestBuilder { + let path = "/user/logout" + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Updated user + + - parameter username: (path) name that need to be deleted + - parameter body: (body) Updated user object + - parameter completion: completion handler to receive the data and the error objects + */ + open class func updateUser(username: String, body: User, completion: @escaping ((_ error: Error?) -> Void)) { + updateUserWithRequestBuilder(username: username, body: body).execute { (response, error) -> Void in + completion(error); + } + } + + + /** + 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 + + - returns: RequestBuilder + */ + open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder { + var path = "/user/{username}" + path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift new file mode 100644 index 0000000000..b9d2a2727d --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -0,0 +1,307 @@ +// AlamofireImplementations.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire + +class AlamofireRequestBuilderFactory: RequestBuilderFactory { + func getNonDecodableBuilder() -> RequestBuilder.Type { + return AlamofireRequestBuilder.self + } + + func getBuilder() -> RequestBuilder.Type { + return AlamofireDecodableRequestBuilder.self + } +} + +// Store manager to retain its reference +private var managerStore: [String: Alamofire.SessionManager] = [:] + +open class AlamofireRequestBuilder: RequestBuilder { + required public init(method: String, URLString: String, parameters: [String : Any]?, isBody: Bool, headers: [String : String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody, headers: headers) + } + + /** + May be overridden by a subclass if you want to control the session + configuration. + */ + open func createSessionManager() -> Alamofire.SessionManager { + let configuration = URLSessionConfiguration.default + configuration.httpAdditionalHeaders = buildHeaders() + return Alamofire.SessionManager(configuration: configuration) + } + + /** + May be overridden by a subclass if you want to control the Content-Type + that is given to an uploaded form part. + + Return nil to use the default behavior (inferring the Content-Type from + the file extension). Return the desired Content-Type otherwise. + */ + open func contentTypeForFormPart(fileURL: URL) -> String? { + return nil + } + + /** + May be overridden by a subclass if you want to control the request + configuration (e.g. to override the cache policy). + */ + open func makeRequest(manager: SessionManager, method: HTTPMethod, encoding: ParameterEncoding, headers: [String:String]) -> DataRequest { + return manager.request(URLString, method: method, parameters: parameters, encoding: encoding, headers: headers) + } + + override open func execute(_ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { + let managerId:String = UUID().uuidString + // Create a new manager for each request to customize its request header + let manager = createSessionManager() + managerStore[managerId] = manager + + let encoding:ParameterEncoding = isBody ? JSONDataEncoding() : URLEncoding() + + let xMethod = Alamofire.HTTPMethod(rawValue: method) + let fileKeys = parameters == nil ? [] : parameters!.filter { $1 is NSURL } + .map { $0.0 } + + if fileKeys.count > 0 { + manager.upload(multipartFormData: { mpForm in + for (k, v) in self.parameters! { + switch v { + case let fileURL as URL: + if let mimeType = self.contentTypeForFormPart(fileURL: fileURL) { + mpForm.append(fileURL, withName: k, fileName: fileURL.lastPathComponent, mimeType: mimeType) + } + else { + mpForm.append(fileURL, withName: k) + } + break + case let string as String: + mpForm.append(string.data(using: String.Encoding.utf8)!, withName: k) + break + case let number as NSNumber: + mpForm.append(number.stringValue.data(using: String.Encoding.utf8)!, withName: k) + break + default: + fatalError("Unprocessable value \(v) with key \(k)") + break + } + } + }, to: URLString, method: xMethod!, headers: nil, encodingCompletion: { encodingResult in + switch encodingResult { + case .success(let upload, _, _): + if let onProgressReady = self.onProgressReady { + onProgressReady(upload.uploadProgress) + } + self.processRequest(request: upload, managerId, completion) + case .failure(let encodingError): + completion(nil, ErrorResponse.Error(415, nil, encodingError)) + } + }) + } else { + let request = makeRequest(manager: manager, method: xMethod!, encoding: encoding, headers: headers) + if let onProgressReady = self.onProgressReady { + onProgressReady(request.progress) + } + processRequest(request: request, managerId, completion) + } + + } + + fileprivate func processRequest(request: DataRequest, _ managerId: String, _ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { + if let credential = self.credential { + request.authenticate(usingCredential: credential) + } + + let cleanupRequest = { + _ = managerStore.removeValue(forKey: managerId) + } + + let validatedRequest = request.validate() + + switch T.self { + case is String.Type: + validatedRequest.responseString(completionHandler: { (stringResponse) in + cleanupRequest() + + if stringResponse.result.isFailure { + completion( + nil, + ErrorResponse.Error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.result.error as Error!) + ) + return + } + + completion( + Response( + response: stringResponse.response!, + body: ((stringResponse.result.value ?? "") as! T) + ), + nil + ) + }) + case is Void.Type: + validatedRequest.responseData(completionHandler: { (voidResponse) in + cleanupRequest() + + if voidResponse.result.isFailure { + completion( + nil, + ErrorResponse.Error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.result.error!) + ) + return + } + + completion( + Response( + response: voidResponse.response!, + body: nil), + nil + ) + }) + default: + validatedRequest.responseData(completionHandler: { (dataResponse) in + cleanupRequest() + + if (dataResponse.result.isFailure) { + completion( + nil, + ErrorResponse.Error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!) + ) + return + } + + completion( + Response( + response: dataResponse.response!, + body: (dataResponse.data as! T) + ), + nil + ) + }) + } + } + + open func buildHeaders() -> [String: String] { + var httpHeaders = SessionManager.defaultHTTPHeaders + for (key, value) in self.headers { + httpHeaders[key] = value + } + return httpHeaders + } +} + +public enum AlamofireDecodableRequestBuilderError: Error { + case emptyDataResponse + case nilHTTPResponse + case jsonDecoding(DecodingError) + case generalError(Error) +} + +open class AlamofireDecodableRequestBuilder: AlamofireRequestBuilder { + + override fileprivate func processRequest(request: DataRequest, _ managerId: String, _ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { + if let credential = self.credential { + request.authenticate(usingCredential: credential) + } + + let cleanupRequest = { + _ = managerStore.removeValue(forKey: managerId) + } + + let validatedRequest = request.validate() + + switch T.self { + case is String.Type: + validatedRequest.responseString(completionHandler: { (stringResponse) in + cleanupRequest() + + if stringResponse.result.isFailure { + completion( + nil, + ErrorResponse.Error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.result.error as Error!) + ) + return + } + + completion( + Response( + response: stringResponse.response!, + body: ((stringResponse.result.value ?? "") as! T) + ), + nil + ) + }) + case is Void.Type: + validatedRequest.responseData(completionHandler: { (voidResponse) in + cleanupRequest() + + if voidResponse.result.isFailure { + completion( + nil, + ErrorResponse.Error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.result.error!) + ) + return + } + + completion( + Response( + response: voidResponse.response!, + body: nil), + nil + ) + }) + case is Data.Type: + validatedRequest.responseData(completionHandler: { (dataResponse) in + cleanupRequest() + + if (dataResponse.result.isFailure) { + completion( + nil, + ErrorResponse.Error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!) + ) + return + } + + completion( + Response( + response: dataResponse.response!, + body: (dataResponse.data as! T) + ), + nil + ) + }) + default: + validatedRequest.responseData(completionHandler: { (dataResponse: DataResponse) in + cleanupRequest() + + guard dataResponse.result.isSuccess else { + completion(nil, ErrorResponse.Error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!)) + return + } + + guard let data = dataResponse.data, !data.isEmpty else { + completion(nil, ErrorResponse.Error(-1, nil, AlamofireDecodableRequestBuilderError.emptyDataResponse)) + return + } + + guard let httpResponse = dataResponse.response else { + completion(nil, ErrorResponse.Error(-2, nil, AlamofireDecodableRequestBuilderError.nilHTTPResponse)) + return + } + + var responseObj: Response? = nil + + let decodeResult: (decodableObj: T?, error: Error?) = CodableHelper.decode(T.self, from: data) + if decodeResult.error == nil { + responseObj = Response(response: httpResponse, body: decodeResult.decodableObj) + } + + completion(responseObj, decodeResult.error) + }) + } + } + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/CodableHelper.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/CodableHelper.swift new file mode 100644 index 0000000000..7603003824 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/CodableHelper.swift @@ -0,0 +1,53 @@ +// +// CodableHelper.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +public typealias EncodeResult = (data: Data?, error: Error?) + +open class CodableHelper { + + open class func decode(_ type: T.Type, from data: Data) -> (decodableObj: T?, error: Error?) where T : Decodable { + var returnedDecodable: T? = nil + var returnedError: Error? = nil + + let decoder = JSONDecoder() + decoder.dataDecodingStrategy = .base64Decode + if #available(iOS 10.0, *) { + decoder.dateDecodingStrategy = .iso8601 + } + + do { + returnedDecodable = try decoder.decode(type, from: data) + } catch { + returnedError = error + } + + return (returnedDecodable, returnedError) + } + + open class func encode(_ value: T, prettyPrint: Bool = false) -> EncodeResult where T : Encodable { + var returnedData: Data? + var returnedError: Error? = nil + + let encoder = JSONEncoder() + encoder.outputFormatting = (prettyPrint ? .prettyPrinted : .compact) + encoder.dataEncodingStrategy = .base64Encode + if #available(iOS 10.0, *) { + encoder.dateEncodingStrategy = .iso8601 + } + + do { + returnedData = try encoder.encode(value) + } catch { + returnedError = error + } + + return (returnedData, returnedError) + } + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Configuration.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Configuration.swift new file mode 100644 index 0000000000..c03a10b930 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Configuration.swift @@ -0,0 +1,15 @@ +// Configuration.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +open class Configuration { + + // This value is used to configure the date formatter that is used to serialize dates into JSON format. + // You must set it prior to encoding any dates, and it will only be read once. + open static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + +} \ No newline at end of file diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Extensions.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Extensions.swift new file mode 100644 index 0000000000..202b47449d --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Extensions.swift @@ -0,0 +1,87 @@ +// Extensions.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire + +extension Bool: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension Float: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension Int: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension Int32: JSONEncodable { + func encodeToJSON() -> Any { return NSNumber(value: self as Int32) } +} + +extension Int64: JSONEncodable { + func encodeToJSON() -> Any { return NSNumber(value: self as Int64) } +} + +extension Double: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension String: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +private func encodeIfPossible(_ object: T) -> Any { + if let encodableObject = object as? JSONEncodable { + return encodableObject.encodeToJSON() + } else { + return object as Any + } +} + +extension Array: JSONEncodable { + func encodeToJSON() -> Any { + return self.map(encodeIfPossible) + } +} + +extension Dictionary: JSONEncodable { + func encodeToJSON() -> Any { + var dictionary = [AnyHashable: Any]() + for (key, value) in self { + dictionary[key as! NSObject] = encodeIfPossible(value) + } + return dictionary as Any + } +} + +extension Data: JSONEncodable { + func encodeToJSON() -> Any { + return self.base64EncodedString(options: Data.Base64EncodingOptions()) + } +} + +private let dateFormatter: DateFormatter = { + let fmt = DateFormatter() + fmt.dateFormat = Configuration.dateFormat + fmt.locale = Locale(identifier: "en_US_POSIX") + return fmt +}() + +extension Date: JSONEncodable { + func encodeToJSON() -> Any { + return dateFormatter.string(from: self) as Any + } +} + +extension UUID: JSONEncodable { + func encodeToJSON() -> Any { + return self.uuidString + } +} + + diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/JSONEncodableEncoding.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/JSONEncodableEncoding.swift new file mode 100644 index 0000000000..472e955ee8 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/JSONEncodableEncoding.swift @@ -0,0 +1,54 @@ +// +// JSONDataEncoding.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire + +public struct JSONDataEncoding: ParameterEncoding { + + // MARK: Properties + + private static let jsonDataKey = "jsonData" + + // MARK: Encoding + + /// 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. This should have a single key/value + /// pair with "jsonData" as the key and a Data object as the value. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let jsonData = parameters?[JSONDataEncoding.jsonDataKey] as? Data, !jsonData.isEmpty else { + return urlRequest + } + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = jsonData + + return urlRequest + } + + public static func encodingParameters(jsonData: Data?) -> Parameters? { + var returnedParams: Parameters? = nil + if let jsonData = jsonData, !jsonData.isEmpty { + var params = Parameters() + params[jsonDataKey] = jsonData + returnedParams = params + } + return returnedParams + } + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/JSONEncodingHelper.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/JSONEncodingHelper.swift new file mode 100644 index 0000000000..4cf4ac206a --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/JSONEncodingHelper.swift @@ -0,0 +1,27 @@ +// +// JSONEncodingHelper.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire + +open class JSONEncodingHelper { + + open class func encodingParameters(forEncodableObject encodableObj: T?) -> Parameters? { + var params: Parameters? = nil + + // Encode the Encodable object + if let encodableObj = encodableObj { + let encodeResult = CodableHelper.encode(encodableObj, prettyPrint: true) + if encodeResult.error == nil { + params = JSONDataEncoding.encodingParameters(jsonData: encodeResult.data) + } + } + + return params + } + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models.swift new file mode 100644 index 0000000000..2c19b32158 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models.swift @@ -0,0 +1,36 @@ +// Models.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +protocol JSONEncodable { + func encodeToJSON() -> Any +} + +public enum ErrorResponse : Error { + case Error(Int, Data?, Error) +} + +open class Response { + open let statusCode: Int + open let header: [String: String] + open 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: HTTPURLResponse, 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) + } +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift new file mode 100644 index 0000000000..8d3e08500d --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift @@ -0,0 +1,18 @@ +// +// AdditionalPropertiesClass.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class AdditionalPropertiesClass: Codable { + + public var mapProperty: [String:String]? + public var mapOfMapProperty: [String:[String:String]]? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Animal.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Animal.swift new file mode 100644 index 0000000000..b2079ff79c --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Animal.swift @@ -0,0 +1,18 @@ +// +// Animal.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Animal: Codable { + + public var className: String? + public var color: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/AnimalFarm.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/AnimalFarm.swift new file mode 100644 index 0000000000..6830836489 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/AnimalFarm.swift @@ -0,0 +1,11 @@ +// +// AnimalFarm.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift new file mode 100644 index 0000000000..b9af1103e2 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift @@ -0,0 +1,19 @@ +// +// ApiResponse.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class ApiResponse: Codable { + + public var code: Int32? + public var type: String? + public var message: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift new file mode 100644 index 0000000000..7eb6b23bd2 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift @@ -0,0 +1,17 @@ +// +// ArrayOfArrayOfNumberOnly.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class ArrayOfArrayOfNumberOnly: Codable { + + public var arrayArrayNumber: [[Double]]? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift new file mode 100644 index 0000000000..ab6493cb3c --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift @@ -0,0 +1,17 @@ +// +// ArrayOfNumberOnly.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class ArrayOfNumberOnly: Codable { + + public var arrayNumber: [Double]? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift new file mode 100644 index 0000000000..bf28bb3cc9 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift @@ -0,0 +1,19 @@ +// +// ArrayTest.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class ArrayTest: Codable { + + public var arrayOfString: [String]? + public var arrayArrayOfInteger: [[Int64]]? + public var arrayArrayOfModel: [[ReadOnlyFirst]]? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift new file mode 100644 index 0000000000..e9569b9fb0 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift @@ -0,0 +1,23 @@ +// +// Capitalization.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Capitalization: Codable { + + public var smallCamel: String? + public var capitalCamel: String? + public var smallSnake: String? + public var capitalSnake: String? + public var sCAETHFlowPoints: String? + /** Name of the pet */ + public var ATT_NAME: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Cat.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Cat.swift new file mode 100644 index 0000000000..5ea6f4ea94 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Cat.swift @@ -0,0 +1,17 @@ +// +// Cat.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Cat: Animal { + + public var declawed: Bool? + + + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Category.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Category.swift new file mode 100644 index 0000000000..e21a4c54dd --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Category.swift @@ -0,0 +1,18 @@ +// +// Category.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Category: Codable { + + public var id: Int64? + public var name: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift new file mode 100644 index 0000000000..8fe4a89e76 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift @@ -0,0 +1,18 @@ +// +// ClassModel.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +/** Model for testing model with \"_class\" property */ +open class ClassModel: Codable { + + public var _class: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Client.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Client.swift new file mode 100644 index 0000000000..874bdd7cee --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Client.swift @@ -0,0 +1,17 @@ +// +// Client.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Client: Codable { + + public var client: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Dog.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Dog.swift new file mode 100644 index 0000000000..2b4c3f8a3e --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Dog.swift @@ -0,0 +1,17 @@ +// +// Dog.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Dog: Animal { + + public var breed: String? + + + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift new file mode 100644 index 0000000000..d3da696d1c --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift @@ -0,0 +1,26 @@ +// +// EnumArrays.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class EnumArrays: Codable { + + public enum JustSymbol: String, Codable { + case greaterThanOrEqualTo = ">=" + case dollar = "$" + } + public enum ArrayEnum: String, Codable { + case fish = "fish" + case crab = "crab" + } + public var justSymbol: JustSymbol? + public var arrayEnum: [ArrayEnum]? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/EnumClass.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/EnumClass.swift new file mode 100644 index 0000000000..d0889a3520 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/EnumClass.swift @@ -0,0 +1,16 @@ +// +// EnumClass.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public enum EnumClass: String, Codable { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift new file mode 100644 index 0000000000..7e0266de3f --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift @@ -0,0 +1,33 @@ +// +// EnumTest.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class EnumTest: Codable { + + public enum EnumString: String, Codable { + case upper = "UPPER" + case lower = "lower" + case empty = "" + } + public enum EnumInteger: Int32, Codable { + case _1 = 1 + case numberminus1 = -1 + } + public enum EnumNumber: Double, Codable { + case _11 = 1.1 + case numberminus12 = -1.2 + } + public var enumString: EnumString? + public var enumInteger: EnumInteger? + public var enumNumber: EnumNumber? + public var outerEnum: OuterEnum? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift new file mode 100644 index 0000000000..3c6ef7d3e3 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift @@ -0,0 +1,29 @@ +// +// FormatTest.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class FormatTest: Codable { + + public var integer: Int32? + public var int32: Int32? + public var int64: Int64? + public var number: Double? + public var float: Float? + public var double: Double? + public var string: String? + public var byte: Data? + public var binary: Data? + public var date: Date? + public var dateTime: Date? + public var uuid: UUID? + public var password: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift new file mode 100644 index 0000000000..fef361d308 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift @@ -0,0 +1,18 @@ +// +// HasOnlyReadOnly.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class HasOnlyReadOnly: Codable { + + public var bar: String? + public var foo: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/List.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/List.swift new file mode 100644 index 0000000000..5fab950e8e --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/List.swift @@ -0,0 +1,17 @@ +// +// List.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class List: Codable { + + public var _123List: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/MapTest.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/MapTest.swift new file mode 100644 index 0000000000..584b181f02 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/MapTest.swift @@ -0,0 +1,22 @@ +// +// MapTest.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class MapTest: Codable { + + public enum MapOfEnumString: String, Codable { + case upper = "UPPER" + case lower = "lower" + } + public var mapMapOfString: [String:[String:String]]? + public var mapOfEnumString: [String:String]? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift new file mode 100644 index 0000000000..7fd6c6cf10 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -0,0 +1,19 @@ +// +// MixedPropertiesAndAdditionalPropertiesClass.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class MixedPropertiesAndAdditionalPropertiesClass: Codable { + + public var uuid: UUID? + public var dateTime: Date? + public var map: [String:Animal]? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift new file mode 100644 index 0000000000..ac1ec94073 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift @@ -0,0 +1,19 @@ +// +// Model200Response.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +/** Model for testing model name starting with number */ +open class Model200Response: Codable { + + public var name: Int32? + public var _class: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Name.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Name.swift new file mode 100644 index 0000000000..de6751e52d --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Name.swift @@ -0,0 +1,21 @@ +// +// Name.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +/** Model for testing model name same as property name */ +open class Name: Codable { + + public var name: Int32? + public var snakeCase: Int32? + public var property: String? + public var _123Number: Int32? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift new file mode 100644 index 0000000000..e4f4dc0f7c --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift @@ -0,0 +1,17 @@ +// +// NumberOnly.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class NumberOnly: Codable { + + public var justNumber: Double? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Order.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Order.swift new file mode 100644 index 0000000000..f5fab2487e --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Order.swift @@ -0,0 +1,28 @@ +// +// Order.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Order: Codable { + + public enum Status: String, Codable { + case placed = "placed" + case approved = "approved" + case delivered = "delivered" + } + public var id: Int64? + public var petId: Int64? + public var quantity: Int32? + public var shipDate: Date? + /** Order Status */ + public var status: Status? + public var complete: Bool? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/OuterBoolean.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/OuterBoolean.swift new file mode 100644 index 0000000000..3c49ad2940 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/OuterBoolean.swift @@ -0,0 +1,11 @@ +// +// OuterBoolean.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public typealias OuterBoolean = Bool diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/OuterComposite.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/OuterComposite.swift new file mode 100644 index 0000000000..6d3b435cd1 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/OuterComposite.swift @@ -0,0 +1,19 @@ +// +// OuterComposite.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class OuterComposite: Codable { + + public var myNumber: OuterNumber? + public var myString: OuterString? + public var myBoolean: OuterBoolean? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/OuterEnum.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/OuterEnum.swift new file mode 100644 index 0000000000..d6222d2b1c --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/OuterEnum.swift @@ -0,0 +1,16 @@ +// +// OuterEnum.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public enum OuterEnum: String, Codable { + case placed = "placed" + case approved = "approved" + case delivered = "delivered" + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/OuterNumber.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/OuterNumber.swift new file mode 100644 index 0000000000..f285f4e5e2 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/OuterNumber.swift @@ -0,0 +1,11 @@ +// +// OuterNumber.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public typealias OuterNumber = Double diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/OuterString.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/OuterString.swift new file mode 100644 index 0000000000..9da794627d --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/OuterString.swift @@ -0,0 +1,11 @@ +// +// OuterString.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public typealias OuterString = String diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Pet.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Pet.swift new file mode 100644 index 0000000000..08128cc529 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Pet.swift @@ -0,0 +1,28 @@ +// +// Pet.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Pet: Codable { + + public enum Status: String, Codable { + 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() {} + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift new file mode 100644 index 0000000000..0a779fdd48 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift @@ -0,0 +1,18 @@ +// +// ReadOnlyFirst.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class ReadOnlyFirst: Codable { + + public var bar: String? + public var baz: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Return.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Return.swift new file mode 100644 index 0000000000..629ec1fba6 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Return.swift @@ -0,0 +1,18 @@ +// +// Return.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +/** Model for testing reserved words */ +open class Return: Codable { + + public var _return: Int32? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift new file mode 100644 index 0000000000..e012be66e3 --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift @@ -0,0 +1,17 @@ +// +// SpecialModelName.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class SpecialModelName: Codable { + + public var specialPropertyName: Int64? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Tag.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Tag.swift new file mode 100644 index 0000000000..219dd5bade --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/Tag.swift @@ -0,0 +1,18 @@ +// +// Tag.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Tag: Codable { + + public var id: Int64? + public var name: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/User.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/User.swift new file mode 100644 index 0000000000..2e80b7d20f --- /dev/null +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/Swaggers/Models/User.swift @@ -0,0 +1,25 @@ +// +// User.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class User: Codable { + + 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() {} + +} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Podfile b/samples/client/petstore/swift4/default/SwaggerClientTests/Podfile new file mode 100644 index 0000000000..77b1f16f2f --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Podfile @@ -0,0 +1,18 @@ +use_frameworks! +source 'https://github.com/CocoaPods/Specs.git' + +target 'SwaggerClient' do + pod "PetstoreClient", :path => "../" + + target 'SwaggerClientTests' do + inherit! :search_paths + end +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + target.build_configurations.each do |configuration| + configuration.build_settings['SWIFT_VERSION'] = "3.0" + end + end +end diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Podfile.lock b/samples/client/petstore/swift4/default/SwaggerClientTests/Podfile.lock new file mode 100644 index 0000000000..de11941ae6 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Podfile.lock @@ -0,0 +1,19 @@ +PODS: + - Alamofire (4.5.0) + - PetstoreClient (0.0.1): + - Alamofire (~> 4.5) + +DEPENDENCIES: + - PetstoreClient (from `../`) + +EXTERNAL SOURCES: + PetstoreClient: + :path: ../ + +SPEC CHECKSUMS: + Alamofire: f28cdffd29de33a7bfa022cbd63ae95a27fae140 + PetstoreClient: 77e3465a18f2380eff57e5075a2d59021308dde4 + +PODFILE CHECKSUM: 417049e9ed0e4680602b34d838294778389bd418 + +COCOAPODS: 1.1.1 diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/LICENSE b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/LICENSE new file mode 100644 index 0000000000..4cfbf72a4d --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/LICENSE @@ -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. diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/README.md b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/README.md new file mode 100644 index 0000000000..e1966fdca0 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/README.md @@ -0,0 +1,1857 @@ +![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/assets/alamofire.png) + +[![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg?branch=master)](https://travis-ci.org/Alamofire/Alamofire) +[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg) +[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) +[![Platform](https://img.shields.io/cocoapods/p/Alamofire.svg?style=flat)](http://cocoadocs.org/docsets/Alamofire) +[![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat)](http://twitter.com/AlamofireSF) +[![Gitter](https://badges.gitter.im/Alamofire/Alamofire.svg)](https://gitter.im/Alamofire/Alamofire?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) + +Alamofire is an HTTP networking library written in Swift. + +- [Features](#features) +- [Component Libraries](#component-libraries) +- [Requirements](#requirements) +- [Migration Guides](#migration-guides) +- [Communication](#communication) +- [Installation](#installation) +- [Usage](#usage) + - **Intro -** [Making a Request](#making-a-request), [Response Handling](#response-handling), [Response Validation](#response-validation), [Response Caching](#response-caching) + - **HTTP -** [HTTP Methods](#http-methods), [Parameter Encoding](#parameter-encoding), [HTTP Headers](#http-headers), [Authentication](#authentication) + - **Large Data -** [Downloading Data to a File](#downloading-data-to-a-file), [Uploading Data to a Server](#uploading-data-to-a-server) + - **Tools -** [Statistical Metrics](#statistical-metrics), [cURL Command Output](#curl-command-output) +- [Advanced Usage](#advanced-usage) + - **URL Session -** [Session Manager](#session-manager), [Session Delegate](#session-delegate), [Request](#request) + - **Routing -** [Routing Requests](#routing-requests), [Adapting and Retrying Requests](#adapting-and-retrying-requests) + - **Model Objects -** [Custom Response Serialization](#custom-response-serialization) + - **Connection -** [Security](#security), [Network Reachability](#network-reachability) +- [Open Radars](#open-radars) +- [FAQ](#faq) +- [Credits](#credits) +- [Donations](#donations) +- [License](#license) + +## Features + +- [x] Chainable Request / Response Methods +- [x] URL / JSON / plist Parameter Encoding +- [x] Upload File / Data / Stream / MultipartFormData +- [x] Download File using Request or Resume Data +- [x] Authentication with URLCredential +- [x] HTTP Response Validation +- [x] Upload and Download Progress Closures with Progress +- [x] cURL Command Output +- [x] Dynamically Adapt and Retry Requests +- [x] TLS Certificate and Public Key Pinning +- [x] Network Reachability +- [x] Comprehensive Unit and Integration Test Coverage +- [x] [Complete Documentation](http://cocoadocs.org/docsets/Alamofire) + +## Component Libraries + +In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem. + +- [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system. +- [AlamofireNetworkActivityIndicator](https://github.com/Alamofire/AlamofireNetworkActivityIndicator) - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support `URLSession` instances not managed by Alamofire. + +## Requirements + +- iOS 8.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ +- Xcode 8.1, 8.2, 8.3, and 9.0 +- Swift 3.0, 3.1, 3.2, and 4.0 + +## Migration Guides + +- [Alamofire 4.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md) +- [Alamofire 3.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md) +- [Alamofire 2.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%202.0%20Migration%20Guide.md) + +## Communication + +- If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/alamofire). (Tag 'alamofire') +- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/alamofire). +- If you **found a bug**, open an issue. +- If you **have a feature request**, open an issue. +- If you **want to contribute**, submit a pull request. + +## Installation + +### CocoaPods + +[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command: + +```bash +$ gem install cocoapods +``` + +> CocoaPods 1.1.0+ is required to build Alamofire 4.0.0+. + +To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`: + +```ruby +source 'https://github.com/CocoaPods/Specs.git' +platform :ios, '10.0' +use_frameworks! + +target '' do + pod 'Alamofire', '~> 4.4' +end +``` + +Then, run the following command: + +```bash +$ pod install +``` + +### Carthage + +[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. + +You can install Carthage with [Homebrew](http://brew.sh/) using the following command: + +```bash +$ brew update +$ brew install carthage +``` + +To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: + +```ogdl +github "Alamofire/Alamofire" ~> 4.4 +``` + +Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project. + +### Swift Package Manager + +The [Swift Package Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the `swift` compiler. It is in early development, but Alamofire does support its use on supported platforms. + +Once you have your Swift package set up, adding Alamofire as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`. + +```swift +dependencies: [ + .Package(url: "https://github.com/Alamofire/Alamofire.git", majorVersion: 4) +] +``` + +### Manually + +If you prefer not to use any of the aforementioned dependency managers, you can integrate Alamofire into your project manually. + +#### Embedded Framework + +- Open up Terminal, `cd` into your top-level project directory, and run the following command "if" your project is not initialized as a git repository: + + ```bash + $ git init + ``` + +- Add Alamofire as a git [submodule](http://git-scm.com/docs/git-submodule) by running the following command: + + ```bash + $ git submodule add https://github.com/Alamofire/Alamofire.git + ``` + +- Open the new `Alamofire` folder, and drag the `Alamofire.xcodeproj` into the Project Navigator of your application's Xcode project. + + > It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter. + +- Select the `Alamofire.xcodeproj` in the Project Navigator and verify the deployment target matches that of your application target. +- Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar. +- In the tab bar at the top of that window, open the "General" panel. +- Click on the `+` button under the "Embedded Binaries" section. +- You will see two different `Alamofire.xcodeproj` folders each with two different versions of the `Alamofire.framework` nested inside a `Products` folder. + + > It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`. + +- Select the top `Alamofire.framework` for iOS and the bottom one for OS X. + + > You can verify which one you selected by inspecting the build log for your project. The build target for `Alamofire` will be listed as either `Alamofire iOS`, `Alamofire macOS`, `Alamofire tvOS` or `Alamofire watchOS`. + +- And that's it! + + > The `Alamofire.framework` is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device. + +--- + +## Usage + +### Making a Request + +```swift +import Alamofire + +Alamofire.request("https://httpbin.org/get") +``` + +### Response Handling + +Handling the `Response` of a `Request` made in Alamofire involves chaining a response handler onto the `Request`. + +```swift +Alamofire.request("https://httpbin.org/get").responseJSON { response in + print("Request: \(String(describing: response.request))") // original url request + print("Response: \(String(describing: response.response))") // http url response + print("Result: \(response.result)") // response serialization result + + if let json = response.result.value { + print("JSON: \(json)") // serialized json response + } + + if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) { + print("Data: \(utf8Text)") // original server data as UTF8 string + } +} +``` + +In the above example, the `responseJSON` handler is appended to the `Request` to be executed once the `Request` is complete. Rather than blocking execution to wait for a response from the server, a [callback](http://en.wikipedia.org/wiki/Callback_%28computer_programming%29) in the form of a closure is specified to handle the response once it's received. The result of a request is only available inside the scope of a response closure. Any execution contingent on the response or data received from the server must be done within a response closure. + +> Networking in Alamofire is done _asynchronously_. Asynchronous programming may be a source of frustration to programmers unfamiliar with the concept, but there are [very good reasons](https://developer.apple.com/library/ios/qa/qa1693/_index.html) for doing it this way. + +Alamofire contains five different response handlers by default including: + +```swift +// Response Handler - Unserialized Response +func response( + queue: DispatchQueue?, + completionHandler: @escaping (DefaultDataResponse) -> Void) + -> Self + +// Response Data Handler - Serialized into Data +func responseData( + queue: DispatchQueue?, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + +// Response String Handler - Serialized into String +func responseString( + queue: DispatchQueue?, + encoding: String.Encoding?, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + +// Response JSON Handler - Serialized into Any +func responseJSON( + queue: DispatchQueue?, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + +// Response PropertyList (plist) Handler - Serialized into Any +func responsePropertyList( + queue: DispatchQueue?, + completionHandler: @escaping (DataResponse) -> Void)) + -> Self +``` + +None of the response handlers perform any validation of the `HTTPURLResponse` it gets back from the server. + +> For example, response status codes in the `400..<500` and `500..<600` ranges do NOT automatically trigger an `Error`. Alamofire uses [Response Validation](#response-validation) method chaining to achieve this. + +#### Response Handler + +The `response` handler does NOT evaluate any of the response data. It merely forwards on all information directly from the URL session delegate. It is the Alamofire equivalent of using `cURL` to execute a `Request`. + +```swift +Alamofire.request("https://httpbin.org/get").response { response in + print("Request: \(response.request)") + print("Response: \(response.response)") + print("Error: \(response.error)") + + if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) { + print("Data: \(utf8Text)") + } +} +``` + +> We strongly encourage you to leverage the other response serializers taking advantage of `Response` and `Result` types. + +#### Response Data Handler + +The `responseData` handler uses the `responseDataSerializer` (the object that serializes the server data into some other type) to extract the `Data` returned by the server. If no errors occur and `Data` is returned, the response `Result` will be a `.success` and the `value` will be of type `Data`. + +```swift +Alamofire.request("https://httpbin.org/get").responseData { response in + debugPrint("All Response Info: \(response)") + + if let data = response.result.value, let utf8Text = String(data: data, encoding: .utf8) { + print("Data: \(utf8Text)") + } +} +``` + +#### Response String Handler + +The `responseString` handler uses the `responseStringSerializer` to convert the `Data` returned by the server into a `String` with the specified encoding. If no errors occur and the server data is successfully serialized into a `String`, the response `Result` will be a `.success` and the `value` will be of type `String`. + +```swift +Alamofire.request("https://httpbin.org/get").responseString { response in + print("Success: \(response.result.isSuccess)") + print("Response String: \(response.result.value)") +} +``` + +> If no encoding is specified, Alamofire will use the text encoding specified in the `HTTPURLResponse` from the server. If the text encoding cannot be determined by the server response, it defaults to `.isoLatin1`. + +#### Response JSON Handler + +The `responseJSON` handler uses the `responseJSONSerializer` to convert the `Data` returned by the server into an `Any` type using the specified `JSONSerialization.ReadingOptions`. If no errors occur and the server data is successfully serialized into a JSON object, the response `Result` will be a `.success` and the `value` will be of type `Any`. + +```swift +Alamofire.request("https://httpbin.org/get").responseJSON { response in + debugPrint(response) + + if let json = response.result.value { + print("JSON: \(json)") + } +} +``` + +> All JSON serialization is handled by the `JSONSerialization` API in the `Foundation` framework. + +#### Chained Response Handlers + +Response handlers can even be chained: + +```swift +Alamofire.request("https://httpbin.org/get") + .responseString { response in + print("Response String: \(response.result.value)") + } + .responseJSON { response in + print("Response JSON: \(response.result.value)") + } +``` + +> It is important to note that using multiple response handlers on the same `Request` requires the server data to be serialized multiple times. Once for each response handler. + +#### Response Handler Queue + +Response handlers by default are executed on the main dispatch queue. However, a custom dispatch queue can be provided instead. + +```swift +let utilityQueue = DispatchQueue.global(qos: .utility) + +Alamofire.request("https://httpbin.org/get").responseJSON(queue: utilityQueue) { response in + print("Executing response handler on utility queue") +} +``` + +### Response Validation + +By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling `validate` before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type. + +#### Manual Validation + +```swift +Alamofire.request("https://httpbin.org/get") + .validate(statusCode: 200..<300) + .validate(contentType: ["application/json"]) + .responseData { response in + switch response.result { + case .success: + print("Validation Successful") + case .failure(let error): + print(error) + } + } +``` + +#### Automatic Validation + +Automatically validates status code within `200..<300` range, and that the `Content-Type` header of the response matches the `Accept` header of the request, if one is provided. + +```swift +Alamofire.request("https://httpbin.org/get").validate().responseJSON { response in + switch response.result { + case .success: + print("Validation Successful") + case .failure(let error): + print(error) + } +} +``` + +### Response Caching + +Response Caching is handled on the system framework level by [`URLCache`](https://developer.apple.com/reference/foundation/urlcache). It provides a composite in-memory and on-disk cache and lets you manipulate the sizes of both the in-memory and on-disk portions. + +> By default, Alamofire leverages the shared `URLCache`. In order to customize it, see the [Session Manager Configurations](#session-manager) section. + +### HTTP Methods + +The `HTTPMethod` enumeration lists the HTTP methods defined in [RFC 7231 §4.3](http://tools.ietf.org/html/rfc7231#section-4.3): + +```swift +public enum HTTPMethod: String { + case options = "OPTIONS" + case get = "GET" + case head = "HEAD" + case post = "POST" + case put = "PUT" + case patch = "PATCH" + case delete = "DELETE" + case trace = "TRACE" + case connect = "CONNECT" +} +``` + +These values can be passed as the `method` argument to the `Alamofire.request` API: + +```swift +Alamofire.request("https://httpbin.org/get") // method defaults to `.get` + +Alamofire.request("https://httpbin.org/post", method: .post) +Alamofire.request("https://httpbin.org/put", method: .put) +Alamofire.request("https://httpbin.org/delete", method: .delete) +``` + +> The `Alamofire.request` method parameter defaults to `.get`. + +### Parameter Encoding + +Alamofire supports three types of parameter encoding including: `URL`, `JSON` and `PropertyList`. It can also support any custom encoding that conforms to the `ParameterEncoding` protocol. + +#### URL Encoding + +The `URLEncoding` type creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP body of the URL request. Whether the query string is set or appended to any existing URL query string or set as the HTTP body depends on the `Destination` of the encoding. The `Destination` enumeration has three cases: + +- `.methodDependent` - Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` requests and sets as the HTTP body for requests with any other HTTP method. +- `.queryString` - Sets or appends encoded query string result to existing query string. +- `.httpBody` - Sets encoded query string result as the HTTP body of the URL request. + +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`). + +##### GET Request With URL-Encoded Parameters + +```swift +let parameters: Parameters = ["foo": "bar"] + +// All three of these calls are equivalent +Alamofire.request("https://httpbin.org/get", parameters: parameters) // encoding defaults to `URLEncoding.default` +Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding.default) +Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding(destination: .methodDependent)) + +// https://httpbin.org/get?foo=bar +``` + +##### POST Request With URL-Encoded Parameters + +```swift +let parameters: Parameters = [ + "foo": "bar", + "baz": ["a", 1], + "qux": [ + "x": 1, + "y": 2, + "z": 3 + ] +] + +// All three of these calls are equivalent +Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters) +Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.default) +Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.httpBody) + +// HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3 +``` + +#### JSON Encoding + +The `JSONEncoding` type creates a JSON representation of the parameters object, which is set as the HTTP body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. + +##### POST Request with JSON-Encoded Parameters + +```swift +let parameters: Parameters = [ + "foo": [1,2,3], + "bar": [ + "baz": "qux" + ] +] + +// Both calls are equivalent +Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding.default) +Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding(options: [])) + +// HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}} +``` + +#### Property List Encoding + +The `PropertyListEncoding` uses `PropertyListSerialization` 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 Encoding + +In the event that the provided `ParameterEncoding` types do not meet your needs, you can create your own custom encoding. Here's a quick example of how you could build a custom `JSONStringArrayEncoding` type to encode a JSON string array onto a `Request`. + +```swift +struct JSONStringArrayEncoding: ParameterEncoding { + private let array: [String] + + init(array: [String]) { + self.array = array + } + + func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + let data = try JSONSerialization.data(withJSONObject: array, options: []) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = data + + return urlRequest + } +} +``` + +#### Manual Parameter Encoding of a URLRequest + +The `ParameterEncoding` APIs can be used outside of making network requests. + +```swift +let url = URL(string: "https://httpbin.org/get")! +var urlRequest = URLRequest(url: url) + +let parameters: Parameters = ["foo": "bar"] +let encodedURLRequest = try URLEncoding.queryString.encode(urlRequest, with: parameters) +``` + +### HTTP Headers + +Adding a custom HTTP header to a `Request` is supported directly in the global `request` method. This makes it easy to attach HTTP headers to a `Request` that can be constantly changing. + +```swift +let headers: HTTPHeaders = [ + "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", + "Accept": "application/json" +] + +Alamofire.request("https://httpbin.org/headers", headers: headers).responseJSON { response in + debugPrint(response) +} +``` + +> For HTTP headers that do not change, it is recommended to set them on the `URLSessionConfiguration` so they are automatically applied to any `URLSessionTask` created by the underlying `URLSession`. For more information, see the [Session Manager Configurations](#session-manager) section. + +The default Alamofire `SessionManager` provides a default set of headers for every `Request`. These include: + +- `Accept-Encoding`, which defaults to `gzip;q=1.0, compress;q=0.5`, per [RFC 7230 §4.2.3](https://tools.ietf.org/html/rfc7230#section-4.2.3). +- `Accept-Language`, which defaults to up to the top 6 preferred languages on the system, formatted like `en;q=1.0`, per [RFC 7231 §5.3.5](https://tools.ietf.org/html/rfc7231#section-5.3.5). +- `User-Agent`, which contains versioning information about the current app. For example: `iOS Example/1.0 (com.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0`, per [RFC 7231 §5.5.3](https://tools.ietf.org/html/rfc7231#section-5.5.3). + +If you need to customize these headers, a custom `URLSessionConfiguration` should be created, the `defaultHTTPHeaders` property updated and the configuration applied to a new `SessionManager` instance. + +### Authentication + +Authentication is handled on the system framework level by [`URLCredential`](https://developer.apple.com/reference/foundation/nsurlcredential) and [`URLAuthenticationChallenge`](https://developer.apple.com/reference/foundation/urlauthenticationchallenge). + +**Supported Authentication Schemes** + +- [HTTP Basic](http://en.wikipedia.org/wiki/Basic_access_authentication) +- [HTTP Digest](http://en.wikipedia.org/wiki/Digest_access_authentication) +- [Kerberos](http://en.wikipedia.org/wiki/Kerberos_%28protocol%29) +- [NTLM](http://en.wikipedia.org/wiki/NT_LAN_Manager) + +#### HTTP Basic Authentication + +The `authenticate` method on a `Request` will automatically provide a `URLCredential` to a `URLAuthenticationChallenge` when appropriate: + +```swift +let user = "user" +let password = "password" + +Alamofire.request("https://httpbin.org/basic-auth/\(user)/\(password)") + .authenticate(user: user, password: password) + .responseJSON { response in + debugPrint(response) + } +``` + +Depending upon your server implementation, an `Authorization` header may also be appropriate: + +```swift +let user = "user" +let password = "password" + +var headers: HTTPHeaders = [:] + +if let authorizationHeader = Request.authorizationHeader(user: user, password: password) { + headers[authorizationHeader.key] = authorizationHeader.value +} + +Alamofire.request("https://httpbin.org/basic-auth/user/password", headers: headers) + .responseJSON { response in + debugPrint(response) + } +``` + +#### Authentication with URLCredential + +```swift +let user = "user" +let password = "password" + +let credential = URLCredential(user: user, password: password, persistence: .forSession) + +Alamofire.request("https://httpbin.org/basic-auth/\(user)/\(password)") + .authenticate(usingCredential: credential) + .responseJSON { response in + debugPrint(response) + } +``` + +> It is important to note that when using a `URLCredential` for authentication, the underlying `URLSession` will actually end up making two requests if a challenge is issued by the server. The first request will not include the credential which "may" trigger a challenge from the server. The challenge is then received by Alamofire, the credential is appended and the request is retried by the underlying `URLSession`. + +### Downloading Data to a File + +Requests made in Alamofire that fetch data from a server can download the data in-memory or on-disk. The `Alamofire.request` APIs used in all the examples so far always downloads the server data in-memory. This is great for smaller payloads because it's more efficient, but really bad for larger payloads because the download could run your entire application out-of-memory. Because of this, you can also use the `Alamofire.download` APIs to download the server data to a temporary file on-disk. + +> This will only work on `macOS` as is. Other platforms don't allow access to the filesystem outside of your app's sandbox. To download files on other platforms, see the [Download File Destination](#download-file-destination) section. + +```swift +Alamofire.download("https://httpbin.org/image/png").responseData { response in + if let data = response.result.value { + let image = UIImage(data: data) + } +} +``` + +> The `Alamofire.download` APIs should also be used if you need to download data while your app is in the background. For more information, please see the [Session Manager Configurations](#session-manager) section. + +#### Download File Destination + +You can also provide a `DownloadFileDestination` closure to move the file from the temporary directory to a final destination. Before the temporary file is actually moved to the `destinationURL`, the `DownloadOptions` specified in the closure will be executed. The two currently supported `DownloadOptions` are: + +- `.createIntermediateDirectories` - Creates intermediate directories for the destination URL if specified. +- `.removePreviousFile` - Removes a previous file from the destination URL if specified. + +```swift +let destination: DownloadRequest.DownloadFileDestination = { _, _ in + let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] + let fileURL = documentsURL.appendingPathComponent("pig.png") + + return (fileURL, [.removePreviousFile, .createIntermediateDirectories]) +} + +Alamofire.download(urlString, to: destination).response { response in + print(response) + + if response.error == nil, let imagePath = response.destinationURL?.path { + let image = UIImage(contentsOfFile: imagePath) + } +} +``` + +You can also use the suggested download destination API. + +```swift +let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory) +Alamofire.download("https://httpbin.org/image/png", to: destination) +``` + +#### Download Progress + +Many times it can be helpful to report download progress to the user. Any `DownloadRequest` can report download progress using the `downloadProgress` API. + +```swift +Alamofire.download("https://httpbin.org/image/png") + .downloadProgress { progress in + print("Download Progress: \(progress.fractionCompleted)") + } + .responseData { response in + if let data = response.result.value { + let image = UIImage(data: data) + } + } +``` + +The `downloadProgress` API also takes a `queue` parameter which defines which `DispatchQueue` the download progress closure should be called on. + +```swift +let utilityQueue = DispatchQueue.global(qos: .utility) + +Alamofire.download("https://httpbin.org/image/png") + .downloadProgress(queue: utilityQueue) { progress in + print("Download Progress: \(progress.fractionCompleted)") + } + .responseData { response in + if let data = response.result.value { + let image = UIImage(data: data) + } + } +``` + +#### Resuming a Download + +If a `DownloadRequest` is cancelled or interrupted, the underlying URL session may generate resume data for the active `DownloadRequest`. If this happens, the resume data can be re-used to restart the `DownloadRequest` where it left off. The resume data can be accessed through the download response, then reused when trying to restart the request. + +> **IMPORTANT:** On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the data is written incorrectly and will always fail to resume the download. For more information about the bug and possible workarounds, please see this Stack Overflow [post](http://stackoverflow.com/a/39347461/1342462). + +```swift +class ImageRequestor { + private var resumeData: Data? + private var image: UIImage? + + func fetchImage(completion: (UIImage?) -> Void) { + guard image == nil else { completion(image) ; return } + + let destination: DownloadRequest.DownloadFileDestination = { _, _ in + let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] + let fileURL = documentsURL.appendingPathComponent("pig.png") + + return (fileURL, [.removePreviousFile, .createIntermediateDirectories]) + } + + let request: DownloadRequest + + if let resumeData = resumeData { + request = Alamofire.download(resumingWith: resumeData) + } else { + request = Alamofire.download("https://httpbin.org/image/png") + } + + request.responseData { response in + switch response.result { + case .success(let data): + self.image = UIImage(data: data) + case .failure: + self.resumeData = response.resumeData + } + } + } +} +``` + +### Uploading Data to a Server + +When sending relatively small amounts of data to a server using JSON or URL encoded parameters, the `Alamofire.request` APIs are usually sufficient. If you need to send much larger amounts of data from a file URL or an `InputStream`, then the `Alamofire.upload` APIs are what you want to use. + +> The `Alamofire.upload` APIs should also be used if you need to upload data while your app is in the background. For more information, please see the [Session Manager Configurations](#session-manager) section. + +#### Uploading Data + +```swift +let imageData = UIPNGRepresentation(image)! + +Alamofire.upload(imageData, to: "https://httpbin.org/post").responseJSON { response in + debugPrint(response) +} +``` + +#### Uploading a File + +```swift +let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov") + +Alamofire.upload(fileURL, to: "https://httpbin.org/post").responseJSON { response in + debugPrint(response) +} +``` + +#### Uploading Multipart Form Data + +```swift +Alamofire.upload( + multipartFormData: { multipartFormData in + multipartFormData.append(unicornImageURL, withName: "unicorn") + multipartFormData.append(rainbowImageURL, withName: "rainbow") + }, + to: "https://httpbin.org/post", + encodingCompletion: { encodingResult in + switch encodingResult { + case .success(let upload, _, _): + upload.responseJSON { response in + debugPrint(response) + } + case .failure(let encodingError): + print(encodingError) + } + } +) +``` + +#### Upload Progress + +While your user is waiting for their upload to complete, sometimes it can be handy to show the progress of the upload to the user. Any `UploadRequest` can report both upload progress and download progress of the response data using the `uploadProgress` and `downloadProgress` APIs. + +```swift +let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov") + +Alamofire.upload(fileURL, to: "https://httpbin.org/post") + .uploadProgress { progress in // main queue by default + print("Upload Progress: \(progress.fractionCompleted)") + } + .downloadProgress { progress in // main queue by default + print("Download Progress: \(progress.fractionCompleted)") + } + .responseJSON { response in + debugPrint(response) + } +``` + +### Statistical Metrics + +#### Timeline + +Alamofire collects timings throughout the lifecycle of a `Request` and creates a `Timeline` object exposed as a property on all response types. + +```swift +Alamofire.request("https://httpbin.org/get").responseJSON { response in + print(response.timeline) +} +``` + +The above reports the following `Timeline` info: + +- `Latency`: 0.428 seconds +- `Request Duration`: 0.428 seconds +- `Serialization Duration`: 0.001 seconds +- `Total Duration`: 0.429 seconds + +#### URL Session Task Metrics + +In iOS and tvOS 10 and macOS 10.12, Apple introduced the new [URLSessionTaskMetrics](https://developer.apple.com/reference/foundation/urlsessiontaskmetrics) APIs. The task metrics encapsulate some fantastic statistical information about the request and response execution. The API is very similar to the `Timeline`, but provides many more statistics that Alamofire doesn't have access to compute. The metrics can be accessed through any response type. + +```swift +Alamofire.request("https://httpbin.org/get").responseJSON { response in + print(response.metrics) +} +``` + +It's important to note that these APIs are only available on iOS and tvOS 10 and macOS 10.12. Therefore, depending on your deployment target, you may need to use these inside availability checks: + +```swift +Alamofire.request("https://httpbin.org/get").responseJSON { response in + if #available(iOS 10.0, *) { + print(response.metrics) + } +} +``` + +### cURL Command Output + +Debugging platform issues can be frustrating. Thankfully, Alamofire `Request` objects conform to both the `CustomStringConvertible` and `CustomDebugStringConvertible` protocols to provide some VERY helpful debugging tools. + +#### CustomStringConvertible + +```swift +let request = Alamofire.request("https://httpbin.org/ip") + +print(request) +// GET https://httpbin.org/ip (200) +``` + +#### CustomDebugStringConvertible + +```swift +let request = Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"]) +debugPrint(request) +``` + +Outputs: + +```bash +$ curl -i \ + -H "User-Agent: Alamofire/4.0.0" \ + -H "Accept-Encoding: gzip;q=1.0, compress;q=0.5" \ + -H "Accept-Language: en;q=1.0,fr;q=0.9,de;q=0.8,zh-Hans;q=0.7,zh-Hant;q=0.6,ja;q=0.5" \ + "https://httpbin.org/get?foo=bar" +``` + +--- + +## Advanced Usage + +Alamofire is built on `URLSession` and the Foundation URL Loading System. To make the most of this framework, it is recommended that you be familiar with the concepts and capabilities of the underlying networking stack. + +**Recommended Reading** + +- [URL Loading System Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html) +- [URLSession Class Reference](https://developer.apple.com/reference/foundation/nsurlsession) +- [URLCache Class Reference](https://developer.apple.com/reference/foundation/urlcache) +- [URLAuthenticationChallenge Class Reference](https://developer.apple.com/reference/foundation/urlauthenticationchallenge) + +### Session Manager + +Top-level convenience methods like `Alamofire.request` use a default instance of `Alamofire.SessionManager`, which is configured with the default `URLSessionConfiguration`. + +As such, the following two statements are equivalent: + +```swift +Alamofire.request("https://httpbin.org/get") +``` + +```swift +let sessionManager = Alamofire.SessionManager.default +sessionManager.request("https://httpbin.org/get") +``` + +Applications can create session managers for background and ephemeral sessions, as well as new managers that customize the default session configuration, such as for default headers (`httpAdditionalHeaders`) or timeout interval (`timeoutIntervalForRequest`). + +#### Creating a Session Manager with Default Configuration + +```swift +let configuration = URLSessionConfiguration.default +let sessionManager = Alamofire.SessionManager(configuration: configuration) +``` + +#### Creating a Session Manager with Background Configuration + +```swift +let configuration = URLSessionConfiguration.background(withIdentifier: "com.example.app.background") +let sessionManager = Alamofire.SessionManager(configuration: configuration) +``` + +#### Creating a Session Manager with Ephemeral Configuration + +```swift +let configuration = URLSessionConfiguration.ephemeral +let sessionManager = Alamofire.SessionManager(configuration: configuration) +``` + +#### Modifying the Session Configuration + +```swift +var defaultHeaders = Alamofire.SessionManager.defaultHTTPHeaders +defaultHeaders["DNT"] = "1 (Do Not Track Enabled)" + +let configuration = URLSessionConfiguration.default +configuration.httpAdditionalHeaders = defaultHeaders + +let sessionManager = Alamofire.SessionManager(configuration: configuration) +``` + +> This is **not** recommended for `Authorization` or `Content-Type` headers. Instead, use the `headers` parameter in the top-level `Alamofire.request` APIs, `URLRequestConvertible` and `ParameterEncoding`, respectively. + +### Session Delegate + +By default, an Alamofire `SessionManager` instance creates a `SessionDelegate` object to handle all the various types of delegate callbacks that are generated by the underlying `URLSession`. The implementations of each delegate method handle the most common use cases for these types of calls abstracting the complexity away from the top-level APIs. However, advanced users may find the need to override the default functionality for various reasons. + +#### Override Closures + +The first way to customize the `SessionDelegate` behavior is through the use of the override closures. Each closure gives you the ability to override the implementation of the matching `SessionDelegate` API, yet still use the default implementation for all other APIs. This makes it easy to customize subsets of the delegate functionality. Here are a few examples of some of the override closures available: + +```swift +/// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`. +open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + +/// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`. +open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)? + +/// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`. +open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? + +/// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`. +open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? +``` + +The following is a short example of how to use the `taskWillPerformHTTPRedirection` to avoid following redirects to any `apple.com` domains. + +```swift +let sessionManager = Alamofire.SessionManager(configuration: URLSessionConfiguration.default) +let delegate: Alamofire.SessionDelegate = sessionManager.delegate + +delegate.taskWillPerformHTTPRedirection = { session, task, response, request in + var finalRequest = request + + if + let originalRequest = task.originalRequest, + let urlString = originalRequest.url?.urlString, + urlString.contains("apple.com") + { + finalRequest = originalRequest + } + + return finalRequest +} +``` + +#### Subclassing + +Another way to override the default implementation of the `SessionDelegate` is to subclass it. Subclassing allows you completely customize the behavior of the API or to create a proxy for the API and still use the default implementation. Creating a proxy allows you to log events, emit notifications, provide pre and post hook implementations, etc. Here's a quick example of subclassing the `SessionDelegate` and logging a message when a redirect occurs. + +```swift +class LoggingSessionDelegate: SessionDelegate { + override func urlSession( + _ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) + { + print("URLSession will perform HTTP redirection to request: \(request)") + + super.urlSession( + session, + task: task, + willPerformHTTPRedirection: response, + newRequest: request, + completionHandler: completionHandler + ) + } +} +``` + +Generally speaking, either the default implementation or the override closures should provide the necessary functionality required. Subclassing should only be used as a last resort. + +> It is important to keep in mind that the `subdelegates` are initialized and destroyed in the default implementation. Be careful when subclassing to not introduce memory leaks. + +### Request + +The result of a `request`, `download`, `upload` or `stream` methods are a `DataRequest`, `DownloadRequest`, `UploadRequest` and `StreamRequest` which all inherit from `Request`. All `Request` instances are always created by an owning session manager, and never initialized directly. + +Each subclass has specialized methods such as `authenticate`, `validate`, `responseJSON` and `uploadProgress` that each return the caller instance in order to facilitate method chaining. + +Requests can be suspended, resumed and cancelled: + +- `suspend()`: Suspends the underlying task and dispatch queue. +- `resume()`: Resumes the underlying task and dispatch queue. If the owning manager does not have `startRequestsImmediately` set to `true`, the request must call `resume()` in order to start. +- `cancel()`: Cancels the underlying task, producing an error that is passed to any registered response handlers. + +### Routing Requests + +As apps grow in size, it's important to adopt common patterns as you build out your network stack. An important part of that design is how to route your requests. The Alamofire `URLConvertible` and `URLRequestConvertible` protocols along with the `Router` design pattern are here to help. + +#### URLConvertible + +Types adopting the `URLConvertible` protocol can be used to construct URLs, which are then used to construct URL requests internally. `String`, `URL`, and `URLComponents` conform to `URLConvertible` by default, allowing any of them to be passed as `url` parameters to the `request`, `upload`, and `download` methods: + +```swift +let urlString = "https://httpbin.org/post" +Alamofire.request(urlString, method: .post) + +let url = URL(string: urlString)! +Alamofire.request(url, method: .post) + +let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true)! +Alamofire.request(urlComponents, method: .post) +``` + +Applications interacting with web applications in a significant manner are encouraged to have custom types conform to `URLConvertible` as a convenient way to map domain-specific models to server resources. + +##### Type-Safe Routing + +```swift +extension User: URLConvertible { + static let baseURLString = "https://example.com" + + func asURL() throws -> URL { + let urlString = User.baseURLString + "/users/\(username)/" + return try urlString.asURL() + } +} +``` + +```swift +let user = User(username: "mattt") +Alamofire.request(user) // https://example.com/users/mattt +``` + +#### URLRequestConvertible + +Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. `URLRequest` conforms to `URLRequestConvertible` by default, allowing it to be passed into `request`, `upload`, and `download` methods directly (this is the recommended way to specify custom HTTP body for individual requests): + +```swift +let url = URL(string: "https://httpbin.org/post")! +var urlRequest = URLRequest(url: url) +urlRequest.httpMethod = "POST" + +let parameters = ["foo": "bar"] + +do { + urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: []) +} catch { + // No-op +} + +urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + +Alamofire.request(urlRequest) +``` + +Applications interacting with web applications in a significant manner are encouraged to have custom types conform to `URLRequestConvertible` as a way to ensure consistency of requested endpoints. Such an approach can be used to abstract away server-side inconsistencies and provide type-safe routing, as well as manage authentication credentials and other state. + +##### API Parameter Abstraction + +```swift +enum Router: URLRequestConvertible { + case search(query: String, page: Int) + + static let baseURLString = "https://example.com" + static let perPage = 50 + + // MARK: URLRequestConvertible + + func asURLRequest() throws -> URLRequest { + let result: (path: String, parameters: Parameters) = { + switch self { + case let .search(query, page) where page > 0: + return ("/search", ["q": query, "offset": Router.perPage * page]) + case let .search(query, _): + return ("/search", ["q": query]) + } + }() + + let url = try Router.baseURLString.asURL() + let urlRequest = URLRequest(url: url.appendingPathComponent(result.path)) + + return try URLEncoding.default.encode(urlRequest, with: result.parameters) + } +} +``` + +```swift +Alamofire.request(Router.search(query: "foo bar", page: 1)) // https://example.com/search?q=foo%20bar&offset=50 +``` + +##### CRUD & Authorization + +```swift +import Alamofire + +enum Router: URLRequestConvertible { + case createUser(parameters: Parameters) + case readUser(username: String) + case updateUser(username: String, parameters: Parameters) + case destroyUser(username: String) + + static let baseURLString = "https://example.com" + + var method: HTTPMethod { + switch self { + case .createUser: + return .post + case .readUser: + return .get + case .updateUser: + return .put + case .destroyUser: + return .delete + } + } + + var path: String { + switch self { + case .createUser: + return "/users" + case .readUser(let username): + return "/users/\(username)" + case .updateUser(let username, _): + return "/users/\(username)" + case .destroyUser(let username): + return "/users/\(username)" + } + } + + // MARK: URLRequestConvertible + + func asURLRequest() throws -> URLRequest { + let url = try Router.baseURLString.asURL() + + var urlRequest = URLRequest(url: url.appendingPathComponent(path)) + urlRequest.httpMethod = method.rawValue + + switch self { + case .createUser(let parameters): + urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters) + case .updateUser(_, let parameters): + urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters) + default: + break + } + + return urlRequest + } +} +``` + +```swift +Alamofire.request(Router.readUser("mattt")) // GET https://example.com/users/mattt +``` + +### Adapting and Retrying Requests + +Most web services these days are behind some sort of authentication system. One of the more common ones today is OAuth. This generally involves generating an access token authorizing your application or user to call the various supported web services. While creating these initial access tokens can be laborsome, it can be even more complicated when your access token expires and you need to fetch a new one. There are many thread-safety issues that need to be considered. + +The `RequestAdapter` and `RequestRetrier` protocols were created to make it much easier to create a thread-safe authentication system for a specific set of web services. + +#### RequestAdapter + +The `RequestAdapter` protocol allows each `Request` made on a `SessionManager` to be inspected and adapted before being created. One very specific way to use an adapter is to append an `Authorization` header to requests behind a certain type of authentication. + +```swift +class AccessTokenAdapter: RequestAdapter { + private let accessToken: String + + init(accessToken: String) { + self.accessToken = accessToken + } + + func adapt(_ urlRequest: URLRequest) throws -> URLRequest { + var urlRequest = urlRequest + + if let urlString = urlRequest.url?.absoluteString, urlString.hasPrefix("https://httpbin.org") { + urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization") + } + + return urlRequest + } +} +``` + +```swift +let sessionManager = SessionManager() +sessionManager.adapter = AccessTokenAdapter(accessToken: "1234") + +sessionManager.request("https://httpbin.org/get") +``` + +#### RequestRetrier + +The `RequestRetrier` protocol allows a `Request` that encountered an `Error` while being executed to be retried. When using both the `RequestAdapter` and `RequestRetrier` protocols together, you can create credential refresh systems for OAuth1, OAuth2, Basic Auth and even exponential backoff retry policies. The possibilities are endless. Here's an example of how you could implement a refresh flow for OAuth2 access tokens. + +> **DISCLAIMER:** This is **NOT** a global `OAuth2` solution. It is merely an example demonstrating how one could use the `RequestAdapter` in conjunction with the `RequestRetrier` to create a thread-safe refresh system. + +> To reiterate, **do NOT copy** this sample code and drop it into a production application. This is merely an example. Each authentication system must be tailored to a particular platform and authentication type. + +```swift +class OAuth2Handler: RequestAdapter, RequestRetrier { + private typealias RefreshCompletion = (_ succeeded: Bool, _ accessToken: String?, _ refreshToken: String?) -> Void + + private let sessionManager: SessionManager = { + let configuration = URLSessionConfiguration.default + configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders + + return SessionManager(configuration: configuration) + }() + + private let lock = NSLock() + + private var clientID: String + private var baseURLString: String + private var accessToken: String + private var refreshToken: String + + private var isRefreshing = false + private var requestsToRetry: [RequestRetryCompletion] = [] + + // MARK: - Initialization + + public init(clientID: String, baseURLString: String, accessToken: String, refreshToken: String) { + self.clientID = clientID + self.baseURLString = baseURLString + self.accessToken = accessToken + self.refreshToken = refreshToken + } + + // MARK: - RequestAdapter + + func adapt(_ urlRequest: URLRequest) throws -> URLRequest { + if let urlString = urlRequest.url?.absoluteString, urlString.hasPrefix(baseURLString) { + var urlRequest = urlRequest + urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization") + return urlRequest + } + + return urlRequest + } + + // MARK: - RequestRetrier + + func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) { + lock.lock() ; defer { lock.unlock() } + + if let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401 { + requestsToRetry.append(completion) + + if !isRefreshing { + refreshTokens { [weak self] succeeded, accessToken, refreshToken in + guard let strongSelf = self else { return } + + strongSelf.lock.lock() ; defer { strongSelf.lock.unlock() } + + if let accessToken = accessToken, let refreshToken = refreshToken { + strongSelf.accessToken = accessToken + strongSelf.refreshToken = refreshToken + } + + strongSelf.requestsToRetry.forEach { $0(succeeded, 0.0) } + strongSelf.requestsToRetry.removeAll() + } + } + } else { + completion(false, 0.0) + } + } + + // MARK: - Private - Refresh Tokens + + private func refreshTokens(completion: @escaping RefreshCompletion) { + guard !isRefreshing else { return } + + isRefreshing = true + + let urlString = "\(baseURLString)/oauth2/token" + + let parameters: [String: Any] = [ + "access_token": accessToken, + "refresh_token": refreshToken, + "client_id": clientID, + "grant_type": "refresh_token" + ] + + sessionManager.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default) + .responseJSON { [weak self] response in + guard let strongSelf = self else { return } + + if + let json = response.result.value as? [String: Any], + let accessToken = json["access_token"] as? String, + let refreshToken = json["refresh_token"] as? String + { + completion(true, accessToken, refreshToken) + } else { + completion(false, nil, nil) + } + + strongSelf.isRefreshing = false + } + } +} +``` + +```swift +let baseURLString = "https://some.domain-behind-oauth2.com" + +let oauthHandler = OAuth2Handler( + clientID: "12345678", + baseURLString: baseURLString, + accessToken: "abcd1234", + refreshToken: "ef56789a" +) + +let sessionManager = SessionManager() +sessionManager.adapter = oauthHandler +sessionManager.retrier = oauthHandler + +let urlString = "\(baseURLString)/some/endpoint" + +sessionManager.request(urlString).validate().responseJSON { response in + debugPrint(response) +} +``` + +Once the `OAuth2Handler` is applied as both the `adapter` and `retrier` for the `SessionManager`, it will handle an invalid access token error by automatically refreshing the access token and retrying all failed requests in the same order they failed. + +> If you needed them to execute in the same order they were created, you could sort them by their task identifiers. + +The example above only checks for a `401` response code which is not nearly robust enough, but does demonstrate how one could check for an invalid access token error. In a production application, one would want to check the `realm` and most likely the `www-authenticate` header response although it depends on the OAuth2 implementation. + +Another important note is that this authentication system could be shared between multiple session managers. For example, you may need to use both a `default` and `ephemeral` session configuration for the same set of web services. The example above allows the same `oauthHandler` instance to be shared across multiple session managers to manage the single refresh flow. + +### Custom Response Serialization + +Alamofire provides built-in response serialization for data, strings, JSON, and property lists: + +```swift +Alamofire.request(...).responseData { (resp: DataResponse) in ... } +Alamofire.request(...).responseString { (resp: DataResponse) in ... } +Alamofire.request(...).responseJSON { (resp: DataResponse) in ... } +Alamofire.request(...).responsePropertyList { resp: DataResponse) in ... } +``` + +Those responses wrap deserialized *values* (Data, String, Any) or *errors* (network, validation errors), as well as *meta-data* (URL request, HTTP headers, status code, [metrics](#statistical-metrics), ...). + +You have several ways to customize all of those response elements: + +- [Response Mapping](#response-mapping) +- [Handling Errors](#handling-errors) +- [Creating a Custom Response Serializer](#creating-a-custom-response-serializer) +- [Generic Response Object Serialization](#generic-response-object-serialization) + +#### Response Mapping + +Response mapping is the simplest way to produce customized responses. It transforms the value of a response, while preserving eventual errors and meta-data. For example, you can turn a json response `DataResponse` into a response that holds an application model, such as `DataResponse`. You perform response mapping with the `DataResponse.map` method: + +```swift +Alamofire.request("https://example.com/users/mattt").responseJSON { (response: DataResponse) in + let userResponse = response.map { json in + // We assume an existing User(json: Any) initializer + return User(json: json) + } + + // Process userResponse, of type DataResponse: + if let user = userResponse.value { + print("User: { username: \(user.username), name: \(user.name) }") + } +} +``` + +When the transformation may throw an error, use `flatMap` instead: + +```swift +Alamofire.request("https://example.com/users/mattt").responseJSON { response in + let userResponse = response.flatMap { json in + try User(json: json) + } +} +``` + +Response mapping is a good fit for your custom completion handlers: + +```swift +@discardableResult +func loadUser(completionHandler: @escaping (DataResponse) -> Void) -> Alamofire.DataRequest { + return Alamofire.request("https://example.com/users/mattt").responseJSON { response in + let userResponse = response.flatMap { json in + try User(json: json) + } + + completionHandler(userResponse) + } +} + +loadUser { response in + if let user = response.value { + print("User: { username: \(user.username), name: \(user.name) }") + } +} +``` + +When the map/flatMap closure may process a big amount of data, make sure you execute it outside of the main thread: + +```swift +@discardableResult +func loadUser(completionHandler: @escaping (DataResponse) -> Void) -> Alamofire.DataRequest { + let utilityQueue = DispatchQueue.global(qos: .utility) + + return Alamofire.request("https://example.com/users/mattt").responseJSON(queue: utilityQueue) { response in + let userResponse = response.flatMap { json in + try User(json: json) + } + + DispatchQueue.main.async { + completionHandler(userResponse) + } + } +} +``` + +`map` and `flatMap` are also available for [download responses](#downloading-data-to-a-file). + +#### Handling Errors + +Before implementing custom response serializers or object serialization methods, it's important to consider how to handle any errors that may occur. There are two basic options: passing existing errors along unmodified, to be dealt with at response time; or, wrapping all errors in an `Error` type specific to your app. + +For example, here's a simple `BackendError` enum which will be used in later examples: + +```swift +enum BackendError: Error { + case network(error: Error) // Capture any underlying Error from the URLSession API + case dataSerialization(error: Error) + case jsonSerialization(error: Error) + case xmlSerialization(error: Error) + case objectSerialization(reason: String) +} +``` + +#### Creating a Custom Response Serializer + +Alamofire provides built-in response serialization for strings, JSON, and property lists, but others can be added in extensions on `Alamofire.DataRequest` and / or `Alamofire.DownloadRequest`. + +For example, here's how a response handler using [Ono](https://github.com/mattt/Ono) might be implemented: + +```swift +extension DataRequest { + static func xmlResponseSerializer() -> DataResponseSerializer { + return DataResponseSerializer { request, response, data, error in + // Pass through any underlying URLSession error to the .network case. + guard error == nil else { return .failure(BackendError.network(error: error!)) } + + // Use Alamofire's existing data serializer to extract the data, passing the error as nil, as it has + // already been handled. + let result = Request.serializeResponseData(response: response, data: data, error: nil) + + guard case let .success(validData) = result else { + return .failure(BackendError.dataSerialization(error: result.error! as! AFError)) + } + + do { + let xml = try ONOXMLDocument(data: validData) + return .success(xml) + } catch { + return .failure(BackendError.xmlSerialization(error: error)) + } + } + } + + @discardableResult + func responseXMLDocument( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.xmlResponseSerializer(), + completionHandler: completionHandler + ) + } +} +``` + +#### Generic Response Object Serialization + +Generics can be used to provide automatic, type-safe response object serialization. + +```swift +protocol ResponseObjectSerializable { + init?(response: HTTPURLResponse, representation: Any) +} + +extension DataRequest { + func responseObject( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + let responseSerializer = DataResponseSerializer { request, response, data, error in + guard error == nil else { return .failure(BackendError.network(error: error!)) } + + let jsonResponseSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments) + let result = jsonResponseSerializer.serializeResponse(request, response, data, nil) + + guard case let .success(jsonObject) = result else { + return .failure(BackendError.jsonSerialization(error: result.error!)) + } + + guard let response = response, let responseObject = T(response: response, representation: jsonObject) else { + return .failure(BackendError.objectSerialization(reason: "JSON could not be serialized: \(jsonObject)")) + } + + return .success(responseObject) + } + + return response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) + } +} +``` + +```swift +struct User: ResponseObjectSerializable, CustomStringConvertible { + let username: String + let name: String + + var description: String { + return "User: { username: \(username), name: \(name) }" + } + + init?(response: HTTPURLResponse, representation: Any) { + guard + let username = response.url?.lastPathComponent, + let representation = representation as? [String: Any], + let name = representation["name"] as? String + else { return nil } + + self.username = username + self.name = name + } +} +``` + +```swift +Alamofire.request("https://example.com/users/mattt").responseObject { (response: DataResponse) in + debugPrint(response) + + if let user = response.result.value { + print("User: { username: \(user.username), name: \(user.name) }") + } +} +``` + +The same approach can also be used to handle endpoints that return a representation of a collection of objects: + +```swift +protocol ResponseCollectionSerializable { + static func collection(from response: HTTPURLResponse, withRepresentation representation: Any) -> [Self] +} + +extension ResponseCollectionSerializable where Self: ResponseObjectSerializable { + static func collection(from response: HTTPURLResponse, withRepresentation representation: Any) -> [Self] { + var collection: [Self] = [] + + if let representation = representation as? [[String: Any]] { + for itemRepresentation in representation { + if let item = Self(response: response, representation: itemRepresentation) { + collection.append(item) + } + } + } + + return collection + } +} +``` + +```swift +extension DataRequest { + @discardableResult + func responseCollection( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DataResponse<[T]>) -> Void) -> Self + { + let responseSerializer = DataResponseSerializer<[T]> { request, response, data, error in + guard error == nil else { return .failure(BackendError.network(error: error!)) } + + let jsonSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments) + let result = jsonSerializer.serializeResponse(request, response, data, nil) + + guard case let .success(jsonObject) = result else { + return .failure(BackendError.jsonSerialization(error: result.error!)) + } + + guard let response = response else { + let reason = "Response collection could not be serialized due to nil response." + return .failure(BackendError.objectSerialization(reason: reason)) + } + + return .success(T.collection(from: response, withRepresentation: jsonObject)) + } + + return response(responseSerializer: responseSerializer, completionHandler: completionHandler) + } +} +``` + +```swift +struct User: ResponseObjectSerializable, ResponseCollectionSerializable, CustomStringConvertible { + let username: String + let name: String + + var description: String { + return "User: { username: \(username), name: \(name) }" + } + + init?(response: HTTPURLResponse, representation: Any) { + guard + let username = response.url?.lastPathComponent, + let representation = representation as? [String: Any], + let name = representation["name"] as? String + else { return nil } + + self.username = username + self.name = name + } +} +``` + +```swift +Alamofire.request("https://example.com/users").responseCollection { (response: DataResponse<[User]>) in + debugPrint(response) + + if let users = response.result.value { + users.forEach { print("- \($0)") } + } +} +``` + +### Security + +Using a secure HTTPS connection when communicating with servers and web services is an important step in securing sensitive data. By default, Alamofire will evaluate the certificate chain provided by the server using Apple's built in validation provided by the Security framework. While this guarantees the certificate chain is valid, it does not prevent man-in-the-middle (MITM) attacks or other potential vulnerabilities. In order to mitigate MITM attacks, applications dealing with sensitive customer data or financial information should use certificate or public key pinning provided by the `ServerTrustPolicy`. + +#### ServerTrustPolicy + +The `ServerTrustPolicy` enumeration evaluates the server trust generally provided by an `URLAuthenticationChallenge` when connecting to a server over a secure HTTPS connection. + +```swift +let serverTrustPolicy = ServerTrustPolicy.pinCertificates( + certificates: ServerTrustPolicy.certificates(), + validateCertificateChain: true, + validateHost: true +) +``` + +There are many different cases of server trust evaluation giving you complete control over the validation process: + +* `performDefaultEvaluation`: Uses the default server trust evaluation while allowing you to control whether to validate the host provided by the challenge. +* `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. +* `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. +* `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 thus giving you complete control over the validation process. Use with caution. + +#### Server Trust Policy Manager + +The `ServerTrustPolicyManager` is responsible for storing an internal mapping of server trust policies to a particular host. This allows Alamofire to evaluate each host against a different server trust policy. + +```swift +let serverTrustPolicies: [String: ServerTrustPolicy] = [ + "test.example.com": .pinCertificates( + certificates: ServerTrustPolicy.certificates(), + validateCertificateChain: true, + validateHost: true + ), + "insecure.expired-apis.com": .disableEvaluation +] + +let sessionManager = SessionManager( + serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies) +) +``` + +> Make sure to keep a reference to the new `SessionManager` instance, otherwise your requests will all get cancelled when your `sessionManager` is deallocated. + +These server trust policies will result in the following behavior: + +- `test.example.com` will always use certificate pinning with certificate chain and host validation enabled thus requiring the following criteria to be met to allow the TLS handshake to succeed: + - Certificate chain MUST be valid. + - Certificate chain MUST include one of the pinned certificates. + - Challenge host MUST match the host in the certificate chain's leaf certificate. +- `insecure.expired-apis.com` will never evaluate the certificate chain and will always allow the TLS handshake to succeed. +- All other hosts will use the default evaluation provided by Apple. + +##### Subclassing Server Trust Policy Manager + +If you find yourself needing more flexible server trust policy matching behavior (i.e. wildcarded domains), then subclass the `ServerTrustPolicyManager` and override the `serverTrustPolicyForHost` method with your own custom implementation. + +```swift +class CustomServerTrustPolicyManager: ServerTrustPolicyManager { + override func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? { + var policy: ServerTrustPolicy? + + // Implement your custom domain matching behavior... + + return policy + } +} +``` + +#### Validating the Host + +The `.performDefaultEvaluation`, `.pinCertificates` and `.pinPublicKeys` server trust policies all take a `validateHost` parameter. Setting the value to `true` will cause the server trust evaluation to verify that hostname in the certificate matches the hostname of the challenge. If they do not match, evaluation will fail. A `validateHost` value of `false` will still evaluate the full certificate chain, but will not validate the hostname of the leaf certificate. + +> It is recommended that `validateHost` always be set to `true` in production environments. + +#### Validating the Certificate Chain + +Pinning certificates and public keys both have the option of validating the certificate chain using the `validateCertificateChain` parameter. By setting this value to `true`, the full certificate chain will be evaluated in addition to performing a byte equality check against the pinned certificates or public keys. A value of `false` will skip the certificate chain validation, but will still perform the byte equality check. + +There are several cases where it may make sense to disable certificate chain validation. The most common use cases for disabling validation are self-signed and expired certificates. The evaluation would always fail in both of these cases, but the byte equality check will still ensure you are receiving the certificate you expect from the server. + +> It is recommended that `validateCertificateChain` always be set to `true` in production environments. + +#### App Transport Security + +With the addition of App Transport Security (ATS) in iOS 9, it is possible that using a custom `ServerTrustPolicyManager` with several `ServerTrustPolicy` objects will have no effect. If you continuously see `CFNetwork SSLHandshake failed (-9806)` errors, you have probably run into this problem. Apple's ATS system overrides the entire challenge system unless you configure the ATS settings in your app's plist to disable enough of it to allow your app to evaluate the server trust. + +If you run into this problem (high probability with self-signed certificates), you can work around this issue by adding the following to your `Info.plist`. + +```xml + + NSAppTransportSecurity + + NSExceptionDomains + + example.com + + NSExceptionAllowsInsecureHTTPLoads + + NSExceptionRequiresForwardSecrecy + + NSIncludesSubdomains + + + NSTemporaryExceptionMinimumTLSVersion + TLSv1.2 + + + + +``` + +Whether you need to set the `NSExceptionRequiresForwardSecrecy` to `NO` depends on whether your TLS connection is using an allowed cipher suite. In certain cases, it will need to be set to `NO`. The `NSExceptionAllowsInsecureHTTPLoads` MUST be set to `YES` in order to allow the `SessionDelegate` to receive challenge callbacks. Once the challenge callbacks are being called, the `ServerTrustPolicyManager` will take over the server trust evaluation. You may also need to specify the `NSTemporaryExceptionMinimumTLSVersion` if you're trying to connect to a host that only supports TLS versions less than `1.2`. + +> It is recommended to always use valid certificates in production environments. + +### Network Reachability + +The `NetworkReachabilityManager` listens for reachability changes of hosts and addresses for both WWAN and WiFi network interfaces. + +```swift +let manager = NetworkReachabilityManager(host: "www.apple.com") + +manager?.listener = { status in + print("Network Status Changed: \(status)") +} + +manager?.startListening() +``` + +> Make sure to remember to retain the `manager` in the above example, or no status changes will be reported. +> Also, do not include the scheme in the `host` string or reachability won't function correctly. + +There are some important things to remember when using network reachability to determine what to do next. + +- **Do NOT** use Reachability to determine if a network request should be sent. + - You should **ALWAYS** send it. +- When Reachability is restored, use the event to retry failed network requests. + - Even though the network requests may still fail, this is a good moment to retry them. +- The network reachability status can be useful for determining why a network request may have failed. + - If a network request fails, it is more useful to tell the user that the network request failed due to being offline rather than a more technical error, such as "request timed out." + +> It is recommended to check out [WWDC 2012 Session 706, "Networking Best Practices"](https://developer.apple.com/videos/play/wwdc2012-706/) for more info. + +--- + +## Open Radars + +The following radars have some effect on the current implementation of Alamofire. + +- [`rdar://21349340`](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case +- [`rdar://26761490`](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage +- `rdar://26870455` - Background URL Session Configurations do not work in the simulator +- `rdar://26849668` - Some URLProtocol APIs do not properly handle `URLRequest` + +## FAQ + +### What's the origin of the name Alamofire? + +Alamofire is named after the [Alamo Fire flower](https://aggie-horticulture.tamu.edu/wildseed/alamofire.html), a hybrid variant of the Bluebonnet, the official state flower of Texas. + +### What logic belongs in a Router vs. a Request Adapter? + +Simple, static data such as paths, parameters and common headers belong in the `Router`. Dynamic data such as an `Authorization` header whose value can changed based on an authentication system belongs in a `RequestAdapter`. + +The reason the dynamic data MUST be placed into the `RequestAdapter` is to support retry operations. When a `Request` is retried, the original request is not rebuilt meaning the `Router` will not be called again. The `RequestAdapter` is called again allowing the dynamic data to be updated on the original request before retrying the `Request`. + +--- + +## Credits + +Alamofire is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). You can follow them on Twitter at [@AlamofireSF](https://twitter.com/AlamofireSF) for project updates and releases. + +### Security Disclosure + +If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. + +## Donations + +The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise money to officially register as a federal non-profit organization. Registering will allow us members to gain some legal protections and also allow us to put donations to use, tax free. Donating to the ASF will enable us to: + +- Pay our legal fees to register as a federal non-profit organization +- Pay our yearly legal fees to keep the non-profit in good status +- Pay for our mail servers to help us stay on top of all questions and security issues +- Potentially fund test servers to make it easier for us to test the edge cases +- Potentially fund developers to work on one of our projects full-time + +The community adoption of the ASF libraries has been amazing. We are greatly humbled by your enthusiasm around the projects, and want to continue to do everything we can to move the needle forward. With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. If you use any of our libraries for work, see if your employers would be interested in donating. Our initial goal is to raise $1000 to get all our legal ducks in a row and kickstart this campaign. Any amount you can donate today to help us reach our goal would be greatly appreciated. + +Click here to lend your support to: Alamofire Software Foundation and make a donation at pledgie.com ! + +## License + +Alamofire is released under the MIT license. [See LICENSE](https://github.com/Alamofire/Alamofire/blob/master/LICENSE) for details. diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/AFError.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/AFError.swift new file mode 100644 index 0000000000..f047695b6d --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/AFError.swift @@ -0,0 +1,460 @@ +// +// AFError.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 + +/// `AFError` is the error type returned by Alamofire. It encompasses a few different types of errors, each with +/// their own associated reasons. +/// +/// - invalidURL: Returned when a `URLConvertible` type fails to create a valid `URL`. +/// - parameterEncodingFailed: Returned when a parameter encoding object throws an error during the encoding process. +/// - multipartEncodingFailed: Returned when some step in the multipart encoding process fails. +/// - responseValidationFailed: Returned when a `validate()` call fails. +/// - responseSerializationFailed: Returned when a response serializer encounters an error in the serialization process. +public enum AFError: Error { + /// The underlying reason the parameter encoding error occurred. + /// + /// - missingURL: The URL request did not have a URL to encode. + /// - jsonEncodingFailed: JSON serialization failed with an underlying system error during the + /// encoding process. + /// - propertyListEncodingFailed: Property list serialization failed with an underlying system error during + /// encoding process. + public enum ParameterEncodingFailureReason { + case missingURL + case jsonEncodingFailed(error: Error) + case propertyListEncodingFailed(error: Error) + } + + /// The underlying reason the multipart encoding error occurred. + /// + /// - bodyPartURLInvalid: The `fileURL` provided for reading an encodable body part isn't a + /// file URL. + /// - bodyPartFilenameInvalid: The filename of the `fileURL` provided has either an empty + /// `lastPathComponent` or `pathExtension. + /// - bodyPartFileNotReachable: The file at the `fileURL` provided was not reachable. + /// - bodyPartFileNotReachableWithError: Attempting to check the reachability of the `fileURL` provided threw + /// an error. + /// - bodyPartFileIsDirectory: The file at the `fileURL` provided is actually a directory. + /// - bodyPartFileSizeNotAvailable: The size of the file at the `fileURL` provided was not returned by + /// the system. + /// - bodyPartFileSizeQueryFailedWithError: The attempt to find the size of the file at the `fileURL` provided + /// threw an error. + /// - bodyPartInputStreamCreationFailed: An `InputStream` could not be created for the provided `fileURL`. + /// - outputStreamCreationFailed: An `OutputStream` could not be created when attempting to write the + /// encoded data to disk. + /// - outputStreamFileAlreadyExists: The encoded body data could not be writtent disk because a file + /// already exists at the provided `fileURL`. + /// - outputStreamURLInvalid: The `fileURL` provided for writing the encoded body data to disk is + /// not a file URL. + /// - outputStreamWriteFailed: The attempt to write the encoded body data to disk failed with an + /// underlying error. + /// - inputStreamReadFailed: The attempt to read an encoded body part `InputStream` failed with + /// underlying system error. + public enum MultipartEncodingFailureReason { + case bodyPartURLInvalid(url: URL) + case bodyPartFilenameInvalid(in: URL) + case bodyPartFileNotReachable(at: URL) + case bodyPartFileNotReachableWithError(atURL: URL, error: Error) + case bodyPartFileIsDirectory(at: URL) + case bodyPartFileSizeNotAvailable(at: URL) + case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error) + case bodyPartInputStreamCreationFailed(for: URL) + + case outputStreamCreationFailed(for: URL) + case outputStreamFileAlreadyExists(at: URL) + case outputStreamURLInvalid(url: URL) + case outputStreamWriteFailed(error: Error) + + case inputStreamReadFailed(error: Error) + } + + /// The underlying reason the response validation error occurred. + /// + /// - dataFileNil: The data file containing the server response did not exist. + /// - dataFileReadFailed: The data file containing the server response could not be read. + /// - missingContentType: The response did not contain a `Content-Type` and the `acceptableContentTypes` + /// provided did not contain wildcard type. + /// - unacceptableContentType: The response `Content-Type` did not match any type in the provided + /// `acceptableContentTypes`. + /// - unacceptableStatusCode: The response status code was not acceptable. + public enum ResponseValidationFailureReason { + case dataFileNil + case dataFileReadFailed(at: URL) + case missingContentType(acceptableContentTypes: [String]) + case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String) + case unacceptableStatusCode(code: Int) + } + + /// The underlying reason the response serialization error occurred. + /// + /// - inputDataNil: The server response contained no data. + /// - inputDataNilOrZeroLength: The server response contained no data or the data was zero length. + /// - inputFileNil: The file containing the server response did not exist. + /// - inputFileReadFailed: The file containing the server response could not be read. + /// - stringSerializationFailed: String serialization failed using the provided `String.Encoding`. + /// - jsonSerializationFailed: JSON serialization failed with an underlying system error. + /// - propertyListSerializationFailed: Property list serialization failed with an underlying system error. + public enum ResponseSerializationFailureReason { + case inputDataNil + case inputDataNilOrZeroLength + case inputFileNil + case inputFileReadFailed(at: URL) + case stringSerializationFailed(encoding: String.Encoding) + case jsonSerializationFailed(error: Error) + case propertyListSerializationFailed(error: Error) + } + + case invalidURL(url: URLConvertible) + case parameterEncodingFailed(reason: ParameterEncodingFailureReason) + case multipartEncodingFailed(reason: MultipartEncodingFailureReason) + case responseValidationFailed(reason: ResponseValidationFailureReason) + case responseSerializationFailed(reason: ResponseSerializationFailureReason) +} + +// MARK: - Adapt Error + +struct AdaptError: Error { + let error: Error +} + +extension Error { + var underlyingAdaptError: Error? { return (self as? AdaptError)?.error } +} + +// MARK: - Error Booleans + +extension AFError { + /// Returns whether the AFError is an invalid URL error. + public var isInvalidURLError: Bool { + if case .invalidURL = self { return true } + return false + } + + /// Returns whether the AFError is a parameter encoding error. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isParameterEncodingError: Bool { + if case .parameterEncodingFailed = self { return true } + return false + } + + /// Returns whether the AFError is a multipart encoding error. When `true`, the `url` and `underlyingError` properties + /// will contain the associated values. + public var isMultipartEncodingError: Bool { + if case .multipartEncodingFailed = self { return true } + return false + } + + /// Returns whether the `AFError` is a response validation error. When `true`, the `acceptableContentTypes`, + /// `responseContentType`, and `responseCode` properties will contain the associated values. + public var isResponseValidationError: Bool { + if case .responseValidationFailed = self { return true } + return false + } + + /// Returns whether the `AFError` is a response serialization error. When `true`, the `failedStringEncoding` and + /// `underlyingError` properties will contain the associated values. + public var isResponseSerializationError: Bool { + if case .responseSerializationFailed = self { return true } + return false + } +} + +// MARK: - Convenience Properties + +extension AFError { + /// The `URLConvertible` associated with the error. + public var urlConvertible: URLConvertible? { + switch self { + case .invalidURL(let url): + return url + default: + return nil + } + } + + /// The `URL` associated with the error. + public var url: URL? { + switch self { + case .multipartEncodingFailed(let reason): + return reason.url + default: + return nil + } + } + + /// The `Error` returned by a system framework associated with a `.parameterEncodingFailed`, + /// `.multipartEncodingFailed` or `.responseSerializationFailed` error. + public var underlyingError: Error? { + switch self { + case .parameterEncodingFailed(let reason): + return reason.underlyingError + case .multipartEncodingFailed(let reason): + return reason.underlyingError + case .responseSerializationFailed(let reason): + return reason.underlyingError + default: + return nil + } + } + + /// The acceptable `Content-Type`s of a `.responseValidationFailed` error. + public var acceptableContentTypes: [String]? { + switch self { + case .responseValidationFailed(let reason): + return reason.acceptableContentTypes + default: + return nil + } + } + + /// The response `Content-Type` of a `.responseValidationFailed` error. + public var responseContentType: String? { + switch self { + case .responseValidationFailed(let reason): + return reason.responseContentType + default: + return nil + } + } + + /// The response code of a `.responseValidationFailed` error. + public var responseCode: Int? { + switch self { + case .responseValidationFailed(let reason): + return reason.responseCode + default: + return nil + } + } + + /// The `String.Encoding` associated with a failed `.stringResponse()` call. + public var failedStringEncoding: String.Encoding? { + switch self { + case .responseSerializationFailed(let reason): + return reason.failedStringEncoding + default: + return nil + } + } +} + +extension AFError.ParameterEncodingFailureReason { + var underlyingError: Error? { + switch self { + case .jsonEncodingFailed(let error), .propertyListEncodingFailed(let error): + return error + default: + return nil + } + } +} + +extension AFError.MultipartEncodingFailureReason { + var url: URL? { + switch self { + case .bodyPartURLInvalid(let url), .bodyPartFilenameInvalid(let url), .bodyPartFileNotReachable(let url), + .bodyPartFileIsDirectory(let url), .bodyPartFileSizeNotAvailable(let url), + .bodyPartInputStreamCreationFailed(let url), .outputStreamCreationFailed(let url), + .outputStreamFileAlreadyExists(let url), .outputStreamURLInvalid(let url), + .bodyPartFileNotReachableWithError(let url, _), .bodyPartFileSizeQueryFailedWithError(let url, _): + return url + default: + return nil + } + } + + var underlyingError: Error? { + switch self { + case .bodyPartFileNotReachableWithError(_, let error), .bodyPartFileSizeQueryFailedWithError(_, let error), + .outputStreamWriteFailed(let error), .inputStreamReadFailed(let error): + return error + default: + return nil + } + } +} + +extension AFError.ResponseValidationFailureReason { + var acceptableContentTypes: [String]? { + switch self { + case .missingContentType(let types), .unacceptableContentType(let types, _): + return types + default: + return nil + } + } + + var responseContentType: String? { + switch self { + case .unacceptableContentType(_, let responseType): + return responseType + default: + return nil + } + } + + var responseCode: Int? { + switch self { + case .unacceptableStatusCode(let code): + return code + default: + return nil + } + } +} + +extension AFError.ResponseSerializationFailureReason { + var failedStringEncoding: String.Encoding? { + switch self { + case .stringSerializationFailed(let encoding): + return encoding + default: + return nil + } + } + + var underlyingError: Error? { + switch self { + case .jsonSerializationFailed(let error), .propertyListSerializationFailed(let error): + return error + default: + return nil + } + } +} + +// MARK: - Error Descriptions + +extension AFError: LocalizedError { + public var errorDescription: String? { + switch self { + case .invalidURL(let url): + return "URL is not valid: \(url)" + case .parameterEncodingFailed(let reason): + return reason.localizedDescription + case .multipartEncodingFailed(let reason): + return reason.localizedDescription + case .responseValidationFailed(let reason): + return reason.localizedDescription + case .responseSerializationFailed(let reason): + return reason.localizedDescription + } + } +} + +extension AFError.ParameterEncodingFailureReason { + var localizedDescription: String { + switch self { + case .missingURL: + return "URL request to encode was missing a URL" + case .jsonEncodingFailed(let error): + return "JSON could not be encoded because of error:\n\(error.localizedDescription)" + case .propertyListEncodingFailed(let error): + return "PropertyList could not be encoded because of error:\n\(error.localizedDescription)" + } + } +} + +extension AFError.MultipartEncodingFailureReason { + var localizedDescription: String { + switch self { + case .bodyPartURLInvalid(let url): + return "The URL provided is not a file URL: \(url)" + case .bodyPartFilenameInvalid(let url): + return "The URL provided does not have a valid filename: \(url)" + case .bodyPartFileNotReachable(let url): + return "The URL provided is not reachable: \(url)" + case .bodyPartFileNotReachableWithError(let url, let error): + return ( + "The system returned an error while checking the provided URL for " + + "reachability.\nURL: \(url)\nError: \(error)" + ) + case .bodyPartFileIsDirectory(let url): + return "The URL provided is a directory: \(url)" + case .bodyPartFileSizeNotAvailable(let url): + return "Could not fetch the file size from the provided URL: \(url)" + case .bodyPartFileSizeQueryFailedWithError(let url, let error): + return ( + "The system returned an error while attempting to fetch the file size from the " + + "provided URL.\nURL: \(url)\nError: \(error)" + ) + case .bodyPartInputStreamCreationFailed(let url): + return "Failed to create an InputStream for the provided URL: \(url)" + case .outputStreamCreationFailed(let url): + return "Failed to create an OutputStream for URL: \(url)" + case .outputStreamFileAlreadyExists(let url): + return "A file already exists at the provided URL: \(url)" + case .outputStreamURLInvalid(let url): + return "The provided OutputStream URL is invalid: \(url)" + case .outputStreamWriteFailed(let error): + return "OutputStream write failed with error: \(error)" + case .inputStreamReadFailed(let error): + return "InputStream read failed with error: \(error)" + } + } +} + +extension AFError.ResponseSerializationFailureReason { + var localizedDescription: String { + switch self { + case .inputDataNil: + return "Response could not be serialized, input data was nil." + case .inputDataNilOrZeroLength: + return "Response could not be serialized, input data was nil or zero length." + case .inputFileNil: + return "Response could not be serialized, input file was nil." + case .inputFileReadFailed(let url): + return "Response could not be serialized, input file could not be read: \(url)." + case .stringSerializationFailed(let encoding): + return "String could not be serialized with encoding: \(encoding)." + case .jsonSerializationFailed(let error): + return "JSON could not be serialized because of error:\n\(error.localizedDescription)" + case .propertyListSerializationFailed(let error): + return "PropertyList could not be serialized because of error:\n\(error.localizedDescription)" + } + } +} + +extension AFError.ResponseValidationFailureReason { + var localizedDescription: String { + switch self { + case .dataFileNil: + return "Response could not be validated, data file was nil." + case .dataFileReadFailed(let url): + return "Response could not be validated, data file could not be read: \(url)." + case .missingContentType(let types): + return ( + "Response Content-Type was missing and acceptable content types " + + "(\(types.joined(separator: ","))) do not match \"*/*\"." + ) + case .unacceptableContentType(let acceptableTypes, let responseType): + return ( + "Response Content-Type \"\(responseType)\" does not match any acceptable types: " + + "\(acceptableTypes.joined(separator: ","))." + ) + case .unacceptableStatusCode(let code): + return "Response status code was unacceptable: \(code)." + } + } +} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift new file mode 100644 index 0000000000..edcf717ca9 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift @@ -0,0 +1,465 @@ +// +// 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 + +/// Types adopting the `URLConvertible` protocol can be used to construct URLs, which are then used to construct +/// URL requests. +public protocol URLConvertible { + /// Returns a URL that conforms to RFC 2396 or throws an `Error`. + /// + /// - throws: An `Error` if the type cannot be converted to a `URL`. + /// + /// - returns: A URL or throws an `Error`. + func asURL() throws -> URL +} + +extension String: URLConvertible { + /// Returns a URL if `self` represents a valid URL string that conforms to RFC 2396 or throws an `AFError`. + /// + /// - throws: An `AFError.invalidURL` if `self` is not a valid URL string. + /// + /// - returns: A URL or throws an `AFError`. + public func asURL() throws -> URL { + guard let url = URL(string: self) else { throw AFError.invalidURL(url: self) } + return url + } +} + +extension URL: URLConvertible { + /// Returns self. + public func asURL() throws -> URL { return self } +} + +extension URLComponents: URLConvertible { + /// Returns a URL if `url` is not nil, otherwise throws an `Error`. + /// + /// - throws: An `AFError.invalidURL` if `url` is `nil`. + /// + /// - returns: A URL or throws an `AFError`. + public func asURL() throws -> URL { + guard let url = url else { throw AFError.invalidURL(url: self) } + return url + } +} + +// MARK: - + +/// Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. +public protocol URLRequestConvertible { + /// Returns a URL request or throws if an `Error` was encountered. + /// + /// - throws: An `Error` if the underlying `URLRequest` is `nil`. + /// + /// - returns: A URL request. + func asURLRequest() throws -> URLRequest +} + +extension URLRequestConvertible { + /// The URL request. + public var urlRequest: URLRequest? { return try? asURLRequest() } +} + +extension URLRequest: URLRequestConvertible { + /// Returns a URL request or throws if an `Error` was encountered. + public func asURLRequest() throws -> URLRequest { return self } +} + +// MARK: - + +extension URLRequest { + /// Creates an instance with the specified `method`, `urlString` and `headers`. + /// + /// - parameter url: The URL. + /// - parameter method: The HTTP method. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The new `URLRequest` instance. + public init(url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws { + let url = try url.asURL() + + self.init(url: url) + + httpMethod = method.rawValue + + if let headers = headers { + for (headerField, headerValue) in headers { + setValue(headerValue, forHTTPHeaderField: headerField) + } + } + } + + func adapt(using adapter: RequestAdapter?) throws -> URLRequest { + guard let adapter = adapter else { return self } + return try adapter.adapt(self) + } +} + +// MARK: - Data Request + +/// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, +/// `method`, `parameters`, `encoding` and `headers`. +/// +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.get` by default. +/// - parameter parameters: The parameters. `nil` by default. +/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `DataRequest`. +@discardableResult +public func request( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil) + -> DataRequest +{ + return SessionManager.default.request( + url, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers + ) +} + +/// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of a URL based on the +/// specified `urlRequest`. +/// +/// - parameter urlRequest: The URL request +/// +/// - returns: The created `DataRequest`. +@discardableResult +public func request(_ urlRequest: URLRequestConvertible) -> DataRequest { + return SessionManager.default.request(urlRequest) +} + +// MARK: - Download Request + +// MARK: URL Request + +/// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, +/// `method`, `parameters`, `encoding`, `headers` and save them to the `destination`. +/// +/// If `destination` is not specified, the contents will remain in the temporary location determined by the +/// underlying URL session. +/// +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.get` by default. +/// - parameter parameters: The parameters. `nil` by default. +/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. +/// +/// - returns: The created `DownloadRequest`. +@discardableResult +public func download( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest +{ + return SessionManager.default.download( + url, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers, + to: destination + ) +} + +/// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of a URL based on the +/// specified `urlRequest` and save them to the `destination`. +/// +/// If `destination` is not specified, the contents will remain in the temporary location determined by the +/// underlying URL session. +/// +/// - parameter urlRequest: The URL request. +/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. +/// +/// - returns: The created `DownloadRequest`. +@discardableResult +public func download( + _ urlRequest: URLRequestConvertible, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest +{ + return SessionManager.default.download(urlRequest, to: destination) +} + +// MARK: Resume Data + +/// Creates a `DownloadRequest` using the default `SessionManager` from the `resumeData` produced from a +/// previous request cancellation to retrieve the contents of the original request and save them to the `destination`. +/// +/// If `destination` is not specified, the contents will remain in the temporary location determined by the +/// underlying URL session. +/// +/// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken +/// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the +/// data is written incorrectly and will always fail to resume the download. For more information about the bug and +/// possible workarounds, please refer to the following Stack Overflow post: +/// +/// - http://stackoverflow.com/a/39347461/1342462 +/// +/// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` +/// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for additional +/// information. +/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. +/// +/// - returns: The created `DownloadRequest`. +@discardableResult +public func download( + resumingWith resumeData: Data, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest +{ + return SessionManager.default.download(resumingWith: resumeData, to: destination) +} + +// MARK: - Upload Request + +// MARK: File + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` +/// for uploading the `file`. +/// +/// - parameter file: The file to upload. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload( + _ fileURL: URL, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest +{ + return SessionManager.default.upload(fileURL, to: url, method: method, headers: headers) +} + +/// Creates a `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for +/// uploading the `file`. +/// +/// - parameter file: The file to upload. +/// - parameter urlRequest: The URL request. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { + return SessionManager.default.upload(fileURL, with: urlRequest) +} + +// MARK: Data + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` +/// for uploading the `data`. +/// +/// - parameter data: The data to upload. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload( + _ data: Data, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest +{ + return SessionManager.default.upload(data, to: url, method: method, headers: headers) +} + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for +/// uploading the `data`. +/// +/// - parameter data: The data to upload. +/// - parameter urlRequest: The URL request. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { + return SessionManager.default.upload(data, with: urlRequest) +} + +// MARK: InputStream + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` +/// for uploading the `stream`. +/// +/// - parameter stream: The stream to upload. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload( + _ stream: InputStream, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest +{ + return SessionManager.default.upload(stream, to: url, method: method, headers: headers) +} + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for +/// uploading the `stream`. +/// +/// - parameter urlRequest: The URL request. +/// - parameter stream: The stream to upload. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { + return SessionManager.default.upload(stream, with: urlRequest) +} + +// MARK: MultipartFormData + +/// Encodes `multipartFormData` using `encodingMemoryThreshold` with the default `SessionManager` and calls +/// `encodingCompletion` with new `UploadRequest` using the `url`, `method` and `headers`. +/// +/// 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. +/// +/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. +/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. +/// `multipartFormDataEncodingMemoryThreshold` by default. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. +public func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) +{ + return SessionManager.default.upload( + multipartFormData: multipartFormData, + usingThreshold: encodingMemoryThreshold, + to: url, + method: method, + headers: headers, + encodingCompletion: encodingCompletion + ) +} + +/// Encodes `multipartFormData` using `encodingMemoryThreshold` and the default `SessionManager` and +/// calls `encodingCompletion` with new `UploadRequest` using the `urlRequest`. +/// +/// 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. +/// +/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. +/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. +/// `multipartFormDataEncodingMemoryThreshold` by default. +/// - parameter urlRequest: The URL request. +/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. +public func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + with urlRequest: URLRequestConvertible, + encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) +{ + return SessionManager.default.upload( + multipartFormData: multipartFormData, + usingThreshold: encodingMemoryThreshold, + with: urlRequest, + encodingCompletion: encodingCompletion + ) +} + +#if !os(watchOS) + +// MARK: - Stream Request + +// MARK: Hostname and Port + +/// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `hostname` +/// and `port`. +/// +/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. +/// +/// - parameter hostName: The hostname of the server to connect to. +/// - parameter port: The port of the server to connect to. +/// +/// - returns: The created `StreamRequest`. +@discardableResult +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +public func stream(withHostName hostName: String, port: Int) -> StreamRequest { + return SessionManager.default.stream(withHostName: hostName, port: port) +} + +// MARK: NetService + +/// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `netService`. +/// +/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. +/// +/// - parameter netService: The net service used to identify the endpoint. +/// +/// - returns: The created `StreamRequest`. +@discardableResult +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +public func stream(with netService: NetService) -> StreamRequest { + return SessionManager.default.stream(with: netService) +} + +#endif diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift new file mode 100644 index 0000000000..78e214ea17 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift @@ -0,0 +1,37 @@ +// +// DispatchQueue+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 Dispatch +import Foundation + +extension DispatchQueue { + static var userInteractive: DispatchQueue { return DispatchQueue.global(qos: .userInteractive) } + static var userInitiated: DispatchQueue { return DispatchQueue.global(qos: .userInitiated) } + static var utility: DispatchQueue { return DispatchQueue.global(qos: .utility) } + static var background: DispatchQueue { return DispatchQueue.global(qos: .background) } + + func after(_ delay: TimeInterval, execute closure: @escaping () -> Void) { + asyncAfter(deadline: .now() + delay, execute: closure) + } +} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift new file mode 100644 index 0000000000..c5093f9f85 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift @@ -0,0 +1,580 @@ +// +// 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(macOS) +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 +open 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(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data { + 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.data(using: String.Encoding.utf8, allowLossyConversion: false)! + } + } + + class BodyPart { + let headers: HTTPHeaders + let bodyStream: InputStream + let bodyContentLength: UInt64 + var hasInitialBoundary = false + var hasFinalBoundary = false + + init(headers: HTTPHeaders, bodyStream: InputStream, 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`. + open lazy var contentType: String = "multipart/form-data; boundary=\(self.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: AFError? + 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 append(_ data: Data, withName name: String) { + let headers = contentHeaders(withName: name) + let stream = InputStream(data: data) + let length = UInt64(data.count) + + append(stream, withLength: 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 append(_ data: Data, withName name: String, mimeType: String) { + let headers = contentHeaders(withName: name, mimeType: mimeType) + let stream = InputStream(data: data) + let length = UInt64(data.count) + + append(stream, withLength: 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 append(_ data: Data, withName name: String, fileName: String, mimeType: String) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + let stream = InputStream(data: data) + let length = UInt64(data.count) + + append(stream, withLength: 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 append(_ fileURL: URL, withName name: String) { + let fileName = fileURL.lastPathComponent + let pathExtension = fileURL.pathExtension + + if !fileName.isEmpty && !pathExtension.isEmpty { + let mime = mimeType(forPathExtension: pathExtension) + append(fileURL, withName: name, fileName: fileName, mimeType: mime) + } else { + setBodyPartError(withReason: .bodyPartFilenameInvalid(in: fileURL)) + } + } + + /// 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 append(_ fileURL: URL, withName name: String, fileName: String, mimeType: String) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + + //============================================================ + // Check 1 - is file URL? + //============================================================ + + guard fileURL.isFileURL else { + setBodyPartError(withReason: .bodyPartURLInvalid(url: fileURL)) + return + } + + //============================================================ + // Check 2 - is file URL reachable? + //============================================================ + + do { + let isReachable = try fileURL.checkPromisedItemIsReachable() + guard isReachable else { + setBodyPartError(withReason: .bodyPartFileNotReachable(at: fileURL)) + return + } + } catch { + setBodyPartError(withReason: .bodyPartFileNotReachableWithError(atURL: fileURL, error: error)) + return + } + + //============================================================ + // Check 3 - is file URL a directory? + //============================================================ + + var isDirectory: ObjCBool = false + let path = fileURL.path + + guard FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) && !isDirectory.boolValue else { + setBodyPartError(withReason: .bodyPartFileIsDirectory(at: fileURL)) + return + } + + //============================================================ + // Check 4 - can the file size be extracted? + //============================================================ + + let bodyContentLength: UInt64 + + do { + guard let fileSize = try FileManager.default.attributesOfItem(atPath: path)[.size] as? NSNumber else { + setBodyPartError(withReason: .bodyPartFileSizeNotAvailable(at: fileURL)) + return + } + + bodyContentLength = fileSize.uint64Value + } + catch { + setBodyPartError(withReason: .bodyPartFileSizeQueryFailedWithError(forURL: fileURL, error: error)) + return + } + + //============================================================ + // Check 5 - can a stream be created from file URL? + //============================================================ + + guard let stream = InputStream(url: fileURL) else { + setBodyPartError(withReason: .bodyPartInputStreamCreationFailed(for: fileURL)) + return + } + + append(stream, withLength: bodyContentLength, 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 append( + _ stream: InputStream, + withLength length: UInt64, + name: String, + fileName: String, + mimeType: String) + { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + append(stream, withLength: 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 append(_ stream: InputStream, withLength length: UInt64, headers: HTTPHeaders) { + let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length) + bodyParts.append(bodyPart) + } + + // MARK: - Data Encoding + + /// Encodes all the appended body parts into a single `Data` value. + /// + /// 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 `AFError` if encoding encounters an error. + /// + /// - returns: The encoded `Data` if encoding is successful. + public func encode() throws -> Data { + if let bodyPartError = bodyPartError { + throw bodyPartError + } + + var encoded = Data() + + bodyParts.first?.hasInitialBoundary = true + bodyParts.last?.hasFinalBoundary = true + + for bodyPart in bodyParts { + let encodedData = try encode(bodyPart) + encoded.append(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 `AFError` if encoding encounters an error. + public func writeEncodedData(to fileURL: URL) throws { + if let bodyPartError = bodyPartError { + throw bodyPartError + } + + if FileManager.default.fileExists(atPath: fileURL.path) { + throw AFError.multipartEncodingFailed(reason: .outputStreamFileAlreadyExists(at: fileURL)) + } else if !fileURL.isFileURL { + throw AFError.multipartEncodingFailed(reason: .outputStreamURLInvalid(url: fileURL)) + } + + guard let outputStream = OutputStream(url: fileURL, append: false) else { + throw AFError.multipartEncodingFailed(reason: .outputStreamCreationFailed(for: fileURL)) + } + + outputStream.open() + defer { outputStream.close() } + + self.bodyParts.first?.hasInitialBoundary = true + self.bodyParts.last?.hasFinalBoundary = true + + for bodyPart in self.bodyParts { + try write(bodyPart, to: outputStream) + } + } + + // MARK: - Private - Body Part Encoding + + private func encode(_ bodyPart: BodyPart) throws -> Data { + var encoded = Data() + + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + encoded.append(initialData) + + let headerData = encodeHeaders(for: bodyPart) + encoded.append(headerData) + + let bodyStreamData = try encodeBodyStream(for: bodyPart) + encoded.append(bodyStreamData) + + if bodyPart.hasFinalBoundary { + encoded.append(finalBoundaryData()) + } + + return encoded + } + + private func encodeHeaders(for bodyPart: BodyPart) -> Data { + var headerText = "" + + for (key, value) in bodyPart.headers { + headerText += "\(key): \(value)\(EncodingCharacters.crlf)" + } + headerText += EncodingCharacters.crlf + + return headerText.data(using: String.Encoding.utf8, allowLossyConversion: false)! + } + + private func encodeBodyStream(for bodyPart: BodyPart) throws -> Data { + let inputStream = bodyPart.bodyStream + inputStream.open() + defer { inputStream.close() } + + var encoded = Data() + + while inputStream.hasBytesAvailable { + var buffer = [UInt8](repeating: 0, count: streamBufferSize) + let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) + + if let error = inputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error)) + } + + if bytesRead > 0 { + encoded.append(buffer, count: bytesRead) + } else { + break + } + } + + return encoded + } + + // MARK: - Private - Writing Body Part to Output Stream + + private func write(_ bodyPart: BodyPart, to outputStream: OutputStream) throws { + try writeInitialBoundaryData(for: bodyPart, to: outputStream) + try writeHeaderData(for: bodyPart, to: outputStream) + try writeBodyStream(for: bodyPart, to: outputStream) + try writeFinalBoundaryData(for: bodyPart, to: outputStream) + } + + private func writeInitialBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + return try write(initialData, to: outputStream) + } + + private func writeHeaderData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let headerData = encodeHeaders(for: bodyPart) + return try write(headerData, to: outputStream) + } + + private func writeBodyStream(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let inputStream = bodyPart.bodyStream + + inputStream.open() + defer { inputStream.close() } + + while inputStream.hasBytesAvailable { + var buffer = [UInt8](repeating: 0, count: streamBufferSize) + let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) + + if let streamError = inputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: streamError)) + } + + if bytesRead > 0 { + if buffer.count != bytesRead { + buffer = Array(buffer[0.. 0, outputStream.hasSpaceAvailable { + let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite) + + if let error = outputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .outputStreamWriteFailed(error: error)) + } + + bytesToWrite -= bytesWritten + + if bytesToWrite > 0 { + buffer = Array(buffer[bytesWritten.. String { + if + let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), + let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() + { + return contentType as String + } + + return "application/octet-stream" + } + + // MARK: - Private - Content Headers + + private func contentHeaders(withName name: String, fileName: String? = nil, mimeType: String? = nil) -> [String: String] { + var disposition = "form-data; name=\"\(name)\"" + if let fileName = fileName { disposition += "; filename=\"\(fileName)\"" } + + var headers = ["Content-Disposition": disposition] + if let mimeType = mimeType { headers["Content-Type"] = mimeType } + + return headers + } + + // MARK: - Private - Boundary Encoding + + private func initialBoundaryData() -> Data { + return BoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary) + } + + private func encapsulatedBoundaryData() -> Data { + return BoundaryGenerator.boundaryData(forBoundaryType: .encapsulated, boundary: boundary) + } + + private func finalBoundaryData() -> Data { + return BoundaryGenerator.boundaryData(forBoundaryType: .final, boundary: boundary) + } + + // MARK: - Private - Errors + + private func setBodyPartError(withReason reason: AFError.MultipartEncodingFailureReason) { + guard bodyPartError == nil else { return } + bodyPartError = AFError.multipartEncodingFailed(reason: reason) + } +} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/NetworkReachabilityManager.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/NetworkReachabilityManager.swift new file mode 100644 index 0000000000..30443b99b2 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/NetworkReachabilityManager.swift @@ -0,0 +1,233 @@ +// +// NetworkReachabilityManager.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#if !os(watchOS) + +import Foundation +import SystemConfiguration + +/// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and +/// WiFi network interfaces. +/// +/// Reachability can be used to determine background information about why a network operation failed, or to retry +/// network requests when a connection is established. It should not be used to prevent a user from initiating a network +/// request, as it's possible that an initial request may be required to establish reachability. +public class NetworkReachabilityManager { + /// Defines the various states of network reachability. + /// + /// - unknown: It is unknown whether the network is reachable. + /// - notReachable: The network is not reachable. + /// - reachable: The network is reachable. + public enum NetworkReachabilityStatus { + case unknown + case notReachable + case reachable(ConnectionType) + } + + /// Defines the various connection types detected by reachability flags. + /// + /// - ethernetOrWiFi: The connection type is either over Ethernet or WiFi. + /// - wwan: The connection type is a WWAN connection. + public enum ConnectionType { + case ethernetOrWiFi + case wwan + } + + /// A closure executed when the network reachability status changes. The closure takes a single argument: the + /// network reachability status. + public typealias Listener = (NetworkReachabilityStatus) -> Void + + // MARK: - Properties + + /// Whether the network is currently reachable. + public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi } + + /// Whether the network is currently reachable over the WWAN interface. + public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .reachable(.wwan) } + + /// Whether the network is currently reachable over Ethernet or WiFi interface. + public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .reachable(.ethernetOrWiFi) } + + /// The current network reachability status. + public var networkReachabilityStatus: NetworkReachabilityStatus { + guard let flags = self.flags else { return .unknown } + return networkReachabilityStatusForFlags(flags) + } + + /// The dispatch queue to execute the `listener` closure on. + public var listenerQueue: DispatchQueue = DispatchQueue.main + + /// A closure executed when the network reachability status changes. + public var listener: Listener? + + private var flags: SCNetworkReachabilityFlags? { + var flags = SCNetworkReachabilityFlags() + + if SCNetworkReachabilityGetFlags(reachability, &flags) { + return flags + } + + return nil + } + + private let reachability: SCNetworkReachability + private var previousFlags: SCNetworkReachabilityFlags + + // MARK: - Initialization + + /// Creates a `NetworkReachabilityManager` instance with the specified host. + /// + /// - parameter host: The host used to evaluate network reachability. + /// + /// - returns: The new `NetworkReachabilityManager` instance. + public convenience init?(host: String) { + guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } + self.init(reachability: reachability) + } + + /// Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0. + /// + /// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing + /// status of the device, both IPv4 and IPv6. + /// + /// - returns: The new `NetworkReachabilityManager` instance. + public convenience init?() { + var address = sockaddr_in() + address.sin_len = UInt8(MemoryLayout.size) + address.sin_family = sa_family_t(AF_INET) + + guard let reachability = withUnsafePointer(to: &address, { pointer in + return pointer.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout.size) { + return SCNetworkReachabilityCreateWithAddress(nil, $0) + } + }) else { return nil } + + self.init(reachability: reachability) + } + + private init(reachability: SCNetworkReachability) { + self.reachability = reachability + self.previousFlags = SCNetworkReachabilityFlags() + } + + deinit { + stopListening() + } + + // MARK: - Listening + + /// Starts listening for changes in network reachability status. + /// + /// - returns: `true` if listening was started successfully, `false` otherwise. + @discardableResult + public func startListening() -> Bool { + var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) + context.info = Unmanaged.passUnretained(self).toOpaque() + + let callbackEnabled = SCNetworkReachabilitySetCallback( + reachability, + { (_, flags, info) in + let reachability = Unmanaged.fromOpaque(info!).takeUnretainedValue() + reachability.notifyListener(flags) + }, + &context + ) + + let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue) + + listenerQueue.async { + self.previousFlags = SCNetworkReachabilityFlags() + self.notifyListener(self.flags ?? SCNetworkReachabilityFlags()) + } + + return callbackEnabled && queueEnabled + } + + /// Stops listening for changes in network reachability status. + public func stopListening() { + SCNetworkReachabilitySetCallback(reachability, nil, nil) + SCNetworkReachabilitySetDispatchQueue(reachability, nil) + } + + // MARK: - Internal - Listener Notification + + func notifyListener(_ flags: SCNetworkReachabilityFlags) { + guard previousFlags != flags else { return } + previousFlags = flags + + listener?(networkReachabilityStatusForFlags(flags)) + } + + // MARK: - Internal - Network Reachability Status + + func networkReachabilityStatusForFlags(_ flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus { + guard isNetworkReachable(with: flags) else { return .notReachable } + + var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi) + + #if os(iOS) + if flags.contains(.isWWAN) { networkStatus = .reachable(.wwan) } + #endif + + return networkStatus + } + + func isNetworkReachable(with flags: SCNetworkReachabilityFlags) -> Bool { + let isReachable = flags.contains(.reachable) + let needsConnection = flags.contains(.connectionRequired) + let canConnectAutomatically = flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic) + let canConnectWithoutUserInteraction = canConnectAutomatically && !flags.contains(.interventionRequired) + + return isReachable && (!needsConnection || canConnectWithoutUserInteraction) + } +} + +// MARK: - + +extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} + +/// Returns whether the two network reachability status values are equal. +/// +/// - parameter lhs: The left-hand side value to compare. +/// - parameter rhs: The right-hand side value to compare. +/// +/// - returns: `true` if the two values are equal, `false` otherwise. +public func ==( + lhs: NetworkReachabilityManager.NetworkReachabilityStatus, + rhs: NetworkReachabilityManager.NetworkReachabilityStatus) + -> Bool +{ + switch (lhs, rhs) { + case (.unknown, .unknown): + return true + case (.notReachable, .notReachable): + return true + case let (.reachable(lhsConnectionType), .reachable(rhsConnectionType)): + return lhsConnectionType == rhsConnectionType + default: + return false + } +} + +#endif diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Notifications.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Notifications.swift new file mode 100644 index 0000000000..81f6e378c8 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Notifications.swift @@ -0,0 +1,52 @@ +// +// Notifications.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension Notification.Name { + /// Used as a namespace for all `URLSessionTask` related notifications. + public struct Task { + /// Posted when a `URLSessionTask` is resumed. The notification `object` contains the resumed `URLSessionTask`. + public static let DidResume = Notification.Name(rawValue: "org.alamofire.notification.name.task.didResume") + + /// Posted when a `URLSessionTask` is suspended. The notification `object` contains the suspended `URLSessionTask`. + public static let DidSuspend = Notification.Name(rawValue: "org.alamofire.notification.name.task.didSuspend") + + /// Posted when a `URLSessionTask` is cancelled. The notification `object` contains the cancelled `URLSessionTask`. + public static let DidCancel = Notification.Name(rawValue: "org.alamofire.notification.name.task.didCancel") + + /// Posted when a `URLSessionTask` is completed. The notification `object` contains the completed `URLSessionTask`. + public static let DidComplete = Notification.Name(rawValue: "org.alamofire.notification.name.task.didComplete") + } +} + +// MARK: - + +extension Notification { + /// Used as a namespace for all `Notification` user info dictionary keys. + public struct Key { + /// User info dictionary key representing the `URLSessionTask` associated with the notification. + public static let Task = "org.alamofire.notification.key.task" + } +} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift new file mode 100644 index 0000000000..959af6f936 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift @@ -0,0 +1,436 @@ +// +// 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 HTTPMethod: String { + case options = "OPTIONS" + case get = "GET" + case head = "HEAD" + case post = "POST" + case put = "PUT" + case patch = "PATCH" + case delete = "DELETE" + case trace = "TRACE" + case connect = "CONNECT" +} + +// MARK: - + +/// A dictionary of parameters to apply to a `URLRequest`. +public typealias Parameters = [String: Any] + +/// A type used to define how a set of parameters are applied to a `URLRequest`. +public protocol ParameterEncoding { + /// 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. + /// + /// - throws: An `AFError.parameterEncodingFailed` error if encoding fails. + /// + /// - returns: The encoded request. + func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest +} + +// MARK: - + +/// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP +/// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as +/// the HTTP body depends on the destination of the encoding. +/// +/// 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`). +public struct URLEncoding: ParameterEncoding { + + // MARK: Helper Types + + /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the + /// resulting URL request. + /// + /// - methodDependent: Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` + /// requests and sets as the HTTP body for requests with any other HTTP method. + /// - queryString: Sets or appends encoded query string result to existing query string. + /// - httpBody: Sets encoded query string result as the HTTP body of the URL request. + public enum Destination { + case methodDependent, queryString, httpBody + } + + // MARK: Properties + + /// Returns a default `URLEncoding` instance. + public static var `default`: URLEncoding { return URLEncoding() } + + /// Returns a `URLEncoding` instance with a `.methodDependent` destination. + public static var methodDependent: URLEncoding { return URLEncoding() } + + /// Returns a `URLEncoding` instance with a `.queryString` destination. + public static var queryString: URLEncoding { return URLEncoding(destination: .queryString) } + + /// Returns a `URLEncoding` instance with an `.httpBody` destination. + public static var httpBody: URLEncoding { return URLEncoding(destination: .httpBody) } + + /// The destination defining where the encoded query string is to be applied to the URL request. + public let destination: Destination + + // MARK: Initialization + + /// Creates a `URLEncoding` instance using the specified destination. + /// + /// - parameter destination: The destination defining where the encoded query string is to be applied. + /// + /// - returns: The new `URLEncoding` instance. + public init(destination: Destination = .methodDependent) { + self.destination = destination + } + + // MARK: Encoding + + /// 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. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters = parameters else { return urlRequest } + + if let method = HTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: method) { + guard let url = urlRequest.url else { + throw AFError.parameterEncodingFailed(reason: .missingURL) + } + + if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { + let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) + urlComponents.percentEncodedQuery = percentEncodedQuery + urlRequest.url = urlComponents.url + } + } else { + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false) + } + + return urlRequest + } + + /// 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(fromKey key: String, value: Any) -> [(String, String)] { + var components: [(String, String)] = [] + + if let dictionary = value as? [String: Any] { + for (nestedKey, value) in dictionary { + components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value) + } + } else if let array = value as? [Any] { + for value in array { + components += queryComponents(fromKey: "\(key)[]", value: value) + } + } else if let value = value as? NSNumber { + if value.isBool { + components.append((escape(key), escape((value.boolValue ? "1" : "0")))) + } else { + components.append((escape(key), escape("\(value)"))) + } + } else if let bool = value as? Bool { + components.append((escape(key), escape((bool ? "1" : "0")))) + } 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 = "!$&'()*+,;=" + + var allowedCharacterSet = CharacterSet.urlQueryAllowed + allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") + + var escaped = "" + + //========================================================================================================== + // + // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few + // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no + // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more + // info, please refer to: + // + // - https://github.com/Alamofire/Alamofire/issues/206 + // + //========================================================================================================== + + if #available(iOS 8.3, *) { + escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string + } else { + let batchSize = 50 + var index = string.startIndex + + while index != string.endIndex { + let startIndex = index + let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex + let range = startIndex.. String { + var components: [(String, String)] = [] + + for key in parameters.keys.sorted(by: <) { + let value = parameters[key]! + components += queryComponents(fromKey: key, value: value) + } + #if swift(>=4.0) + return components.map { "\($0.0)=\($0.1)" }.joined(separator: "&") + #else + return components.map { "\($0)=\($1)" }.joined(separator: "&") + #endif + } + + private func encodesParametersInURL(with method: HTTPMethod) -> Bool { + switch destination { + case .queryString: + return true + case .httpBody: + return false + default: + break + } + + switch method { + case .get, .head, .delete: + return true + default: + return false + } + } +} + +// MARK: - + +/// Uses `JSONSerialization` 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`. +public struct JSONEncoding: ParameterEncoding { + + // MARK: Properties + + /// Returns a `JSONEncoding` instance with default writing options. + public static var `default`: JSONEncoding { return JSONEncoding() } + + /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options. + public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) } + + /// The options for writing the parameters as JSON data. + public let options: JSONSerialization.WritingOptions + + // MARK: Initialization + + /// Creates a `JSONEncoding` instance using the specified options. + /// + /// - parameter options: The options for writing the parameters as JSON data. + /// + /// - returns: The new `JSONEncoding` instance. + public init(options: JSONSerialization.WritingOptions = []) { + self.options = options + } + + // MARK: Encoding + + /// 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. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters = parameters else { return urlRequest } + + do { + let data = try JSONSerialization.data(withJSONObject: parameters, options: options) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return urlRequest + } + + /// Creates a URL request by encoding the JSON object and setting the resulting data on the HTTP body. + /// + /// - parameter urlRequest: The request to apply the JSON object to. + /// - parameter jsonObject: The JSON object to apply to the request. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let jsonObject = jsonObject else { return urlRequest } + + do { + let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return urlRequest + } +} + +// MARK: - + +/// Uses `PropertyListSerialization` 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`. +public struct PropertyListEncoding: ParameterEncoding { + + // MARK: Properties + + /// Returns a default `PropertyListEncoding` instance. + public static var `default`: PropertyListEncoding { return PropertyListEncoding() } + + /// Returns a `PropertyListEncoding` instance with xml formatting and default writing options. + public static var xml: PropertyListEncoding { return PropertyListEncoding(format: .xml) } + + /// Returns a `PropertyListEncoding` instance with binary formatting and default writing options. + public static var binary: PropertyListEncoding { return PropertyListEncoding(format: .binary) } + + /// The property list serialization format. + public let format: PropertyListSerialization.PropertyListFormat + + /// The options for writing the parameters as plist data. + public let options: PropertyListSerialization.WriteOptions + + // MARK: Initialization + + /// Creates a `PropertyListEncoding` instance using the specified format and options. + /// + /// - parameter format: The property list serialization format. + /// - parameter options: The options for writing the parameters as plist data. + /// + /// - returns: The new `PropertyListEncoding` instance. + public init( + format: PropertyListSerialization.PropertyListFormat = .xml, + options: PropertyListSerialization.WriteOptions = 0) + { + self.format = format + self.options = options + } + + // MARK: Encoding + + /// 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. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters = parameters else { return urlRequest } + + do { + let data = try PropertyListSerialization.data( + fromPropertyList: parameters, + format: format, + options: options + ) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .propertyListEncodingFailed(error: error)) + } + + return urlRequest + } +} + +// MARK: - + +extension NSNumber { + fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) } +} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Request.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Request.swift new file mode 100644 index 0000000000..4f6350c5bf --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Request.swift @@ -0,0 +1,647 @@ +// +// 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 + +/// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary. +public protocol RequestAdapter { + /// Inspects and adapts the specified `URLRequest` in some manner if necessary and returns the result. + /// + /// - parameter urlRequest: The URL request to adapt. + /// + /// - throws: An `Error` if the adaptation encounters an error. + /// + /// - returns: The adapted `URLRequest`. + func adapt(_ urlRequest: URLRequest) throws -> URLRequest +} + +// MARK: - + +/// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not. +public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void + +/// A type that determines whether a request should be retried after being executed by the specified session manager +/// and encountering an error. +public protocol RequestRetrier { + /// Determines whether the `Request` should be retried by calling the `completion` closure. + /// + /// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs + /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly + /// cleaned up after. + /// + /// - parameter manager: The session manager the request was executed on. + /// - parameter request: The request that failed due to the encountered error. + /// - parameter error: The error encountered when executing the request. + /// - parameter completion: The completion closure to be executed when retry decision has been determined. + func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) +} + +// MARK: - + +protocol TaskConvertible { + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask +} + +/// A dictionary of headers to apply to a `URLRequest`. +public typealias HTTPHeaders = [String: String] + +// MARK: - + +/// Responsible for sending a request and receiving the response and associated data from the server, as well as +/// managing its underlying `URLSessionTask`. +open class Request { + + // MARK: Helper Types + + /// A closure executed when monitoring upload or download progress of a request. + public typealias ProgressHandler = (Progress) -> Void + + enum RequestTask { + case data(TaskConvertible?, URLSessionTask?) + case download(TaskConvertible?, URLSessionTask?) + case upload(TaskConvertible?, URLSessionTask?) + case stream(TaskConvertible?, URLSessionTask?) + } + + // MARK: Properties + + /// The delegate for the underlying task. + open internal(set) var delegate: TaskDelegate { + get { + taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } + return taskDelegate + } + set { + taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } + taskDelegate = newValue + } + } + + /// The underlying task. + open var task: URLSessionTask? { return delegate.task } + + /// The session belonging to the underlying task. + open let session: URLSession + + /// The request sent or to be sent to the server. + open var request: URLRequest? { return task?.originalRequest } + + /// The response received from the server, if any. + open var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse } + + /// The number of times the request has been retried. + open internal(set) var retryCount: UInt = 0 + + let originalTask: TaskConvertible? + + var startTime: CFAbsoluteTime? + var endTime: CFAbsoluteTime? + + var validations: [() -> Void] = [] + + private var taskDelegate: TaskDelegate + private var taskDelegateLock = NSLock() + + // MARK: Lifecycle + + init(session: URLSession, requestTask: RequestTask, error: Error? = nil) { + self.session = session + + switch requestTask { + case .data(let originalTask, let task): + taskDelegate = DataTaskDelegate(task: task) + self.originalTask = originalTask + case .download(let originalTask, let task): + taskDelegate = DownloadTaskDelegate(task: task) + self.originalTask = originalTask + case .upload(let originalTask, let task): + taskDelegate = UploadTaskDelegate(task: task) + self.originalTask = originalTask + case .stream(let originalTask, let task): + taskDelegate = TaskDelegate(task: task) + self.originalTask = originalTask + } + + delegate.error = error + delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() } + } + + // MARK: Authentication + + /// Associates an HTTP Basic credential with the request. + /// + /// - parameter user: The user. + /// - parameter password: The password. + /// - parameter persistence: The URL credential persistence. `.ForSession` by default. + /// + /// - returns: The request. + @discardableResult + open func authenticate( + user: String, + password: String, + persistence: URLCredential.Persistence = .forSession) + -> Self + { + let credential = URLCredential(user: user, password: password, persistence: persistence) + return authenticate(usingCredential: credential) + } + + /// Associates a specified credential with the request. + /// + /// - parameter credential: The credential. + /// + /// - returns: The request. + @discardableResult + open func authenticate(usingCredential credential: URLCredential) -> Self { + delegate.credential = credential + return self + } + + /// Returns a base64 encoded basic authentication credential as an authorization header tuple. + /// + /// - parameter user: The user. + /// - parameter password: The password. + /// + /// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise. + open static func authorizationHeader(user: String, password: String) -> (key: String, value: String)? { + guard let data = "\(user):\(password)".data(using: .utf8) else { return nil } + + let credential = data.base64EncodedString(options: []) + + return (key: "Authorization", value: "Basic \(credential)") + } + + // MARK: State + + /// Resumes the request. + open func resume() { + guard let task = task else { delegate.queue.isSuspended = false ; return } + + if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } + + task.resume() + + NotificationCenter.default.post( + name: Notification.Name.Task.DidResume, + object: self, + userInfo: [Notification.Key.Task: task] + ) + } + + /// Suspends the request. + open func suspend() { + guard let task = task else { return } + + task.suspend() + + NotificationCenter.default.post( + name: Notification.Name.Task.DidSuspend, + object: self, + userInfo: [Notification.Key.Task: task] + ) + } + + /// Cancels the request. + open func cancel() { + guard let task = task else { return } + + task.cancel() + + NotificationCenter.default.post( + name: Notification.Name.Task.DidCancel, + object: self, + userInfo: [Notification.Key.Task: task] + ) + } +} + +// 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. + open 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.joined(separator: " ") + } +} + +// MARK: - CustomDebugStringConvertible + +extension Request: CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, in the form of a cURL command. + open var debugDescription: String { + return cURLRepresentation() + } + + func cURLRepresentation() -> String { + var components = ["$ curl -v"] + + guard let request = self.request, + let url = request.url, + let host = url.host + else { + return "$ curl command could not be created" + } + + if let httpMethod = request.httpMethod, httpMethod != "GET" { + components.append("-X \(httpMethod)") + } + + if let credentialStorage = self.session.configuration.urlCredentialStorage { + let protectionSpace = URLProtectionSpace( + host: host, + port: url.port ?? 0, + protocol: url.scheme, + realm: host, + authenticationMethod: NSURLAuthenticationMethodHTTPBasic + ) + + if let credentials = credentialStorage.credentials(for: 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, + let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty + { + let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" } + components.append("-b \"\(string.substring(to: string.characters.index(before: string.endIndex)))\"") + } + } + + var headers: [AnyHashable: Any] = [:] + + if let additionalHeaders = session.configuration.httpAdditionalHeaders { + for (field, value) in additionalHeaders where field != AnyHashable("Cookie") { + headers[field] = value + } + } + + if let headerFields = request.allHTTPHeaderFields { + for (field, value) in headerFields where field != "Cookie" { + headers[field] = value + } + } + + for (field, value) in headers { + components.append("-H \"\(field): \(value)\"") + } + + if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) { + var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"") + escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"") + + components.append("-d \"\(escapedBody)\"") + } + + components.append("\"\(url.absoluteString)\"") + + return components.joined(separator: " \\\n\t") + } +} + +// MARK: - + +/// Specific type of `Request` that manages an underlying `URLSessionDataTask`. +open class DataRequest: Request { + + // MARK: Helper Types + + struct Requestable: TaskConvertible { + let urlRequest: URLRequest + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + do { + let urlRequest = try self.urlRequest.adapt(using: adapter) + return queue.sync { session.dataTask(with: urlRequest) } + } catch { + throw AdaptError(error: error) + } + } + } + + // MARK: Properties + + /// The request sent or to be sent to the server. + open override var request: URLRequest? { + if let request = super.request { return request } + if let requestable = originalTask as? Requestable { return requestable.urlRequest } + + return nil + } + + /// The progress of fetching the response data from the server for the request. + open var progress: Progress { return dataDelegate.progress } + + var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate } + + // MARK: Stream + + /// 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 server data in any `Response` object will be `nil`. + /// + /// - parameter closure: The code to be executed periodically during the lifecycle of the request. + /// + /// - returns: The request. + @discardableResult + open func stream(closure: ((Data) -> Void)? = nil) -> Self { + dataDelegate.dataStream = closure + return self + } + + // MARK: Progress + + /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. + /// + /// - parameter queue: The dispatch queue to execute the closure on. + /// - parameter closure: The code to be executed periodically as data is read from the server. + /// + /// - returns: The request. + @discardableResult + open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { + dataDelegate.progressHandler = (closure, queue) + return self + } +} + +// MARK: - + +/// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`. +open class DownloadRequest: Request { + + // MARK: Helper Types + + /// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the + /// destination URL. + public struct DownloadOptions: OptionSet { + /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol. + public let rawValue: UInt + + /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified. + public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0) + + /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified. + public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1) + + /// Creates a `DownloadFileDestinationOptions` instance with the specified raw value. + /// + /// - parameter rawValue: The raw bitmask value for the option. + /// + /// - returns: A new log level instance. + public init(rawValue: UInt) { + self.rawValue = rawValue + } + } + + /// A closure executed once a download 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 two arguments: the file URL where the temporary file should be moved and + /// the options defining how the file should be moved. + public typealias DownloadFileDestination = ( + _ temporaryURL: URL, + _ response: HTTPURLResponse) + -> (destinationURL: URL, options: DownloadOptions) + + enum Downloadable: TaskConvertible { + case request(URLRequest) + case resumeData(Data) + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + do { + let task: URLSessionTask + + switch self { + case let .request(urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.downloadTask(with: urlRequest) } + case let .resumeData(resumeData): + task = queue.sync { session.downloadTask(withResumeData: resumeData) } + } + + return task + } catch { + throw AdaptError(error: error) + } + } + } + + // MARK: Properties + + /// The request sent or to be sent to the server. + open override var request: URLRequest? { + if let request = super.request { return request } + + if let downloadable = originalTask as? Downloadable, case let .request(urlRequest) = downloadable { + return urlRequest + } + + return nil + } + + /// The resume data of the underlying download task if available after a failure. + open var resumeData: Data? { return downloadDelegate.resumeData } + + /// The progress of downloading the response data from the server for the request. + open var progress: Progress { return downloadDelegate.progress } + + var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate } + + // MARK: State + + /// Cancels the request. + open override func cancel() { + downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 } + + NotificationCenter.default.post( + name: Notification.Name.Task.DidCancel, + object: self, + userInfo: [Notification.Key.Task: task as Any] + ) + } + + // MARK: Progress + + /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. + /// + /// - parameter queue: The dispatch queue to execute the closure on. + /// - parameter closure: The code to be executed periodically as data is read from the server. + /// + /// - returns: The request. + @discardableResult + open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { + downloadDelegate.progressHandler = (closure, queue) + return self + } + + // MARK: Destination + + /// 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. + open class func suggestedDownloadDestination( + for directory: FileManager.SearchPathDirectory = .documentDirectory, + in domain: FileManager.SearchPathDomainMask = .userDomainMask) + -> DownloadFileDestination + { + return { temporaryURL, response in + let directoryURLs = FileManager.default.urls(for: directory, in: domain) + + if !directoryURLs.isEmpty { + return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), []) + } + + return (temporaryURL, []) + } + } +} + +// MARK: - + +/// Specific type of `Request` that manages an underlying `URLSessionUploadTask`. +open class UploadRequest: DataRequest { + + // MARK: Helper Types + + enum Uploadable: TaskConvertible { + case data(Data, URLRequest) + case file(URL, URLRequest) + case stream(InputStream, URLRequest) + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + do { + let task: URLSessionTask + + switch self { + case let .data(data, urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.uploadTask(with: urlRequest, from: data) } + case let .file(url, urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.uploadTask(with: urlRequest, fromFile: url) } + case let .stream(_, urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.uploadTask(withStreamedRequest: urlRequest) } + } + + return task + } catch { + throw AdaptError(error: error) + } + } + } + + // MARK: Properties + + /// The request sent or to be sent to the server. + open override var request: URLRequest? { + if let request = super.request { return request } + + guard let uploadable = originalTask as? Uploadable else { return nil } + + switch uploadable { + case .data(_, let urlRequest), .file(_, let urlRequest), .stream(_, let urlRequest): + return urlRequest + } + } + + /// The progress of uploading the payload to the server for the upload request. + open var uploadProgress: Progress { return uploadDelegate.uploadProgress } + + var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate } + + // MARK: Upload Progress + + /// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to + /// the server. + /// + /// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress + /// of data being read from the server. + /// + /// - parameter queue: The dispatch queue to execute the closure on. + /// - parameter closure: The code to be executed periodically as data is sent to the server. + /// + /// - returns: The request. + @discardableResult + open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { + uploadDelegate.uploadProgressHandler = (closure, queue) + return self + } +} + +// MARK: - + +#if !os(watchOS) + +/// Specific type of `Request` that manages an underlying `URLSessionStreamTask`. +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +open class StreamRequest: Request { + enum Streamable: TaskConvertible { + case stream(hostName: String, port: Int) + case netService(NetService) + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + let task: URLSessionTask + + switch self { + case let .stream(hostName, port): + task = queue.sync { session.streamTask(withHostName: hostName, port: port) } + case let .netService(netService): + task = queue.sync { session.streamTask(with: netService) } + } + + return task + } + } +} + +#endif diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Response.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Response.swift new file mode 100644 index 0000000000..5d3b6d2542 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Response.swift @@ -0,0 +1,465 @@ +// +// 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 data associated with an non-serialized response of a data or upload request. +public struct DefaultDataResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The data returned by the server. + public let data: Data? + + /// The error encountered while executing or validating the request. + public let error: Error? + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + var _metrics: AnyObject? + + /// Creates a `DefaultDataResponse` instance from the specified parameters. + /// + /// - Parameters: + /// - request: The URL request sent to the server. + /// - response: The server's response to the URL request. + /// - data: The data returned by the server. + /// - error: The error encountered while executing or validating the request. + /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. + /// - metrics: The task metrics containing the request / response statistics. `nil` by default. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + data: Data?, + error: Error?, + timeline: Timeline = Timeline(), + metrics: AnyObject? = nil) + { + self.request = request + self.response = response + self.data = data + self.error = error + self.timeline = timeline + } +} + +// MARK: - + +/// Used to store all data associated with a serialized response of a data or upload request. +public struct DataResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The data returned by the server. + public let data: Data? + + /// The result of response serialization. + public let result: Result + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + /// Returns the associated value of the result if it is a success, `nil` otherwise. + public var value: Value? { return result.value } + + /// Returns the associated error value if the result if it is a failure, `nil` otherwise. + public var error: Error? { return result.error } + + var _metrics: AnyObject? + + /// Creates a `DataResponse` instance with the specified parameters derived from response serialization. + /// + /// - parameter request: The URL request sent to the server. + /// - parameter response: The server's response to the URL request. + /// - parameter data: The data returned by the server. + /// - parameter result: The result of response serialization. + /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. + /// + /// - returns: The new `DataResponse` instance. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + data: Data?, + result: Result, + timeline: Timeline = Timeline()) + { + self.request = request + self.response = response + self.data = data + self.result = result + self.timeline = timeline + } +} + +// MARK: - + +extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible { + /// 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 + } + + /// The debug textual representation used when written to an output stream, which includes the URL request, the URL + /// response, the server data, the response serialization result and the timeline. + public var debugDescription: String { + var output: [String] = [] + + output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") + output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") + output.append("[Data]: \(data?.count ?? 0) bytes") + output.append("[Result]: \(result.debugDescription)") + output.append("[Timeline]: \(timeline.debugDescription)") + + return output.joined(separator: "\n") + } +} + +// MARK: - + +extension DataResponse { + /// Evaluates the specified closure when the result of this `DataResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `map` method with a closure that does not throw. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleInt = possibleData.map { $0.count } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A `DataResponse` whose result wraps the value returned by the given closure. If this instance's + /// result is a failure, returns a response wrapping the same failure. + public func map(_ transform: (Value) -> T) -> DataResponse { + var response = DataResponse( + request: request, + response: self.response, + data: data, + result: result.map(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result + /// value as a parameter. + /// + /// Use the `flatMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleObject = possibleData.flatMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A success or failure `DataResponse` depending on the result of the given closure. If this instance's + /// result is a failure, returns the same failure. + public func flatMap(_ transform: (Value) throws -> T) -> DataResponse { + var response = DataResponse( + request: request, + response: self.response, + data: data, + result: result.flatMap(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } +} + +// MARK: - + +/// Used to store all data associated with an non-serialized response of a download request. +public struct DefaultDownloadResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The temporary destination URL of the data returned from the server. + public let temporaryURL: URL? + + /// The final destination URL of the data returned from the server if it was moved. + public let destinationURL: URL? + + /// The resume data generated if the request was cancelled. + public let resumeData: Data? + + /// The error encountered while executing or validating the request. + public let error: Error? + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + var _metrics: AnyObject? + + /// Creates a `DefaultDownloadResponse` instance from the specified parameters. + /// + /// - Parameters: + /// - request: The URL request sent to the server. + /// - response: The server's response to the URL request. + /// - temporaryURL: The temporary destination URL of the data returned from the server. + /// - destinationURL: The final destination URL of the data returned from the server if it was moved. + /// - resumeData: The resume data generated if the request was cancelled. + /// - error: The error encountered while executing or validating the request. + /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. + /// - metrics: The task metrics containing the request / response statistics. `nil` by default. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + temporaryURL: URL?, + destinationURL: URL?, + resumeData: Data?, + error: Error?, + timeline: Timeline = Timeline(), + metrics: AnyObject? = nil) + { + self.request = request + self.response = response + self.temporaryURL = temporaryURL + self.destinationURL = destinationURL + self.resumeData = resumeData + self.error = error + self.timeline = timeline + } +} + +// MARK: - + +/// Used to store all data associated with a serialized response of a download request. +public struct DownloadResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The temporary destination URL of the data returned from the server. + public let temporaryURL: URL? + + /// The final destination URL of the data returned from the server if it was moved. + public let destinationURL: URL? + + /// The resume data generated if the request was cancelled. + public let resumeData: Data? + + /// The result of response serialization. + public let result: Result + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + /// Returns the associated value of the result if it is a success, `nil` otherwise. + public var value: Value? { return result.value } + + /// Returns the associated error value if the result if it is a failure, `nil` otherwise. + public var error: Error? { return result.error } + + var _metrics: AnyObject? + + /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization. + /// + /// - parameter request: The URL request sent to the server. + /// - parameter response: The server's response to the URL request. + /// - parameter temporaryURL: The temporary destination URL of the data returned from the server. + /// - parameter destinationURL: The final destination URL of the data returned from the server if it was moved. + /// - parameter resumeData: The resume data generated if the request was cancelled. + /// - parameter result: The result of response serialization. + /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. + /// + /// - returns: The new `DownloadResponse` instance. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + temporaryURL: URL?, + destinationURL: URL?, + resumeData: Data?, + result: Result, + timeline: Timeline = Timeline()) + { + self.request = request + self.response = response + self.temporaryURL = temporaryURL + self.destinationURL = destinationURL + self.resumeData = resumeData + self.result = result + self.timeline = timeline + } +} + +// MARK: - + +extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible { + /// 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 + } + + /// The debug textual representation used when written to an output stream, which includes the URL request, the URL + /// response, the temporary and destination URLs, the resume data, the response serialization result and the + /// timeline. + public var debugDescription: String { + var output: [String] = [] + + output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") + output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") + output.append("[TemporaryURL]: \(temporaryURL?.path ?? "nil")") + output.append("[DestinationURL]: \(destinationURL?.path ?? "nil")") + output.append("[ResumeData]: \(resumeData?.count ?? 0) bytes") + output.append("[Result]: \(result.debugDescription)") + output.append("[Timeline]: \(timeline.debugDescription)") + + return output.joined(separator: "\n") + } +} + +// MARK: - + +extension DownloadResponse { + /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `map` method with a closure that does not throw. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleInt = possibleData.map { $0.count } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's + /// result is a failure, returns a response wrapping the same failure. + public func map(_ transform: (Value) -> T) -> DownloadResponse { + var response = DownloadResponse( + request: request, + response: self.response, + temporaryURL: temporaryURL, + destinationURL: destinationURL, + resumeData: resumeData, + result: result.map(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `flatMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleObject = possibleData.flatMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this + /// instance's result is a failure, returns the same failure. + public func flatMap(_ transform: (Value) throws -> T) -> DownloadResponse { + var response = DownloadResponse( + request: request, + response: self.response, + temporaryURL: temporaryURL, + destinationURL: destinationURL, + resumeData: resumeData, + result: result.flatMap(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } +} + +// MARK: - + +protocol Response { + /// The task metrics containing the request / response statistics. + var _metrics: AnyObject? { get set } + mutating func add(_ metrics: AnyObject?) +} + +extension Response { + mutating func add(_ metrics: AnyObject?) { + #if !os(watchOS) + guard #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) else { return } + guard let metrics = metrics as? URLSessionTaskMetrics else { return } + + _metrics = metrics + #endif + } +} + +// MARK: - + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DefaultDataResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DataResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DefaultDownloadResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DownloadResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift new file mode 100644 index 0000000000..1a59da550a --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift @@ -0,0 +1,715 @@ +// +// 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 + +/// The type in which all data response serializers must conform to in order to serialize a response. +public protocol DataResponseSerializerProtocol { + /// The type of serialized object to be created by this `DataResponseSerializerType`. + associatedtype SerializedObject + + /// A closure used by response handlers that takes a request, response, data and error and returns a result. + var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result { get } +} + +// MARK: - + +/// A generic `DataResponseSerializerType` used to serialize a request, response, and data into a serialized object. +public struct DataResponseSerializer: DataResponseSerializerProtocol { + /// The type of serialized object to be created by this `DataResponseSerializer`. + public typealias SerializedObject = Value + + /// A closure used by response handlers that takes a request, response, data and error and returns a result. + public var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result + + /// 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: @escaping (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result) { + self.serializeResponse = serializeResponse + } +} + +// MARK: - + +/// The type in which all download response serializers must conform to in order to serialize a response. +public protocol DownloadResponseSerializerProtocol { + /// The type of serialized object to be created by this `DownloadResponseSerializerType`. + associatedtype SerializedObject + + /// A closure used by response handlers that takes a request, response, url and error and returns a result. + var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result { get } +} + +// MARK: - + +/// A generic `DownloadResponseSerializerType` used to serialize a request, response, and data into a serialized object. +public struct DownloadResponseSerializer: DownloadResponseSerializerProtocol { + /// The type of serialized object to be created by this `DownloadResponseSerializer`. + public typealias SerializedObject = Value + + /// A closure used by response handlers that takes a request, response, url and error and returns a result. + public var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result + + /// 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: @escaping (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result) { + self.serializeResponse = serializeResponse + } +} + +// MARK: - Timeline + +extension Request { + var timeline: Timeline { + let requestStartTime = self.startTime ?? CFAbsoluteTimeGetCurrent() + let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent() + let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime + + return Timeline( + requestStartTime: requestStartTime, + initialResponseTime: initialResponseTime, + requestCompletedTime: requestCompletedTime, + serializationCompletedTime: CFAbsoluteTimeGetCurrent() + ) + } +} + +// MARK: - Default + +extension DataRequest { + /// 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. + @discardableResult + public func response(queue: DispatchQueue? = nil, completionHandler: @escaping (DefaultDataResponse) -> Void) -> Self { + delegate.queue.addOperation { + (queue ?? DispatchQueue.main).async { + var dataResponse = DefaultDataResponse( + request: self.request, + response: self.response, + data: self.delegate.data, + error: self.delegate.error, + timeline: self.timeline + ) + + dataResponse.add(self.delegate.metrics) + + completionHandler(dataResponse) + } + } + + 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. + @discardableResult + public func response( + queue: DispatchQueue? = nil, + responseSerializer: T, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + delegate.queue.addOperation { + let result = responseSerializer.serializeResponse( + self.request, + self.response, + self.delegate.data, + self.delegate.error + ) + + var dataResponse = DataResponse( + request: self.request, + response: self.response, + data: self.delegate.data, + result: result, + timeline: self.timeline + ) + + dataResponse.add(self.delegate.metrics) + + (queue ?? DispatchQueue.main).async { completionHandler(dataResponse) } + } + + return self + } +} + +extension DownloadRequest { + /// 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. + @discardableResult + public func response( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DefaultDownloadResponse) -> Void) + -> Self + { + delegate.queue.addOperation { + (queue ?? DispatchQueue.main).async { + var downloadResponse = DefaultDownloadResponse( + request: self.request, + response: self.response, + temporaryURL: self.downloadDelegate.temporaryURL, + destinationURL: self.downloadDelegate.destinationURL, + resumeData: self.downloadDelegate.resumeData, + error: self.downloadDelegate.error, + timeline: self.timeline + ) + + downloadResponse.add(self.delegate.metrics) + + completionHandler(downloadResponse) + } + } + + 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 contained in the destination url. + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func response( + queue: DispatchQueue? = nil, + responseSerializer: T, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + delegate.queue.addOperation { + let result = responseSerializer.serializeResponse( + self.request, + self.response, + self.downloadDelegate.fileURL, + self.downloadDelegate.error + ) + + var downloadResponse = DownloadResponse( + request: self.request, + response: self.response, + temporaryURL: self.downloadDelegate.temporaryURL, + destinationURL: self.downloadDelegate.destinationURL, + resumeData: self.downloadDelegate.resumeData, + result: result, + timeline: self.timeline + ) + + downloadResponse.add(self.delegate.metrics) + + (queue ?? DispatchQueue.main).async { completionHandler(downloadResponse) } + } + + return self + } +} + +// MARK: - Data + +extension Request { + /// Returns a result data type that contains the response data as-is. + /// + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponseData(response: HTTPURLResponse?, data: Data?, error: Error?) -> Result { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(Data()) } + + guard let validData = data else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) + } + + return .success(validData) + } +} + +extension DataRequest { + /// Creates a response serializer that returns the associated data as-is. + /// + /// - returns: A data response serializer. + public static func dataResponseSerializer() -> DataResponseSerializer { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponseData(response: response, data: data, error: error) + } + } + + /// 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. + @discardableResult + public func responseData( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.dataResponseSerializer(), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns the associated data as-is. + /// + /// - returns: A data response serializer. + public static func dataResponseSerializer() -> DownloadResponseSerializer { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponseData(response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// 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. + @discardableResult + public func responseData( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.dataResponseSerializer(), + completionHandler: completionHandler + ) + } +} + +// MARK: - String + +extension Request { + /// Returns a result string type 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. + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponseString( + encoding: String.Encoding?, + response: HTTPURLResponse?, + data: Data?, + error: Error?) + -> Result + { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success("") } + + guard let validData = data else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) + } + + var convertedEncoding = encoding + + if let encodingName = response?.textEncodingName as CFString!, convertedEncoding == nil { + convertedEncoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding( + CFStringConvertIANACharSetNameToEncoding(encodingName)) + ) + } + + let actualEncoding = convertedEncoding ?? String.Encoding.isoLatin1 + + if let string = String(data: validData, encoding: actualEncoding) { + return .success(string) + } else { + return .failure(AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding))) + } + } +} + +extension DataRequest { + /// Creates a response serializer that returns a result string type initialized from the response data with + /// the specified string encoding. + /// + /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server + /// response, falling back to the default HTTP default character set, ISO-8859-1. + /// + /// - returns: A string response serializer. + public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DataResponseSerializer { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: 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. + @discardableResult + public func responseString( + queue: DispatchQueue? = nil, + encoding: String.Encoding? = nil, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.stringResponseSerializer(encoding: encoding), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns a result string type initialized from the response data with + /// the specified string encoding. + /// + /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server + /// response, falling back to the default HTTP default character set, ISO-8859-1. + /// + /// - returns: A string response serializer. + public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DownloadResponseSerializer { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// 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. + @discardableResult + public func responseString( + queue: DispatchQueue? = nil, + encoding: String.Encoding? = nil, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.stringResponseSerializer(encoding: encoding), + completionHandler: completionHandler + ) + } +} + +// MARK: - JSON + +extension Request { + /// Returns a JSON object contained in a result type constructed from the response data using `JSONSerialization` + /// with the specified reading options. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponseJSON( + options: JSONSerialization.ReadingOptions, + response: HTTPURLResponse?, + data: Data?, + error: Error?) + -> Result + { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } + + guard let validData = data, validData.count > 0 else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) + } + + do { + let json = try JSONSerialization.jsonObject(with: validData, options: options) + return .success(json) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error))) + } + } +} + +extension DataRequest { + /// Creates a response serializer that returns a JSON object result type constructed from the response data using + /// `JSONSerialization` with the specified reading options. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// + /// - returns: A JSON object response serializer. + public static func jsonResponseSerializer( + options: JSONSerialization.ReadingOptions = .allowFragments) + -> DataResponseSerializer + { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseJSON( + queue: DispatchQueue? = nil, + options: JSONSerialization.ReadingOptions = .allowFragments, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.jsonResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns a JSON object result type constructed from the response data using + /// `JSONSerialization` with the specified reading options. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// + /// - returns: A JSON object response serializer. + public static func jsonResponseSerializer( + options: JSONSerialization.ReadingOptions = .allowFragments) + -> DownloadResponseSerializer + { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseJSON( + queue: DispatchQueue? = nil, + options: JSONSerialization.ReadingOptions = .allowFragments, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.jsonResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +// MARK: - Property List + +extension Request { + /// Returns a plist object contained in a result type constructed from the response data using + /// `PropertyListSerialization` with the specified reading options. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponsePropertyList( + options: PropertyListSerialization.ReadOptions, + response: HTTPURLResponse?, + data: Data?, + error: Error?) + -> Result + { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } + + guard let validData = data, validData.count > 0 else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) + } + + do { + let plist = try PropertyListSerialization.propertyList(from: validData, options: options, format: nil) + return .success(plist) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .propertyListSerializationFailed(error: error))) + } + } +} + +extension DataRequest { + /// Creates a response serializer that returns an object constructed from the response data using + /// `PropertyListSerialization` with the specified reading options. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// + /// - returns: A property list object response serializer. + public static func propertyListResponseSerializer( + options: PropertyListSerialization.ReadOptions = []) + -> DataResponseSerializer + { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responsePropertyList( + queue: DispatchQueue? = nil, + options: PropertyListSerialization.ReadOptions = [], + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.propertyListResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns an object constructed from the response data using + /// `PropertyListSerialization` with the specified reading options. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// + /// - returns: A property list object response serializer. + public static func propertyListResponseSerializer( + options: PropertyListSerialization.ReadOptions = []) + -> DownloadResponseSerializer + { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responsePropertyList( + queue: DispatchQueue? = nil, + options: PropertyListSerialization.ReadOptions = [], + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.propertyListResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +/// A set of HTTP response status code that do not contain response data. +private let emptyDataStatusCodes: Set = [204, 205] diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Result.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Result.swift new file mode 100644 index 0000000000..bf7e70255b --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Result.swift @@ -0,0 +1,300 @@ +// +// 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 { + 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)" + } + } +} + +// MARK: - Functional APIs + +extension Result { + /// Creates a `Result` instance from the result of a closure. + /// + /// A failure result is created when the closure throws, and a success result is created when the closure + /// succeeds without throwing an error. + /// + /// func someString() throws -> String { ... } + /// + /// let result = Result(value: { + /// return try someString() + /// }) + /// + /// // The type of result is Result + /// + /// The trailing closure syntax is also supported: + /// + /// let result = Result { try someString() } + /// + /// - parameter value: The closure to execute and create the result for. + public init(value: () throws -> Value) { + do { + self = try .success(value()) + } catch { + self = .failure(error) + } + } + + /// Returns the success value, or throws the failure error. + /// + /// let possibleString: Result = .success("success") + /// try print(possibleString.unwrap()) + /// // Prints "success" + /// + /// let noString: Result = .failure(error) + /// try print(noString.unwrap()) + /// // Throws error + public func unwrap() throws -> Value { + switch self { + case .success(let value): + return value + case .failure(let error): + throw error + } + } + + /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. + /// + /// Use the `map` method with a closure that does not throw. For example: + /// + /// let possibleData: Result = .success(Data()) + /// let possibleInt = possibleData.map { $0.count } + /// try print(possibleInt.unwrap()) + /// // Prints "0" + /// + /// let noData: Result = .failure(error) + /// let noInt = noData.map { $0.count } + /// try print(noInt.unwrap()) + /// // Throws error + /// + /// - parameter transform: A closure that takes the success value of the `Result` instance. + /// + /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the + /// same failure. + public func map(_ transform: (Value) -> T) -> Result { + switch self { + case .success(let value): + return .success(transform(value)) + case .failure(let error): + return .failure(error) + } + } + + /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. + /// + /// Use the `flatMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: Result = .success(Data(...)) + /// let possibleObject = possibleData.flatMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance. + /// + /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the + /// same failure. + public func flatMap(_ transform: (Value) throws -> T) -> Result { + switch self { + case .success(let value): + do { + return try .success(transform(value)) + } catch { + return .failure(error) + } + case .failure(let error): + return .failure(error) + } + } + + /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `mapError` function with a closure that does not throw. For example: + /// + /// let possibleData: Result = .failure(someError) + /// let withMyError: Result = possibleData.mapError { MyError.error($0) } + /// + /// - Parameter transform: A closure that takes the error of the instance. + /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns + /// the same instance. + public func mapError(_ transform: (Error) -> T) -> Result { + switch self { + case .failure(let error): + return .failure(transform(error)) + case .success: + return self + } + } + + /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `flatMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: Result = .success(Data(...)) + /// let possibleObject = possibleData.flatMapError { + /// try someFailableFunction(taking: $0) + /// } + /// + /// - Parameter transform: A throwing closure that takes the error of the instance. + /// + /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns + /// the same instance. + public func flatMapError(_ transform: (Error) throws -> T) -> Result { + switch self { + case .failure(let error): + do { + return try .failure(transform(error)) + } catch { + return .failure(error) + } + case .success: + return self + } + } + + /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. + /// + /// Use the `withValue` function to evaluate the passed closure without modifying the `Result` instance. + /// + /// - Parameter closure: A closure that takes the success value of this instance. + /// - Returns: This `Result` instance, unmodified. + @discardableResult + public func withValue(_ closure: (Value) -> Void) -> Result { + if case let .success(value) = self { closure(value) } + + return self + } + + /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `withError` function to evaluate the passed closure without modifying the `Result` instance. + /// + /// - Parameter closure: A closure that takes the success value of this instance. + /// - Returns: This `Result` instance, unmodified. + @discardableResult + public func withError(_ closure: (Error) -> Void) -> Result { + if case let .failure(error) = self { closure(error) } + + return self + } + + /// Evaluates the specified closure when the `Result` is a success. + /// + /// Use the `ifSuccess` function to evaluate the passed closure without modifying the `Result` instance. + /// + /// - Parameter closure: A `Void` closure. + /// - Returns: This `Result` instance, unmodified. + @discardableResult + public func ifSuccess(_ closure: () -> Void) -> Result { + if isSuccess { closure() } + + return self + } + + /// Evaluates the specified closure when the `Result` is a failure. + /// + /// Use the `ifFailure` function to evaluate the passed closure without modifying the `Result` instance. + /// + /// - Parameter closure: A `Void` closure. + /// - Returns: This `Result` instance, unmodified. + @discardableResult + public func ifFailure(_ closure: () -> Void) -> Result { + if isFailure { closure() } + + return self + } +} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift new file mode 100644 index 0000000000..9c0e7c8d50 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift @@ -0,0 +1,307 @@ +// +// 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. +open class ServerTrustPolicyManager { + /// The dictionary of policies mapped to a particular host. + open 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. + open func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? { + return policies[host] + } +} + +// MARK: - + +extension URLSession { + private struct AssociatedKeys { + static var managerKey = "URLSession.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. +/// +/// - performRevokedEvaluation: Uses the default and revoked server trust evaluations allowing you to control whether to +/// validate the host provided by the challenge as well as specify the revocation flags for +/// testing for revoked certificates. Apple platforms did not start testing for revoked +/// certificates automatically until iOS 10.1, macOS 10.12 and tvOS 10.1 which is +/// demonstrated in our TLS tests. 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 performRevokedEvaluation(validateHost: Bool, revocationFlags: CFOptionFlags) + 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 certificates(in bundle: Bundle = Bundle.main) -> [SecCertificate] { + var certificates: [SecCertificate] = [] + + let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in + bundle.paths(forResourcesOfType: fileExtension, inDirectory: nil) + }.joined()) + + for path in paths { + if + let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData, + let 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 publicKeys(in bundle: Bundle = Bundle.main) -> [SecKey] { + var publicKeys: [SecKey] = [] + + for certificate in certificates(in: bundle) { + if let publicKey = publicKey(for: 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 evaluate(_ serverTrust: SecTrust, forHost 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 .performRevokedEvaluation(validateHost, revocationFlags): + let defaultPolicy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + let revokedPolicy = SecPolicyCreateRevocation(revocationFlags) + SecTrustSetPolicies(serverTrust, [defaultPolicy, revokedPolicy] as CFTypeRef) + + 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 as CFArray) + SecTrustSetAnchorCertificatesOnly(serverTrust, true) + + serverTrustIsValid = trustIsValid(serverTrust) + } else { + let serverCertificatesDataArray = certificateData(for: serverTrust) + let pinnedCertificatesDataArray = certificateData(for: pinnedCertificates) + + outerLoop: for serverCertificateData in serverCertificatesDataArray { + for pinnedCertificateData in pinnedCertificatesDataArray { + if serverCertificateData == 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.publicKeys(for: 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, host) + } + + return serverTrustIsValid + } + + // MARK: - Private - Trust Validation + + private func trustIsValid(_ trust: SecTrust) -> Bool { + var isValid = false + + var result = SecTrustResultType.invalid + let status = SecTrustEvaluate(trust, &result) + + if status == errSecSuccess { + let unspecified = SecTrustResultType.unspecified + let proceed = SecTrustResultType.proceed + + + isValid = result == unspecified || result == proceed + } + + return isValid + } + + // MARK: - Private - Certificate Data + + private func certificateData(for trust: SecTrust) -> [Data] { + var certificates: [SecCertificate] = [] + + for index in 0.. [Data] { + return certificates.map { SecCertificateCopyData($0) as Data } + } + + // MARK: - Private - Public Key Extraction + + private static func publicKeys(for trust: SecTrust) -> [SecKey] { + var publicKeys: [SecKey] = [] + + for index in 0.. SecKey? { + var publicKey: SecKey? + + let policy = SecPolicyCreateBasicX509() + var trust: SecTrust? + let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust) + + if let trust = trust, trustCreationStatus == errSecSuccess { + publicKey = SecTrustCopyPublicKey(trust) + } + + return publicKey + } +} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/SessionDelegate.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/SessionDelegate.swift new file mode 100644 index 0000000000..8edb492b69 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/SessionDelegate.swift @@ -0,0 +1,719 @@ +// +// SessionDelegate.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 handling all delegate callbacks for the underlying session. +open class SessionDelegate: NSObject { + + // MARK: URLSessionDelegate Overrides + + /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didBecomeInvalidWithError:)`. + open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)? + + /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`. + open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + + /// Overrides all behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)` and requires the caller to call the `completionHandler`. + open var sessionDidReceiveChallengeWithCompletion: ((URLSession, URLAuthenticationChallenge, @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`. + open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)? + + // MARK: URLSessionTaskDelegate Overrides + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`. + open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? + + /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` and + /// requires the caller to call the `completionHandler`. + open var taskWillPerformHTTPRedirectionWithCompletion: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest, @escaping (URLRequest?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)`. + open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + + /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)` and + /// requires the caller to call the `completionHandler`. + open var taskDidReceiveChallengeWithCompletion: ((URLSession, URLSessionTask, URLAuthenticationChallenge, @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)`. + open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? + + /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)` and + /// requires the caller to call the `completionHandler`. + open var taskNeedNewBodyStreamWithCompletion: ((URLSession, URLSessionTask, @escaping (InputStream?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)`. + open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didCompleteWithError:)`. + open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)? + + // MARK: URLSessionDataDelegate Overrides + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)`. + open var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? + + /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)` and + /// requires caller to call the `completionHandler`. + open var dataTaskDidReceiveResponseWithCompletion: ((URLSession, URLSessionDataTask, URLResponse, @escaping (URLSession.ResponseDisposition) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didBecome:)`. + open var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:)`. + open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`. + open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? + + /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)` and + /// requires caller to call the `completionHandler`. + open var dataTaskWillCacheResponseWithCompletion: ((URLSession, URLSessionDataTask, CachedURLResponse, @escaping (CachedURLResponse?) -> Void) -> Void)? + + // MARK: URLSessionDownloadDelegate Overrides + + /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didFinishDownloadingTo:)`. + open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)? + + /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)`. + open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + + /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)`. + open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? + + // MARK: URLSessionStreamDelegate Overrides + +#if !os(watchOS) + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:readClosedFor:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskReadClosed: ((URLSession, URLSessionStreamTask) -> Void)? { + get { + return _streamTaskReadClosed as? (URLSession, URLSessionStreamTask) -> Void + } + set { + _streamTaskReadClosed = newValue + } + } + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:writeClosedFor:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskWriteClosed: ((URLSession, URLSessionStreamTask) -> Void)? { + get { + return _streamTaskWriteClosed as? (URLSession, URLSessionStreamTask) -> Void + } + set { + _streamTaskWriteClosed = newValue + } + } + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:betterRouteDiscoveredFor:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskBetterRouteDiscovered: ((URLSession, URLSessionStreamTask) -> Void)? { + get { + return _streamTaskBetterRouteDiscovered as? (URLSession, URLSessionStreamTask) -> Void + } + set { + _streamTaskBetterRouteDiscovered = newValue + } + } + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:streamTask:didBecome:outputStream:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskDidBecomeInputAndOutputStreams: ((URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void)? { + get { + return _streamTaskDidBecomeInputStream as? (URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void + } + set { + _streamTaskDidBecomeInputStream = newValue + } + } + + var _streamTaskReadClosed: Any? + var _streamTaskWriteClosed: Any? + var _streamTaskBetterRouteDiscovered: Any? + var _streamTaskDidBecomeInputStream: Any? + +#endif + + // MARK: Properties + + var retrier: RequestRetrier? + weak var sessionManager: SessionManager? + + private var requests: [Int: Request] = [:] + private let lock = NSLock() + + /// Access the task delegate for the specified task in a thread-safe manner. + open subscript(task: URLSessionTask) -> Request? { + get { + lock.lock() ; defer { lock.unlock() } + return requests[task.taskIdentifier] + } + set { + lock.lock() ; defer { lock.unlock() } + requests[task.taskIdentifier] = newValue + } + } + + // MARK: Lifecycle + + /// Initializes the `SessionDelegate` instance. + /// + /// - returns: The new `SessionDelegate` instance. + public override init() { + super.init() + } + + // MARK: NSObject Overrides + + /// Returns a `Bool` indicating whether the `SessionDelegate` implements or inherits a method that can respond + /// to a specified message. + /// + /// - parameter selector: A selector that identifies a message. + /// + /// - returns: `true` if the receiver implements or inherits a method that can respond to selector, otherwise `false`. + open override func responds(to selector: Selector) -> Bool { + #if !os(macOS) + if selector == #selector(URLSessionDelegate.urlSessionDidFinishEvents(forBackgroundURLSession:)) { + return sessionDidFinishEventsForBackgroundURLSession != nil + } + #endif + + #if !os(watchOS) + if #available(iOS 9.0, macOS 10.11, tvOS 9.0, *) { + switch selector { + case #selector(URLSessionStreamDelegate.urlSession(_:readClosedFor:)): + return streamTaskReadClosed != nil + case #selector(URLSessionStreamDelegate.urlSession(_:writeClosedFor:)): + return streamTaskWriteClosed != nil + case #selector(URLSessionStreamDelegate.urlSession(_:betterRouteDiscoveredFor:)): + return streamTaskBetterRouteDiscovered != nil + case #selector(URLSessionStreamDelegate.urlSession(_:streamTask:didBecome:outputStream:)): + return streamTaskDidBecomeInputAndOutputStreams != nil + default: + break + } + } + #endif + + switch selector { + case #selector(URLSessionDelegate.urlSession(_:didBecomeInvalidWithError:)): + return sessionDidBecomeInvalidWithError != nil + case #selector(URLSessionDelegate.urlSession(_:didReceive:completionHandler:)): + return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil) + case #selector(URLSessionTaskDelegate.urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)): + return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil) + case #selector(URLSessionDataDelegate.urlSession(_:dataTask:didReceive:completionHandler:)): + return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil) + default: + return type(of: self).instancesRespond(to: selector) + } + } +} + +// MARK: - URLSessionDelegate + +extension SessionDelegate: URLSessionDelegate { + /// 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. + open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { + 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. + open func urlSession( + _ session: URLSession, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + guard sessionDidReceiveChallengeWithCompletion == nil else { + sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler) + return + } + + var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling + var credential: URLCredential? + + 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?.serverTrustPolicy(forHost: host), + let serverTrust = challenge.protectionSpace.serverTrust + { + if serverTrustPolicy.evaluate(serverTrust, forHost: host) { + disposition = .useCredential + credential = URLCredential(trust: serverTrust) + } else { + disposition = .cancelAuthenticationChallenge + } + } + } + + completionHandler(disposition, credential) + } + +#if !os(macOS) + + /// Tells the delegate that all messages enqueued for a session have been delivered. + /// + /// - parameter session: The session that no longer has any outstanding requests. + open func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { + sessionDidFinishEventsForBackgroundURLSession?(session) + } + +#endif +} + +// MARK: - URLSessionTaskDelegate + +extension SessionDelegate: URLSessionTaskDelegate { + /// 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. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) + { + guard taskWillPerformHTTPRedirectionWithCompletion == nil else { + taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler) + return + } + + var redirectRequest: URLRequest? = 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. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + guard taskDidReceiveChallengeWithCompletion == nil else { + taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler) + return + } + + if let taskDidReceiveChallenge = taskDidReceiveChallenge { + let result = taskDidReceiveChallenge(session, task, challenge) + completionHandler(result.0, result.1) + } else if let delegate = self[task]?.delegate { + delegate.urlSession( + session, + task: task, + didReceive: challenge, + completionHandler: completionHandler + ) + } else { + urlSession(session, didReceive: 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. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) + { + guard taskNeedNewBodyStreamWithCompletion == nil else { + taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler) + return + } + + if let taskNeedNewBodyStream = taskNeedNewBodyStream { + completionHandler(taskNeedNewBodyStream(session, task)) + } else if let delegate = self[task]?.delegate { + 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. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) + { + if let taskDidSendBodyData = taskDidSendBodyData { + taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) + } else if let delegate = self[task]?.delegate as? UploadTaskDelegate { + delegate.URLSession( + session, + task: task, + didSendBodyData: bytesSent, + totalBytesSent: totalBytesSent, + totalBytesExpectedToSend: totalBytesExpectedToSend + ) + } + } + +#if !os(watchOS) + + /// Tells the delegate that the session finished collecting metrics for the task. + /// + /// - parameter session: The session collecting the metrics. + /// - parameter task: The task whose metrics have been collected. + /// - parameter metrics: The collected metrics. + @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) + @objc(URLSession:task:didFinishCollectingMetrics:) + open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { + self[task]?.delegate.metrics = metrics + } + +#endif + + /// 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. + open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + /// Executed after it is determined that the request is not going to be retried + let completeTask: (URLSession, URLSessionTask, Error?) -> Void = { [weak self] session, task, error in + guard let strongSelf = self else { return } + + strongSelf.taskDidComplete?(session, task, error) + + strongSelf[task]?.delegate.urlSession(session, task: task, didCompleteWithError: error) + + NotificationCenter.default.post( + name: Notification.Name.Task.DidComplete, + object: strongSelf, + userInfo: [Notification.Key.Task: task] + ) + + strongSelf[task] = nil + } + + guard let request = self[task], let sessionManager = sessionManager else { + completeTask(session, task, error) + return + } + + // Run all validations on the request before checking if an error occurred + request.validations.forEach { $0() } + + // Determine whether an error has occurred + var error: Error? = error + + if request.delegate.error != nil { + error = request.delegate.error + } + + /// If an error occurred and the retrier is set, asynchronously ask the retrier if the request + /// should be retried. Otherwise, complete the task by notifying the task delegate. + if let retrier = retrier, let error = error { + retrier.should(sessionManager, retry: request, with: error) { [weak self] shouldRetry, timeDelay in + guard shouldRetry else { completeTask(session, task, error) ; return } + + DispatchQueue.utility.after(timeDelay) { [weak self] in + guard let strongSelf = self else { return } + + let retrySucceeded = strongSelf.sessionManager?.retry(request) ?? false + + if retrySucceeded, let task = request.task { + strongSelf[task] = request + return + } else { + completeTask(session, task, error) + } + } + } + } else { + completeTask(session, task, error) + } + } +} + +// MARK: - URLSessionDataDelegate + +extension SessionDelegate: URLSessionDataDelegate { + /// 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. + open func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didReceive response: URLResponse, + completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) + { + guard dataTaskDidReceiveResponseWithCompletion == nil else { + dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler) + return + } + + var disposition: URLSession.ResponseDisposition = .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. + open func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didBecome downloadTask: URLSessionDownloadTask) + { + if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask { + dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask) + } else { + self[downloadTask]?.delegate = DownloadTaskDelegate(task: downloadTask) + } + } + + /// 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. + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + if let dataTaskDidReceiveData = dataTaskDidReceiveData { + dataTaskDidReceiveData(session, dataTask, data) + } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { + delegate.urlSession(session, dataTask: dataTask, didReceive: 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. + open func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse, + completionHandler: @escaping (CachedURLResponse?) -> Void) + { + guard dataTaskWillCacheResponseWithCompletion == nil else { + dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler) + return + } + + if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { + completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) + } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { + delegate.urlSession( + session, + dataTask: dataTask, + willCacheResponse: proposedResponse, + completionHandler: completionHandler + ) + } else { + completionHandler(proposedResponse) + } + } +} + +// MARK: - URLSessionDownloadDelegate + +extension SessionDelegate: URLSessionDownloadDelegate { + /// 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. + open func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didFinishDownloadingTo location: URL) + { + if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { + downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) + } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { + delegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: 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`. + open func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) + { + if let downloadTaskDidWriteData = downloadTaskDidWriteData { + downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) + } else if let delegate = self[downloadTask]?.delegate as? 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. + open func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) + { + if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { + downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) + } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { + delegate.urlSession( + session, + downloadTask: downloadTask, + didResumeAtOffset: fileOffset, + expectedTotalBytes: expectedTotalBytes + ) + } + } +} + +// MARK: - URLSessionStreamDelegate + +#if !os(watchOS) + +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +extension SessionDelegate: URLSessionStreamDelegate { + /// Tells the delegate that the read side of the connection has been closed. + /// + /// - parameter session: The session. + /// - parameter streamTask: The stream task. + open func urlSession(_ session: URLSession, readClosedFor streamTask: URLSessionStreamTask) { + 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. + open func urlSession(_ session: URLSession, writeClosedFor streamTask: URLSessionStreamTask) { + 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. + open func urlSession(_ session: URLSession, betterRouteDiscoveredFor streamTask: URLSessionStreamTask) { + 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. + open func urlSession( + _ session: URLSession, + streamTask: URLSessionStreamTask, + didBecome inputStream: InputStream, + outputStream: OutputStream) + { + streamTaskDidBecomeInputAndOutputStreams?(session, streamTask, inputStream, outputStream) + } +} + +#endif diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/SessionManager.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/SessionManager.swift new file mode 100644 index 0000000000..493ce29cb4 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/SessionManager.swift @@ -0,0 +1,899 @@ +// +// SessionManager.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`. +open class SessionManager { + + // MARK: - Helper Types + + /// 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 `UploadRequest` 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: UploadRequest, streamingFromDisk: Bool, streamFileURL: URL?) + case failure(Error) + } + + // MARK: - Properties + + /// A default instance of `SessionManager`, used by top-level Alamofire request methods, and suitable for use + /// directly for any ad hoc requests. + open static let `default`: SessionManager = { + let configuration = URLSessionConfiguration.default + configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders + + return SessionManager(configuration: configuration) + }() + + /// Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. + open static let defaultHTTPHeaders: HTTPHeaders = { + // 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 + #if swift(>=4.0) + let acceptLanguage = Locale.preferredLanguages.prefix(6).enumerated().map { enumeratedLanguage in + let (index, languageCode) = enumeratedLanguage + let quality = 1.0 - (Double(index) * 0.1) + return "\(languageCode);q=\(quality)" + }.joined(separator: ", ") + #else + let acceptLanguage = Locale.preferredLanguages.prefix(6).enumerated().map { index, languageCode in + let quality = 1.0 - (Double(index) * 0.1) + return "\(languageCode);q=\(quality)" + }.joined(separator: ", ") + #endif + + // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 + // Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0` + let userAgent: String = { + if let info = Bundle.main.infoDictionary { + let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" + let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" + let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown" + let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown" + + let osNameVersion: String = { + let version = ProcessInfo.processInfo.operatingSystemVersion + let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" + + let osName: String = { + #if os(iOS) + return "iOS" + #elseif os(watchOS) + return "watchOS" + #elseif os(tvOS) + return "tvOS" + #elseif os(macOS) + return "OS X" + #elseif os(Linux) + return "Linux" + #else + return "Unknown" + #endif + }() + + return "\(osName) \(versionString)" + }() + + let alamofireVersion: String = { + guard + let afInfo = Bundle(for: SessionManager.self).infoDictionary, + let build = afInfo["CFBundleShortVersionString"] + else { return "Unknown" } + + return "Alamofire/\(build)" + }() + + return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)" + } + + return "Alamofire" + }() + + return [ + "Accept-Encoding": acceptEncoding, + "Accept-Language": acceptLanguage, + "User-Agent": userAgent + ] + }() + + /// Default memory threshold used when encoding `MultipartFormData` in bytes. + open static let multipartFormDataEncodingMemoryThreshold: UInt64 = 10_000_000 + + /// The underlying session. + open let session: URLSession + + /// The session delegate handling all the task and session delegate callbacks. + open let delegate: SessionDelegate + + /// Whether to start requests immediately after being constructed. `true` by default. + open var startRequestsImmediately: Bool = true + + /// The request adapter called each time a new request is created. + open var adapter: RequestAdapter? + + /// The request retrier called each time a request encounters an error to determine whether to retry the request. + open var retrier: RequestRetrier? { + get { return delegate.retrier } + set { delegate.retrier = newValue } + } + + /// 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. + open var backgroundCompletionHandler: (() -> Void)? + + let queue = DispatchQueue(label: "org.alamofire.session-manager." + UUID().uuidString) + + // MARK: - Lifecycle + + /// Creates an instance with the specified `configuration`, `delegate` and `serverTrustPolicyManager`. + /// + /// - parameter configuration: The configuration used to construct the managed session. + /// `URLSessionConfiguration.default` 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 `SessionManager` instance. + public init( + configuration: URLSessionConfiguration = URLSessionConfiguration.default, + delegate: SessionDelegate = SessionDelegate(), + serverTrustPolicyManager: ServerTrustPolicyManager? = nil) + { + self.delegate = delegate + self.session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) + + commonInit(serverTrustPolicyManager: serverTrustPolicyManager) + } + + /// Creates an instance with the specified `session`, `delegate` and `serverTrustPolicyManager`. + /// + /// - 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 `SessionManager` instance if the URL session's delegate matches; `nil` otherwise. + public init?( + session: URLSession, + delegate: SessionDelegate, + serverTrustPolicyManager: ServerTrustPolicyManager? = nil) + { + guard delegate === session.delegate else { return nil } + + self.delegate = delegate + self.session = session + + commonInit(serverTrustPolicyManager: serverTrustPolicyManager) + } + + private func commonInit(serverTrustPolicyManager: ServerTrustPolicyManager?) { + session.serverTrustPolicyManager = serverTrustPolicyManager + + delegate.sessionManager = self + + delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in + guard let strongSelf = self else { return } + DispatchQueue.main.async { strongSelf.backgroundCompletionHandler?() } + } + } + + deinit { + session.invalidateAndCancel() + } + + // MARK: - Data Request + + /// Creates a `DataRequest` to retrieve the contents of the specified `url`, `method`, `parameters`, `encoding` + /// and `headers`. + /// + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.get` by default. + /// - parameter parameters: The parameters. `nil` by default. + /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `DataRequest`. + @discardableResult + open func request( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil) + -> DataRequest + { + var originalRequest: URLRequest? + + do { + originalRequest = try URLRequest(url: url, method: method, headers: headers) + let encodedURLRequest = try encoding.encode(originalRequest!, with: parameters) + return request(encodedURLRequest) + } catch { + return request(originalRequest, failedWith: error) + } + } + + /// Creates a `DataRequest` to retrieve the contents of a URL based on the specified `urlRequest`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `DataRequest`. + open func request(_ urlRequest: URLRequestConvertible) -> DataRequest { + var originalRequest: URLRequest? + + do { + originalRequest = try urlRequest.asURLRequest() + let originalTask = DataRequest.Requestable(urlRequest: originalRequest!) + + let task = try originalTask.task(session: session, adapter: adapter, queue: queue) + let request = DataRequest(session: session, requestTask: .data(originalTask, task)) + + delegate[task] = request + + if startRequestsImmediately { request.resume() } + + return request + } catch { + return request(originalRequest, failedWith: error) + } + } + + // MARK: Private - Request Implementation + + private func request(_ urlRequest: URLRequest?, failedWith error: Error) -> DataRequest { + var requestTask: Request.RequestTask = .data(nil, nil) + + if let urlRequest = urlRequest { + let originalTask = DataRequest.Requestable(urlRequest: urlRequest) + requestTask = .data(originalTask, nil) + } + + let underlyingError = error.underlyingAdaptError ?? error + let request = DataRequest(session: session, requestTask: requestTask, error: underlyingError) + + if let retrier = retrier, error is AdaptError { + allowRetrier(retrier, toRetry: request, with: underlyingError) + } else { + if startRequestsImmediately { request.resume() } + } + + return request + } + + // MARK: - Download Request + + // MARK: URL Request + + /// Creates a `DownloadRequest` to retrieve the contents the specified `url`, `method`, `parameters`, `encoding`, + /// `headers` and save them to the `destination`. + /// + /// If `destination` is not specified, the contents will remain in the temporary location determined by the + /// underlying URL session. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.get` by default. + /// - parameter parameters: The parameters. `nil` by default. + /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. + /// + /// - returns: The created `DownloadRequest`. + @discardableResult + open func download( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + let encodedURLRequest = try encoding.encode(urlRequest, with: parameters) + return download(encodedURLRequest, to: destination) + } catch { + return download(nil, to: destination, failedWith: error) + } + } + + /// Creates a `DownloadRequest` to retrieve the contents of a URL based on the specified `urlRequest` and save + /// them to the `destination`. + /// + /// If `destination` is not specified, the contents will remain in the temporary location determined by the + /// underlying URL session. + /// + /// 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. `nil` by default. + /// + /// - returns: The created `DownloadRequest`. + @discardableResult + open func download( + _ urlRequest: URLRequestConvertible, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest + { + do { + let urlRequest = try urlRequest.asURLRequest() + return download(.request(urlRequest), to: destination) + } catch { + return download(nil, to: destination, failedWith: error) + } + } + + // MARK: Resume Data + + /// Creates a `DownloadRequest` from the `resumeData` produced from a previous request cancellation to retrieve + /// the contents of the original request and save them to the `destination`. + /// + /// If `destination` is not specified, the contents will remain in the temporary location determined by the + /// underlying URL session. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken + /// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the + /// data is written incorrectly and will always fail to resume the download. For more information about the bug and + /// possible workarounds, please refer to the following Stack Overflow post: + /// + /// - http://stackoverflow.com/a/39347461/1342462 + /// + /// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` + /// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for + /// additional information. + /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. + /// + /// - returns: The created `DownloadRequest`. + @discardableResult + open func download( + resumingWith resumeData: Data, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest + { + return download(.resumeData(resumeData), to: destination) + } + + // MARK: Private - Download Implementation + + private func download( + _ downloadable: DownloadRequest.Downloadable, + to destination: DownloadRequest.DownloadFileDestination?) + -> DownloadRequest + { + do { + let task = try downloadable.task(session: session, adapter: adapter, queue: queue) + let download = DownloadRequest(session: session, requestTask: .download(downloadable, task)) + + download.downloadDelegate.destination = destination + + delegate[task] = download + + if startRequestsImmediately { download.resume() } + + return download + } catch { + return download(downloadable, to: destination, failedWith: error) + } + } + + private func download( + _ downloadable: DownloadRequest.Downloadable?, + to destination: DownloadRequest.DownloadFileDestination?, + failedWith error: Error) + -> DownloadRequest + { + var downloadTask: Request.RequestTask = .download(nil, nil) + + if let downloadable = downloadable { + downloadTask = .download(downloadable, nil) + } + + let underlyingError = error.underlyingAdaptError ?? error + + let download = DownloadRequest(session: session, requestTask: downloadTask, error: underlyingError) + download.downloadDelegate.destination = destination + + if let retrier = retrier, error is AdaptError { + allowRetrier(retrier, toRetry: download, with: underlyingError) + } else { + if startRequestsImmediately { download.resume() } + } + + return download + } + + // MARK: - Upload Request + + // MARK: File + + /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `file`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter file: The file to upload. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload( + _ fileURL: URL, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + return upload(fileURL, with: urlRequest) + } catch { + return upload(nil, failedWith: error) + } + } + + /// Creates a `UploadRequest` from the specified `urlRequest` for uploading the `file`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter file: The file to upload. + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { + do { + let urlRequest = try urlRequest.asURLRequest() + return upload(.file(fileURL, urlRequest)) + } catch { + return upload(nil, failedWith: error) + } + } + + // MARK: Data + + /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `data`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter data: The data to upload. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload( + _ data: Data, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + return upload(data, with: urlRequest) + } catch { + return upload(nil, failedWith: error) + } + } + + /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `data`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter data: The data to upload. + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { + do { + let urlRequest = try urlRequest.asURLRequest() + return upload(.data(data, urlRequest)) + } catch { + return upload(nil, failedWith: error) + } + } + + // MARK: InputStream + + /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `stream`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter stream: The stream to upload. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload( + _ stream: InputStream, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + return upload(stream, with: urlRequest) + } catch { + return upload(nil, failedWith: error) + } + } + + /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `stream`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter stream: The stream to upload. + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { + do { + let urlRequest = try urlRequest.asURLRequest() + return upload(.stream(stream, urlRequest)) + } catch { + return upload(nil, failedWith: error) + } + } + + // MARK: MultipartFormData + + /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new + /// `UploadRequest` using the `url`, `method` and `headers`. + /// + /// 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 multipartFormData: The closure used to append body parts to the `MultipartFormData`. + /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + /// `multipartFormDataEncodingMemoryThreshold` by default. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. + open func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + + return upload( + multipartFormData: multipartFormData, + usingThreshold: encodingMemoryThreshold, + with: urlRequest, + encodingCompletion: encodingCompletion + ) + } catch { + DispatchQueue.main.async { encodingCompletion?(.failure(error)) } + } + } + + /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new + /// `UploadRequest` using the `urlRequest`. + /// + /// 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 multipartFormData: The closure used to append body parts to the `MultipartFormData`. + /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + /// `multipartFormDataEncodingMemoryThreshold` by default. + /// - parameter urlRequest: The URL request. + /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. + open func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + with urlRequest: URLRequestConvertible, + encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) + { + DispatchQueue.global(qos: .utility).async { + let formData = MultipartFormData() + multipartFormData(formData) + + var tempFileURL: URL? + + do { + var urlRequestWithContentType = try urlRequest.asURLRequest() + urlRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type") + + let isBackgroundSession = self.session.configuration.identifier != nil + + if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession { + let data = try formData.encode() + + let encodingResult = MultipartFormDataEncodingResult.success( + request: self.upload(data, with: urlRequestWithContentType), + streamingFromDisk: false, + streamFileURL: nil + ) + + DispatchQueue.main.async { encodingCompletion?(encodingResult) } + } else { + let fileManager = FileManager.default + let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory()) + let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data") + let fileName = UUID().uuidString + let fileURL = directoryURL.appendingPathComponent(fileName) + + tempFileURL = fileURL + + var directoryError: Error? + + // Create directory inside serial queue to ensure two threads don't do this in parallel + self.queue.sync { + do { + try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) + } catch { + directoryError = error + } + } + + if let directoryError = directoryError { throw directoryError } + + try formData.writeEncodedData(to: fileURL) + + let upload = self.upload(fileURL, with: urlRequestWithContentType) + + // Cleanup the temp file once the upload is complete + upload.delegate.queue.addOperation { + do { + try FileManager.default.removeItem(at: fileURL) + } catch { + // No-op + } + } + + DispatchQueue.main.async { + let encodingResult = MultipartFormDataEncodingResult.success( + request: upload, + streamingFromDisk: true, + streamFileURL: fileURL + ) + + encodingCompletion?(encodingResult) + } + } + } catch { + // Cleanup the temp file in the event that the multipart form data encoding failed + if let tempFileURL = tempFileURL { + do { + try FileManager.default.removeItem(at: tempFileURL) + } catch { + // No-op + } + } + + DispatchQueue.main.async { encodingCompletion?(.failure(error)) } + } + } + } + + // MARK: Private - Upload Implementation + + private func upload(_ uploadable: UploadRequest.Uploadable) -> UploadRequest { + do { + let task = try uploadable.task(session: session, adapter: adapter, queue: queue) + let upload = UploadRequest(session: session, requestTask: .upload(uploadable, task)) + + if case let .stream(inputStream, _) = uploadable { + upload.delegate.taskNeedNewBodyStream = { _, _ in inputStream } + } + + delegate[task] = upload + + if startRequestsImmediately { upload.resume() } + + return upload + } catch { + return upload(uploadable, failedWith: error) + } + } + + private func upload(_ uploadable: UploadRequest.Uploadable?, failedWith error: Error) -> UploadRequest { + var uploadTask: Request.RequestTask = .upload(nil, nil) + + if let uploadable = uploadable { + uploadTask = .upload(uploadable, nil) + } + + let underlyingError = error.underlyingAdaptError ?? error + let upload = UploadRequest(session: session, requestTask: uploadTask, error: underlyingError) + + if let retrier = retrier, error is AdaptError { + allowRetrier(retrier, toRetry: upload, with: underlyingError) + } else { + if startRequestsImmediately { upload.resume() } + } + + return upload + } + +#if !os(watchOS) + + // MARK: - Stream Request + + // MARK: Hostname and Port + + /// Creates a `StreamRequest` for bidirectional streaming using the `hostname` and `port`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter hostName: The hostname of the server to connect to. + /// - parameter port: The port of the server to connect to. + /// + /// - returns: The created `StreamRequest`. + @discardableResult + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open func stream(withHostName hostName: String, port: Int) -> StreamRequest { + return stream(.stream(hostName: hostName, port: port)) + } + + // MARK: NetService + + /// Creates a `StreamRequest` for bidirectional streaming using the `netService`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter netService: The net service used to identify the endpoint. + /// + /// - returns: The created `StreamRequest`. + @discardableResult + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open func stream(with netService: NetService) -> StreamRequest { + return stream(.netService(netService)) + } + + // MARK: Private - Stream Implementation + + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + private func stream(_ streamable: StreamRequest.Streamable) -> StreamRequest { + do { + let task = try streamable.task(session: session, adapter: adapter, queue: queue) + let request = StreamRequest(session: session, requestTask: .stream(streamable, task)) + + delegate[task] = request + + if startRequestsImmediately { request.resume() } + + return request + } catch { + return stream(failedWith: error) + } + } + + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + private func stream(failedWith error: Error) -> StreamRequest { + let stream = StreamRequest(session: session, requestTask: .stream(nil, nil), error: error) + if startRequestsImmediately { stream.resume() } + return stream + } + +#endif + + // MARK: - Internal - Retry Request + + func retry(_ request: Request) -> Bool { + guard let originalTask = request.originalTask else { return false } + + do { + let task = try originalTask.task(session: session, adapter: adapter, queue: queue) + + request.delegate.task = task // resets all task delegate data + + request.retryCount += 1 + request.startTime = CFAbsoluteTimeGetCurrent() + request.endTime = nil + + task.resume() + + return true + } catch { + request.delegate.error = error.underlyingAdaptError ?? error + return false + } + } + + private func allowRetrier(_ retrier: RequestRetrier, toRetry request: Request, with error: Error) { + DispatchQueue.utility.async { [weak self] in + guard let strongSelf = self else { return } + + retrier.should(strongSelf, retry: request, with: error) { shouldRetry, timeDelay in + guard let strongSelf = self else { return } + + guard shouldRetry else { + if strongSelf.startRequestsImmediately { request.resume() } + return + } + + DispatchQueue.utility.after(timeDelay) { + guard let strongSelf = self else { return } + + let retrySucceeded = strongSelf.retry(request) + + if retrySucceeded, let task = request.task { + strongSelf.delegate[task] = request + } else { + if strongSelf.startRequestsImmediately { request.resume() } + } + } + } + } + } +} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/TaskDelegate.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/TaskDelegate.swift new file mode 100644 index 0000000000..d4fd2163c1 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/TaskDelegate.swift @@ -0,0 +1,453 @@ +// +// TaskDelegate.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 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. +open class TaskDelegate: NSObject { + + // MARK: Properties + + /// The serial operation queue used to execute all operations after the task completes. + open let queue: OperationQueue + + /// The data returned by the server. + public var data: Data? { return nil } + + /// The error generated throughout the lifecyle of the task. + public var error: Error? + + var task: URLSessionTask? { + didSet { reset() } + } + + var initialResponseTime: CFAbsoluteTime? + var credential: URLCredential? + var metrics: AnyObject? // URLSessionTaskMetrics + + // MARK: Lifecycle + + init(task: URLSessionTask?) { + self.task = task + + self.queue = { + let operationQueue = OperationQueue() + + operationQueue.maxConcurrentOperationCount = 1 + operationQueue.isSuspended = true + operationQueue.qualityOfService = .utility + + return operationQueue + }() + } + + func reset() { + error = nil + initialResponseTime = nil + } + + // MARK: URLSessionTaskDelegate + + var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? + var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? + var taskDidCompleteWithError: ((URLSession, URLSessionTask, Error?) -> Void)? + + @objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:) + func urlSession( + _ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) + { + var redirectRequest: URLRequest? = request + + if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { + redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) + } + + completionHandler(redirectRequest) + } + + @objc(URLSession:task:didReceiveChallenge:completionHandler:) + func urlSession( + _ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling + var credential: URLCredential? + + 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?.serverTrustPolicy(forHost: host), + let serverTrust = challenge.protectionSpace.serverTrust + { + if serverTrustPolicy.evaluate(serverTrust, forHost: host) { + disposition = .useCredential + credential = URLCredential(trust: serverTrust) + } else { + disposition = .cancelAuthenticationChallenge + } + } + } else { + if challenge.previousFailureCount > 0 { + disposition = .rejectProtectionSpace + } else { + credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace) + + if credential != nil { + disposition = .useCredential + } + } + } + + completionHandler(disposition, credential) + } + + @objc(URLSession:task:needNewBodyStream:) + func urlSession( + _ session: URLSession, + task: URLSessionTask, + needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) + { + var bodyStream: InputStream? + + if let taskNeedNewBodyStream = taskNeedNewBodyStream { + bodyStream = taskNeedNewBodyStream(session, task) + } + + completionHandler(bodyStream) + } + + @objc(URLSession:task:didCompleteWithError:) + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + if let taskDidCompleteWithError = taskDidCompleteWithError { + taskDidCompleteWithError(session, task, error) + } else { + if let error = error { + if self.error == nil { self.error = error } + + if + let downloadDelegate = self as? DownloadTaskDelegate, + let resumeData = (error as NSError).userInfo[NSURLSessionDownloadTaskResumeData] as? Data + { + downloadDelegate.resumeData = resumeData + } + } + + queue.isSuspended = false + } + } +} + +// MARK: - + +class DataTaskDelegate: TaskDelegate, URLSessionDataDelegate { + + // MARK: Properties + + var dataTask: URLSessionDataTask { return task as! URLSessionDataTask } + + override var data: Data? { + if dataStream != nil { + return nil + } else { + return mutableData + } + } + + var progress: Progress + var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? + + var dataStream: ((_ data: Data) -> Void)? + + private var totalBytesReceived: Int64 = 0 + private var mutableData: Data + + private var expectedContentLength: Int64? + + // MARK: Lifecycle + + override init(task: URLSessionTask?) { + mutableData = Data() + progress = Progress(totalUnitCount: 0) + + super.init(task: task) + } + + override func reset() { + super.reset() + + progress = Progress(totalUnitCount: 0) + totalBytesReceived = 0 + mutableData = Data() + expectedContentLength = nil + } + + // MARK: URLSessionDataDelegate + + var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? + var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? + var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? + var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? + + func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didReceive response: URLResponse, + completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) + { + var disposition: URLSession.ResponseDisposition = .allow + + expectedContentLength = response.expectedContentLength + + if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { + disposition = dataTaskDidReceiveResponse(session, dataTask, response) + } + + completionHandler(disposition) + } + + func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didBecome downloadTask: URLSessionDownloadTask) + { + dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask) + } + + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + + if let dataTaskDidReceiveData = dataTaskDidReceiveData { + dataTaskDidReceiveData(session, dataTask, data) + } else { + if let dataStream = dataStream { + dataStream(data) + } else { + mutableData.append(data) + } + + let bytesReceived = Int64(data.count) + totalBytesReceived += bytesReceived + let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown + + progress.totalUnitCount = totalBytesExpected + progress.completedUnitCount = totalBytesReceived + + if let progressHandler = progressHandler { + progressHandler.queue.async { progressHandler.closure(self.progress) } + } + } + } + + func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse, + completionHandler: @escaping (CachedURLResponse?) -> Void) + { + var cachedResponse: CachedURLResponse? = proposedResponse + + if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { + cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse) + } + + completionHandler(cachedResponse) + } +} + +// MARK: - + +class DownloadTaskDelegate: TaskDelegate, URLSessionDownloadDelegate { + + // MARK: Properties + + var downloadTask: URLSessionDownloadTask { return task as! URLSessionDownloadTask } + + var progress: Progress + var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? + + var resumeData: Data? + override var data: Data? { return resumeData } + + var destination: DownloadRequest.DownloadFileDestination? + + var temporaryURL: URL? + var destinationURL: URL? + + var fileURL: URL? { return destination != nil ? destinationURL : temporaryURL } + + // MARK: Lifecycle + + override init(task: URLSessionTask?) { + progress = Progress(totalUnitCount: 0) + super.init(task: task) + } + + override func reset() { + super.reset() + + progress = Progress(totalUnitCount: 0) + resumeData = nil + } + + // MARK: URLSessionDownloadDelegate + + var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> URL)? + var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? + + func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didFinishDownloadingTo location: URL) + { + temporaryURL = location + + guard + let destination = destination, + let response = downloadTask.response as? HTTPURLResponse + else { return } + + let result = destination(location, response) + let destinationURL = result.destinationURL + let options = result.options + + self.destinationURL = destinationURL + + do { + if options.contains(.removePreviousFile), FileManager.default.fileExists(atPath: destinationURL.path) { + try FileManager.default.removeItem(at: destinationURL) + } + + if options.contains(.createIntermediateDirectories) { + let directory = destinationURL.deletingLastPathComponent() + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + + try FileManager.default.moveItem(at: location, to: destinationURL) + } catch { + self.error = error + } + } + + func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) + { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + + if let downloadTaskDidWriteData = downloadTaskDidWriteData { + downloadTaskDidWriteData( + session, + downloadTask, + bytesWritten, + totalBytesWritten, + totalBytesExpectedToWrite + ) + } else { + progress.totalUnitCount = totalBytesExpectedToWrite + progress.completedUnitCount = totalBytesWritten + + if let progressHandler = progressHandler { + progressHandler.queue.async { progressHandler.closure(self.progress) } + } + } + } + + func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) + { + if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { + downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) + } else { + progress.totalUnitCount = expectedTotalBytes + progress.completedUnitCount = fileOffset + } + } +} + +// MARK: - + +class UploadTaskDelegate: DataTaskDelegate { + + // MARK: Properties + + var uploadTask: URLSessionUploadTask { return task as! URLSessionUploadTask } + + var uploadProgress: Progress + var uploadProgressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? + + // MARK: Lifecycle + + override init(task: URLSessionTask?) { + uploadProgress = Progress(totalUnitCount: 0) + super.init(task: task) + } + + override func reset() { + super.reset() + uploadProgress = Progress(totalUnitCount: 0) + } + + // MARK: URLSessionTaskDelegate + + var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? + + func URLSession( + _ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) + { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + + if let taskDidSendBodyData = taskDidSendBodyData { + taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) + } else { + uploadProgress.totalUnitCount = totalBytesExpectedToSend + uploadProgress.completedUnitCount = totalBytesSent + + if let uploadProgressHandler = uploadProgressHandler { + uploadProgressHandler.queue.async { uploadProgressHandler.closure(self.uploadProgress) } + } + } + } +} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Timeline.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Timeline.swift new file mode 100644 index 0000000000..1440989d5f --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Timeline.swift @@ -0,0 +1,136 @@ +// +// Timeline.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Responsible for computing the timing metrics for the complete lifecycle of a `Request`. +public struct Timeline { + /// The time the request was initialized. + public let requestStartTime: CFAbsoluteTime + + /// The time the first bytes were received from or sent to the server. + public let initialResponseTime: CFAbsoluteTime + + /// The time when the request was completed. + public let requestCompletedTime: CFAbsoluteTime + + /// The time when the response serialization was completed. + public let serializationCompletedTime: CFAbsoluteTime + + /// The time interval in seconds from the time the request started to the initial response from the server. + public let latency: TimeInterval + + /// The time interval in seconds from the time the request started to the time the request completed. + public let requestDuration: TimeInterval + + /// The time interval in seconds from the time the request completed to the time response serialization completed. + public let serializationDuration: TimeInterval + + /// The time interval in seconds from the time the request started to the time response serialization completed. + public let totalDuration: TimeInterval + + /// Creates a new `Timeline` instance with the specified request times. + /// + /// - parameter requestStartTime: The time the request was initialized. Defaults to `0.0`. + /// - parameter initialResponseTime: The time the first bytes were received from or sent to the server. + /// Defaults to `0.0`. + /// - parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`. + /// - parameter serializationCompletedTime: The time when the response serialization was completed. Defaults + /// to `0.0`. + /// + /// - returns: The new `Timeline` instance. + public init( + requestStartTime: CFAbsoluteTime = 0.0, + initialResponseTime: CFAbsoluteTime = 0.0, + requestCompletedTime: CFAbsoluteTime = 0.0, + serializationCompletedTime: CFAbsoluteTime = 0.0) + { + self.requestStartTime = requestStartTime + self.initialResponseTime = initialResponseTime + self.requestCompletedTime = requestCompletedTime + self.serializationCompletedTime = serializationCompletedTime + + self.latency = initialResponseTime - requestStartTime + self.requestDuration = requestCompletedTime - requestStartTime + self.serializationDuration = serializationCompletedTime - requestCompletedTime + self.totalDuration = serializationCompletedTime - requestStartTime + } +} + +// MARK: - CustomStringConvertible + +extension Timeline: CustomStringConvertible { + /// The textual representation used when written to an output stream, which includes the latency, the request + /// duration and the total duration. + public var description: String { + let latency = String(format: "%.3f", self.latency) + let requestDuration = String(format: "%.3f", self.requestDuration) + let serializationDuration = String(format: "%.3f", self.serializationDuration) + let totalDuration = String(format: "%.3f", self.totalDuration) + + // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is + // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. + let timings = [ + "\"Latency\": " + latency + " secs", + "\"Request Duration\": " + requestDuration + " secs", + "\"Serialization Duration\": " + serializationDuration + " secs", + "\"Total Duration\": " + totalDuration + " secs" + ] + + return "Timeline: { " + timings.joined(separator: ", ") + " }" + } +} + +// MARK: - CustomDebugStringConvertible + +extension Timeline: CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes the request start time, the + /// initial response time, the request completed time, the serialization completed time, the latency, the request + /// duration and the total duration. + public var debugDescription: String { + let requestStartTime = String(format: "%.3f", self.requestStartTime) + let initialResponseTime = String(format: "%.3f", self.initialResponseTime) + let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime) + let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime) + let latency = String(format: "%.3f", self.latency) + let requestDuration = String(format: "%.3f", self.requestDuration) + let serializationDuration = String(format: "%.3f", self.serializationDuration) + let totalDuration = String(format: "%.3f", self.totalDuration) + + // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is + // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. + let timings = [ + "\"Request Start Time\": " + requestStartTime, + "\"Initial Response Time\": " + initialResponseTime, + "\"Request Completed Time\": " + requestCompletedTime, + "\"Serialization Completed Time\": " + serializationCompletedTime, + "\"Latency\": " + latency + " secs", + "\"Request Duration\": " + requestDuration + " secs", + "\"Serialization Duration\": " + serializationDuration + " secs", + "\"Total Duration\": " + totalDuration + " secs" + ] + + return "Timeline: { " + timings.joined(separator: ", ") + " }" + } +} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift new file mode 100644 index 0000000000..c405d02af1 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift @@ -0,0 +1,309 @@ +// +// 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 { + + // MARK: Helper Types + + fileprivate typealias ErrorReason = AFError.ResponseValidationFailureReason + + /// 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(Error) + } + + fileprivate struct MIMEType { + let type: String + let subtype: String + + var isWildcard: Bool { return type == "*" && subtype == "*" } + + init?(_ string: String) { + let components: [String] = { + let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines) + let split = stripped.substring(to: stripped.range(of: ";")?.lowerBound ?? stripped.endIndex) + return split.components(separatedBy: "/") + }() + + if let type = components.first, let 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 + } + } + } + + // MARK: Properties + + fileprivate var acceptableStatusCodes: [Int] { return Array(200..<300) } + + fileprivate var acceptableContentTypes: [String] { + if let accept = request?.value(forHTTPHeaderField: "Accept") { + return accept.components(separatedBy: ",") + } + + return ["*/*"] + } + + // MARK: Status Code + + fileprivate func validate( + statusCode acceptableStatusCodes: S, + response: HTTPURLResponse) + -> ValidationResult + where S.Iterator.Element == Int + { + if acceptableStatusCodes.contains(response.statusCode) { + return .success + } else { + let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode) + return .failure(AFError.responseValidationFailed(reason: reason)) + } + } + + // MARK: Content Type + + fileprivate func validate( + contentType acceptableContentTypes: S, + response: HTTPURLResponse, + data: Data?) + -> ValidationResult + where S.Iterator.Element == String + { + guard let data = data, data.count > 0 else { return .success } + + guard + let responseContentType = response.mimeType, + let responseMIMEType = MIMEType(responseContentType) + else { + for contentType in acceptableContentTypes { + if let mimeType = MIMEType(contentType), mimeType.isWildcard { + return .success + } + } + + let error: AFError = { + let reason: ErrorReason = .missingContentType(acceptableContentTypes: Array(acceptableContentTypes)) + return AFError.responseValidationFailed(reason: reason) + }() + + return .failure(error) + } + + for contentType in acceptableContentTypes { + if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) { + return .success + } + } + + let error: AFError = { + let reason: ErrorReason = .unacceptableContentType( + acceptableContentTypes: Array(acceptableContentTypes), + responseContentType: responseContentType + ) + + return AFError.responseValidationFailed(reason: reason) + }() + + return .failure(error) + } +} + +// MARK: - + +extension DataRequest { + /// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the + /// request was valid. + public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> 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. + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validationExecution: () -> Void = { [unowned self] in + if + let response = self.response, + self.delegate.error == nil, + case let .failure(error) = validation(self.request, response, self.delegate.data) + { + self.delegate.error = error + } + } + + validations.append(validationExecution) + + return self + } + + /// Validates that the response has a status code in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter range: The range of acceptable status codes. + /// + /// - returns: The request. + @discardableResult + public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { + return validate { [unowned self] _, response, _ in + return self.validate(statusCode: acceptableStatusCodes, response: response) + } + } + + /// Validates that the response has a content type in the specified sequence. + /// + /// 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. + @discardableResult + public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { + return validate { [unowned self] _, response, data in + return self.validate(contentType: acceptableContentTypes, response: response, data: data) + } + } + + /// 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. + @discardableResult + public func validate() -> Self { + return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes) + } +} + +// MARK: - + +extension DownloadRequest { + /// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a + /// destination URL, and returns whether the request was valid. + public typealias Validation = ( + _ request: URLRequest?, + _ response: HTTPURLResponse, + _ temporaryURL: URL?, + _ destinationURL: URL?) + -> 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. + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validationExecution: () -> Void = { [unowned self] in + let request = self.request + let temporaryURL = self.downloadDelegate.temporaryURL + let destinationURL = self.downloadDelegate.destinationURL + + if + let response = self.response, + self.delegate.error == nil, + case let .failure(error) = validation(request, response, temporaryURL, destinationURL) + { + self.delegate.error = error + } + } + + validations.append(validationExecution) + + return self + } + + /// Validates that the response has a status code in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter range: The range of acceptable status codes. + /// + /// - returns: The request. + @discardableResult + public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { + return validate { [unowned self] _, response, _, _ in + return self.validate(statusCode: acceptableStatusCodes, response: response) + } + } + + /// Validates that the response has a content type in the specified sequence. + /// + /// 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. + @discardableResult + public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { + return validate { [unowned self] _, response, _, _ in + let fileURL = self.downloadDelegate.fileURL + + guard let validFileURL = fileURL else { + return .failure(AFError.responseValidationFailed(reason: .dataFileNil)) + } + + do { + let data = try Data(contentsOf: validFileURL) + return self.validate(contentType: acceptableContentTypes, response: response, data: data) + } catch { + return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL))) + } + } + } + + /// 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. + @discardableResult + public func validate() -> Self { + return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes) + } +} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json new file mode 100644 index 0000000000..6e7e3ef32c --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json @@ -0,0 +1,22 @@ +{ + "name": "PetstoreClient", + "platforms": { + "ios": "9.0", + "osx": "10.11" + }, + "version": "0.0.1", + "source": { + "git": "git@github.com:swagger-api/swagger-mustache.git", + "tag": "v1.0.0" + }, + "authors": "", + "license": "Proprietary", + "homepage": "https://github.com/swagger-api/swagger-codegen", + "summary": "PetstoreClient", + "source_files": "PetstoreClient/Classes/Swaggers/**/*.swift", + "dependencies": { + "Alamofire": [ + "~> 4.5" + ] + } +} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Manifest.lock b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Manifest.lock new file mode 100644 index 0000000000..de11941ae6 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Manifest.lock @@ -0,0 +1,19 @@ +PODS: + - Alamofire (4.5.0) + - PetstoreClient (0.0.1): + - Alamofire (~> 4.5) + +DEPENDENCIES: + - PetstoreClient (from `../`) + +EXTERNAL SOURCES: + PetstoreClient: + :path: ../ + +SPEC CHECKSUMS: + Alamofire: f28cdffd29de33a7bfa022cbd63ae95a27fae140 + PetstoreClient: 77e3465a18f2380eff57e5075a2d59021308dde4 + +PODFILE CHECKSUM: 417049e9ed0e4680602b34d838294778389bd418 + +COCOAPODS: 1.1.1 diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj new file mode 100644 index 0000000000..d761f17efc --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj @@ -0,0 +1,1193 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 079F2BD52F24416F7C5A53877F54566A /* Dog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 975DAA5E04C557E1AA63DD67304C3466 /* Dog.swift */; }; + 0D33BB30417B9584629B6D880037AA2B /* ClassModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = D679EE988B8B8734D2AAAAAFD25CDB9B /* ClassModel.swift */; }; + 10EB23E9ECC4B33E16933BB1EA560B6A /* Timeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = 87882A1F5A92C8138D54545E51D51E6F /* Timeline.swift */; }; + 1151CDE98B5CB5F152ED39BF798EF5CF /* EnumArrays.swift in Sources */ = {isa = PBXBuildFile; fileRef = 249B8C876D70EDBA1D831123AE8EE0F8 /* EnumArrays.swift */; }; + 154A6488A4E591935A82473995C15AE4 /* JSONEncodingHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 25616A3E91482393BFD64C92FE312F0E /* JSONEncodingHelper.swift */; }; + 1B13BFD9084781D7ED2E079E6BF2C557 /* EnumTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4199B3084AC46DC42D15500A1C964ECC /* EnumTest.swift */; }; + 1B9EDEDC964E6B08F78920B4F4B9DB84 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = B44A27EFBB0DA84D738057B77F3413B1 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1CFDE72D9E7E9750A9ADE03AB4669311 /* FakeAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6815FAC9A7B1782239E161DEEF54357F /* FakeAPI.swift */; }; + 1E2B97D6050471F3C9440D7AEA63029D /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 706C7AFFE37BA158C3553250F4B5FAED /* Alamofire.framework */; }; + 22FDE110EA91A85020A5B47486558282 /* MixedPropertiesAndAdditionalPropertiesClass.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4EE549F80BAFEF84BF212F0C315BC9BF /* MixedPropertiesAndAdditionalPropertiesClass.swift */; }; + 24FFD130F7E23492281B79C5C678F00D /* AlamofireImplementations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1024470B7B0142DFF1DF7E009ED9260D /* AlamofireImplementations.swift */; }; + 253BED146B97E5F268DB986D0EC87081 /* OuterEnum.swift in Sources */ = {isa = PBXBuildFile; fileRef = C2A49053FD4226BD3513549F61A5944F /* OuterEnum.swift */; }; + 27BF2E059FCCB3CDA349738B75A9EDD3 /* ReadOnlyFirst.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1DF0A17DD1DCF7B53BFC5E09C07C84B1 /* ReadOnlyFirst.swift */; }; + 2940D84FC5A76050A9281E6E49A8BDFC /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3F9B2E024A80A62FE090406312870D33 /* Foundation.framework */; }; + 29BBA290461F57554F9D63A842505063 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3F9B2E024A80A62FE090406312870D33 /* Foundation.framework */; }; + 2D5A60538984183CDF16344E07DE6016 /* FormatTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8DD5A1187D47A6FFAC34F927DA186750 /* FormatTest.swift */; }; + 2DEA81B2292287FEE1BC4A520801F675 /* Category.swift in Sources */ = {isa = PBXBuildFile; fileRef = F69BC1C993ED1722CE6D63E07381785E /* Category.swift */; }; + 31F8B86E3672D0B828B6352C875649C4 /* Pods-SwaggerClientTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 342645FD19CD3977B12C869E662DF658 /* OuterComposite.swift in Sources */ = {isa = PBXBuildFile; fileRef = 749C03CC31823CCADA2EFFFD06BF9E98 /* OuterComposite.swift */; }; + 3626B94094672CB1C9DEA32B9F9502E1 /* TaskDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = A01C037B4034EDA3D7955BC5E4E9D9D6 /* TaskDelegate.swift */; }; + 39755FB5994F45FBD67C9ADFD5915EF2 /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1194146F3B5CFFECFE93B4E1DBB369BA /* Configuration.swift */; }; + 424F25F3C040D2362DD353C82A86740B /* Pods-SwaggerClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 4378EAAAA7D2FDACD110A1ED9D2FED5F /* FakeclassnametagsAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 09F0396C30B906DB9EFEFBE97E091406 /* FakeclassnametagsAPI.swift */; }; + 483C65BB55BCA70C8B65BBD266151A1C /* User.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83A7AB2A1DA3632E843B3336E8D41A8E /* User.swift */; }; + 491FD17DCEA4455874451D174A9A182E /* StoreAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10156F0F886EC2F50651B704A3A6D742 /* StoreAPI.swift */; }; + 4AE57833EC2315CC8EDA4864CAD7382B /* Pet.swift in Sources */ = {isa = PBXBuildFile; fileRef = DE081085EBFE0D670AAC85E74ACFDE8D /* Pet.swift */; }; + 4E168284FE74373DE791FA46610F6E85 /* Models.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C877E250DAECFEE1CDABF476EF2B25C /* Models.swift */; }; + 5387216E723A3C68E851CA15573CDD71 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1E230A0448B394DE26E688DAC8E6201E /* Request.swift */; }; + 61200D01A1855D7920CEF835C8BE00B0 /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0FCBF1EED873F61C6D46CE37FA5C39D3 /* DispatchQueue+Alamofire.swift */; }; + 62F65AD8DC4F0F9610F4B8B4738EC094 /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 32B030D27CAC730C5EB0F22390645310 /* ServerTrustPolicy.swift */; }; + 700AFFD25A3F79F704E1F48E1090C719 /* ApiResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26189A4CE9006C2C9BB1AAE144CB191F /* ApiResponse.swift */; }; + 75332AEFA1C56AD923C581FB7CC4B580 /* PetstoreClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 785570E189782F883FC7F30096107F05 /* APIHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 14FA6FDDB70F2EFB58DE7D635F6946D4 /* APIHelper.swift */; }; + 798B0EDE6CDDDFA67A576CC5D7356197 /* Cat.swift in Sources */ = {isa = PBXBuildFile; fileRef = C21C617FCA30726E782E8A67D0149138 /* Cat.swift */; }; + 7B5FE28C7EA4122B0598738E54DBEBD8 /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 195D73DD9EF275A3C56569E2B1CA8026 /* SessionDelegate.swift */; }; + 7D8CC01E8C9EFFF9F4D65406CDE0AB66 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D60BC9955B4F7FFA62D7440CB385C11 /* Result.swift */; }; + 7EA0B4343115F6BD6062C1A3C5924380 /* Tag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A3C1EDF28A8B80DB140B65CDE450E09 /* Tag.swift */; }; + 804A773AC1F6CAD0833113365C437ED6 /* Client.swift in Sources */ = {isa = PBXBuildFile; fileRef = E2FCD5F3D2C6621D4355CACB49530DB3 /* Client.swift */; }; + 858A507A04D7EBD392B5E38BFA5C0FB1 /* Name.swift in Sources */ = {isa = PBXBuildFile; fileRef = 237AE2907A722F87C756BCE4EF772C4C /* Name.swift */; }; + 897985FA042CD12B825C3032898FAB26 /* Pods-SwaggerClientTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */; }; + 8B3DB4230FDB986C273707551D5C098D /* Order.swift in Sources */ = {isa = PBXBuildFile; fileRef = E80F4034540947434A69B02246F8ABBD /* Order.swift */; }; + 8CBE860E26B3E63F905AABB8C2ED8408 /* AnimalFarm.swift in Sources */ = {isa = PBXBuildFile; fileRef = 688103EFA108516ADBACAFEF5DF33690 /* AnimalFarm.swift */; }; + 94B455FDE2B057DB680F439EA3FD1B49 /* AdditionalPropertiesClass.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F54BE613A3988D2B9B506E8E6BEE157 /* AdditionalPropertiesClass.swift */; }; + 97809A3EC41B70910367804F24749488 /* Capitalization.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE4C2705D4C3B913D44B4F26C6817A9C /* Capitalization.swift */; }; + 97D4E3413AADDB57435C6E01E40F1737 /* OuterNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = E6E0984D5B0599817A4E48CBAE9AAB9A /* OuterNumber.swift */; }; + 98A62599B00ECECEE6693F10291DCA8E /* NumberOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = 076A25934936127AC03A2B855ACCDF5E /* NumberOnly.swift */; }; + 9D4EC73C4EC0F4CA643BFB0F744E206E /* Model200Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = C82495B2E8EC7A268E3C9F068458102B /* Model200Response.swift */; }; + 9DF1DB10A8D8AD5D760AD2119464BBFA /* ArrayOfNumberOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D9891D7095BE60AF5240E9C34D72085 /* ArrayOfNumberOnly.swift */; }; + 9ED1C3E564D542971480A55F74192BA2 /* CodableHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = C387A09BFC4D29F2B2C308F55CD2BFB7 /* CodableHelper.swift */; }; + 9ED2BB2981896E0A39EFA365503F58CE /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4AF006B0AD5765D1BFA8253C2DCBB126 /* AFError.swift */; }; + A04BFC558D69E7DBB68023C80A9CFE4E /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3F9B2E024A80A62FE090406312870D33 /* Foundation.framework */; }; + A19592FE4371E4FCDAAB8AEE09AB93B9 /* EnumClass.swift in Sources */ = {isa = PBXBuildFile; fileRef = 03597C306A2FB3B657BCFF572F74F4D4 /* EnumClass.swift */; }; + A2A6F71B727312BD45CC7A4AAD7B0AB7 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5A8AA5F9EDED0A0BDDE7E830BF4AEE0 /* NetworkReachabilityManager.swift */; }; + A563CBF0CB0A2D620BCE488727AFE9BC /* JSONEncodableEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F07EB5B38222CE6DB8CC7EC894E9E73 /* JSONEncodableEncoding.swift */; }; + A63D913EAA7D50833B860D9FB011E761 /* SpecialModelName.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2AC757CC02124D5B17B6867095DBB70D /* SpecialModelName.swift */; }; + A6546161061DFBD9AD9CD2669B3407DD /* APIs.swift in Sources */ = {isa = PBXBuildFile; fileRef = 798454EC551811276A6837CFCD4ADC8A /* APIs.swift */; }; + A73E115FCBAE1F29A37D5327AE87AAB8 /* ArrayTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 53AFC29FAA23E6156D43BCDE6F4EFEF7 /* ArrayTest.swift */; }; + A7F2C30678B7926A18C64F71A5CFDB3E /* PetAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A0B8917069F5E9591DD17A113737986 /* PetAPI.swift */; }; + A9EEEA7477981DEEBC72432DE9990A4B /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 22C1C119BCE81C53F76CAC2BE27C38E0 /* Alamofire-dummy.m */; }; + AE1EF48399533730D0066E04B22CA2D6 /* SessionManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46CDAC6C1187C5467E576980E1062C8B /* SessionManager.swift */; }; + B0A93172B99BF60154ED6242AFBE4026 /* HasOnlyReadOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A2DACCC87696D352D52090A939EE230 /* HasOnlyReadOnly.swift */; }; + B65FCF589DA398C3EFE0128064E510EC /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 155538D91ACEEEDF82069ACF6C1A02E7 /* MultipartFormData.swift */; }; + B746D752789DABA80AC0ABF066B719BB /* UserAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC87361174534D6D1655DD60071A3D83 /* UserAPI.swift */; }; + BBEFE2F9CEB73DC7BD97FFA66A0D9D4F /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = B029DBC43E49A740F12B5E4D2E6DD452 /* Validation.swift */; }; + BE5C67A07E289FE1F9BE27335B159997 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6639346628280A0D0FAD35196BF56108 /* ParameterEncoding.swift */; }; + C05B6F5687193D4F8C45A876DD05D53E /* Animal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 44E7AE2E18EA6D3B341C419A4B2813F3 /* Animal.swift */; }; + CB6D60925223897FFA2662667DF83E8A /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 04F47F5C9CDB035C5AFADEBA5BF44F1C /* Response.swift */; }; + D000C65F968C44B544101279E763C0C9 /* Return.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F57C400928D9344121036AC8E4220D /* Return.swift */; }; + D102CB4FA078626BF684F476910012A1 /* PetstoreClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */; }; + D319019CE9A48494F3ED480F1226517A /* OuterBoolean.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1365D135EB77F78D4ED50CB4CEA2BA76 /* OuterBoolean.swift */; }; + D32130A2C8AC5B1FF21AF43BCC2B5217 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3F9B2E024A80A62FE090406312870D33 /* Foundation.framework */; }; + D5F1BBD60108412FD5C8B320D20B2993 /* Pods-SwaggerClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */; }; + D9657D5FFD53727FA47D8C6E8EE258A3 /* Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 074AB602E0D52FDEFEAC391A71BE362C /* Extensions.swift */; }; + EE614419EAB1923DFB520AE1E35D4D54 /* OuterString.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA8F6D8048F257672069D2008983C66D /* OuterString.swift */; }; + EFD264FC408EBF3BA2528E70B08DDD94 /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 66A46F517F0AF7E85A16D723F6406896 /* Notifications.swift */; }; + F37C6CFB2C08C9727ABCBD83044789EE /* List.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3BD1A4B33356A3CDF1DC77EE6C70D752 /* List.swift */; }; + F6BECD98B97CBFEBE2C96F0E9E72A6C0 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = E2F9510473F6FFD7AA66524DB16C2263 /* ResponseSerialization.swift */; }; + F8B3D3092ED0417E8CDF32033F6122F5 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = DFCB8C44DE758E906C0BCDA455937B85 /* Alamofire.swift */; }; + F9B80B148598B14AF1EFC8C590CDA38B /* ArrayOfArrayOfNumberOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = 81632F006BE1334AB9EE06329318FE60 /* ArrayOfArrayOfNumberOnly.swift */; }; + FA158D72EECF92FF935BB38B670E6CFE /* MapTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0C11B4AA97BB6048B4FFD944AEE16E85 /* MapTest.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 398B30E9B8AE28E1BDA1C6D292107659 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 872AA614769F12C7EFF56226C25D2EE5; + remoteInfo = PetstoreClient; + }; + DD169196715C246D6848CD38092BCBFE /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 88E9EC28B8B46C3631E6B242B50F4442; + remoteInfo = Alamofire; + }; + F9E1549CFEDAD61BECA92DB5B12B4019 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 88E9EC28B8B46C3631E6B242B50F4442; + remoteInfo = Alamofire; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 00ACB4396DD1B4E4539E4E81C1D7A14E /* Pods-SwaggerClientTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = "Pods-SwaggerClientTests.modulemap"; sourceTree = ""; }; + 02F28E719AA874BE9213D6CF8CE7E36B /* Pods-SwaggerClientTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClientTests-acknowledgements.plist"; sourceTree = ""; }; + 03597C306A2FB3B657BCFF572F74F4D4 /* EnumClass.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = EnumClass.swift; sourceTree = ""; }; + 04F47F5C9CDB035C5AFADEBA5BF44F1C /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; + 074AB602E0D52FDEFEAC391A71BE362C /* Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Extensions.swift; sourceTree = ""; }; + 076A25934936127AC03A2B855ACCDF5E /* NumberOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = NumberOnly.swift; sourceTree = ""; }; + 09F0396C30B906DB9EFEFBE97E091406 /* FakeclassnametagsAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = FakeclassnametagsAPI.swift; sourceTree = ""; }; + 0C11B4AA97BB6048B4FFD944AEE16E85 /* MapTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MapTest.swift; sourceTree = ""; }; + 0FCBF1EED873F61C6D46CE37FA5C39D3 /* DispatchQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Alamofire.swift"; path = "Source/DispatchQueue+Alamofire.swift"; sourceTree = ""; }; + 10156F0F886EC2F50651B704A3A6D742 /* StoreAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = StoreAPI.swift; sourceTree = ""; }; + 1024470B7B0142DFF1DF7E009ED9260D /* AlamofireImplementations.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AlamofireImplementations.swift; sourceTree = ""; }; + 1194146F3B5CFFECFE93B4E1DBB369BA /* Configuration.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Configuration.swift; sourceTree = ""; }; + 1365D135EB77F78D4ED50CB4CEA2BA76 /* OuterBoolean.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterBoolean.swift; sourceTree = ""; }; + 13A0A663B36A229C69D5274A83E93F88 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 14FA6FDDB70F2EFB58DE7D635F6946D4 /* APIHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIHelper.swift; sourceTree = ""; }; + 155538D91ACEEEDF82069ACF6C1A02E7 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; + 195D73DD9EF275A3C56569E2B1CA8026 /* SessionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDelegate.swift; path = Source/SessionDelegate.swift; sourceTree = ""; }; + 1DF0A17DD1DCF7B53BFC5E09C07C84B1 /* ReadOnlyFirst.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ReadOnlyFirst.swift; sourceTree = ""; }; + 1E230A0448B394DE26E688DAC8E6201E /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; + 22C1C119BCE81C53F76CAC2BE27C38E0 /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; + 237AE2907A722F87C756BCE4EF772C4C /* Name.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Name.swift; sourceTree = ""; }; + 249B8C876D70EDBA1D831123AE8EE0F8 /* EnumArrays.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = EnumArrays.swift; sourceTree = ""; }; + 25616A3E91482393BFD64C92FE312F0E /* JSONEncodingHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = JSONEncodingHelper.swift; sourceTree = ""; }; + 26189A4CE9006C2C9BB1AAE144CB191F /* ApiResponse.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ApiResponse.swift; sourceTree = ""; }; + 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClient-dummy.m"; sourceTree = ""; }; + 2A2DACCC87696D352D52090A939EE230 /* HasOnlyReadOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HasOnlyReadOnly.swift; sourceTree = ""; }; + 2AC757CC02124D5B17B6867095DBB70D /* SpecialModelName.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = SpecialModelName.swift; sourceTree = ""; }; + 2C877E250DAECFEE1CDABF476EF2B25C /* Models.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Models.swift; sourceTree = ""; }; + 2FF17440CCD2E1A69791A4AA23325AD5 /* Pods-SwaggerClient-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClient-acknowledgements.markdown"; sourceTree = ""; }; + 32B030D27CAC730C5EB0F22390645310 /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; + 3BD1A4B33356A3CDF1DC77EE6C70D752 /* List.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = List.swift; sourceTree = ""; }; + 3D60BC9955B4F7FFA62D7440CB385C11 /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; + 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClient-umbrella.h"; sourceTree = ""; }; + 3F16B43ABD2C8CD4A311AA1AB3B6C02F /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 3F9B2E024A80A62FE090406312870D33 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + 4199B3084AC46DC42D15500A1C964ECC /* EnumTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = EnumTest.swift; sourceTree = ""; }; + 43FC49AA70D3E2A84CAED9C37BE9C4B5 /* Pods-SwaggerClientTests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-frameworks.sh"; sourceTree = ""; }; + 44E7AE2E18EA6D3B341C419A4B2813F3 /* Animal.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Animal.swift; sourceTree = ""; }; + 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PetstoreClient-dummy.m"; sourceTree = ""; }; + 46CDAC6C1187C5467E576980E1062C8B /* SessionManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionManager.swift; path = Source/SessionManager.swift; sourceTree = ""; }; + 49A9B3BBFEA1CFFC48229E438EA64F9E /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Alamofire.framework; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 4AF006B0AD5765D1BFA8253C2DCBB126 /* AFError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AFError.swift; path = Source/AFError.swift; sourceTree = ""; }; + 4EE549F80BAFEF84BF212F0C315BC9BF /* MixedPropertiesAndAdditionalPropertiesClass.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MixedPropertiesAndAdditionalPropertiesClass.swift; sourceTree = ""; }; + 53AFC29FAA23E6156D43BCDE6F4EFEF7 /* ArrayTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ArrayTest.swift; sourceTree = ""; }; + 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; + 56F57C400928D9344121036AC8E4220D /* Return.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Return.swift; sourceTree = ""; }; + 5F54BE613A3988D2B9B506E8E6BEE157 /* AdditionalPropertiesClass.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AdditionalPropertiesClass.swift; sourceTree = ""; }; + 6639346628280A0D0FAD35196BF56108 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; + 66A46F517F0AF7E85A16D723F6406896 /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; + 6815FAC9A7B1782239E161DEEF54357F /* FakeAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = FakeAPI.swift; sourceTree = ""; }; + 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClientTests-dummy.m"; sourceTree = ""; }; + 688103EFA108516ADBACAFEF5DF33690 /* AnimalFarm.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AnimalFarm.swift; sourceTree = ""; }; + 6C0ACB269F0C836F1865A56C4AF7A07E /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_SwaggerClient.framework; path = "Pods-SwaggerClient.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + 6D9891D7095BE60AF5240E9C34D72085 /* ArrayOfNumberOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ArrayOfNumberOnly.swift; sourceTree = ""; }; + 706C7AFFE37BA158C3553250F4B5FAED /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 749C03CC31823CCADA2EFFFD06BF9E98 /* OuterComposite.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterComposite.swift; sourceTree = ""; }; + 798454EC551811276A6837CFCD4ADC8A /* APIs.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIs.swift; sourceTree = ""; }; + 7A0B8917069F5E9591DD17A113737986 /* PetAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PetAPI.swift; sourceTree = ""; }; + 7C8E63660D346FD8ED2A97242E74EA09 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 7D141D1953E5C6E67E362CE73090E48A /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = Alamofire.modulemap; sourceTree = ""; }; + 81632F006BE1334AB9EE06329318FE60 /* ArrayOfArrayOfNumberOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ArrayOfArrayOfNumberOnly.swift; sourceTree = ""; }; + 83A7AB2A1DA3632E843B3336E8D41A8E /* User.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = User.swift; sourceTree = ""; }; + 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; + 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; + 87882A1F5A92C8138D54545E51D51E6F /* Timeline.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeline.swift; path = Source/Timeline.swift; sourceTree = ""; }; + 897F0C201C5E0C66A1F1E359AECF4C9C /* PetstoreClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = PetstoreClient.framework; path = PetstoreClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 8A3C1EDF28A8B80DB140B65CDE450E09 /* Tag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Tag.swift; sourceTree = ""; }; + 8DD5A1187D47A6FFAC34F927DA186750 /* FormatTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = FormatTest.swift; sourceTree = ""; }; + 8F07EB5B38222CE6DB8CC7EC894E9E73 /* JSONEncodableEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = JSONEncodableEncoding.swift; sourceTree = ""; }; + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; + 975DAA5E04C557E1AA63DD67304C3466 /* Dog.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Dog.swift; sourceTree = ""; }; + 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-umbrella.h"; sourceTree = ""; }; + A01C037B4034EDA3D7955BC5E4E9D9D6 /* TaskDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TaskDelegate.swift; path = Source/TaskDelegate.swift; sourceTree = ""; }; + B029DBC43E49A740F12B5E4D2E6DD452 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; + B3A144887C8B13FD888B76AB096B0CA1 /* PetstoreClient-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-prefix.pch"; sourceTree = ""; }; + B44A27EFBB0DA84D738057B77F3413B1 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; + BCCA9CA7D9C1A2047BB93336C5708DFD /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; + BCF2D4DFF08D2A18E8C8FE4C4B4633FB /* Pods-SwaggerClient-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-frameworks.sh"; sourceTree = ""; }; + BE4C2705D4C3B913D44B4F26C6817A9C /* Capitalization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Capitalization.swift; sourceTree = ""; }; + C21C617FCA30726E782E8A67D0149138 /* Cat.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Cat.swift; sourceTree = ""; }; + C2A49053FD4226BD3513549F61A5944F /* OuterEnum.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterEnum.swift; sourceTree = ""; }; + C387A09BFC4D29F2B2C308F55CD2BFB7 /* CodableHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CodableHelper.swift; sourceTree = ""; }; + C82495B2E8EC7A268E3C9F068458102B /* Model200Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Model200Response.swift; sourceTree = ""; }; + CC87361174534D6D1655DD60071A3D83 /* UserAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = UserAPI.swift; sourceTree = ""; }; + D2841E5E2183846280B97F6E660DA26C /* Pods-SwaggerClient-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-resources.sh"; sourceTree = ""; }; + D679EE988B8B8734D2AAAAAFD25CDB9B /* ClassModel.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ClassModel.swift; sourceTree = ""; }; + DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PetstoreClient.xcconfig; sourceTree = ""; }; + DE081085EBFE0D670AAC85E74ACFDE8D /* Pet.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Pet.swift; sourceTree = ""; }; + DE164497A94DD3215ED4D1AE0D4703B1 /* Pods-SwaggerClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = "Pods-SwaggerClient.modulemap"; sourceTree = ""; }; + DFCB8C44DE758E906C0BCDA455937B85 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; + E1E4BCB344D3C100253B24B79421F00A /* Pods-SwaggerClient-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClient-acknowledgements.plist"; sourceTree = ""; }; + E2F9510473F6FFD7AA66524DB16C2263 /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; + E2FCD5F3D2C6621D4355CACB49530DB3 /* Client.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Client.swift; sourceTree = ""; }; + E3D1141B63DF38660CD6F3AC588A782B /* PetstoreClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = PetstoreClient.modulemap; sourceTree = ""; }; + E4E6F4A58FE7868CA2177D3AC79AD2FA /* Pods-SwaggerClientTests-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-resources.sh"; sourceTree = ""; }; + E5A8AA5F9EDED0A0BDDE7E830BF4AEE0 /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; + E6E0984D5B0599817A4E48CBAE9AAB9A /* OuterNumber.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterNumber.swift; sourceTree = ""; }; + E6F34CCF86067ED508C12C676E298C69 /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; + E80F4034540947434A69B02246F8ABBD /* Order.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Order.swift; sourceTree = ""; }; + EA3FFA48FB4D08FC02C47F71C0089CD9 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_SwaggerClientTests.framework; path = "Pods-SwaggerClientTests.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + EA8F6D8048F257672069D2008983C66D /* OuterString.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterString.swift; sourceTree = ""; }; + F0D4E00A8974E74325E9E53D456F9AD4 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClientTests-umbrella.h"; sourceTree = ""; }; + F69BC1C993ED1722CE6D63E07381785E /* Category.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Category.swift; sourceTree = ""; }; + FB170EFD14935F121CDE3211DB4C5CA3 /* Pods-SwaggerClientTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClientTests-acknowledgements.markdown"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 606C951710A3AAEA962F236422DE5D8C /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 1E2B97D6050471F3C9440D7AEA63029D /* Alamofire.framework in Frameworks */, + 29BBA290461F57554F9D63A842505063 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 87AF7EC7404199AC8C5D22375A6059BF /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + D32130A2C8AC5B1FF21AF43BCC2B5217 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 950A5F242B4B2310D94F7C4B29699C1E /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 2940D84FC5A76050A9281E6E49A8BDFC /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 99195E4207764744AEC07ECCBCD550EB /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + A04BFC558D69E7DBB68023C80A9CFE4E /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 02E57F930C8EDC9AD0C9932B5CAD1DC8 /* Classes */ = { + isa = PBXGroup; + children = ( + 6D8231D013B59DBC75D89B4D4FC1781D /* Swaggers */, + ); + name = Classes; + path = Classes; + sourceTree = ""; + }; + 200D10EB20F0397D47F022B50CF0433F /* Alamofire */ = { + isa = PBXGroup; + children = ( + 4AF006B0AD5765D1BFA8253C2DCBB126 /* AFError.swift */, + DFCB8C44DE758E906C0BCDA455937B85 /* Alamofire.swift */, + 0FCBF1EED873F61C6D46CE37FA5C39D3 /* DispatchQueue+Alamofire.swift */, + 155538D91ACEEEDF82069ACF6C1A02E7 /* MultipartFormData.swift */, + E5A8AA5F9EDED0A0BDDE7E830BF4AEE0 /* NetworkReachabilityManager.swift */, + 66A46F517F0AF7E85A16D723F6406896 /* Notifications.swift */, + 6639346628280A0D0FAD35196BF56108 /* ParameterEncoding.swift */, + 1E230A0448B394DE26E688DAC8E6201E /* Request.swift */, + 04F47F5C9CDB035C5AFADEBA5BF44F1C /* Response.swift */, + E2F9510473F6FFD7AA66524DB16C2263 /* ResponseSerialization.swift */, + 3D60BC9955B4F7FFA62D7440CB385C11 /* Result.swift */, + 32B030D27CAC730C5EB0F22390645310 /* ServerTrustPolicy.swift */, + 195D73DD9EF275A3C56569E2B1CA8026 /* SessionDelegate.swift */, + 46CDAC6C1187C5467E576980E1062C8B /* SessionManager.swift */, + A01C037B4034EDA3D7955BC5E4E9D9D6 /* TaskDelegate.swift */, + 87882A1F5A92C8138D54545E51D51E6F /* Timeline.swift */, + B029DBC43E49A740F12B5E4D2E6DD452 /* Validation.swift */, + 55F14F994FE7AB51F028BFE66CEF3106 /* Support Files */, + ); + name = Alamofire; + path = Alamofire; + sourceTree = ""; + }; + 22F52349E1BE90FC6E064DAAC9EA9612 /* Development Pods */ = { + isa = PBXGroup; + children = ( + E9F8459055B900A58FB97600A53E5D1C /* PetstoreClient */, + ); + name = "Development Pods"; + sourceTree = ""; + }; + 35F128EB69B6F7FB7DA93BBF6C130FAE /* Pods */ = { + isa = PBXGroup; + children = ( + 200D10EB20F0397D47F022B50CF0433F /* Alamofire */, + ); + name = Pods; + sourceTree = ""; + }; + 55F14F994FE7AB51F028BFE66CEF3106 /* Support Files */ = { + isa = PBXGroup; + children = ( + 7D141D1953E5C6E67E362CE73090E48A /* Alamofire.modulemap */, + E6F34CCF86067ED508C12C676E298C69 /* Alamofire.xcconfig */, + 22C1C119BCE81C53F76CAC2BE27C38E0 /* Alamofire-dummy.m */, + BCCA9CA7D9C1A2047BB93336C5708DFD /* Alamofire-prefix.pch */, + B44A27EFBB0DA84D738057B77F3413B1 /* Alamofire-umbrella.h */, + 13A0A663B36A229C69D5274A83E93F88 /* Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/Alamofire"; + sourceTree = ""; + }; + 59B91F212518421F271EBA85D5530651 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 706C7AFFE37BA158C3553250F4B5FAED /* Alamofire.framework */, + 7EB15E2C7EC8DD0E4C409FA3E5AC30A1 /* iOS */, + ); + name = Frameworks; + sourceTree = ""; + }; + 6D8231D013B59DBC75D89B4D4FC1781D /* Swaggers */ = { + isa = PBXGroup; + children = ( + 1024470B7B0142DFF1DF7E009ED9260D /* AlamofireImplementations.swift */, + 14FA6FDDB70F2EFB58DE7D635F6946D4 /* APIHelper.swift */, + 798454EC551811276A6837CFCD4ADC8A /* APIs.swift */, + C387A09BFC4D29F2B2C308F55CD2BFB7 /* CodableHelper.swift */, + 1194146F3B5CFFECFE93B4E1DBB369BA /* Configuration.swift */, + 074AB602E0D52FDEFEAC391A71BE362C /* Extensions.swift */, + 8F07EB5B38222CE6DB8CC7EC894E9E73 /* JSONEncodableEncoding.swift */, + 25616A3E91482393BFD64C92FE312F0E /* JSONEncodingHelper.swift */, + 2C877E250DAECFEE1CDABF476EF2B25C /* Models.swift */, + 79B0B5EF51D76393D11143FD83D1F224 /* APIs */, + BDF2B05EE3EDF246153D7BDD1A3D065A /* Models */, + ); + name = Swaggers; + path = Swaggers; + sourceTree = ""; + }; + 79B0B5EF51D76393D11143FD83D1F224 /* APIs */ = { + isa = PBXGroup; + children = ( + 6815FAC9A7B1782239E161DEEF54357F /* FakeAPI.swift */, + 09F0396C30B906DB9EFEFBE97E091406 /* FakeclassnametagsAPI.swift */, + 7A0B8917069F5E9591DD17A113737986 /* PetAPI.swift */, + 10156F0F886EC2F50651B704A3A6D742 /* StoreAPI.swift */, + CC87361174534D6D1655DD60071A3D83 /* UserAPI.swift */, + ); + name = APIs; + path = APIs; + sourceTree = ""; + }; + 7DB346D0F39D3F0E887471402A8071AB = { + isa = PBXGroup; + children = ( + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, + 22F52349E1BE90FC6E064DAAC9EA9612 /* Development Pods */, + 59B91F212518421F271EBA85D5530651 /* Frameworks */, + 35F128EB69B6F7FB7DA93BBF6C130FAE /* Pods */, + 9BBD96A0F02B8F92DD3659B2DCDF1A8C /* Products */, + C1A60D10CED0E61146591438999C7502 /* Targets Support Files */, + ); + sourceTree = ""; + }; + 7EB15E2C7EC8DD0E4C409FA3E5AC30A1 /* iOS */ = { + isa = PBXGroup; + children = ( + 3F9B2E024A80A62FE090406312870D33 /* Foundation.framework */, + ); + name = iOS; + sourceTree = ""; + }; + 88CE2B3F08C34DDB098AD8A5DCC1DF1E /* Pods-SwaggerClient */ = { + isa = PBXGroup; + children = ( + 7C8E63660D346FD8ED2A97242E74EA09 /* Info.plist */, + DE164497A94DD3215ED4D1AE0D4703B1 /* Pods-SwaggerClient.modulemap */, + 2FF17440CCD2E1A69791A4AA23325AD5 /* Pods-SwaggerClient-acknowledgements.markdown */, + E1E4BCB344D3C100253B24B79421F00A /* Pods-SwaggerClient-acknowledgements.plist */, + 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */, + BCF2D4DFF08D2A18E8C8FE4C4B4633FB /* Pods-SwaggerClient-frameworks.sh */, + D2841E5E2183846280B97F6E660DA26C /* Pods-SwaggerClient-resources.sh */, + 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */, + 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */, + 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */, + ); + name = "Pods-SwaggerClient"; + path = "Target Support Files/Pods-SwaggerClient"; + sourceTree = ""; + }; + 8F6D133867EE63820DFB7E83F4C51252 /* Support Files */ = { + isa = PBXGroup; + children = ( + F0D4E00A8974E74325E9E53D456F9AD4 /* Info.plist */, + E3D1141B63DF38660CD6F3AC588A782B /* PetstoreClient.modulemap */, + DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */, + 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */, + B3A144887C8B13FD888B76AB096B0CA1 /* PetstoreClient-prefix.pch */, + 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */, + ); + name = "Support Files"; + path = "SwaggerClientTests/Pods/Target Support Files/PetstoreClient"; + sourceTree = ""; + }; + 9BBD96A0F02B8F92DD3659B2DCDF1A8C /* Products */ = { + isa = PBXGroup; + children = ( + 49A9B3BBFEA1CFFC48229E438EA64F9E /* Alamofire.framework */, + 897F0C201C5E0C66A1F1E359AECF4C9C /* PetstoreClient.framework */, + 6C0ACB269F0C836F1865A56C4AF7A07E /* Pods_SwaggerClient.framework */, + EA3FFA48FB4D08FC02C47F71C0089CD9 /* Pods_SwaggerClientTests.framework */, + ); + name = Products; + sourceTree = ""; + }; + BDF2B05EE3EDF246153D7BDD1A3D065A /* Models */ = { + isa = PBXGroup; + children = ( + 5F54BE613A3988D2B9B506E8E6BEE157 /* AdditionalPropertiesClass.swift */, + 44E7AE2E18EA6D3B341C419A4B2813F3 /* Animal.swift */, + 688103EFA108516ADBACAFEF5DF33690 /* AnimalFarm.swift */, + 26189A4CE9006C2C9BB1AAE144CB191F /* ApiResponse.swift */, + 81632F006BE1334AB9EE06329318FE60 /* ArrayOfArrayOfNumberOnly.swift */, + 6D9891D7095BE60AF5240E9C34D72085 /* ArrayOfNumberOnly.swift */, + 53AFC29FAA23E6156D43BCDE6F4EFEF7 /* ArrayTest.swift */, + BE4C2705D4C3B913D44B4F26C6817A9C /* Capitalization.swift */, + C21C617FCA30726E782E8A67D0149138 /* Cat.swift */, + F69BC1C993ED1722CE6D63E07381785E /* Category.swift */, + D679EE988B8B8734D2AAAAAFD25CDB9B /* ClassModel.swift */, + E2FCD5F3D2C6621D4355CACB49530DB3 /* Client.swift */, + 975DAA5E04C557E1AA63DD67304C3466 /* Dog.swift */, + 249B8C876D70EDBA1D831123AE8EE0F8 /* EnumArrays.swift */, + 03597C306A2FB3B657BCFF572F74F4D4 /* EnumClass.swift */, + 4199B3084AC46DC42D15500A1C964ECC /* EnumTest.swift */, + 8DD5A1187D47A6FFAC34F927DA186750 /* FormatTest.swift */, + 2A2DACCC87696D352D52090A939EE230 /* HasOnlyReadOnly.swift */, + 3BD1A4B33356A3CDF1DC77EE6C70D752 /* List.swift */, + 0C11B4AA97BB6048B4FFD944AEE16E85 /* MapTest.swift */, + 4EE549F80BAFEF84BF212F0C315BC9BF /* MixedPropertiesAndAdditionalPropertiesClass.swift */, + C82495B2E8EC7A268E3C9F068458102B /* Model200Response.swift */, + 237AE2907A722F87C756BCE4EF772C4C /* Name.swift */, + 076A25934936127AC03A2B855ACCDF5E /* NumberOnly.swift */, + E80F4034540947434A69B02246F8ABBD /* Order.swift */, + 1365D135EB77F78D4ED50CB4CEA2BA76 /* OuterBoolean.swift */, + 749C03CC31823CCADA2EFFFD06BF9E98 /* OuterComposite.swift */, + C2A49053FD4226BD3513549F61A5944F /* OuterEnum.swift */, + E6E0984D5B0599817A4E48CBAE9AAB9A /* OuterNumber.swift */, + EA8F6D8048F257672069D2008983C66D /* OuterString.swift */, + DE081085EBFE0D670AAC85E74ACFDE8D /* Pet.swift */, + 1DF0A17DD1DCF7B53BFC5E09C07C84B1 /* ReadOnlyFirst.swift */, + 56F57C400928D9344121036AC8E4220D /* Return.swift */, + 2AC757CC02124D5B17B6867095DBB70D /* SpecialModelName.swift */, + 8A3C1EDF28A8B80DB140B65CDE450E09 /* Tag.swift */, + 83A7AB2A1DA3632E843B3336E8D41A8E /* User.swift */, + ); + name = Models; + path = Models; + sourceTree = ""; + }; + C1A60D10CED0E61146591438999C7502 /* Targets Support Files */ = { + isa = PBXGroup; + children = ( + 88CE2B3F08C34DDB098AD8A5DCC1DF1E /* Pods-SwaggerClient */, + D6D0CD30E3EAF2ED10AE0CBC07506C5A /* Pods-SwaggerClientTests */, + ); + name = "Targets Support Files"; + sourceTree = ""; + }; + D6D0CD30E3EAF2ED10AE0CBC07506C5A /* Pods-SwaggerClientTests */ = { + isa = PBXGroup; + children = ( + 3F16B43ABD2C8CD4A311AA1AB3B6C02F /* Info.plist */, + 00ACB4396DD1B4E4539E4E81C1D7A14E /* Pods-SwaggerClientTests.modulemap */, + FB170EFD14935F121CDE3211DB4C5CA3 /* Pods-SwaggerClientTests-acknowledgements.markdown */, + 02F28E719AA874BE9213D6CF8CE7E36B /* Pods-SwaggerClientTests-acknowledgements.plist */, + 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */, + 43FC49AA70D3E2A84CAED9C37BE9C4B5 /* Pods-SwaggerClientTests-frameworks.sh */, + E4E6F4A58FE7868CA2177D3AC79AD2FA /* Pods-SwaggerClientTests-resources.sh */, + F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */, + 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */, + 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */, + ); + name = "Pods-SwaggerClientTests"; + path = "Target Support Files/Pods-SwaggerClientTests"; + sourceTree = ""; + }; + E73D9BF152C59F341559DE62A3143721 /* PetstoreClient */ = { + isa = PBXGroup; + children = ( + 02E57F930C8EDC9AD0C9932B5CAD1DC8 /* Classes */, + ); + name = PetstoreClient; + path = PetstoreClient; + sourceTree = ""; + }; + E9F8459055B900A58FB97600A53E5D1C /* PetstoreClient */ = { + isa = PBXGroup; + children = ( + E73D9BF152C59F341559DE62A3143721 /* PetstoreClient */, + 8F6D133867EE63820DFB7E83F4C51252 /* Support Files */, + ); + name = PetstoreClient; + path = ../..; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 1353AC7A6419F876B294A55E5550D1E4 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 31F8B86E3672D0B828B6352C875649C4 /* Pods-SwaggerClientTests-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 2EA2C52BF67117065AE36B4A6D8D6377 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 75332AEFA1C56AD923C581FB7CC4B580 /* PetstoreClient-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + B4002B6E97835FDCCAA5963EFE09A3E0 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 1B9EDEDC964E6B08F78920B4F4B9DB84 /* Alamofire-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + DC071B9D59E4680147F481F53FBCE180 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 424F25F3C040D2362DD353C82A86740B /* Pods-SwaggerClient-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 41903051A113E887E262FB29130EB187 /* Pods-SwaggerClient */ = { + isa = PBXNativeTarget; + buildConfigurationList = 5DE561894A3D2FE43769BF10CB87D407 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClient" */; + buildPhases = ( + 9A1B5AE4D97D5E0097B7054904D06663 /* Sources */, + 950A5F242B4B2310D94F7C4B29699C1E /* Frameworks */, + DC071B9D59E4680147F481F53FBCE180 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + AC31F7EF81A7A1C4862B1BA6879CEC1C /* PBXTargetDependency */, + 374AD22F26F7E9801AB27C2FCBBF4EC9 /* PBXTargetDependency */, + ); + name = "Pods-SwaggerClient"; + productName = "Pods-SwaggerClient"; + productReference = 6C0ACB269F0C836F1865A56C4AF7A07E /* Pods_SwaggerClient.framework */; + productType = "com.apple.product-type.framework"; + }; + 872AA614769F12C7EFF56226C25D2EE5 /* PetstoreClient */ = { + isa = PBXNativeTarget; + buildConfigurationList = 5F49FB411DAA9B738ED9CDC2D3A52892 /* Build configuration list for PBXNativeTarget "PetstoreClient" */; + buildPhases = ( + E4E9EABE96879C615522F4577C46D492 /* Sources */, + 606C951710A3AAEA962F236422DE5D8C /* Frameworks */, + 2EA2C52BF67117065AE36B4A6D8D6377 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + 79FA2B89589FCBFA2C873E411E00D832 /* PBXTargetDependency */, + ); + name = PetstoreClient; + productName = PetstoreClient; + productReference = 897F0C201C5E0C66A1F1E359AECF4C9C /* PetstoreClient.framework */; + productType = "com.apple.product-type.framework"; + }; + 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */ = { + isa = PBXNativeTarget; + buildConfigurationList = 419E5D95491847CD79841B971A8A3277 /* Build configuration list for PBXNativeTarget "Alamofire" */; + buildPhases = ( + 32B9974868188C4803318E36329C87FE /* Sources */, + 99195E4207764744AEC07ECCBCD550EB /* Frameworks */, + B4002B6E97835FDCCAA5963EFE09A3E0 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Alamofire; + productName = Alamofire; + productReference = 49A9B3BBFEA1CFFC48229E438EA64F9E /* Alamofire.framework */; + productType = "com.apple.product-type.framework"; + }; + F3DF8DD6DBDCB07B04D7B1CC8A462562 /* Pods-SwaggerClientTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = B462F7329881FF6565EF44016BE2B959 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClientTests" */; + buildPhases = ( + BDFDEE831A91E115AA482B4E9E9B5CC8 /* Sources */, + 87AF7EC7404199AC8C5D22375A6059BF /* Frameworks */, + 1353AC7A6419F876B294A55E5550D1E4 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "Pods-SwaggerClientTests"; + productName = "Pods-SwaggerClientTests"; + productReference = EA3FFA48FB4D08FC02C47F71C0089CD9 /* Pods_SwaggerClientTests.framework */; + productType = "com.apple.product-type.framework"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + D41D8CD98F00B204E9800998ECF8427E /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0730; + LastUpgradeCheck = 0700; + }; + buildConfigurationList = 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = 7DB346D0F39D3F0E887471402A8071AB; + productRefGroup = 9BBD96A0F02B8F92DD3659B2DCDF1A8C /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */, + 872AA614769F12C7EFF56226C25D2EE5 /* PetstoreClient */, + 41903051A113E887E262FB29130EB187 /* Pods-SwaggerClient */, + F3DF8DD6DBDCB07B04D7B1CC8A462562 /* Pods-SwaggerClientTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXSourcesBuildPhase section */ + 32B9974868188C4803318E36329C87FE /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 9ED2BB2981896E0A39EFA365503F58CE /* AFError.swift in Sources */, + A9EEEA7477981DEEBC72432DE9990A4B /* Alamofire-dummy.m in Sources */, + F8B3D3092ED0417E8CDF32033F6122F5 /* Alamofire.swift in Sources */, + 61200D01A1855D7920CEF835C8BE00B0 /* DispatchQueue+Alamofire.swift in Sources */, + B65FCF589DA398C3EFE0128064E510EC /* MultipartFormData.swift in Sources */, + A2A6F71B727312BD45CC7A4AAD7B0AB7 /* NetworkReachabilityManager.swift in Sources */, + EFD264FC408EBF3BA2528E70B08DDD94 /* Notifications.swift in Sources */, + BE5C67A07E289FE1F9BE27335B159997 /* ParameterEncoding.swift in Sources */, + 5387216E723A3C68E851CA15573CDD71 /* Request.swift in Sources */, + CB6D60925223897FFA2662667DF83E8A /* Response.swift in Sources */, + F6BECD98B97CBFEBE2C96F0E9E72A6C0 /* ResponseSerialization.swift in Sources */, + 7D8CC01E8C9EFFF9F4D65406CDE0AB66 /* Result.swift in Sources */, + 62F65AD8DC4F0F9610F4B8B4738EC094 /* ServerTrustPolicy.swift in Sources */, + 7B5FE28C7EA4122B0598738E54DBEBD8 /* SessionDelegate.swift in Sources */, + AE1EF48399533730D0066E04B22CA2D6 /* SessionManager.swift in Sources */, + 3626B94094672CB1C9DEA32B9F9502E1 /* TaskDelegate.swift in Sources */, + 10EB23E9ECC4B33E16933BB1EA560B6A /* Timeline.swift in Sources */, + BBEFE2F9CEB73DC7BD97FFA66A0D9D4F /* Validation.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9A1B5AE4D97D5E0097B7054904D06663 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + D5F1BBD60108412FD5C8B320D20B2993 /* Pods-SwaggerClient-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + BDFDEE831A91E115AA482B4E9E9B5CC8 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 897985FA042CD12B825C3032898FAB26 /* Pods-SwaggerClientTests-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E4E9EABE96879C615522F4577C46D492 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 94B455FDE2B057DB680F439EA3FD1B49 /* AdditionalPropertiesClass.swift in Sources */, + 24FFD130F7E23492281B79C5C678F00D /* AlamofireImplementations.swift in Sources */, + C05B6F5687193D4F8C45A876DD05D53E /* Animal.swift in Sources */, + 8CBE860E26B3E63F905AABB8C2ED8408 /* AnimalFarm.swift in Sources */, + 785570E189782F883FC7F30096107F05 /* APIHelper.swift in Sources */, + 700AFFD25A3F79F704E1F48E1090C719 /* ApiResponse.swift in Sources */, + A6546161061DFBD9AD9CD2669B3407DD /* APIs.swift in Sources */, + F9B80B148598B14AF1EFC8C590CDA38B /* ArrayOfArrayOfNumberOnly.swift in Sources */, + 9DF1DB10A8D8AD5D760AD2119464BBFA /* ArrayOfNumberOnly.swift in Sources */, + A73E115FCBAE1F29A37D5327AE87AAB8 /* ArrayTest.swift in Sources */, + 97809A3EC41B70910367804F24749488 /* Capitalization.swift in Sources */, + 798B0EDE6CDDDFA67A576CC5D7356197 /* Cat.swift in Sources */, + 2DEA81B2292287FEE1BC4A520801F675 /* Category.swift in Sources */, + 0D33BB30417B9584629B6D880037AA2B /* ClassModel.swift in Sources */, + 804A773AC1F6CAD0833113365C437ED6 /* Client.swift in Sources */, + 9ED1C3E564D542971480A55F74192BA2 /* CodableHelper.swift in Sources */, + 39755FB5994F45FBD67C9ADFD5915EF2 /* Configuration.swift in Sources */, + 079F2BD52F24416F7C5A53877F54566A /* Dog.swift in Sources */, + 1151CDE98B5CB5F152ED39BF798EF5CF /* EnumArrays.swift in Sources */, + A19592FE4371E4FCDAAB8AEE09AB93B9 /* EnumClass.swift in Sources */, + 1B13BFD9084781D7ED2E079E6BF2C557 /* EnumTest.swift in Sources */, + D9657D5FFD53727FA47D8C6E8EE258A3 /* Extensions.swift in Sources */, + 1CFDE72D9E7E9750A9ADE03AB4669311 /* FakeAPI.swift in Sources */, + 4378EAAAA7D2FDACD110A1ED9D2FED5F /* FakeclassnametagsAPI.swift in Sources */, + 2D5A60538984183CDF16344E07DE6016 /* FormatTest.swift in Sources */, + B0A93172B99BF60154ED6242AFBE4026 /* HasOnlyReadOnly.swift in Sources */, + A563CBF0CB0A2D620BCE488727AFE9BC /* JSONEncodableEncoding.swift in Sources */, + 154A6488A4E591935A82473995C15AE4 /* JSONEncodingHelper.swift in Sources */, + F37C6CFB2C08C9727ABCBD83044789EE /* List.swift in Sources */, + FA158D72EECF92FF935BB38B670E6CFE /* MapTest.swift in Sources */, + 22FDE110EA91A85020A5B47486558282 /* MixedPropertiesAndAdditionalPropertiesClass.swift in Sources */, + 9D4EC73C4EC0F4CA643BFB0F744E206E /* Model200Response.swift in Sources */, + 4E168284FE74373DE791FA46610F6E85 /* Models.swift in Sources */, + 858A507A04D7EBD392B5E38BFA5C0FB1 /* Name.swift in Sources */, + 98A62599B00ECECEE6693F10291DCA8E /* NumberOnly.swift in Sources */, + 8B3DB4230FDB986C273707551D5C098D /* Order.swift in Sources */, + D319019CE9A48494F3ED480F1226517A /* OuterBoolean.swift in Sources */, + 342645FD19CD3977B12C869E662DF658 /* OuterComposite.swift in Sources */, + 253BED146B97E5F268DB986D0EC87081 /* OuterEnum.swift in Sources */, + 97D4E3413AADDB57435C6E01E40F1737 /* OuterNumber.swift in Sources */, + EE614419EAB1923DFB520AE1E35D4D54 /* OuterString.swift in Sources */, + 4AE57833EC2315CC8EDA4864CAD7382B /* Pet.swift in Sources */, + A7F2C30678B7926A18C64F71A5CFDB3E /* PetAPI.swift in Sources */, + D102CB4FA078626BF684F476910012A1 /* PetstoreClient-dummy.m in Sources */, + 27BF2E059FCCB3CDA349738B75A9EDD3 /* ReadOnlyFirst.swift in Sources */, + D000C65F968C44B544101279E763C0C9 /* Return.swift in Sources */, + A63D913EAA7D50833B860D9FB011E761 /* SpecialModelName.swift in Sources */, + 491FD17DCEA4455874451D174A9A182E /* StoreAPI.swift in Sources */, + 7EA0B4343115F6BD6062C1A3C5924380 /* Tag.swift in Sources */, + 483C65BB55BCA70C8B65BBD266151A1C /* User.swift in Sources */, + B746D752789DABA80AC0ABF066B719BB /* UserAPI.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 374AD22F26F7E9801AB27C2FCBBF4EC9 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = PetstoreClient; + target = 872AA614769F12C7EFF56226C25D2EE5 /* PetstoreClient */; + targetProxy = 398B30E9B8AE28E1BDA1C6D292107659 /* PBXContainerItemProxy */; + }; + 79FA2B89589FCBFA2C873E411E00D832 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */; + targetProxy = DD169196715C246D6848CD38092BCBFE /* PBXContainerItemProxy */; + }; + AC31F7EF81A7A1C4862B1BA6879CEC1C /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */; + targetProxy = F9E1549CFEDAD61BECA92DB5B12B4019 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 0A29B6F510198AF64EFD762EF6FA97A5 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = E6F34CCF86067ED508C12C676E298C69 /* Alamofire.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 42A81EAE5BACD74C1473CE27A30E0600 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/PetstoreClient/PetstoreClient-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/PetstoreClient/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/PetstoreClient/PetstoreClient.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = PetstoreClient; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 72DE84F6EA4EE4A32348CCB7D5F4B968 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClient/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.2; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClient; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 82D3AD5A5FD240EEC1B1FEFF53FE2566 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClient/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.2; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClient; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + A658260C69CC5FE8D2D4A6E6D37E820A /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClientTests/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.2; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClientTests; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + AADB9822762AD81BBAE83335B2AB1EB0 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGNING_REQUIRED = NO; + COPY_PHASE_STRIP = YES; + ENABLE_NS_ASSERTIONS = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_RELEASE=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.2; + PROVISIONING_PROFILE_SPECIFIER = NO_SIGNING/; + STRIP_INSTALLED_PRODUCT = NO; + SYMROOT = "${SRCROOT}/../build"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + B1B5EB0850F98CB5AECDB015B690777F /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGNING_REQUIRED = NO; + COPY_PHASE_STRIP = NO; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_DEBUG=1", + "DEBUG=1", + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.2; + ONLY_ACTIVE_ARCH = YES; + PROVISIONING_PROFILE_SPECIFIER = NO_SIGNING/; + STRIP_INSTALLED_PRODUCT = NO; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Debug; + }; + C17C4519E8C8AFCD2A0153817F672A34 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/PetstoreClient/PetstoreClient-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/PetstoreClient/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/PetstoreClient/PetstoreClient.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = PetstoreClient; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + EFA70F2EAB610CE73EB4B75FFD679D69 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClientTests/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.2; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClientTests; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + F383079BFBF927813EA3613CFB679FDE /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = E6F34CCF86067ED508C12C676E298C69 /* Alamofire.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + B1B5EB0850F98CB5AECDB015B690777F /* Debug */, + AADB9822762AD81BBAE83335B2AB1EB0 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 419E5D95491847CD79841B971A8A3277 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + F383079BFBF927813EA3613CFB679FDE /* Debug */, + 0A29B6F510198AF64EFD762EF6FA97A5 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 5DE561894A3D2FE43769BF10CB87D407 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClient" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 72DE84F6EA4EE4A32348CCB7D5F4B968 /* Debug */, + 82D3AD5A5FD240EEC1B1FEFF53FE2566 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 5F49FB411DAA9B738ED9CDC2D3A52892 /* Build configuration list for PBXNativeTarget "PetstoreClient" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 42A81EAE5BACD74C1473CE27A30E0600 /* Debug */, + C17C4519E8C8AFCD2A0153817F672A34 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + B462F7329881FF6565EF44016BE2B959 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClientTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + EFA70F2EAB610CE73EB4B75FFD679D69 /* Debug */, + A658260C69CC5FE8D2D4A6E6D37E820A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = D41D8CD98F00B204E9800998ECF8427E /* Project object */; +} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-dummy.m b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-dummy.m new file mode 100644 index 0000000000..a6c4594242 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Alamofire : NSObject +@end +@implementation PodsDummy_Alamofire +@end diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch new file mode 100644 index 0000000000..aa992a4adb --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch @@ -0,0 +1,4 @@ +#ifdef __OBJC__ +#import +#endif + diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h new file mode 100644 index 0000000000..02327b85e8 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h @@ -0,0 +1,8 @@ +#ifdef __OBJC__ +#import +#endif + + +FOUNDATION_EXPORT double AlamofireVersionNumber; +FOUNDATION_EXPORT const unsigned char AlamofireVersionString[]; + diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.modulemap b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.modulemap new file mode 100644 index 0000000000..d1f125fab6 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.modulemap @@ -0,0 +1,6 @@ +framework module Alamofire { + umbrella header "Alamofire-umbrella.h" + + export * + module * { export * } +} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.xcconfig b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.xcconfig new file mode 100644 index 0000000000..772ef0b2bc --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.xcconfig @@ -0,0 +1,9 @@ +CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/Alamofire +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist new file mode 100644 index 0000000000..c1c4a98b9a --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 4.5.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/Info.plist b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/Info.plist new file mode 100644 index 0000000000..cba258550b --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 0.0.1 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-dummy.m b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-dummy.m new file mode 100644 index 0000000000..749b412f85 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_PetstoreClient : NSObject +@end +@implementation PodsDummy_PetstoreClient +@end diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-prefix.pch b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-prefix.pch new file mode 100644 index 0000000000..aa992a4adb --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-prefix.pch @@ -0,0 +1,4 @@ +#ifdef __OBJC__ +#import +#endif + diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-umbrella.h b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-umbrella.h new file mode 100644 index 0000000000..435b682a10 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-umbrella.h @@ -0,0 +1,8 @@ +#ifdef __OBJC__ +#import +#endif + + +FOUNDATION_EXPORT double PetstoreClientVersionNumber; +FOUNDATION_EXPORT const unsigned char PetstoreClientVersionString[]; + diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.modulemap b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.modulemap new file mode 100644 index 0000000000..7fdfc46cf7 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.modulemap @@ -0,0 +1,6 @@ +framework module PetstoreClient { + umbrella header "PetstoreClient-umbrella.h" + + export * + module * { export * } +} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.xcconfig b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.xcconfig new file mode 100644 index 0000000000..323b0fc6f1 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.xcconfig @@ -0,0 +1,10 @@ +CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/PetstoreClient +FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Info.plist b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Info.plist new file mode 100644 index 0000000000..2243fe6e27 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.markdown b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.markdown new file mode 100644 index 0000000000..e04b910c37 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.markdown @@ -0,0 +1,26 @@ +# Acknowledgements +This application makes use of the following third party libraries: + +## Alamofire + +Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +Generated by CocoaPods - https://cocoapods.org diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.plist b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.plist new file mode 100644 index 0000000000..931747768b --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.plist @@ -0,0 +1,58 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + 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. + + License + MIT + Title + Alamofire + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-dummy.m b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-dummy.m new file mode 100644 index 0000000000..6236440163 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_SwaggerClient : NSObject +@end +@implementation PodsDummy_Pods_SwaggerClient +@end diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh new file mode 100755 index 0000000000..d3d3acc302 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh @@ -0,0 +1,93 @@ +#!/bin/sh +set -e + +echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" +mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + +SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" + +install_framework() +{ + if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then + local source="${BUILT_PRODUCTS_DIR}/$1" + elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then + local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" + elif [ -r "$1" ]; then + local source="$1" + fi + + local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + + if [ -L "${source}" ]; then + echo "Symlinked..." + source="$(readlink "${source}")" + fi + + # use filter instead of exclude so missing patterns dont' throw errors + echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" + rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" + + local basename + basename="$(basename -s .framework "$1")" + binary="${destination}/${basename}.framework/${basename}" + if ! [ -r "$binary" ]; then + binary="${destination}/${basename}" + fi + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then + strip_invalid_archs "$binary" + fi + + # Resign the code if required by the build settings to avoid unstable apps + code_sign_if_enabled "${destination}/$(basename "$1")" + + # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. + if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then + local swift_runtime_libs + swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) + for lib in $swift_runtime_libs; do + echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" + rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" + code_sign_if_enabled "${destination}/${lib}" + done + fi +} + +# Signs a framework with the provided identity +code_sign_if_enabled() { + if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then + # Use the current code_sign_identitiy + echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" + echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements \"$1\"" + /usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements "$1" + fi +} + +# Strip invalid architectures +strip_invalid_archs() { + binary="$1" + # Get architectures for current file + archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)" + stripped="" + for arch in $archs; do + if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then + # Strip non-valid architectures in-place + lipo -remove "$arch" -output "$binary" "$binary" || exit 1 + stripped="$stripped $arch" + fi + done + if [[ "$stripped" ]]; then + echo "Stripped $binary of architectures:$stripped" + fi +} + + +if [[ "$CONFIGURATION" == "Debug" ]]; then + install_framework "$BUILT_PRODUCTS_DIR/Alamofire/Alamofire.framework" + install_framework "$BUILT_PRODUCTS_DIR/PetstoreClient/PetstoreClient.framework" +fi +if [[ "$CONFIGURATION" == "Release" ]]; then + install_framework "$BUILT_PRODUCTS_DIR/Alamofire/Alamofire.framework" + install_framework "$BUILT_PRODUCTS_DIR/PetstoreClient/PetstoreClient.framework" +fi diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh new file mode 100755 index 0000000000..25e9d37757 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh @@ -0,0 +1,96 @@ +#!/bin/sh +set -e + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + +RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt +> "$RESOURCES_TO_COPY" + +XCASSET_FILES=() + +case "${TARGETED_DEVICE_FAMILY}" in + 1,2) + TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone" + ;; + 1) + TARGET_DEVICE_ARGS="--target-device iphone" + ;; + 2) + TARGET_DEVICE_ARGS="--target-device ipad" + ;; + *) + TARGET_DEVICE_ARGS="--target-device mac" + ;; +esac + +install_resource() +{ + if [[ "$1" = /* ]] ; then + RESOURCE_PATH="$1" + else + RESOURCE_PATH="${PODS_ROOT}/$1" + fi + if [[ ! -e "$RESOURCE_PATH" ]] ; then + cat << EOM +error: Resource "$RESOURCE_PATH" not found. Run 'pod install' to update the copy resources script. +EOM + exit 1 + fi + case $RESOURCE_PATH in + *.storyboard) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.xib) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.framework) + echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + echo "rsync -av $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + rsync -av "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + ;; + *.xcdatamodel) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH"`.mom\"" + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodel`.mom" + ;; + *.xcdatamodeld) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd\"" + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd" + ;; + *.xcmappingmodel) + echo "xcrun mapc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm\"" + xcrun mapc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm" + ;; + *.xcassets) + ABSOLUTE_XCASSET_FILE="$RESOURCE_PATH" + XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE") + ;; + *) + echo "$RESOURCE_PATH" + echo "$RESOURCE_PATH" >> "$RESOURCES_TO_COPY" + ;; + esac +} + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +if [[ "${ACTION}" == "install" ]] && [[ "${SKIP_INSTALL}" == "NO" ]]; then + mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi +rm -f "$RESOURCES_TO_COPY" + +if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "$XCASSET_FILES" ] +then + # Find all other xcassets (this unfortunately includes those of path pods and other targets). + OTHER_XCASSETS=$(find "$PWD" -iname "*.xcassets" -type d) + while read line; do + if [[ $line != "${PODS_ROOT}*" ]]; then + XCASSET_FILES+=("$line") + fi + done <<<"$OTHER_XCASSETS" + + printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-umbrella.h b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-umbrella.h new file mode 100644 index 0000000000..2bdb03cd93 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-umbrella.h @@ -0,0 +1,8 @@ +#ifdef __OBJC__ +#import +#endif + + +FOUNDATION_EXPORT double Pods_SwaggerClientVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_SwaggerClientVersionString[]; + diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig new file mode 100644 index 0000000000..a5ecec32a8 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig @@ -0,0 +1,11 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +EMBEDDED_CONTENT_CONTAINS_SWIFT = YES +FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient/PetstoreClient.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "PetstoreClient" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT}/Pods diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap new file mode 100644 index 0000000000..ef919b6c0d --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap @@ -0,0 +1,6 @@ +framework module Pods_SwaggerClient { + umbrella header "Pods-SwaggerClient-umbrella.h" + + export * + module * { export * } +} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig new file mode 100644 index 0000000000..a5ecec32a8 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig @@ -0,0 +1,11 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +EMBEDDED_CONTENT_CONTAINS_SWIFT = YES +FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient/PetstoreClient.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "PetstoreClient" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT}/Pods diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Info.plist b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Info.plist new file mode 100644 index 0000000000..2243fe6e27 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-acknowledgements.markdown b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-acknowledgements.markdown new file mode 100644 index 0000000000..102af75385 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-acknowledgements.markdown @@ -0,0 +1,3 @@ +# Acknowledgements +This application makes use of the following third party libraries: +Generated by CocoaPods - https://cocoapods.org diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-acknowledgements.plist b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-acknowledgements.plist new file mode 100644 index 0000000000..7acbad1eab --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-acknowledgements.plist @@ -0,0 +1,29 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-dummy.m b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-dummy.m new file mode 100644 index 0000000000..bb17fa2b80 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_SwaggerClientTests : NSObject +@end +@implementation PodsDummy_Pods_SwaggerClientTests +@end diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh new file mode 100755 index 0000000000..893c16a631 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh @@ -0,0 +1,84 @@ +#!/bin/sh +set -e + +echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" +mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + +SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" + +install_framework() +{ + if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then + local source="${BUILT_PRODUCTS_DIR}/$1" + elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then + local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" + elif [ -r "$1" ]; then + local source="$1" + fi + + local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + + if [ -L "${source}" ]; then + echo "Symlinked..." + source="$(readlink "${source}")" + fi + + # use filter instead of exclude so missing patterns dont' throw errors + echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" + rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" + + local basename + basename="$(basename -s .framework "$1")" + binary="${destination}/${basename}.framework/${basename}" + if ! [ -r "$binary" ]; then + binary="${destination}/${basename}" + fi + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then + strip_invalid_archs "$binary" + fi + + # Resign the code if required by the build settings to avoid unstable apps + code_sign_if_enabled "${destination}/$(basename "$1")" + + # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. + if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then + local swift_runtime_libs + swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) + for lib in $swift_runtime_libs; do + echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" + rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" + code_sign_if_enabled "${destination}/${lib}" + done + fi +} + +# Signs a framework with the provided identity +code_sign_if_enabled() { + if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then + # Use the current code_sign_identitiy + echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" + echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements \"$1\"" + /usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements "$1" + fi +} + +# Strip invalid architectures +strip_invalid_archs() { + binary="$1" + # Get architectures for current file + archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)" + stripped="" + for arch in $archs; do + if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then + # Strip non-valid architectures in-place + lipo -remove "$arch" -output "$binary" "$binary" || exit 1 + stripped="$stripped $arch" + fi + done + if [[ "$stripped" ]]; then + echo "Stripped $binary of architectures:$stripped" + fi +} + diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh new file mode 100755 index 0000000000..25e9d37757 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh @@ -0,0 +1,96 @@ +#!/bin/sh +set -e + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + +RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt +> "$RESOURCES_TO_COPY" + +XCASSET_FILES=() + +case "${TARGETED_DEVICE_FAMILY}" in + 1,2) + TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone" + ;; + 1) + TARGET_DEVICE_ARGS="--target-device iphone" + ;; + 2) + TARGET_DEVICE_ARGS="--target-device ipad" + ;; + *) + TARGET_DEVICE_ARGS="--target-device mac" + ;; +esac + +install_resource() +{ + if [[ "$1" = /* ]] ; then + RESOURCE_PATH="$1" + else + RESOURCE_PATH="${PODS_ROOT}/$1" + fi + if [[ ! -e "$RESOURCE_PATH" ]] ; then + cat << EOM +error: Resource "$RESOURCE_PATH" not found. Run 'pod install' to update the copy resources script. +EOM + exit 1 + fi + case $RESOURCE_PATH in + *.storyboard) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.xib) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.framework) + echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + echo "rsync -av $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + rsync -av "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + ;; + *.xcdatamodel) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH"`.mom\"" + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodel`.mom" + ;; + *.xcdatamodeld) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd\"" + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd" + ;; + *.xcmappingmodel) + echo "xcrun mapc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm\"" + xcrun mapc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm" + ;; + *.xcassets) + ABSOLUTE_XCASSET_FILE="$RESOURCE_PATH" + XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE") + ;; + *) + echo "$RESOURCE_PATH" + echo "$RESOURCE_PATH" >> "$RESOURCES_TO_COPY" + ;; + esac +} + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +if [[ "${ACTION}" == "install" ]] && [[ "${SKIP_INSTALL}" == "NO" ]]; then + mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi +rm -f "$RESOURCES_TO_COPY" + +if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "$XCASSET_FILES" ] +then + # Find all other xcassets (this unfortunately includes those of path pods and other targets). + OTHER_XCASSETS=$(find "$PWD" -iname "*.xcassets" -type d) + while read line; do + if [[ $line != "${PODS_ROOT}*" ]]; then + XCASSET_FILES+=("$line") + fi + done <<<"$OTHER_XCASSETS" + + printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-umbrella.h b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-umbrella.h new file mode 100644 index 0000000000..950bb19ca7 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-umbrella.h @@ -0,0 +1,8 @@ +#ifdef __OBJC__ +#import +#endif + + +FOUNDATION_EXPORT double Pods_SwaggerClientTestsVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_SwaggerClientTestsVersionString[]; + diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig new file mode 100644 index 0000000000..d578539810 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig @@ -0,0 +1,8 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient/PetstoreClient.framework/Headers" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT}/Pods diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap new file mode 100644 index 0000000000..a848da7ffb --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap @@ -0,0 +1,6 @@ +framework module Pods_SwaggerClientTests { + umbrella header "Pods-SwaggerClientTests-umbrella.h" + + export * + module * { export * } +} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig new file mode 100644 index 0000000000..d578539810 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig @@ -0,0 +1,8 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient/PetstoreClient.framework/Headers" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT}/Pods diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj new file mode 100644 index 0000000000..2728b93f24 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -0,0 +1,652 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 54DA06C1D70D78EC0EC72B61 /* Pods_SwaggerClientTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F65B6638217EDDC99D103B16 /* Pods_SwaggerClientTests.framework */; }; + 6D4EFB951C692C6300B96B06 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */; }; + 6D4EFB971C692C6300B96B06 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFB961C692C6300B96B06 /* ViewController.swift */; }; + 6D4EFB9A1C692C6300B96B06 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 6D4EFB981C692C6300B96B06 /* Main.storyboard */; }; + 6D4EFB9C1C692C6300B96B06 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 6D4EFB9B1C692C6300B96B06 /* Assets.xcassets */; }; + 6D4EFB9F1C692C6300B96B06 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 6D4EFB9D1C692C6300B96B06 /* LaunchScreen.storyboard */; }; + 6D4EFBB51C693BE200B96B06 /* PetAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */; }; + 6D4EFBB71C693BED00B96B06 /* StoreAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */; }; + 6D4EFBB91C693BFC00B96B06 /* UserAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */; }; + 751C65B82F596107A3DC8ED9 /* Pods_SwaggerClient.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8F60AECFF321A25553B6A5B0 /* Pods_SwaggerClient.framework */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 6D4EFBA61C692C6300B96B06 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 6D4EFB891C692C6300B96B06 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 6D4EFB901C692C6300B96B06; + remoteInfo = SwaggerClient; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 289E8A9E9C0BB66AD190C7C6 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; + 6D4EFB911C692C6300B96B06 /* SwaggerClient.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SwaggerClient.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 6D4EFB961C692C6300B96B06 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; + 6D4EFB991C692C6300B96B06 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 6D4EFB9B1C692C6300B96B06 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 6D4EFB9E1C692C6300B96B06 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 6D4EFBA01C692C6300B96B06 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 6D4EFBA51C692C6300B96B06 /* SwaggerClientTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = SwaggerClientTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 6D4EFBAB1C692C6300B96B06 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PetAPITests.swift; sourceTree = ""; }; + 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StoreAPITests.swift; sourceTree = ""; }; + 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UserAPITests.swift; sourceTree = ""; }; + 8F60AECFF321A25553B6A5B0 /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + A638467ACFB30852DEA51F7A /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; + B4B2BEC2ECA535C616F2F3FE /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; + C07EC0A94AA0F86D60668B32 /* Pods.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + F65B6638217EDDC99D103B16 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + FC60BDC7328C2AA916F25840 /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 6D4EFB8E1C692C6300B96B06 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 751C65B82F596107A3DC8ED9 /* Pods_SwaggerClient.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6D4EFBA21C692C6300B96B06 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 54DA06C1D70D78EC0EC72B61 /* Pods_SwaggerClientTests.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 0CAA98BEFA303B94D3664C7D /* Pods */ = { + isa = PBXGroup; + children = ( + A638467ACFB30852DEA51F7A /* Pods-SwaggerClient.debug.xcconfig */, + FC60BDC7328C2AA916F25840 /* Pods-SwaggerClient.release.xcconfig */, + 289E8A9E9C0BB66AD190C7C6 /* Pods-SwaggerClientTests.debug.xcconfig */, + B4B2BEC2ECA535C616F2F3FE /* Pods-SwaggerClientTests.release.xcconfig */, + ); + name = Pods; + sourceTree = ""; + }; + 3FABC56EC0BA84CBF4F99564 /* Frameworks */ = { + isa = PBXGroup; + children = ( + C07EC0A94AA0F86D60668B32 /* Pods.framework */, + 8F60AECFF321A25553B6A5B0 /* Pods_SwaggerClient.framework */, + F65B6638217EDDC99D103B16 /* Pods_SwaggerClientTests.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + 6D4EFB881C692C6300B96B06 = { + isa = PBXGroup; + children = ( + 6D4EFB931C692C6300B96B06 /* SwaggerClient */, + 6D4EFBA81C692C6300B96B06 /* SwaggerClientTests */, + 6D4EFB921C692C6300B96B06 /* Products */, + 3FABC56EC0BA84CBF4F99564 /* Frameworks */, + 0CAA98BEFA303B94D3664C7D /* Pods */, + ); + sourceTree = ""; + }; + 6D4EFB921C692C6300B96B06 /* Products */ = { + isa = PBXGroup; + children = ( + 6D4EFB911C692C6300B96B06 /* SwaggerClient.app */, + 6D4EFBA51C692C6300B96B06 /* SwaggerClientTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 6D4EFB931C692C6300B96B06 /* SwaggerClient */ = { + isa = PBXGroup; + children = ( + 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */, + 6D4EFB961C692C6300B96B06 /* ViewController.swift */, + 6D4EFB981C692C6300B96B06 /* Main.storyboard */, + 6D4EFB9B1C692C6300B96B06 /* Assets.xcassets */, + 6D4EFB9D1C692C6300B96B06 /* LaunchScreen.storyboard */, + 6D4EFBA01C692C6300B96B06 /* Info.plist */, + ); + path = SwaggerClient; + sourceTree = ""; + }; + 6D4EFBA81C692C6300B96B06 /* SwaggerClientTests */ = { + isa = PBXGroup; + children = ( + 6D4EFBAB1C692C6300B96B06 /* Info.plist */, + 6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */, + 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */, + 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */, + ); + path = SwaggerClientTests; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 6D4EFB901C692C6300B96B06 /* SwaggerClient */ = { + isa = PBXNativeTarget; + buildConfigurationList = 6D4EFBAE1C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClient" */; + buildPhases = ( + CF310079E3CB0BE5BE604471 /* [CP] Check Pods Manifest.lock */, + 1F03F780DC2D9727E5E64BA9 /* [CP] Check Pods Manifest.lock */, + 6D4EFB8D1C692C6300B96B06 /* Sources */, + 6D4EFB8E1C692C6300B96B06 /* Frameworks */, + 6D4EFB8F1C692C6300B96B06 /* Resources */, + 4485A75250058E2D5BBDF63F /* [CP] Embed Pods Frameworks */, + 808CE4A0CE801CAC5ABF5B08 /* [CP] Copy Pods Resources */, + 3D9471620628F03313096EB2 /* 📦 Embed Pods Frameworks */, + EEEC2B2D0497D38CEAD2DB24 /* 📦 Copy Pods Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = SwaggerClient; + productName = SwaggerClient; + productReference = 6D4EFB911C692C6300B96B06 /* SwaggerClient.app */; + productType = "com.apple.product-type.application"; + }; + 6D4EFBA41C692C6300B96B06 /* SwaggerClientTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 6D4EFBB11C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */; + buildPhases = ( + B4DB169E5F018305D6759D34 /* [CP] Check Pods Manifest.lock */, + 79FE27B09B2DD354C831BD49 /* [CP] Check Pods Manifest.lock */, + 6D4EFBA11C692C6300B96B06 /* Sources */, + 6D4EFBA21C692C6300B96B06 /* Frameworks */, + 6D4EFBA31C692C6300B96B06 /* Resources */, + 796EAD48F1BCCDAA291CD963 /* [CP] Embed Pods Frameworks */, + 1652CB1A246A4689869E442D /* [CP] Copy Pods Resources */, + ECE47F6BF90C3848F6E94AFF /* 📦 Embed Pods Frameworks */, + 1494090872F3F18E536E8902 /* 📦 Copy Pods Resources */, + ); + buildRules = ( + ); + dependencies = ( + 6D4EFBA71C692C6300B96B06 /* PBXTargetDependency */, + ); + name = SwaggerClientTests; + productName = SwaggerClientTests; + productReference = 6D4EFBA51C692C6300B96B06 /* SwaggerClientTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 6D4EFB891C692C6300B96B06 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0720; + LastUpgradeCheck = 0720; + ORGANIZATIONNAME = Swagger; + TargetAttributes = { + 6D4EFB901C692C6300B96B06 = { + CreatedOnToolsVersion = 7.2.1; + LastSwiftMigration = 0800; + }; + 6D4EFBA41C692C6300B96B06 = { + CreatedOnToolsVersion = 7.2.1; + LastSwiftMigration = 0800; + TestTargetID = 6D4EFB901C692C6300B96B06; + }; + }; + }; + buildConfigurationList = 6D4EFB8C1C692C6300B96B06 /* Build configuration list for PBXProject "SwaggerClient" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 6D4EFB881C692C6300B96B06; + productRefGroup = 6D4EFB921C692C6300B96B06 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 6D4EFB901C692C6300B96B06 /* SwaggerClient */, + 6D4EFBA41C692C6300B96B06 /* SwaggerClientTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 6D4EFB8F1C692C6300B96B06 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 6D4EFB9F1C692C6300B96B06 /* LaunchScreen.storyboard in Resources */, + 6D4EFB9C1C692C6300B96B06 /* Assets.xcassets in Resources */, + 6D4EFB9A1C692C6300B96B06 /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6D4EFBA31C692C6300B96B06 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 1494090872F3F18E536E8902 /* 📦 Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "📦 Copy Pods Resources"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; + 1652CB1A246A4689869E442D /* [CP] Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Copy Pods Resources"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; + 1F03F780DC2D9727E5E64BA9 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Check Pods Manifest.lock"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; + showEnvVarsInLog = 0; + }; + 3D9471620628F03313096EB2 /* 📦 Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "📦 Embed Pods Frameworks"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 4485A75250058E2D5BBDF63F /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Embed Pods Frameworks"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 796EAD48F1BCCDAA291CD963 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Embed Pods Frameworks"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 79FE27B09B2DD354C831BD49 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Check Pods Manifest.lock"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; + showEnvVarsInLog = 0; + }; + 808CE4A0CE801CAC5ABF5B08 /* [CP] Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Copy Pods Resources"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; + B4DB169E5F018305D6759D34 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Check Pods Manifest.lock"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n"; + showEnvVarsInLog = 0; + }; + CF310079E3CB0BE5BE604471 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Check Pods Manifest.lock"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n"; + showEnvVarsInLog = 0; + }; + ECE47F6BF90C3848F6E94AFF /* 📦 Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "📦 Embed Pods Frameworks"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + EEEC2B2D0497D38CEAD2DB24 /* 📦 Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "📦 Copy Pods Resources"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 6D4EFB8D1C692C6300B96B06 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 6D4EFB971C692C6300B96B06 /* ViewController.swift in Sources */, + 6D4EFB951C692C6300B96B06 /* AppDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6D4EFBA11C692C6300B96B06 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 6D4EFBB71C693BED00B96B06 /* StoreAPITests.swift in Sources */, + 6D4EFBB91C693BFC00B96B06 /* UserAPITests.swift in Sources */, + 6D4EFBB51C693BE200B96B06 /* PetAPITests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 6D4EFBA71C692C6300B96B06 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 6D4EFB901C692C6300B96B06 /* SwaggerClient */; + targetProxy = 6D4EFBA61C692C6300B96B06 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 6D4EFB981C692C6300B96B06 /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 6D4EFB991C692C6300B96B06 /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 6D4EFB9D1C692C6300B96B06 /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 6D4EFB9E1C692C6300B96B06 /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 6D4EFBAC1C692C6300B96B06 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.2; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 6D4EFBAD1C692C6300B96B06 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.2; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 6D4EFBAF1C692C6300B96B06 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = A638467ACFB30852DEA51F7A /* Pods-SwaggerClient.debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + INFOPLIST_FILE = SwaggerClient/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; + }; + name = Debug; + }; + 6D4EFBB01C692C6300B96B06 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = FC60BDC7328C2AA916F25840 /* Pods-SwaggerClient.release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + INFOPLIST_FILE = SwaggerClient/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; + }; + name = Release; + }; + 6D4EFBB21C692C6300B96B06 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 289E8A9E9C0BB66AD190C7C6 /* Pods-SwaggerClientTests.debug.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + INFOPLIST_FILE = SwaggerClientTests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/SwaggerClient.app/SwaggerClient"; + }; + name = Debug; + }; + 6D4EFBB31C692C6300B96B06 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = B4B2BEC2ECA535C616F2F3FE /* Pods-SwaggerClientTests.release.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + INFOPLIST_FILE = SwaggerClientTests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/SwaggerClient.app/SwaggerClient"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 6D4EFB8C1C692C6300B96B06 /* Build configuration list for PBXProject "SwaggerClient" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 6D4EFBAC1C692C6300B96B06 /* Debug */, + 6D4EFBAD1C692C6300B96B06 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 6D4EFBAE1C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClient" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 6D4EFBAF1C692C6300B96B06 /* Debug */, + 6D4EFBB01C692C6300B96B06 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 6D4EFBB11C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 6D4EFBB21C692C6300B96B06 /* Debug */, + 6D4EFBB31C692C6300B96B06 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 6D4EFB891C692C6300B96B06 /* Project object */; +} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/SwaggerClient.xcscheme b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/SwaggerClient.xcscheme new file mode 100644 index 0000000000..5ba034cec5 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/SwaggerClient.xcscheme @@ -0,0 +1,102 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000000..9b3fa18954 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClient/AppDelegate.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClient/AppDelegate.swift new file mode 100644 index 0000000000..7fd6929617 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClient/AppDelegate.swift @@ -0,0 +1,46 @@ +// +// AppDelegate.swift +// SwaggerClient +// +// Created by Joseph Zuromski on 2/8/16. +// Copyright © 2016 Swagger. All rights reserved. +// + +import UIKit + +@UIApplicationMain +class AppDelegate: UIResponder, UIApplicationDelegate { + + var window: UIWindow? + + + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { + // Override point for customization after application launch. + return true + } + + func applicationWillResignActive(_ application: UIApplication) { + // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. + // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. + } + + func applicationDidEnterBackground(_ application: UIApplication) { + // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. + // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. + } + + func applicationWillEnterForeground(_ application: UIApplication) { + // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. + } + + func applicationDidBecomeActive(_ application: UIApplication) { + // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. + } + + func applicationWillTerminate(_ application: UIApplication) { + // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. + } + + +} + diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClient/Assets.xcassets/AppIcon.appiconset/Contents.json b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClient/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000000..1d060ed288 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClient/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,93 @@ +{ + "images" : [ + { + "idiom" : "iphone", + "size" : "20x20", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "20x20", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "29x29", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "29x29", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "40x40", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "40x40", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "60x60", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "60x60", + "scale" : "3x" + }, + { + "idiom" : "ipad", + "size" : "20x20", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "20x20", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "29x29", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "29x29", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "40x40", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "40x40", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "76x76", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "76x76", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "83.5x83.5", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClient/Base.lproj/LaunchScreen.storyboard b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClient/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000000..2e721e1833 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClient/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClient/Base.lproj/Main.storyboard b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClient/Base.lproj/Main.storyboard new file mode 100644 index 0000000000..3a2a49bad8 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClient/Base.lproj/Main.storyboard @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClient/Info.plist b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClient/Info.plist new file mode 100644 index 0000000000..bb71d00fa8 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClient/Info.plist @@ -0,0 +1,59 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + NSAppTransportSecurity + + NSExceptionDomains + + petstore.swagger.io + + + NSTemporaryExceptionAllowsInsecureHTTPLoads + + + + + + diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClient/ViewController.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClient/ViewController.swift new file mode 100644 index 0000000000..cd7e9a1676 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClient/ViewController.swift @@ -0,0 +1,25 @@ +// +// ViewController.swift +// SwaggerClient +// +// Created by Joseph Zuromski on 2/8/16. +// Copyright © 2016 Swagger. All rights reserved. +// + +import UIKit + +class ViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + // Do any additional setup after loading the view, typically from a nib. + } + + override func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + // Dispose of any resources that can be recreated. + } + + +} + diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClientTests/Info.plist b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClientTests/Info.plist new file mode 100644 index 0000000000..802f84f540 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClientTests/Info.plist @@ -0,0 +1,36 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + BNDL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + NSAppTransportSecurity + + NSExceptionDomains + + petstore.swagger.io + + + NSTemporaryExceptionAllowsInsecureHTTPLoads + + + + + + diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift new file mode 100644 index 0000000000..ffb9e8b209 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift @@ -0,0 +1,86 @@ +// +// PetAPITests.swift +// SwaggerClient +// +// Created by Robin Eggenkamp on 5/21/16. +// Copyright © 2016 Swagger. All rights reserved. +// + +import PetstoreClient +import XCTest +@testable import SwaggerClient + +class PetAPITests: XCTestCase { + + let testTimeout = 10.0 + + override func setUp() { + super.setUp() + // Put setup code here. This method is called before the invocation of each test method in the class. + } + + override func tearDown() { + // Put teardown code here. This method is called after the invocation of each test method in the class. + super.tearDown() + } + + func test1CreatePet() { + let expectation = self.expectation(description: "testCreatePet") + + let newPet = Pet() + let category = PetstoreClient.Category() + category.id = 1234 + category.name = "eyeColor" + newPet.category = category + newPet.id = 1000 + newPet.name = "Fluffy" + newPet.status = .available + + PetAPI.addPet(body: newPet) { (error) in + guard error == nil else { + XCTFail("error creating pet") + return + } + + expectation.fulfill() + } + + self.waitForExpectations(timeout: testTimeout, handler: nil) + } + + func test2GetPet() { + let expectation = self.expectation(description: "testGetPet") + + PetAPI.getPetById(petId: 1000) { (pet, error) in + guard error == nil else { + XCTFail("error retrieving pet") + return + } + + if let pet = pet { + XCTAssert(pet.id == 1000, "invalid id") + XCTAssert(pet.name == "Fluffy", "invalid name") + + expectation.fulfill() + } + } + + self.waitForExpectations(timeout: testTimeout, handler: nil) + } + + func test3DeletePet() { + let expectation = self.expectation(description: "testDeletePet") + + PetAPI.deletePet(petId: 1000) { (error) in + guard error == nil else { + XCTFail("error deleting pet") + return + } + + expectation.fulfill() + } + + self.waitForExpectations(timeout: testTimeout, handler: nil) + } + +} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift new file mode 100644 index 0000000000..c387099bca --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift @@ -0,0 +1,122 @@ +// +// StoreAPITests.swift +// SwaggerClient +// +// Created by Robin Eggenkamp on 5/21/16. +// Copyright © 2016 Swagger. All rights reserved. +// + +import PetstoreClient +import XCTest +@testable import SwaggerClient + +class StoreAPITests: XCTestCase { + + let isoDateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" + + let testTimeout = 10.0 + + func test1PlaceOrder() { + let expectation = self.expectation(description: "testPlaceOrder") + let shipDate = Date() + + let newOrder = Order() + newOrder.id = 1000 + newOrder.petId = 1000 + newOrder.complete = false + newOrder.quantity = 10 + newOrder.shipDate = shipDate + // use explicit naming to reference the enum so that we test we don't regress on enum naming + newOrder.status = Order.Status.placed + + StoreAPI.placeOrder(body: newOrder) { (order, error) in + guard error == nil else { + XCTFail("error placing order: \(error.debugDescription)") + return + } + + if let order = order { + XCTAssert(order.id == 1000, "invalid id") + XCTAssert(order.quantity == 10, "invalid quantity") + XCTAssert(order.status == .placed, "invalid status") + XCTAssert(order.shipDate!.isEqual(shipDate, format: self.isoDateFormat), + "Date should be idempotent") + + expectation.fulfill() + } + } + + self.waitForExpectations(timeout: testTimeout, handler: nil) + } + + func test2GetOrder() { + let expectation = self.expectation(description: "testGetOrder") + + StoreAPI.getOrderById(orderId: 1000) { (order, error) in + guard error == nil else { + XCTFail("error retrieving order: \(error.debugDescription)") + return + } + + if let order = order { + XCTAssert(order.id == 1000, "invalid id") + XCTAssert(order.quantity == 10, "invalid quantity") + XCTAssert(order.status == .placed, "invalid status") + + expectation.fulfill() + } + } + + self.waitForExpectations(timeout: testTimeout, handler: nil) + } + + func test3DeleteOrder() { + let expectation = self.expectation(description: "testDeleteOrder") + + StoreAPI.deleteOrder(orderId: "1000") { (error) in + guard error == nil else { + XCTFail("error deleting order") + return + } + + expectation.fulfill() + } + + self.waitForExpectations(timeout: testTimeout, handler: nil) + } + + func testDownloadProgress() { + let responseExpectation = self.expectation(description: "obtain response") + let progressExpectation = self.expectation(description: "obtain progress") + let requestBuilder = StoreAPI.getOrderByIdWithRequestBuilder(orderId: 1000) + + requestBuilder.onProgressReady = { (progress) in + progressExpectation.fulfill() + } + + requestBuilder.execute { (response, error) in + responseExpectation.fulfill() + } + + self.waitForExpectations(timeout: testTimeout, handler: nil) + } + +} + +private extension Date { + + /** + Returns true if the dates are equal given the format string. + + - parameter date: The date to compare to. + - parameter format: The format string to use to compare. + + - returns: true if the dates are equal, given the format string. + */ + func isEqual(_ date: Date, format: String) -> Bool { + let fmt = DateFormatter() + fmt.dateFormat = format + return fmt.string(from: self).isEqual(fmt.string(from: date)) + } + +} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift new file mode 100644 index 0000000000..103ee1b90d --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift @@ -0,0 +1,121 @@ +// +// UserAPITests.swift +// SwaggerClient +// +// Created by Robin Eggenkamp on 5/21/16. +// Copyright © 2016 Swagger. All rights reserved. +// + +import PetstoreClient +import XCTest +@testable import SwaggerClient + +class UserAPITests: XCTestCase { + + let testTimeout = 10.0 + + override func setUp() { + super.setUp() + // Put setup code here. This method is called before the invocation of each test method in the class. + } + + override func tearDown() { + // Put teardown code here. This method is called after the invocation of each test method in the class. + super.tearDown() + } + + func testLogin() { + let expectation = self.expectation(description: "testLogin") + + UserAPI.loginUser(username: "swiftTester", password: "swift") { (_, error) in + guard error == nil else { + XCTFail("error logging in") + return + } + + expectation.fulfill() + } + + self.waitForExpectations(timeout: testTimeout, handler: nil) + } + + func testLogout() { + let expectation = self.expectation(description: "testLogout") + + UserAPI.logoutUser { (error) in + guard error == nil else { + XCTFail("error logging out") + return + } + + expectation.fulfill() + } + + self.waitForExpectations(timeout: testTimeout, handler: nil) + } + + func test1CreateUser() { + let expectation = self.expectation(description: "testCreateUser") + + let newUser = User() + newUser.email = "test@test.com" + newUser.firstName = "Test" + newUser.lastName = "Tester" + newUser.id = 1000 + newUser.password = "test!" + newUser.phone = "867-5309" + newUser.username = "test@test.com" + newUser.userStatus = 0 + + UserAPI.createUser(body: newUser) { (error) in + guard error == nil else { + XCTFail("error creating user") + return + } + + expectation.fulfill() + } + + self.waitForExpectations(timeout: testTimeout, handler: nil) + } + + func test2GetUser() { + let expectation = self.expectation(description: "testGetUser") + + UserAPI.getUserByName(username: "test@test.com") { (user, error) in + guard error == nil else { + XCTFail("error getting user") + return + } + + if let user = user { + XCTAssert(user.userStatus == 0, "invalid userStatus") + XCTAssert(user.email == "test@test.com", "invalid email") + XCTAssert(user.firstName == "Test", "invalid firstName") + XCTAssert(user.lastName == "Tester", "invalid lastName") + XCTAssert(user.password == "test!", "invalid password") + XCTAssert(user.phone == "867-5309", "invalid phone") + + expectation.fulfill() + } + } + + self.waitForExpectations(timeout: testTimeout, handler: nil) + } + + func test3DeleteUser() { + let expectation = self.expectation(description: "testDeleteUser") + + UserAPI.deleteUser(username: "test@test.com") { (error) in + guard error == nil else { + XCTFail("error deleting user") + return + } + + expectation.fulfill() + } + + self.waitForExpectations(timeout: testTimeout, handler: nil) + } + +} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/pom.xml b/samples/client/petstore/swift4/default/SwaggerClientTests/pom.xml new file mode 100644 index 0000000000..10919bfdda --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/pom.xml @@ -0,0 +1,43 @@ + + 4.0.0 + io.swagger + Swift3PetstoreClientTests + pom + 1.0-SNAPSHOT + Swift3 Swagger Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + xcodebuild-test + integration-test + + exec + + + ./run_xcodebuild.sh + + + + + + + diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/run_xcodebuild.sh b/samples/client/petstore/swift4/default/SwaggerClientTests/run_xcodebuild.sh new file mode 100755 index 0000000000..85622eef70 --- /dev/null +++ b/samples/client/petstore/swift4/default/SwaggerClientTests/run_xcodebuild.sh @@ -0,0 +1,3 @@ +#!/bin/sh + +xcodebuild clean build build-for-testing -workspace "SwaggerClient.xcworkspace" -scheme "SwaggerClient" -destination "platform=iOS Simulator,name=iPhone 6,OS=9.3" && xcodebuild test-without-building -workspace "SwaggerClient.xcworkspace" -scheme "SwaggerClient" -destination "platform=iOS Simulator,name=iPhone 6,OS=9.3" | xcpretty && exit ${PIPESTATUS[0]} diff --git a/samples/client/petstore/swift4/default/git_push.sh b/samples/client/petstore/swift4/default/git_push.sh new file mode 100644 index 0000000000..ed374619b1 --- /dev/null +++ b/samples/client/petstore/swift4/default/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore/swift4/promisekit/.gitignore b/samples/client/petstore/swift4/promisekit/.gitignore new file mode 100644 index 0000000000..5e5d5cebcf --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/.gitignore @@ -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 diff --git a/samples/client/petstore/swift4/promisekit/.swagger-codegen-ignore b/samples/client/petstore/swift4/promisekit/.swagger-codegen-ignore new file mode 100644 index 0000000000..c5fa491b4c --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/.swagger-codegen-ignore @@ -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 diff --git a/samples/client/petstore/swift4/promisekit/.swagger-codegen/VERSION b/samples/client/petstore/swift4/promisekit/.swagger-codegen/VERSION new file mode 100644 index 0000000000..7fea99011a --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.2.3-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift4/promisekit/Cartfile b/samples/client/petstore/swift4/promisekit/Cartfile new file mode 100644 index 0000000000..5e4bd352ee --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/Cartfile @@ -0,0 +1,2 @@ +github "Alamofire/Alamofire" >= 3.1.0 +github "mxcl/PromiseKit" >=1.5.3 diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient.podspec b/samples/client/petstore/swift4/promisekit/PetstoreClient.podspec new file mode 100644 index 0000000000..94ee3447e8 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient.podspec @@ -0,0 +1,14 @@ +Pod::Spec.new do |s| + s.name = 'PetstoreClient' + s.ios.deployment_target = '9.0' + s.osx.deployment_target = '10.11' + s.version = '0.0.1' + s.source = { :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' } + s.authors = '' + s.license = 'Proprietary' + s.homepage = 'https://github.com/swagger-api/swagger-codegen' + s.summary = 'PetstoreClient' + s.source_files = 'PetstoreClient/Classes/Swaggers/**/*.swift' + s.dependency 'PromiseKit', '~> 4.2.2' + s.dependency 'Alamofire', '~> 4.5' +end diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIHelper.swift new file mode 100644 index 0000000000..b612ff9092 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIHelper.swift @@ -0,0 +1,65 @@ +// APIHelper.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +class APIHelper { + static func rejectNil(_ source: [String:Any?]) -> [String:Any]? { + var destination = [String:Any]() + for (key, nillableValue) in source { + if let value: Any = nillableValue { + destination[key] = value + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] { + var destination = [String:String]() + for (key, nillableValue) in source { + if let value: Any = nillableValue { + destination[key] = "\(value)" + } + } + return destination + } + + static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? { + guard let source = source else { + return nil + } + var destination = [String:Any]() + let theTrue = NSNumber(value: true as Bool) + let theFalse = NSNumber(value: false as Bool) + for (key, value) in source { + switch value { + case let x where x as? NSNumber === theTrue || x as? NSNumber === theFalse: + destination[key] = "\(value as! Bool)" as Any? + default: + destination[key] = value + } + } + return destination + } + + + static func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem]? { + let returnValues = values + .filter { $0.1 != nil } + .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in + URLQueryItem(name: item._key, value:"\(item._value!)") + } + if returnValues.count == 0 { + return nil + } + return returnValues + } + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift new file mode 100644 index 0000000000..745d640ec1 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift @@ -0,0 +1,61 @@ +// APIs.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +open class PetstoreClientAPI { + open static var basePath = "http://petstore.swagger.io:80/v2" + open static var credential: URLCredential? + open static var customHeaders: [String:String] = [:] + open static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() +} + +open class RequestBuilder { + var credential: URLCredential? + var headers: [String:String] + let parameters: [String:Any]? + 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: ((Progress) -> ())? + + required public init(method: String, URLString: String, parameters: [String:Any]?, isBody: Bool, headers: [String:String] = [:]) { + self.method = method + self.URLString = URLString + self.parameters = parameters + self.isBody = isBody + self.headers = headers + + addHeaders(PetstoreClientAPI.customHeaders) + } + + open func addHeaders(_ aHeaders:[String:String]) { + for (header, value) in aHeaders { + headers[header] = value + } + } + + open func execute(_ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { } + + public func addHeader(name: String, value: String) -> Self { + if !value.isEmpty { + headers[name] = value + } + return self + } + + open func addCredential() -> Self { + self.credential = PetstoreClientAPI.credential + return self + } +} + +public protocol RequestBuilderFactory { + func getNonDecodableBuilder() -> RequestBuilder.Type + func getBuilder() -> RequestBuilder.Type +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift new file mode 100644 index 0000000000..178d91c131 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift @@ -0,0 +1,543 @@ +// +// FakeAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire +import PromiseKit + + + +open class FakeAPI { + /** + + - parameter body: (body) Input boolean as post body (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + open class func fakeOuterBooleanSerialize(body: OuterBoolean? = nil, completion: @escaping ((_ data: OuterBoolean?,_ error: Error?) -> Void)) { + fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + /** + + - parameter body: (body) Input boolean as post body (optional) + - returns: Promise + */ + open class func fakeOuterBooleanSerialize( body: OuterBoolean? = nil) -> Promise { + let deferred = Promise.pending() + fakeOuterBooleanSerialize(body: body) { data, error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill(data!) + } + } + return deferred.promise + } + + /** + - POST /fake/outer/boolean + - Test serialization of outer boolean types + - examples: [{contentType=application/json, example={ }}] + + - parameter body: (body) Input boolean as post body (optional) + + - returns: RequestBuilder + */ + open class func fakeOuterBooleanSerializeWithRequestBuilder(body: OuterBoolean? = nil) -> RequestBuilder { + let path = "/fake/outer/boolean" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + + - parameter body: (body) Input composite as post body (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, completion: @escaping ((_ data: OuterComposite?,_ error: Error?) -> Void)) { + fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + /** + + - parameter body: (body) Input composite as post body (optional) + - returns: Promise + */ + open class func fakeOuterCompositeSerialize( body: OuterComposite? = nil) -> Promise { + let deferred = Promise.pending() + fakeOuterCompositeSerialize(body: body) { data, error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill(data!) + } + } + return deferred.promise + } + + /** + - POST /fake/outer/composite + - Test serialization of object with outer number type + - examples: [{contentType=application/json, example={ + "my_string" : { }, + "my_number" : { }, + "my_boolean" : { } +}}] + + - parameter body: (body) Input composite as post body (optional) + + - returns: RequestBuilder + */ + open class func fakeOuterCompositeSerializeWithRequestBuilder(body: OuterComposite? = nil) -> RequestBuilder { + let path = "/fake/outer/composite" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + + - parameter body: (body) Input number as post body (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + open class func fakeOuterNumberSerialize(body: OuterNumber? = nil, completion: @escaping ((_ data: OuterNumber?,_ error: Error?) -> Void)) { + fakeOuterNumberSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + /** + + - parameter body: (body) Input number as post body (optional) + - returns: Promise + */ + open class func fakeOuterNumberSerialize( body: OuterNumber? = nil) -> Promise { + let deferred = Promise.pending() + fakeOuterNumberSerialize(body: body) { data, error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill(data!) + } + } + return deferred.promise + } + + /** + - POST /fake/outer/number + - Test serialization of outer number types + - examples: [{contentType=application/json, example={ }}] + + - parameter body: (body) Input number as post body (optional) + + - returns: RequestBuilder + */ + open class func fakeOuterNumberSerializeWithRequestBuilder(body: OuterNumber? = nil) -> RequestBuilder { + let path = "/fake/outer/number" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + + - parameter body: (body) Input string as post body (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + open class func fakeOuterStringSerialize(body: OuterString? = nil, completion: @escaping ((_ data: OuterString?,_ error: Error?) -> Void)) { + fakeOuterStringSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + /** + + - parameter body: (body) Input string as post body (optional) + - returns: Promise + */ + open class func fakeOuterStringSerialize( body: OuterString? = nil) -> Promise { + let deferred = Promise.pending() + fakeOuterStringSerialize(body: body) { data, error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill(data!) + } + } + return deferred.promise + } + + /** + - POST /fake/outer/string + - Test serialization of outer string types + - examples: [{contentType=application/json, example={ }}] + + - parameter body: (body) Input string as post body (optional) + + - returns: RequestBuilder + */ + open class func fakeOuterStringSerializeWithRequestBuilder(body: OuterString? = nil) -> RequestBuilder { + let path = "/fake/outer/string" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + To test \"client\" model + + - parameter body: (body) client model + - parameter completion: completion handler to receive the data and the error objects + */ + open class func testClientModel(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { + testClientModelWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + /** + To test \"client\" model + + - parameter body: (body) client model + - returns: Promise + */ + open class func testClientModel( body: Client) -> Promise { + let deferred = Promise.pending() + testClientModel(body: body) { data, error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill(data!) + } + } + return deferred.promise + } + + /** + To test \"client\" model + - PATCH /fake + - To test \"client\" model + - examples: [{contentType=application/json, example={ + "client" : "aeiou" +}}] + + - parameter body: (body) client model + + - returns: RequestBuilder + */ + open class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder { + let path = "/fake" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + + - parameter number: (form) None + - parameter double: (form) None + - parameter patternWithoutDelimiter: (form) None + - parameter byte: (form) None + - parameter integer: (form) None (optional) + - parameter int32: (form) None (optional) + - parameter int64: (form) None (optional) + - parameter float: (form) None (optional) + - parameter string: (form) None (optional) + - parameter binary: (form) None (optional) + - parameter date: (form) None (optional) + - parameter dateTime: (form) None (optional) + - parameter password: (form) None (optional) + - parameter callback: (form) None (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int32? = nil, int32: Int32? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: Data? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute { (response, error) -> Void in + completion(error); + } + } + + /** + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + + - parameter number: (form) None + - parameter double: (form) None + - parameter patternWithoutDelimiter: (form) None + - parameter byte: (form) None + - parameter integer: (form) None (optional) + - parameter int32: (form) None (optional) + - parameter int64: (form) None (optional) + - parameter float: (form) None (optional) + - parameter string: (form) None (optional) + - parameter binary: (form) None (optional) + - parameter date: (form) None (optional) + - parameter dateTime: (form) None (optional) + - parameter password: (form) None (optional) + - parameter callback: (form) None (optional) + - returns: Promise + */ + open class func testEndpointParameters( number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int32? = nil, int32: Int32? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: Data? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> Promise { + let deferred = Promise.pending() + testEndpointParameters(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback) { error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill() + } + } + return deferred.promise + } + + /** + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + - POST /fake + - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + - BASIC: + - type: basic + - name: http_basic_test + + - parameter number: (form) None + - parameter double: (form) None + - parameter patternWithoutDelimiter: (form) None + - parameter byte: (form) None + - parameter integer: (form) None (optional) + - parameter int32: (form) None (optional) + - parameter int64: (form) None (optional) + - parameter float: (form) None (optional) + - parameter string: (form) None (optional) + - parameter binary: (form) None (optional) + - parameter date: (form) None (optional) + - parameter dateTime: (form) None (optional) + - parameter password: (form) None (optional) + - parameter callback: (form) None (optional) + + - returns: RequestBuilder + */ + open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int32? = nil, int32: Int32? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: Data? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { + let path = "/fake" + let URLString = PetstoreClientAPI.basePath + path + let formParams: [String:Any?] = [ + "integer": integer?.encodeToJSON(), + "int32": int32?.encodeToJSON(), + "int64": int64?.encodeToJSON(), + "number": number, + "float": float, + "double": double, + "string": string, + "pattern_without_delimiter": patternWithoutDelimiter, + "byte": byte, + "binary": binary, + "date": date?.encodeToJSON(), + "dateTime": dateTime?.encodeToJSON(), + "password": password, + "callback": callback + ] + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + * enum for parameter enumFormStringArray + */ + public enum EnumFormStringArray_testEnumParameters: String { + case greaterThan = ">" + case dollar = "$" + } + + /** + * enum for parameter enumFormString + */ + public enum EnumFormString_testEnumParameters: String { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + } + + /** + * enum for parameter enumHeaderStringArray + */ + public enum EnumHeaderStringArray_testEnumParameters: String { + case greaterThan = ">" + case dollar = "$" + } + + /** + * enum for parameter enumHeaderString + */ + public enum EnumHeaderString_testEnumParameters: String { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + } + + /** + * enum for parameter enumQueryStringArray + */ + public enum EnumQueryStringArray_testEnumParameters: String { + case greaterThan = ">" + case dollar = "$" + } + + /** + * enum for parameter enumQueryString + */ + public enum EnumQueryString_testEnumParameters: String { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + } + + /** + * enum for parameter enumQueryInteger + */ + public enum EnumQueryInteger_testEnumParameters: Int32 { + case _1 = 1 + case numberminus2 = -2 + } + + /** + * enum for parameter enumQueryDouble + */ + public enum EnumQueryDouble_testEnumParameters: Double { + case _11 = 1.1 + case numberminus12 = -1.2 + } + + /** + To test enum parameters + + - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional) + - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to -efg) + - parameter enumHeaderStringArray: (header) Header parameter enum test (string array) (optional) + - parameter enumHeaderString: (header) Header parameter enum test (string) (optional, default to -efg) + - parameter enumQueryStringArray: (query) Query parameter enum test (string array) (optional) + - parameter enumQueryString: (query) Query parameter enum test (string) (optional, default to -efg) + - parameter enumQueryInteger: (query) Query parameter enum test (double) (optional) + - parameter enumQueryDouble: (form) Query parameter enum test (double) (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + testEnumParametersWithRequestBuilder(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble).execute { (response, error) -> Void in + completion(error); + } + } + + /** + To test enum parameters + + - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional) + - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to -efg) + - parameter enumHeaderStringArray: (header) Header parameter enum test (string array) (optional) + - parameter enumHeaderString: (header) Header parameter enum test (string) (optional, default to -efg) + - parameter enumQueryStringArray: (query) Query parameter enum test (string array) (optional) + - parameter enumQueryString: (query) Query parameter enum test (string) (optional, default to -efg) + - parameter enumQueryInteger: (query) Query parameter enum test (double) (optional) + - parameter enumQueryDouble: (form) Query parameter enum test (double) (optional) + - returns: Promise + */ + open class func testEnumParameters( enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil) -> Promise { + let deferred = Promise.pending() + testEnumParameters(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble) { error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill() + } + } + return deferred.promise + } + + /** + To test enum parameters + - GET /fake + - To test enum parameters + + - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional) + - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to -efg) + - parameter enumHeaderStringArray: (header) Header parameter enum test (string array) (optional) + - parameter enumHeaderString: (header) Header parameter enum test (string) (optional, default to -efg) + - parameter enumQueryStringArray: (query) Query parameter enum test (string array) (optional) + - parameter enumQueryString: (query) Query parameter enum test (string) (optional, default to -efg) + - parameter enumQueryInteger: (query) Query parameter enum test (double) (optional) + - parameter enumQueryDouble: (form) Query parameter enum test (double) (optional) + + - returns: RequestBuilder + */ + open class func testEnumParametersWithRequestBuilder(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil) -> RequestBuilder { + let path = "/fake" + let URLString = PetstoreClientAPI.basePath + path + let formParams: [String:Any?] = [ + "enum_form_string_array": enumFormStringArray, + "enum_form_string": enumFormString?.rawValue, + "enum_query_double": enumQueryDouble?.rawValue + ] + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + "enum_query_string_array": enumQueryStringArray, + "enum_query_string": enumQueryString?.rawValue, + "enum_query_integer": enumQueryInteger?.rawValue + ]) + + let nillableHeaders: [String: Any?] = [ + "enum_header_string_array": enumHeaderStringArray, + "enum_header_string": enumHeaderString?.rawValue + ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + } + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeclassnametagsAPI.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeclassnametagsAPI.swift new file mode 100644 index 0000000000..ed3c6d0553 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeclassnametagsAPI.swift @@ -0,0 +1,67 @@ +// +// FakeclassnametagsAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire +import PromiseKit + + + +open class FakeclassnametagsAPI { + /** + To test class name in snake case + + - parameter body: (body) client model + - parameter completion: completion handler to receive the data and the error objects + */ + open class func testClassname(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { + testClassnameWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + /** + To test class name in snake case + + - parameter body: (body) client model + - returns: Promise + */ + open class func testClassname( body: Client) -> Promise { + let deferred = Promise.pending() + testClassname(body: body) { data, error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill(data!) + } + } + return deferred.promise + } + + /** + To test class name in snake case + - PATCH /fake_classname_test + - examples: [{contentType=application/json, example={ + "client" : "aeiou" +}}] + + - parameter body: (body) client model + + - returns: RequestBuilder + */ + open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { + let path = "/fake_classname_test" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "PATCH", URLString: URLString, parameters: convertedParameters, isBody: true) + } + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift new file mode 100644 index 0000000000..ef9332e06e --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -0,0 +1,648 @@ +// +// PetAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire +import PromiseKit + + + +open class PetAPI { + /** + Add a new pet to the store + + - parameter body: (body) Pet object that needs to be added to the store + - parameter completion: completion handler to receive the data and the error objects + */ + open class func addPet(body: Pet, completion: @escaping ((_ error: Error?) -> Void)) { + addPetWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error); + } + } + + /** + Add a new pet to the store + + - parameter body: (body) Pet object that needs to be added to the store + - returns: Promise + */ + open class func addPet( body: Pet) -> Promise { + let deferred = Promise.pending() + addPet(body: body) { error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill() + } + } + return deferred.promise + } + + /** + Add a new pet to the store + - POST /pet + - + - OAuth: + - type: oauth2 + - name: petstore_auth + + - parameter body: (body) Pet object that needs to be added to the store + + - returns: RequestBuilder + */ + open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder { + let path = "/pet" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + Deletes a pet + + - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + open class func deletePet(petId: Int64, apiKey: String? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (response, error) -> Void in + completion(error); + } + } + + /** + Deletes a pet + + - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) + - returns: Promise + */ + open class func deletePet( petId: Int64, apiKey: String? = nil) -> Promise { + let deferred = Promise.pending() + deletePet(petId: petId, apiKey: apiKey) { error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill() + } + } + return deferred.promise + } + + /** + Deletes a pet + - DELETE /pet/{petId} + - + - OAuth: + - type: oauth2 + - name: petstore_auth + + - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) + + - returns: RequestBuilder + */ + open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder { + var path = "/pet/{petId}" + path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + "api_key": apiKey + ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + } + + /** + * enum for parameter status + */ + public enum Status_findPetsByStatus: String { + case available = "available" + case pending = "pending" + case sold = "sold" + } + + /** + Finds Pets by status + + - parameter status: (query) Status values that need to be considered for filter + - parameter completion: completion handler to receive the data and the error objects + */ + open class func findPetsByStatus(status: [String], completion: @escaping ((_ data: [Pet]?,_ error: Error?) -> Void)) { + findPetsByStatusWithRequestBuilder(status: status).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + /** + Finds Pets by status + + - parameter status: (query) Status values that need to be considered for filter + - returns: Promise<[Pet]> + */ + open class func findPetsByStatus( status: [String]) -> Promise<[Pet]> { + let deferred = Promise<[Pet]>.pending() + findPetsByStatus(status: status) { data, error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill(data!) + } + } + return deferred.promise + } + + /** + Finds Pets by status + - GET /pet/findByStatus + - Multiple status values can be provided with comma separated strings + - OAuth: + - type: oauth2 + - name: petstore_auth + - examples: [{contentType=application/xml, example= + 123456789 + doggie + + aeiou + + + + aeiou +}, {contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "aeiou", + "id" : 6 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 1 + } ], + "status" : "available" +} ]}] + - examples: [{contentType=application/xml, example= + 123456789 + doggie + + aeiou + + + + aeiou +}, {contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "aeiou", + "id" : 6 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 1 + } ], + "status" : "available" +} ]}] + + - parameter status: (query) Status values that need to be considered for filter + + - returns: RequestBuilder<[Pet]> + */ + open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + let path = "/pet/findByStatus" + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + "status": status + ]) + + + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Finds Pets by tags + + - parameter tags: (query) Tags to filter by + - parameter completion: completion handler to receive the data and the error objects + */ + open class func findPetsByTags(tags: [String], completion: @escaping ((_ data: [Pet]?,_ error: Error?) -> Void)) { + findPetsByTagsWithRequestBuilder(tags: tags).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + /** + Finds Pets by tags + + - parameter tags: (query) Tags to filter by + - returns: Promise<[Pet]> + */ + open class func findPetsByTags( tags: [String]) -> Promise<[Pet]> { + let deferred = Promise<[Pet]>.pending() + findPetsByTags(tags: tags) { data, error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill(data!) + } + } + return deferred.promise + } + + /** + Finds Pets by tags + - GET /pet/findByTags + - Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + - OAuth: + - type: oauth2 + - name: petstore_auth + - examples: [{contentType=application/xml, example= + 123456789 + doggie + + aeiou + + + + aeiou +}, {contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "aeiou", + "id" : 6 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 1 + } ], + "status" : "available" +} ]}] + - examples: [{contentType=application/xml, example= + 123456789 + doggie + + aeiou + + + + aeiou +}, {contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "aeiou", + "id" : 6 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 1 + } ], + "status" : "available" +} ]}] + + - parameter tags: (query) Tags to filter by + + - returns: RequestBuilder<[Pet]> + */ + open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { + let path = "/pet/findByTags" + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + "tags": tags + ]) + + + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Find pet by ID + + - parameter petId: (path) ID of pet to return + - parameter completion: completion handler to receive the data and the error objects + */ + open class func getPetById(petId: Int64, completion: @escaping ((_ data: Pet?,_ error: Error?) -> Void)) { + getPetByIdWithRequestBuilder(petId: petId).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + /** + Find pet by ID + + - parameter petId: (path) ID of pet to return + - returns: Promise + */ + open class func getPetById( petId: Int64) -> Promise { + let deferred = Promise.pending() + getPetById(petId: petId) { data, error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill(data!) + } + } + return deferred.promise + } + + /** + Find pet by ID + - GET /pet/{petId} + - Returns a single pet + - API Key: + - type: apiKey api_key + - name: api_key + - examples: [{contentType=application/xml, example= + 123456789 + doggie + + aeiou + + + + aeiou +}, {contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "aeiou", + "id" : 6 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 1 + } ], + "status" : "available" +}}] + - examples: [{contentType=application/xml, example= + 123456789 + doggie + + aeiou + + + + aeiou +}, {contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "aeiou", + "id" : 6 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 1 + } ], + "status" : "available" +}}] + + - parameter petId: (path) ID of pet to return + + - returns: RequestBuilder + */ + open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder { + var path = "/pet/{petId}" + path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Update an existing pet + + - parameter body: (body) Pet object that needs to be added to the store + - parameter completion: completion handler to receive the data and the error objects + */ + open class func updatePet(body: Pet, completion: @escaping ((_ error: Error?) -> Void)) { + updatePetWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error); + } + } + + /** + Update an existing pet + + - parameter body: (body) Pet object that needs to be added to the store + - returns: Promise + */ + open class func updatePet( body: Pet) -> Promise { + let deferred = Promise.pending() + updatePet(body: body) { error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill() + } + } + return deferred.promise + } + + /** + Update an existing pet + - PUT /pet + - + - OAuth: + - type: oauth2 + - name: petstore_auth + + - parameter body: (body) Pet object that needs to be added to the store + + - returns: RequestBuilder + */ + open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder { + let path = "/pet" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, 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 + */ + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (response, error) -> Void in + completion(error); + } + } + + /** + Updates a pet in the store with form data + + - parameter petId: (path) ID of pet that needs to be updated + - parameter name: (form) Updated name of the pet (optional) + - parameter status: (form) Updated status of the pet (optional) + - returns: Promise + */ + open class func updatePetWithForm( petId: Int64, name: String? = nil, status: String? = nil) -> Promise { + let deferred = Promise.pending() + updatePetWithForm(petId: petId, name: name, status: status) { error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill() + } + } + return deferred.promise + } + + /** + Updates a pet in the store with form data + - POST /pet/{petId} + - + - OAuth: + - type: oauth2 + - name: petstore_auth + + - parameter petId: (path) ID of pet that needs to be updated + - parameter name: (form) Updated name of the pet (optional) + - parameter status: (form) Updated status of the pet (optional) + + - returns: RequestBuilder + */ + open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder { + var path = "/pet/{petId}" + path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let formParams: [String:Any?] = [ + "name": name, + "status": status + ] + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, 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 + */ + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, completion: @escaping ((_ data: ApiResponse?,_ error: Error?) -> Void)) { + uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + /** + uploads an image + + - parameter petId: (path) ID of pet to update + - parameter additionalMetadata: (form) Additional data to pass to server (optional) + - parameter file: (form) file to upload (optional) + - returns: Promise + */ + open class func uploadFile( petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> Promise { + let deferred = Promise.pending() + uploadFile(petId: petId, additionalMetadata: additionalMetadata, file: file) { data, error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill(data!) + } + } + return deferred.promise + } + + /** + uploads an image + - POST /pet/{petId}/uploadImage + - + - OAuth: + - type: oauth2 + - name: petstore_auth + - examples: [{contentType=application/json, example={ + "code" : 0, + "type" : "aeiou", + "message" : "aeiou" +}}] + + - 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 + */ + open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder { + var path = "/pet/{petId}/uploadImage" + path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let formParams: [String:Any?] = [ + "additionalMetadata": additionalMetadata, + "file": file + ] + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift new file mode 100644 index 0000000000..c32e543de3 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -0,0 +1,287 @@ +// +// StoreAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire +import PromiseKit + + + +open class StoreAPI { + /** + 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 + */ + open class func deleteOrder(orderId: String, completion: @escaping ((_ error: Error?) -> Void)) { + deleteOrderWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in + completion(error); + } + } + + /** + Delete purchase order by ID + + - parameter orderId: (path) ID of the order that needs to be deleted + - returns: Promise + */ + open class func deleteOrder( orderId: String) -> Promise { + let deferred = Promise.pending() + deleteOrder(orderId: orderId) { error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill() + } + } + return deferred.promise + } + + /** + Delete purchase order by ID + - DELETE /store/order/{order_id} + - 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 + */ + open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder { + var path = "/store/order/{order_id}" + path = path.replacingOccurrences(of: "{order_id}", with: "\(orderId)", options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Returns pet inventories by status + + - parameter completion: completion handler to receive the data and the error objects + */ + open class func getInventory(completion: @escaping ((_ data: [String:Int32]?,_ error: Error?) -> Void)) { + getInventoryWithRequestBuilder().execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + /** + Returns pet inventories by status + + - returns: Promise<[String:Int32]> + */ + open class func getInventory() -> Promise<[String:Int32]> { + let deferred = Promise<[String:Int32]>.pending() + getInventory() { data, error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill(data!) + } + } + return deferred.promise + } + + /** + Returns pet inventories by status + - GET /store/inventory + - Returns a map of status codes to quantities + - API Key: + - type: apiKey api_key + - name: api_key + - examples: [{contentType=application/json, example={ + "key" : 0 +}}] + + - returns: RequestBuilder<[String:Int32]> + */ + open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String:Int32]> { + let path = "/store/inventory" + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder<[String:Int32]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + 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 + */ + open class func getOrderById(orderId: Int64, completion: @escaping ((_ data: Order?,_ error: Error?) -> Void)) { + getOrderByIdWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + /** + Find purchase order by ID + + - parameter orderId: (path) ID of pet that needs to be fetched + - returns: Promise + */ + open class func getOrderById( orderId: Int64) -> Promise { + let deferred = Promise.pending() + getOrderById(orderId: orderId) { data, error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill(data!) + } + } + return deferred.promise + } + + /** + Find purchase order by ID + - GET /store/order/{order_id} + - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + - examples: [{contentType=application/xml, example= + 123456789 + 123456789 + 123 + 2000-01-23T04:56:07.000Z + aeiou + true +}, {contentType=application/json, example={ + "petId" : 6, + "quantity" : 1, + "id" : 0, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : false, + "status" : "placed" +}}] + - examples: [{contentType=application/xml, example= + 123456789 + 123456789 + 123 + 2000-01-23T04:56:07.000Z + aeiou + true +}, {contentType=application/json, example={ + "petId" : 6, + "quantity" : 1, + "id" : 0, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : false, + "status" : "placed" +}}] + + - parameter orderId: (path) ID of pet that needs to be fetched + + - returns: RequestBuilder + */ + open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder { + var path = "/store/order/{order_id}" + path = path.replacingOccurrences(of: "{order_id}", with: "\(orderId)", options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Place an order for a pet + + - parameter body: (body) order placed for purchasing the pet + - parameter completion: completion handler to receive the data and the error objects + */ + open class func placeOrder(body: Order, completion: @escaping ((_ data: Order?,_ error: Error?) -> Void)) { + placeOrderWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + /** + Place an order for a pet + + - parameter body: (body) order placed for purchasing the pet + - returns: Promise + */ + open class func placeOrder( body: Order) -> Promise { + let deferred = Promise.pending() + placeOrder(body: body) { data, error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill(data!) + } + } + return deferred.promise + } + + /** + Place an order for a pet + - POST /store/order + - + - examples: [{contentType=application/xml, example= + 123456789 + 123456789 + 123 + 2000-01-23T04:56:07.000Z + aeiou + true +}, {contentType=application/json, example={ + "petId" : 6, + "quantity" : 1, + "id" : 0, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : false, + "status" : "placed" +}}] + - examples: [{contentType=application/xml, example= + 123456789 + 123456789 + 123 + 2000-01-23T04:56:07.000Z + aeiou + true +}, {contentType=application/json, example={ + "petId" : 6, + "quantity" : 1, + "id" : 0, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : false, + "status" : "placed" +}}] + + - parameter body: (body) order placed for purchasing the pet + + - returns: RequestBuilder + */ + open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder { + let path = "/store/order" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift new file mode 100644 index 0000000000..06c3957804 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -0,0 +1,482 @@ +// +// UserAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire +import PromiseKit + + + +open class UserAPI { + /** + Create user + + - parameter body: (body) Created user object + - parameter completion: completion handler to receive the data and the error objects + */ + open class func createUser(body: User, completion: @escaping ((_ error: Error?) -> Void)) { + createUserWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error); + } + } + + /** + Create user + + - parameter body: (body) Created user object + - returns: Promise + */ + open class func createUser( body: User) -> Promise { + let deferred = Promise.pending() + createUser(body: body) { error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill() + } + } + return deferred.promise + } + + /** + Create user + - POST /user + - This can only be done by the logged in user. + + - parameter body: (body) Created user object + + - returns: RequestBuilder + */ + open class func createUserWithRequestBuilder(body: User) -> RequestBuilder { + let path = "/user" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + Creates list of users with given input array + + - parameter body: (body) List of user object + - parameter completion: completion handler to receive the data and the error objects + */ + open class func createUsersWithArrayInput(body: [User], completion: @escaping ((_ error: Error?) -> Void)) { + createUsersWithArrayInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error); + } + } + + /** + Creates list of users with given input array + + - parameter body: (body) List of user object + - returns: Promise + */ + open class func createUsersWithArrayInput( body: [User]) -> Promise { + let deferred = Promise.pending() + createUsersWithArrayInput(body: body) { error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill() + } + } + return deferred.promise + } + + /** + Creates list of users with given input array + - POST /user/createWithArray + - + + - parameter body: (body) List of user object + + - returns: RequestBuilder + */ + open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder { + let path = "/user/createWithArray" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + Creates list of users with given input array + + - parameter body: (body) List of user object + - parameter completion: completion handler to receive the data and the error objects + */ + open class func createUsersWithListInput(body: [User], completion: @escaping ((_ error: Error?) -> Void)) { + createUsersWithListInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error); + } + } + + /** + Creates list of users with given input array + + - parameter body: (body) List of user object + - returns: Promise + */ + open class func createUsersWithListInput( body: [User]) -> Promise { + let deferred = Promise.pending() + createUsersWithListInput(body: body) { error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill() + } + } + return deferred.promise + } + + /** + Creates list of users with given input array + - POST /user/createWithList + - + + - parameter body: (body) List of user object + + - returns: RequestBuilder + */ + open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder { + let path = "/user/createWithList" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, 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 + */ + open class func deleteUser(username: String, completion: @escaping ((_ error: Error?) -> Void)) { + deleteUserWithRequestBuilder(username: username).execute { (response, error) -> Void in + completion(error); + } + } + + /** + Delete user + + - parameter username: (path) The name that needs to be deleted + - returns: Promise + */ + open class func deleteUser( username: String) -> Promise { + let deferred = Promise.pending() + deleteUser(username: username) { error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill() + } + } + return deferred.promise + } + + /** + Delete user + - DELETE /user/{username} + - This can only be done by the logged in user. + + - parameter username: (path) The name that needs to be deleted + + - returns: RequestBuilder + */ + open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder { + var path = "/user/{username}" + path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + 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 + */ + open class func getUserByName(username: String, completion: @escaping ((_ data: User?,_ error: Error?) -> Void)) { + getUserByNameWithRequestBuilder(username: username).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + /** + Get user by user name + + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + - returns: Promise + */ + open class func getUserByName( username: String) -> Promise { + let deferred = Promise.pending() + getUserByName(username: username) { data, error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill(data!) + } + } + return deferred.promise + } + + /** + Get user by user name + - GET /user/{username} + - + - examples: [{contentType=application/xml, example= + 123456789 + aeiou + aeiou + aeiou + aeiou + aeiou + aeiou + 123 +}, {contentType=application/json, example={ + "firstName" : "aeiou", + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 6, + "phone" : "aeiou", + "id" : 0, + "email" : "aeiou", + "username" : "aeiou" +}}] + - examples: [{contentType=application/xml, example= + 123456789 + aeiou + aeiou + aeiou + aeiou + aeiou + aeiou + 123 +}, {contentType=application/json, example={ + "firstName" : "aeiou", + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 6, + "phone" : "aeiou", + "id" : 0, + "email" : "aeiou", + "username" : "aeiou" +}}] + + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + + - returns: RequestBuilder + */ + open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder { + var path = "/user/{username}" + path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Logs user into the system + + - parameter username: (query) The user name for login + - parameter password: (query) The password for login in clear text + - parameter completion: completion handler to receive the data and the error objects + */ + open class func loginUser(username: String, password: String, completion: @escaping ((_ data: String?,_ error: Error?) -> Void)) { + loginUserWithRequestBuilder(username: username, password: password).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + /** + Logs user into the system + + - parameter username: (query) The user name for login + - parameter password: (query) The password for login in clear text + - returns: Promise + */ + open class func loginUser( username: String, password: String) -> Promise { + let deferred = Promise.pending() + loginUser(username: username, password: password) { data, error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill(data!) + } + } + return deferred.promise + } + + /** + Logs user into the system + - GET /user/login + - + - responseHeaders: [X-Rate-Limit(Int32), X-Expires-After(Date)] + - responseHeaders: [X-Rate-Limit(Int32), X-Expires-After(Date)] + - examples: [{contentType=application/xml, example=aeiou}, {contentType=application/json, example="aeiou"}] + - examples: [{contentType=application/xml, example=aeiou}, {contentType=application/json, example="aeiou"}] + + - parameter username: (query) The user name for login + - parameter password: (query) The password for login in clear text + + - returns: RequestBuilder + */ + open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { + let path = "/user/login" + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + "username": username, + "password": password + ]) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Logs out current logged in user session + + - parameter completion: completion handler to receive the data and the error objects + */ + open class func logoutUser(completion: @escaping ((_ error: Error?) -> Void)) { + logoutUserWithRequestBuilder().execute { (response, error) -> Void in + completion(error); + } + } + + /** + Logs out current logged in user session + + - returns: Promise + */ + open class func logoutUser() -> Promise { + let deferred = Promise.pending() + logoutUser() { error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill() + } + } + return deferred.promise + } + + /** + Logs out current logged in user session + - GET /user/logout + - + + - returns: RequestBuilder + */ + open class func logoutUserWithRequestBuilder() -> RequestBuilder { + let path = "/user/logout" + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Updated user + + - parameter username: (path) name that need to be deleted + - parameter body: (body) Updated user object + - parameter completion: completion handler to receive the data and the error objects + */ + open class func updateUser(username: String, body: User, completion: @escaping ((_ error: Error?) -> Void)) { + updateUserWithRequestBuilder(username: username, body: body).execute { (response, error) -> Void in + completion(error); + } + } + + /** + Updated user + + - parameter username: (path) name that need to be deleted + - parameter body: (body) Updated user object + - returns: Promise + */ + open class func updateUser( username: String, body: User) -> Promise { + let deferred = Promise.pending() + updateUser(username: username, body: body) { error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill() + } + } + return deferred.promise + } + + /** + Updated user + - PUT /user/{username} + - This can only be done by the logged in user. + + - parameter username: (path) name that need to be deleted + - parameter body: (body) Updated user object + + - returns: RequestBuilder + */ + open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder { + var path = "/user/{username}" + path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift new file mode 100644 index 0000000000..b9d2a2727d --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -0,0 +1,307 @@ +// AlamofireImplementations.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire + +class AlamofireRequestBuilderFactory: RequestBuilderFactory { + func getNonDecodableBuilder() -> RequestBuilder.Type { + return AlamofireRequestBuilder.self + } + + func getBuilder() -> RequestBuilder.Type { + return AlamofireDecodableRequestBuilder.self + } +} + +// Store manager to retain its reference +private var managerStore: [String: Alamofire.SessionManager] = [:] + +open class AlamofireRequestBuilder: RequestBuilder { + required public init(method: String, URLString: String, parameters: [String : Any]?, isBody: Bool, headers: [String : String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody, headers: headers) + } + + /** + May be overridden by a subclass if you want to control the session + configuration. + */ + open func createSessionManager() -> Alamofire.SessionManager { + let configuration = URLSessionConfiguration.default + configuration.httpAdditionalHeaders = buildHeaders() + return Alamofire.SessionManager(configuration: configuration) + } + + /** + May be overridden by a subclass if you want to control the Content-Type + that is given to an uploaded form part. + + Return nil to use the default behavior (inferring the Content-Type from + the file extension). Return the desired Content-Type otherwise. + */ + open func contentTypeForFormPart(fileURL: URL) -> String? { + return nil + } + + /** + May be overridden by a subclass if you want to control the request + configuration (e.g. to override the cache policy). + */ + open func makeRequest(manager: SessionManager, method: HTTPMethod, encoding: ParameterEncoding, headers: [String:String]) -> DataRequest { + return manager.request(URLString, method: method, parameters: parameters, encoding: encoding, headers: headers) + } + + override open func execute(_ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { + let managerId:String = UUID().uuidString + // Create a new manager for each request to customize its request header + let manager = createSessionManager() + managerStore[managerId] = manager + + let encoding:ParameterEncoding = isBody ? JSONDataEncoding() : URLEncoding() + + let xMethod = Alamofire.HTTPMethod(rawValue: method) + let fileKeys = parameters == nil ? [] : parameters!.filter { $1 is NSURL } + .map { $0.0 } + + if fileKeys.count > 0 { + manager.upload(multipartFormData: { mpForm in + for (k, v) in self.parameters! { + switch v { + case let fileURL as URL: + if let mimeType = self.contentTypeForFormPart(fileURL: fileURL) { + mpForm.append(fileURL, withName: k, fileName: fileURL.lastPathComponent, mimeType: mimeType) + } + else { + mpForm.append(fileURL, withName: k) + } + break + case let string as String: + mpForm.append(string.data(using: String.Encoding.utf8)!, withName: k) + break + case let number as NSNumber: + mpForm.append(number.stringValue.data(using: String.Encoding.utf8)!, withName: k) + break + default: + fatalError("Unprocessable value \(v) with key \(k)") + break + } + } + }, to: URLString, method: xMethod!, headers: nil, encodingCompletion: { encodingResult in + switch encodingResult { + case .success(let upload, _, _): + if let onProgressReady = self.onProgressReady { + onProgressReady(upload.uploadProgress) + } + self.processRequest(request: upload, managerId, completion) + case .failure(let encodingError): + completion(nil, ErrorResponse.Error(415, nil, encodingError)) + } + }) + } else { + let request = makeRequest(manager: manager, method: xMethod!, encoding: encoding, headers: headers) + if let onProgressReady = self.onProgressReady { + onProgressReady(request.progress) + } + processRequest(request: request, managerId, completion) + } + + } + + fileprivate func processRequest(request: DataRequest, _ managerId: String, _ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { + if let credential = self.credential { + request.authenticate(usingCredential: credential) + } + + let cleanupRequest = { + _ = managerStore.removeValue(forKey: managerId) + } + + let validatedRequest = request.validate() + + switch T.self { + case is String.Type: + validatedRequest.responseString(completionHandler: { (stringResponse) in + cleanupRequest() + + if stringResponse.result.isFailure { + completion( + nil, + ErrorResponse.Error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.result.error as Error!) + ) + return + } + + completion( + Response( + response: stringResponse.response!, + body: ((stringResponse.result.value ?? "") as! T) + ), + nil + ) + }) + case is Void.Type: + validatedRequest.responseData(completionHandler: { (voidResponse) in + cleanupRequest() + + if voidResponse.result.isFailure { + completion( + nil, + ErrorResponse.Error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.result.error!) + ) + return + } + + completion( + Response( + response: voidResponse.response!, + body: nil), + nil + ) + }) + default: + validatedRequest.responseData(completionHandler: { (dataResponse) in + cleanupRequest() + + if (dataResponse.result.isFailure) { + completion( + nil, + ErrorResponse.Error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!) + ) + return + } + + completion( + Response( + response: dataResponse.response!, + body: (dataResponse.data as! T) + ), + nil + ) + }) + } + } + + open func buildHeaders() -> [String: String] { + var httpHeaders = SessionManager.defaultHTTPHeaders + for (key, value) in self.headers { + httpHeaders[key] = value + } + return httpHeaders + } +} + +public enum AlamofireDecodableRequestBuilderError: Error { + case emptyDataResponse + case nilHTTPResponse + case jsonDecoding(DecodingError) + case generalError(Error) +} + +open class AlamofireDecodableRequestBuilder: AlamofireRequestBuilder { + + override fileprivate func processRequest(request: DataRequest, _ managerId: String, _ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { + if let credential = self.credential { + request.authenticate(usingCredential: credential) + } + + let cleanupRequest = { + _ = managerStore.removeValue(forKey: managerId) + } + + let validatedRequest = request.validate() + + switch T.self { + case is String.Type: + validatedRequest.responseString(completionHandler: { (stringResponse) in + cleanupRequest() + + if stringResponse.result.isFailure { + completion( + nil, + ErrorResponse.Error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.result.error as Error!) + ) + return + } + + completion( + Response( + response: stringResponse.response!, + body: ((stringResponse.result.value ?? "") as! T) + ), + nil + ) + }) + case is Void.Type: + validatedRequest.responseData(completionHandler: { (voidResponse) in + cleanupRequest() + + if voidResponse.result.isFailure { + completion( + nil, + ErrorResponse.Error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.result.error!) + ) + return + } + + completion( + Response( + response: voidResponse.response!, + body: nil), + nil + ) + }) + case is Data.Type: + validatedRequest.responseData(completionHandler: { (dataResponse) in + cleanupRequest() + + if (dataResponse.result.isFailure) { + completion( + nil, + ErrorResponse.Error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!) + ) + return + } + + completion( + Response( + response: dataResponse.response!, + body: (dataResponse.data as! T) + ), + nil + ) + }) + default: + validatedRequest.responseData(completionHandler: { (dataResponse: DataResponse) in + cleanupRequest() + + guard dataResponse.result.isSuccess else { + completion(nil, ErrorResponse.Error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!)) + return + } + + guard let data = dataResponse.data, !data.isEmpty else { + completion(nil, ErrorResponse.Error(-1, nil, AlamofireDecodableRequestBuilderError.emptyDataResponse)) + return + } + + guard let httpResponse = dataResponse.response else { + completion(nil, ErrorResponse.Error(-2, nil, AlamofireDecodableRequestBuilderError.nilHTTPResponse)) + return + } + + var responseObj: Response? = nil + + let decodeResult: (decodableObj: T?, error: Error?) = CodableHelper.decode(T.self, from: data) + if decodeResult.error == nil { + responseObj = Response(response: httpResponse, body: decodeResult.decodableObj) + } + + completion(responseObj, decodeResult.error) + }) + } + } + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/CodableHelper.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/CodableHelper.swift new file mode 100644 index 0000000000..7603003824 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/CodableHelper.swift @@ -0,0 +1,53 @@ +// +// CodableHelper.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +public typealias EncodeResult = (data: Data?, error: Error?) + +open class CodableHelper { + + open class func decode(_ type: T.Type, from data: Data) -> (decodableObj: T?, error: Error?) where T : Decodable { + var returnedDecodable: T? = nil + var returnedError: Error? = nil + + let decoder = JSONDecoder() + decoder.dataDecodingStrategy = .base64Decode + if #available(iOS 10.0, *) { + decoder.dateDecodingStrategy = .iso8601 + } + + do { + returnedDecodable = try decoder.decode(type, from: data) + } catch { + returnedError = error + } + + return (returnedDecodable, returnedError) + } + + open class func encode(_ value: T, prettyPrint: Bool = false) -> EncodeResult where T : Encodable { + var returnedData: Data? + var returnedError: Error? = nil + + let encoder = JSONEncoder() + encoder.outputFormatting = (prettyPrint ? .prettyPrinted : .compact) + encoder.dataEncodingStrategy = .base64Encode + if #available(iOS 10.0, *) { + encoder.dateEncodingStrategy = .iso8601 + } + + do { + returnedData = try encoder.encode(value) + } catch { + returnedError = error + } + + return (returnedData, returnedError) + } + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Configuration.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Configuration.swift new file mode 100644 index 0000000000..c03a10b930 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Configuration.swift @@ -0,0 +1,15 @@ +// Configuration.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +open class Configuration { + + // This value is used to configure the date formatter that is used to serialize dates into JSON format. + // You must set it prior to encoding any dates, and it will only be read once. + open static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + +} \ No newline at end of file diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Extensions.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Extensions.swift new file mode 100644 index 0000000000..d672b1f799 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Extensions.swift @@ -0,0 +1,100 @@ +// Extensions.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire +import PromiseKit + +extension Bool: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension Float: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension Int: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension Int32: JSONEncodable { + func encodeToJSON() -> Any { return NSNumber(value: self as Int32) } +} + +extension Int64: JSONEncodable { + func encodeToJSON() -> Any { return NSNumber(value: self as Int64) } +} + +extension Double: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension String: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +private func encodeIfPossible(_ object: T) -> Any { + if let encodableObject = object as? JSONEncodable { + return encodableObject.encodeToJSON() + } else { + return object as Any + } +} + +extension Array: JSONEncodable { + func encodeToJSON() -> Any { + return self.map(encodeIfPossible) + } +} + +extension Dictionary: JSONEncodable { + func encodeToJSON() -> Any { + var dictionary = [AnyHashable: Any]() + for (key, value) in self { + dictionary[key as! NSObject] = encodeIfPossible(value) + } + return dictionary as Any + } +} + +extension Data: JSONEncodable { + func encodeToJSON() -> Any { + return self.base64EncodedString(options: Data.Base64EncodingOptions()) + } +} + +private let dateFormatter: DateFormatter = { + let fmt = DateFormatter() + fmt.dateFormat = Configuration.dateFormat + fmt.locale = Locale(identifier: "en_US_POSIX") + return fmt +}() + +extension Date: JSONEncodable { + func encodeToJSON() -> Any { + return dateFormatter.string(from: self) as Any + } +} + +extension UUID: JSONEncodable { + func encodeToJSON() -> Any { + return self.uuidString + } +} + +extension RequestBuilder { + public func execute() -> Promise> { + let deferred = Promise>.pending() + self.execute { (response: Response?, error: Error?) in + if let response = response { + deferred.fulfill(response) + } else { + deferred.reject(error!) + } + } + return deferred.promise + } +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/JSONEncodableEncoding.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/JSONEncodableEncoding.swift new file mode 100644 index 0000000000..472e955ee8 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/JSONEncodableEncoding.swift @@ -0,0 +1,54 @@ +// +// JSONDataEncoding.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire + +public struct JSONDataEncoding: ParameterEncoding { + + // MARK: Properties + + private static let jsonDataKey = "jsonData" + + // MARK: Encoding + + /// 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. This should have a single key/value + /// pair with "jsonData" as the key and a Data object as the value. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let jsonData = parameters?[JSONDataEncoding.jsonDataKey] as? Data, !jsonData.isEmpty else { + return urlRequest + } + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = jsonData + + return urlRequest + } + + public static func encodingParameters(jsonData: Data?) -> Parameters? { + var returnedParams: Parameters? = nil + if let jsonData = jsonData, !jsonData.isEmpty { + var params = Parameters() + params[jsonDataKey] = jsonData + returnedParams = params + } + return returnedParams + } + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/JSONEncodingHelper.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/JSONEncodingHelper.swift new file mode 100644 index 0000000000..4cf4ac206a --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/JSONEncodingHelper.swift @@ -0,0 +1,27 @@ +// +// JSONEncodingHelper.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire + +open class JSONEncodingHelper { + + open class func encodingParameters(forEncodableObject encodableObj: T?) -> Parameters? { + var params: Parameters? = nil + + // Encode the Encodable object + if let encodableObj = encodableObj { + let encodeResult = CodableHelper.encode(encodableObj, prettyPrint: true) + if encodeResult.error == nil { + params = JSONDataEncoding.encodingParameters(jsonData: encodeResult.data) + } + } + + return params + } + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models.swift new file mode 100644 index 0000000000..2c19b32158 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models.swift @@ -0,0 +1,36 @@ +// Models.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +protocol JSONEncodable { + func encodeToJSON() -> Any +} + +public enum ErrorResponse : Error { + case Error(Int, Data?, Error) +} + +open class Response { + open let statusCode: Int + open let header: [String: String] + open 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: HTTPURLResponse, 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) + } +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift new file mode 100644 index 0000000000..8d3e08500d --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift @@ -0,0 +1,18 @@ +// +// AdditionalPropertiesClass.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class AdditionalPropertiesClass: Codable { + + public var mapProperty: [String:String]? + public var mapOfMapProperty: [String:[String:String]]? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Animal.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Animal.swift new file mode 100644 index 0000000000..b2079ff79c --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Animal.swift @@ -0,0 +1,18 @@ +// +// Animal.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Animal: Codable { + + public var className: String? + public var color: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/AnimalFarm.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/AnimalFarm.swift new file mode 100644 index 0000000000..6830836489 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/AnimalFarm.swift @@ -0,0 +1,11 @@ +// +// AnimalFarm.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift new file mode 100644 index 0000000000..b9af1103e2 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift @@ -0,0 +1,19 @@ +// +// ApiResponse.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class ApiResponse: Codable { + + public var code: Int32? + public var type: String? + public var message: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift new file mode 100644 index 0000000000..7eb6b23bd2 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift @@ -0,0 +1,17 @@ +// +// ArrayOfArrayOfNumberOnly.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class ArrayOfArrayOfNumberOnly: Codable { + + public var arrayArrayNumber: [[Double]]? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift new file mode 100644 index 0000000000..ab6493cb3c --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift @@ -0,0 +1,17 @@ +// +// ArrayOfNumberOnly.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class ArrayOfNumberOnly: Codable { + + public var arrayNumber: [Double]? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift new file mode 100644 index 0000000000..bf28bb3cc9 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift @@ -0,0 +1,19 @@ +// +// ArrayTest.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class ArrayTest: Codable { + + public var arrayOfString: [String]? + public var arrayArrayOfInteger: [[Int64]]? + public var arrayArrayOfModel: [[ReadOnlyFirst]]? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift new file mode 100644 index 0000000000..e9569b9fb0 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift @@ -0,0 +1,23 @@ +// +// Capitalization.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Capitalization: Codable { + + public var smallCamel: String? + public var capitalCamel: String? + public var smallSnake: String? + public var capitalSnake: String? + public var sCAETHFlowPoints: String? + /** Name of the pet */ + public var ATT_NAME: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Cat.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Cat.swift new file mode 100644 index 0000000000..5ea6f4ea94 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Cat.swift @@ -0,0 +1,17 @@ +// +// Cat.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Cat: Animal { + + public var declawed: Bool? + + + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Category.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Category.swift new file mode 100644 index 0000000000..e21a4c54dd --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Category.swift @@ -0,0 +1,18 @@ +// +// Category.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Category: Codable { + + public var id: Int64? + public var name: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift new file mode 100644 index 0000000000..8fe4a89e76 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift @@ -0,0 +1,18 @@ +// +// ClassModel.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +/** Model for testing model with \"_class\" property */ +open class ClassModel: Codable { + + public var _class: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Client.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Client.swift new file mode 100644 index 0000000000..874bdd7cee --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Client.swift @@ -0,0 +1,17 @@ +// +// Client.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Client: Codable { + + public var client: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Dog.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Dog.swift new file mode 100644 index 0000000000..2b4c3f8a3e --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Dog.swift @@ -0,0 +1,17 @@ +// +// Dog.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Dog: Animal { + + public var breed: String? + + + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift new file mode 100644 index 0000000000..d3da696d1c --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift @@ -0,0 +1,26 @@ +// +// EnumArrays.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class EnumArrays: Codable { + + public enum JustSymbol: String, Codable { + case greaterThanOrEqualTo = ">=" + case dollar = "$" + } + public enum ArrayEnum: String, Codable { + case fish = "fish" + case crab = "crab" + } + public var justSymbol: JustSymbol? + public var arrayEnum: [ArrayEnum]? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/EnumClass.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/EnumClass.swift new file mode 100644 index 0000000000..d0889a3520 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/EnumClass.swift @@ -0,0 +1,16 @@ +// +// EnumClass.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public enum EnumClass: String, Codable { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift new file mode 100644 index 0000000000..7e0266de3f --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift @@ -0,0 +1,33 @@ +// +// EnumTest.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class EnumTest: Codable { + + public enum EnumString: String, Codable { + case upper = "UPPER" + case lower = "lower" + case empty = "" + } + public enum EnumInteger: Int32, Codable { + case _1 = 1 + case numberminus1 = -1 + } + public enum EnumNumber: Double, Codable { + case _11 = 1.1 + case numberminus12 = -1.2 + } + public var enumString: EnumString? + public var enumInteger: EnumInteger? + public var enumNumber: EnumNumber? + public var outerEnum: OuterEnum? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift new file mode 100644 index 0000000000..3c6ef7d3e3 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift @@ -0,0 +1,29 @@ +// +// FormatTest.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class FormatTest: Codable { + + public var integer: Int32? + public var int32: Int32? + public var int64: Int64? + public var number: Double? + public var float: Float? + public var double: Double? + public var string: String? + public var byte: Data? + public var binary: Data? + public var date: Date? + public var dateTime: Date? + public var uuid: UUID? + public var password: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift new file mode 100644 index 0000000000..fef361d308 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift @@ -0,0 +1,18 @@ +// +// HasOnlyReadOnly.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class HasOnlyReadOnly: Codable { + + public var bar: String? + public var foo: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/List.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/List.swift new file mode 100644 index 0000000000..5fab950e8e --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/List.swift @@ -0,0 +1,17 @@ +// +// List.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class List: Codable { + + public var _123List: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/MapTest.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/MapTest.swift new file mode 100644 index 0000000000..584b181f02 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/MapTest.swift @@ -0,0 +1,22 @@ +// +// MapTest.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class MapTest: Codable { + + public enum MapOfEnumString: String, Codable { + case upper = "UPPER" + case lower = "lower" + } + public var mapMapOfString: [String:[String:String]]? + public var mapOfEnumString: [String:String]? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift new file mode 100644 index 0000000000..7fd6c6cf10 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -0,0 +1,19 @@ +// +// MixedPropertiesAndAdditionalPropertiesClass.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class MixedPropertiesAndAdditionalPropertiesClass: Codable { + + public var uuid: UUID? + public var dateTime: Date? + public var map: [String:Animal]? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift new file mode 100644 index 0000000000..ac1ec94073 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift @@ -0,0 +1,19 @@ +// +// Model200Response.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +/** Model for testing model name starting with number */ +open class Model200Response: Codable { + + public var name: Int32? + public var _class: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Name.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Name.swift new file mode 100644 index 0000000000..de6751e52d --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Name.swift @@ -0,0 +1,21 @@ +// +// Name.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +/** Model for testing model name same as property name */ +open class Name: Codable { + + public var name: Int32? + public var snakeCase: Int32? + public var property: String? + public var _123Number: Int32? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift new file mode 100644 index 0000000000..e4f4dc0f7c --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift @@ -0,0 +1,17 @@ +// +// NumberOnly.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class NumberOnly: Codable { + + public var justNumber: Double? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Order.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Order.swift new file mode 100644 index 0000000000..f5fab2487e --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Order.swift @@ -0,0 +1,28 @@ +// +// Order.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Order: Codable { + + public enum Status: String, Codable { + case placed = "placed" + case approved = "approved" + case delivered = "delivered" + } + public var id: Int64? + public var petId: Int64? + public var quantity: Int32? + public var shipDate: Date? + /** Order Status */ + public var status: Status? + public var complete: Bool? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/OuterBoolean.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/OuterBoolean.swift new file mode 100644 index 0000000000..3c49ad2940 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/OuterBoolean.swift @@ -0,0 +1,11 @@ +// +// OuterBoolean.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public typealias OuterBoolean = Bool diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/OuterComposite.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/OuterComposite.swift new file mode 100644 index 0000000000..6d3b435cd1 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/OuterComposite.swift @@ -0,0 +1,19 @@ +// +// OuterComposite.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class OuterComposite: Codable { + + public var myNumber: OuterNumber? + public var myString: OuterString? + public var myBoolean: OuterBoolean? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/OuterEnum.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/OuterEnum.swift new file mode 100644 index 0000000000..d6222d2b1c --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/OuterEnum.swift @@ -0,0 +1,16 @@ +// +// OuterEnum.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public enum OuterEnum: String, Codable { + case placed = "placed" + case approved = "approved" + case delivered = "delivered" + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/OuterNumber.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/OuterNumber.swift new file mode 100644 index 0000000000..f285f4e5e2 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/OuterNumber.swift @@ -0,0 +1,11 @@ +// +// OuterNumber.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public typealias OuterNumber = Double diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/OuterString.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/OuterString.swift new file mode 100644 index 0000000000..9da794627d --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/OuterString.swift @@ -0,0 +1,11 @@ +// +// OuterString.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public typealias OuterString = String diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Pet.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Pet.swift new file mode 100644 index 0000000000..08128cc529 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Pet.swift @@ -0,0 +1,28 @@ +// +// Pet.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Pet: Codable { + + public enum Status: String, Codable { + 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() {} + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift new file mode 100644 index 0000000000..0a779fdd48 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift @@ -0,0 +1,18 @@ +// +// ReadOnlyFirst.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class ReadOnlyFirst: Codable { + + public var bar: String? + public var baz: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Return.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Return.swift new file mode 100644 index 0000000000..629ec1fba6 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Return.swift @@ -0,0 +1,18 @@ +// +// Return.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +/** Model for testing reserved words */ +open class Return: Codable { + + public var _return: Int32? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift new file mode 100644 index 0000000000..e012be66e3 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift @@ -0,0 +1,17 @@ +// +// SpecialModelName.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class SpecialModelName: Codable { + + public var specialPropertyName: Int64? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Tag.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Tag.swift new file mode 100644 index 0000000000..219dd5bade --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/Tag.swift @@ -0,0 +1,18 @@ +// +// Tag.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Tag: Codable { + + public var id: Int64? + public var name: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/User.swift b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/User.swift new file mode 100644 index 0000000000..2e80b7d20f --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/PetstoreClient/Classes/Swaggers/Models/User.swift @@ -0,0 +1,25 @@ +// +// User.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class User: Codable { + + 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() {} + +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Podfile b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Podfile new file mode 100644 index 0000000000..5556eaf234 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Podfile @@ -0,0 +1,18 @@ +use_frameworks! +source 'https://github.com/CocoaPods/Specs.git' + +target 'SwaggerClient' do + pod "PetstoreClient", :path => "../" + + target 'SwaggerClientTests' do + inherit! :search_paths + end +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + target.build_configurations.each do |configuration| + configuration.build_settings['SWIFT_VERSION'] = "3.0" + end + end +end \ No newline at end of file diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Podfile.lock b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Podfile.lock new file mode 100644 index 0000000000..2ecaf7a82b --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Podfile.lock @@ -0,0 +1,32 @@ +PODS: + - Alamofire (4.5.0) + - PetstoreClient (0.0.1): + - Alamofire (~> 4.5) + - PromiseKit (~> 4.2.2) + - PromiseKit (4.2.2): + - PromiseKit/Foundation (= 4.2.2) + - PromiseKit/QuartzCore (= 4.2.2) + - PromiseKit/UIKit (= 4.2.2) + - PromiseKit/CorePromise (4.2.2) + - PromiseKit/Foundation (4.2.2): + - PromiseKit/CorePromise + - PromiseKit/QuartzCore (4.2.2): + - PromiseKit/CorePromise + - PromiseKit/UIKit (4.2.2): + - PromiseKit/CorePromise + +DEPENDENCIES: + - PetstoreClient (from `../`) + +EXTERNAL SOURCES: + PetstoreClient: + :path: ../ + +SPEC CHECKSUMS: + Alamofire: f28cdffd29de33a7bfa022cbd63ae95a27fae140 + PetstoreClient: dd4a9f18265468d1f25e14ed1651245c668448c3 + PromiseKit: 00e8886881f151c7e573d06b437915b0bb2970ec + +PODFILE CHECKSUM: da9f5a7ad6086f2c7abb73cf2c35cefce04a9a30 + +COCOAPODS: 1.1.1 diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/LICENSE b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/LICENSE new file mode 100644 index 0000000000..4cfbf72a4d --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/LICENSE @@ -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. diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/README.md b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/README.md new file mode 100644 index 0000000000..e1966fdca0 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/README.md @@ -0,0 +1,1857 @@ +![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/assets/alamofire.png) + +[![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg?branch=master)](https://travis-ci.org/Alamofire/Alamofire) +[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg) +[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) +[![Platform](https://img.shields.io/cocoapods/p/Alamofire.svg?style=flat)](http://cocoadocs.org/docsets/Alamofire) +[![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat)](http://twitter.com/AlamofireSF) +[![Gitter](https://badges.gitter.im/Alamofire/Alamofire.svg)](https://gitter.im/Alamofire/Alamofire?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) + +Alamofire is an HTTP networking library written in Swift. + +- [Features](#features) +- [Component Libraries](#component-libraries) +- [Requirements](#requirements) +- [Migration Guides](#migration-guides) +- [Communication](#communication) +- [Installation](#installation) +- [Usage](#usage) + - **Intro -** [Making a Request](#making-a-request), [Response Handling](#response-handling), [Response Validation](#response-validation), [Response Caching](#response-caching) + - **HTTP -** [HTTP Methods](#http-methods), [Parameter Encoding](#parameter-encoding), [HTTP Headers](#http-headers), [Authentication](#authentication) + - **Large Data -** [Downloading Data to a File](#downloading-data-to-a-file), [Uploading Data to a Server](#uploading-data-to-a-server) + - **Tools -** [Statistical Metrics](#statistical-metrics), [cURL Command Output](#curl-command-output) +- [Advanced Usage](#advanced-usage) + - **URL Session -** [Session Manager](#session-manager), [Session Delegate](#session-delegate), [Request](#request) + - **Routing -** [Routing Requests](#routing-requests), [Adapting and Retrying Requests](#adapting-and-retrying-requests) + - **Model Objects -** [Custom Response Serialization](#custom-response-serialization) + - **Connection -** [Security](#security), [Network Reachability](#network-reachability) +- [Open Radars](#open-radars) +- [FAQ](#faq) +- [Credits](#credits) +- [Donations](#donations) +- [License](#license) + +## Features + +- [x] Chainable Request / Response Methods +- [x] URL / JSON / plist Parameter Encoding +- [x] Upload File / Data / Stream / MultipartFormData +- [x] Download File using Request or Resume Data +- [x] Authentication with URLCredential +- [x] HTTP Response Validation +- [x] Upload and Download Progress Closures with Progress +- [x] cURL Command Output +- [x] Dynamically Adapt and Retry Requests +- [x] TLS Certificate and Public Key Pinning +- [x] Network Reachability +- [x] Comprehensive Unit and Integration Test Coverage +- [x] [Complete Documentation](http://cocoadocs.org/docsets/Alamofire) + +## Component Libraries + +In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem. + +- [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system. +- [AlamofireNetworkActivityIndicator](https://github.com/Alamofire/AlamofireNetworkActivityIndicator) - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support `URLSession` instances not managed by Alamofire. + +## Requirements + +- iOS 8.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ +- Xcode 8.1, 8.2, 8.3, and 9.0 +- Swift 3.0, 3.1, 3.2, and 4.0 + +## Migration Guides + +- [Alamofire 4.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md) +- [Alamofire 3.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md) +- [Alamofire 2.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%202.0%20Migration%20Guide.md) + +## Communication + +- If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/alamofire). (Tag 'alamofire') +- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/alamofire). +- If you **found a bug**, open an issue. +- If you **have a feature request**, open an issue. +- If you **want to contribute**, submit a pull request. + +## Installation + +### CocoaPods + +[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command: + +```bash +$ gem install cocoapods +``` + +> CocoaPods 1.1.0+ is required to build Alamofire 4.0.0+. + +To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`: + +```ruby +source 'https://github.com/CocoaPods/Specs.git' +platform :ios, '10.0' +use_frameworks! + +target '' do + pod 'Alamofire', '~> 4.4' +end +``` + +Then, run the following command: + +```bash +$ pod install +``` + +### Carthage + +[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. + +You can install Carthage with [Homebrew](http://brew.sh/) using the following command: + +```bash +$ brew update +$ brew install carthage +``` + +To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: + +```ogdl +github "Alamofire/Alamofire" ~> 4.4 +``` + +Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project. + +### Swift Package Manager + +The [Swift Package Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the `swift` compiler. It is in early development, but Alamofire does support its use on supported platforms. + +Once you have your Swift package set up, adding Alamofire as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`. + +```swift +dependencies: [ + .Package(url: "https://github.com/Alamofire/Alamofire.git", majorVersion: 4) +] +``` + +### Manually + +If you prefer not to use any of the aforementioned dependency managers, you can integrate Alamofire into your project manually. + +#### Embedded Framework + +- Open up Terminal, `cd` into your top-level project directory, and run the following command "if" your project is not initialized as a git repository: + + ```bash + $ git init + ``` + +- Add Alamofire as a git [submodule](http://git-scm.com/docs/git-submodule) by running the following command: + + ```bash + $ git submodule add https://github.com/Alamofire/Alamofire.git + ``` + +- Open the new `Alamofire` folder, and drag the `Alamofire.xcodeproj` into the Project Navigator of your application's Xcode project. + + > It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter. + +- Select the `Alamofire.xcodeproj` in the Project Navigator and verify the deployment target matches that of your application target. +- Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar. +- In the tab bar at the top of that window, open the "General" panel. +- Click on the `+` button under the "Embedded Binaries" section. +- You will see two different `Alamofire.xcodeproj` folders each with two different versions of the `Alamofire.framework` nested inside a `Products` folder. + + > It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`. + +- Select the top `Alamofire.framework` for iOS and the bottom one for OS X. + + > You can verify which one you selected by inspecting the build log for your project. The build target for `Alamofire` will be listed as either `Alamofire iOS`, `Alamofire macOS`, `Alamofire tvOS` or `Alamofire watchOS`. + +- And that's it! + + > The `Alamofire.framework` is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device. + +--- + +## Usage + +### Making a Request + +```swift +import Alamofire + +Alamofire.request("https://httpbin.org/get") +``` + +### Response Handling + +Handling the `Response` of a `Request` made in Alamofire involves chaining a response handler onto the `Request`. + +```swift +Alamofire.request("https://httpbin.org/get").responseJSON { response in + print("Request: \(String(describing: response.request))") // original url request + print("Response: \(String(describing: response.response))") // http url response + print("Result: \(response.result)") // response serialization result + + if let json = response.result.value { + print("JSON: \(json)") // serialized json response + } + + if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) { + print("Data: \(utf8Text)") // original server data as UTF8 string + } +} +``` + +In the above example, the `responseJSON` handler is appended to the `Request` to be executed once the `Request` is complete. Rather than blocking execution to wait for a response from the server, a [callback](http://en.wikipedia.org/wiki/Callback_%28computer_programming%29) in the form of a closure is specified to handle the response once it's received. The result of a request is only available inside the scope of a response closure. Any execution contingent on the response or data received from the server must be done within a response closure. + +> Networking in Alamofire is done _asynchronously_. Asynchronous programming may be a source of frustration to programmers unfamiliar with the concept, but there are [very good reasons](https://developer.apple.com/library/ios/qa/qa1693/_index.html) for doing it this way. + +Alamofire contains five different response handlers by default including: + +```swift +// Response Handler - Unserialized Response +func response( + queue: DispatchQueue?, + completionHandler: @escaping (DefaultDataResponse) -> Void) + -> Self + +// Response Data Handler - Serialized into Data +func responseData( + queue: DispatchQueue?, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + +// Response String Handler - Serialized into String +func responseString( + queue: DispatchQueue?, + encoding: String.Encoding?, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + +// Response JSON Handler - Serialized into Any +func responseJSON( + queue: DispatchQueue?, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + +// Response PropertyList (plist) Handler - Serialized into Any +func responsePropertyList( + queue: DispatchQueue?, + completionHandler: @escaping (DataResponse) -> Void)) + -> Self +``` + +None of the response handlers perform any validation of the `HTTPURLResponse` it gets back from the server. + +> For example, response status codes in the `400..<500` and `500..<600` ranges do NOT automatically trigger an `Error`. Alamofire uses [Response Validation](#response-validation) method chaining to achieve this. + +#### Response Handler + +The `response` handler does NOT evaluate any of the response data. It merely forwards on all information directly from the URL session delegate. It is the Alamofire equivalent of using `cURL` to execute a `Request`. + +```swift +Alamofire.request("https://httpbin.org/get").response { response in + print("Request: \(response.request)") + print("Response: \(response.response)") + print("Error: \(response.error)") + + if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) { + print("Data: \(utf8Text)") + } +} +``` + +> We strongly encourage you to leverage the other response serializers taking advantage of `Response` and `Result` types. + +#### Response Data Handler + +The `responseData` handler uses the `responseDataSerializer` (the object that serializes the server data into some other type) to extract the `Data` returned by the server. If no errors occur and `Data` is returned, the response `Result` will be a `.success` and the `value` will be of type `Data`. + +```swift +Alamofire.request("https://httpbin.org/get").responseData { response in + debugPrint("All Response Info: \(response)") + + if let data = response.result.value, let utf8Text = String(data: data, encoding: .utf8) { + print("Data: \(utf8Text)") + } +} +``` + +#### Response String Handler + +The `responseString` handler uses the `responseStringSerializer` to convert the `Data` returned by the server into a `String` with the specified encoding. If no errors occur and the server data is successfully serialized into a `String`, the response `Result` will be a `.success` and the `value` will be of type `String`. + +```swift +Alamofire.request("https://httpbin.org/get").responseString { response in + print("Success: \(response.result.isSuccess)") + print("Response String: \(response.result.value)") +} +``` + +> If no encoding is specified, Alamofire will use the text encoding specified in the `HTTPURLResponse` from the server. If the text encoding cannot be determined by the server response, it defaults to `.isoLatin1`. + +#### Response JSON Handler + +The `responseJSON` handler uses the `responseJSONSerializer` to convert the `Data` returned by the server into an `Any` type using the specified `JSONSerialization.ReadingOptions`. If no errors occur and the server data is successfully serialized into a JSON object, the response `Result` will be a `.success` and the `value` will be of type `Any`. + +```swift +Alamofire.request("https://httpbin.org/get").responseJSON { response in + debugPrint(response) + + if let json = response.result.value { + print("JSON: \(json)") + } +} +``` + +> All JSON serialization is handled by the `JSONSerialization` API in the `Foundation` framework. + +#### Chained Response Handlers + +Response handlers can even be chained: + +```swift +Alamofire.request("https://httpbin.org/get") + .responseString { response in + print("Response String: \(response.result.value)") + } + .responseJSON { response in + print("Response JSON: \(response.result.value)") + } +``` + +> It is important to note that using multiple response handlers on the same `Request` requires the server data to be serialized multiple times. Once for each response handler. + +#### Response Handler Queue + +Response handlers by default are executed on the main dispatch queue. However, a custom dispatch queue can be provided instead. + +```swift +let utilityQueue = DispatchQueue.global(qos: .utility) + +Alamofire.request("https://httpbin.org/get").responseJSON(queue: utilityQueue) { response in + print("Executing response handler on utility queue") +} +``` + +### Response Validation + +By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling `validate` before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type. + +#### Manual Validation + +```swift +Alamofire.request("https://httpbin.org/get") + .validate(statusCode: 200..<300) + .validate(contentType: ["application/json"]) + .responseData { response in + switch response.result { + case .success: + print("Validation Successful") + case .failure(let error): + print(error) + } + } +``` + +#### Automatic Validation + +Automatically validates status code within `200..<300` range, and that the `Content-Type` header of the response matches the `Accept` header of the request, if one is provided. + +```swift +Alamofire.request("https://httpbin.org/get").validate().responseJSON { response in + switch response.result { + case .success: + print("Validation Successful") + case .failure(let error): + print(error) + } +} +``` + +### Response Caching + +Response Caching is handled on the system framework level by [`URLCache`](https://developer.apple.com/reference/foundation/urlcache). It provides a composite in-memory and on-disk cache and lets you manipulate the sizes of both the in-memory and on-disk portions. + +> By default, Alamofire leverages the shared `URLCache`. In order to customize it, see the [Session Manager Configurations](#session-manager) section. + +### HTTP Methods + +The `HTTPMethod` enumeration lists the HTTP methods defined in [RFC 7231 §4.3](http://tools.ietf.org/html/rfc7231#section-4.3): + +```swift +public enum HTTPMethod: String { + case options = "OPTIONS" + case get = "GET" + case head = "HEAD" + case post = "POST" + case put = "PUT" + case patch = "PATCH" + case delete = "DELETE" + case trace = "TRACE" + case connect = "CONNECT" +} +``` + +These values can be passed as the `method` argument to the `Alamofire.request` API: + +```swift +Alamofire.request("https://httpbin.org/get") // method defaults to `.get` + +Alamofire.request("https://httpbin.org/post", method: .post) +Alamofire.request("https://httpbin.org/put", method: .put) +Alamofire.request("https://httpbin.org/delete", method: .delete) +``` + +> The `Alamofire.request` method parameter defaults to `.get`. + +### Parameter Encoding + +Alamofire supports three types of parameter encoding including: `URL`, `JSON` and `PropertyList`. It can also support any custom encoding that conforms to the `ParameterEncoding` protocol. + +#### URL Encoding + +The `URLEncoding` type creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP body of the URL request. Whether the query string is set or appended to any existing URL query string or set as the HTTP body depends on the `Destination` of the encoding. The `Destination` enumeration has three cases: + +- `.methodDependent` - Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` requests and sets as the HTTP body for requests with any other HTTP method. +- `.queryString` - Sets or appends encoded query string result to existing query string. +- `.httpBody` - Sets encoded query string result as the HTTP body of the URL request. + +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`). + +##### GET Request With URL-Encoded Parameters + +```swift +let parameters: Parameters = ["foo": "bar"] + +// All three of these calls are equivalent +Alamofire.request("https://httpbin.org/get", parameters: parameters) // encoding defaults to `URLEncoding.default` +Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding.default) +Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding(destination: .methodDependent)) + +// https://httpbin.org/get?foo=bar +``` + +##### POST Request With URL-Encoded Parameters + +```swift +let parameters: Parameters = [ + "foo": "bar", + "baz": ["a", 1], + "qux": [ + "x": 1, + "y": 2, + "z": 3 + ] +] + +// All three of these calls are equivalent +Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters) +Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.default) +Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.httpBody) + +// HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3 +``` + +#### JSON Encoding + +The `JSONEncoding` type creates a JSON representation of the parameters object, which is set as the HTTP body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. + +##### POST Request with JSON-Encoded Parameters + +```swift +let parameters: Parameters = [ + "foo": [1,2,3], + "bar": [ + "baz": "qux" + ] +] + +// Both calls are equivalent +Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding.default) +Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding(options: [])) + +// HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}} +``` + +#### Property List Encoding + +The `PropertyListEncoding` uses `PropertyListSerialization` 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 Encoding + +In the event that the provided `ParameterEncoding` types do not meet your needs, you can create your own custom encoding. Here's a quick example of how you could build a custom `JSONStringArrayEncoding` type to encode a JSON string array onto a `Request`. + +```swift +struct JSONStringArrayEncoding: ParameterEncoding { + private let array: [String] + + init(array: [String]) { + self.array = array + } + + func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + let data = try JSONSerialization.data(withJSONObject: array, options: []) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = data + + return urlRequest + } +} +``` + +#### Manual Parameter Encoding of a URLRequest + +The `ParameterEncoding` APIs can be used outside of making network requests. + +```swift +let url = URL(string: "https://httpbin.org/get")! +var urlRequest = URLRequest(url: url) + +let parameters: Parameters = ["foo": "bar"] +let encodedURLRequest = try URLEncoding.queryString.encode(urlRequest, with: parameters) +``` + +### HTTP Headers + +Adding a custom HTTP header to a `Request` is supported directly in the global `request` method. This makes it easy to attach HTTP headers to a `Request` that can be constantly changing. + +```swift +let headers: HTTPHeaders = [ + "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", + "Accept": "application/json" +] + +Alamofire.request("https://httpbin.org/headers", headers: headers).responseJSON { response in + debugPrint(response) +} +``` + +> For HTTP headers that do not change, it is recommended to set them on the `URLSessionConfiguration` so they are automatically applied to any `URLSessionTask` created by the underlying `URLSession`. For more information, see the [Session Manager Configurations](#session-manager) section. + +The default Alamofire `SessionManager` provides a default set of headers for every `Request`. These include: + +- `Accept-Encoding`, which defaults to `gzip;q=1.0, compress;q=0.5`, per [RFC 7230 §4.2.3](https://tools.ietf.org/html/rfc7230#section-4.2.3). +- `Accept-Language`, which defaults to up to the top 6 preferred languages on the system, formatted like `en;q=1.0`, per [RFC 7231 §5.3.5](https://tools.ietf.org/html/rfc7231#section-5.3.5). +- `User-Agent`, which contains versioning information about the current app. For example: `iOS Example/1.0 (com.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0`, per [RFC 7231 §5.5.3](https://tools.ietf.org/html/rfc7231#section-5.5.3). + +If you need to customize these headers, a custom `URLSessionConfiguration` should be created, the `defaultHTTPHeaders` property updated and the configuration applied to a new `SessionManager` instance. + +### Authentication + +Authentication is handled on the system framework level by [`URLCredential`](https://developer.apple.com/reference/foundation/nsurlcredential) and [`URLAuthenticationChallenge`](https://developer.apple.com/reference/foundation/urlauthenticationchallenge). + +**Supported Authentication Schemes** + +- [HTTP Basic](http://en.wikipedia.org/wiki/Basic_access_authentication) +- [HTTP Digest](http://en.wikipedia.org/wiki/Digest_access_authentication) +- [Kerberos](http://en.wikipedia.org/wiki/Kerberos_%28protocol%29) +- [NTLM](http://en.wikipedia.org/wiki/NT_LAN_Manager) + +#### HTTP Basic Authentication + +The `authenticate` method on a `Request` will automatically provide a `URLCredential` to a `URLAuthenticationChallenge` when appropriate: + +```swift +let user = "user" +let password = "password" + +Alamofire.request("https://httpbin.org/basic-auth/\(user)/\(password)") + .authenticate(user: user, password: password) + .responseJSON { response in + debugPrint(response) + } +``` + +Depending upon your server implementation, an `Authorization` header may also be appropriate: + +```swift +let user = "user" +let password = "password" + +var headers: HTTPHeaders = [:] + +if let authorizationHeader = Request.authorizationHeader(user: user, password: password) { + headers[authorizationHeader.key] = authorizationHeader.value +} + +Alamofire.request("https://httpbin.org/basic-auth/user/password", headers: headers) + .responseJSON { response in + debugPrint(response) + } +``` + +#### Authentication with URLCredential + +```swift +let user = "user" +let password = "password" + +let credential = URLCredential(user: user, password: password, persistence: .forSession) + +Alamofire.request("https://httpbin.org/basic-auth/\(user)/\(password)") + .authenticate(usingCredential: credential) + .responseJSON { response in + debugPrint(response) + } +``` + +> It is important to note that when using a `URLCredential` for authentication, the underlying `URLSession` will actually end up making two requests if a challenge is issued by the server. The first request will not include the credential which "may" trigger a challenge from the server. The challenge is then received by Alamofire, the credential is appended and the request is retried by the underlying `URLSession`. + +### Downloading Data to a File + +Requests made in Alamofire that fetch data from a server can download the data in-memory or on-disk. The `Alamofire.request` APIs used in all the examples so far always downloads the server data in-memory. This is great for smaller payloads because it's more efficient, but really bad for larger payloads because the download could run your entire application out-of-memory. Because of this, you can also use the `Alamofire.download` APIs to download the server data to a temporary file on-disk. + +> This will only work on `macOS` as is. Other platforms don't allow access to the filesystem outside of your app's sandbox. To download files on other platforms, see the [Download File Destination](#download-file-destination) section. + +```swift +Alamofire.download("https://httpbin.org/image/png").responseData { response in + if let data = response.result.value { + let image = UIImage(data: data) + } +} +``` + +> The `Alamofire.download` APIs should also be used if you need to download data while your app is in the background. For more information, please see the [Session Manager Configurations](#session-manager) section. + +#### Download File Destination + +You can also provide a `DownloadFileDestination` closure to move the file from the temporary directory to a final destination. Before the temporary file is actually moved to the `destinationURL`, the `DownloadOptions` specified in the closure will be executed. The two currently supported `DownloadOptions` are: + +- `.createIntermediateDirectories` - Creates intermediate directories for the destination URL if specified. +- `.removePreviousFile` - Removes a previous file from the destination URL if specified. + +```swift +let destination: DownloadRequest.DownloadFileDestination = { _, _ in + let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] + let fileURL = documentsURL.appendingPathComponent("pig.png") + + return (fileURL, [.removePreviousFile, .createIntermediateDirectories]) +} + +Alamofire.download(urlString, to: destination).response { response in + print(response) + + if response.error == nil, let imagePath = response.destinationURL?.path { + let image = UIImage(contentsOfFile: imagePath) + } +} +``` + +You can also use the suggested download destination API. + +```swift +let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory) +Alamofire.download("https://httpbin.org/image/png", to: destination) +``` + +#### Download Progress + +Many times it can be helpful to report download progress to the user. Any `DownloadRequest` can report download progress using the `downloadProgress` API. + +```swift +Alamofire.download("https://httpbin.org/image/png") + .downloadProgress { progress in + print("Download Progress: \(progress.fractionCompleted)") + } + .responseData { response in + if let data = response.result.value { + let image = UIImage(data: data) + } + } +``` + +The `downloadProgress` API also takes a `queue` parameter which defines which `DispatchQueue` the download progress closure should be called on. + +```swift +let utilityQueue = DispatchQueue.global(qos: .utility) + +Alamofire.download("https://httpbin.org/image/png") + .downloadProgress(queue: utilityQueue) { progress in + print("Download Progress: \(progress.fractionCompleted)") + } + .responseData { response in + if let data = response.result.value { + let image = UIImage(data: data) + } + } +``` + +#### Resuming a Download + +If a `DownloadRequest` is cancelled or interrupted, the underlying URL session may generate resume data for the active `DownloadRequest`. If this happens, the resume data can be re-used to restart the `DownloadRequest` where it left off. The resume data can be accessed through the download response, then reused when trying to restart the request. + +> **IMPORTANT:** On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the data is written incorrectly and will always fail to resume the download. For more information about the bug and possible workarounds, please see this Stack Overflow [post](http://stackoverflow.com/a/39347461/1342462). + +```swift +class ImageRequestor { + private var resumeData: Data? + private var image: UIImage? + + func fetchImage(completion: (UIImage?) -> Void) { + guard image == nil else { completion(image) ; return } + + let destination: DownloadRequest.DownloadFileDestination = { _, _ in + let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] + let fileURL = documentsURL.appendingPathComponent("pig.png") + + return (fileURL, [.removePreviousFile, .createIntermediateDirectories]) + } + + let request: DownloadRequest + + if let resumeData = resumeData { + request = Alamofire.download(resumingWith: resumeData) + } else { + request = Alamofire.download("https://httpbin.org/image/png") + } + + request.responseData { response in + switch response.result { + case .success(let data): + self.image = UIImage(data: data) + case .failure: + self.resumeData = response.resumeData + } + } + } +} +``` + +### Uploading Data to a Server + +When sending relatively small amounts of data to a server using JSON or URL encoded parameters, the `Alamofire.request` APIs are usually sufficient. If you need to send much larger amounts of data from a file URL or an `InputStream`, then the `Alamofire.upload` APIs are what you want to use. + +> The `Alamofire.upload` APIs should also be used if you need to upload data while your app is in the background. For more information, please see the [Session Manager Configurations](#session-manager) section. + +#### Uploading Data + +```swift +let imageData = UIPNGRepresentation(image)! + +Alamofire.upload(imageData, to: "https://httpbin.org/post").responseJSON { response in + debugPrint(response) +} +``` + +#### Uploading a File + +```swift +let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov") + +Alamofire.upload(fileURL, to: "https://httpbin.org/post").responseJSON { response in + debugPrint(response) +} +``` + +#### Uploading Multipart Form Data + +```swift +Alamofire.upload( + multipartFormData: { multipartFormData in + multipartFormData.append(unicornImageURL, withName: "unicorn") + multipartFormData.append(rainbowImageURL, withName: "rainbow") + }, + to: "https://httpbin.org/post", + encodingCompletion: { encodingResult in + switch encodingResult { + case .success(let upload, _, _): + upload.responseJSON { response in + debugPrint(response) + } + case .failure(let encodingError): + print(encodingError) + } + } +) +``` + +#### Upload Progress + +While your user is waiting for their upload to complete, sometimes it can be handy to show the progress of the upload to the user. Any `UploadRequest` can report both upload progress and download progress of the response data using the `uploadProgress` and `downloadProgress` APIs. + +```swift +let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov") + +Alamofire.upload(fileURL, to: "https://httpbin.org/post") + .uploadProgress { progress in // main queue by default + print("Upload Progress: \(progress.fractionCompleted)") + } + .downloadProgress { progress in // main queue by default + print("Download Progress: \(progress.fractionCompleted)") + } + .responseJSON { response in + debugPrint(response) + } +``` + +### Statistical Metrics + +#### Timeline + +Alamofire collects timings throughout the lifecycle of a `Request` and creates a `Timeline` object exposed as a property on all response types. + +```swift +Alamofire.request("https://httpbin.org/get").responseJSON { response in + print(response.timeline) +} +``` + +The above reports the following `Timeline` info: + +- `Latency`: 0.428 seconds +- `Request Duration`: 0.428 seconds +- `Serialization Duration`: 0.001 seconds +- `Total Duration`: 0.429 seconds + +#### URL Session Task Metrics + +In iOS and tvOS 10 and macOS 10.12, Apple introduced the new [URLSessionTaskMetrics](https://developer.apple.com/reference/foundation/urlsessiontaskmetrics) APIs. The task metrics encapsulate some fantastic statistical information about the request and response execution. The API is very similar to the `Timeline`, but provides many more statistics that Alamofire doesn't have access to compute. The metrics can be accessed through any response type. + +```swift +Alamofire.request("https://httpbin.org/get").responseJSON { response in + print(response.metrics) +} +``` + +It's important to note that these APIs are only available on iOS and tvOS 10 and macOS 10.12. Therefore, depending on your deployment target, you may need to use these inside availability checks: + +```swift +Alamofire.request("https://httpbin.org/get").responseJSON { response in + if #available(iOS 10.0, *) { + print(response.metrics) + } +} +``` + +### cURL Command Output + +Debugging platform issues can be frustrating. Thankfully, Alamofire `Request` objects conform to both the `CustomStringConvertible` and `CustomDebugStringConvertible` protocols to provide some VERY helpful debugging tools. + +#### CustomStringConvertible + +```swift +let request = Alamofire.request("https://httpbin.org/ip") + +print(request) +// GET https://httpbin.org/ip (200) +``` + +#### CustomDebugStringConvertible + +```swift +let request = Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"]) +debugPrint(request) +``` + +Outputs: + +```bash +$ curl -i \ + -H "User-Agent: Alamofire/4.0.0" \ + -H "Accept-Encoding: gzip;q=1.0, compress;q=0.5" \ + -H "Accept-Language: en;q=1.0,fr;q=0.9,de;q=0.8,zh-Hans;q=0.7,zh-Hant;q=0.6,ja;q=0.5" \ + "https://httpbin.org/get?foo=bar" +``` + +--- + +## Advanced Usage + +Alamofire is built on `URLSession` and the Foundation URL Loading System. To make the most of this framework, it is recommended that you be familiar with the concepts and capabilities of the underlying networking stack. + +**Recommended Reading** + +- [URL Loading System Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html) +- [URLSession Class Reference](https://developer.apple.com/reference/foundation/nsurlsession) +- [URLCache Class Reference](https://developer.apple.com/reference/foundation/urlcache) +- [URLAuthenticationChallenge Class Reference](https://developer.apple.com/reference/foundation/urlauthenticationchallenge) + +### Session Manager + +Top-level convenience methods like `Alamofire.request` use a default instance of `Alamofire.SessionManager`, which is configured with the default `URLSessionConfiguration`. + +As such, the following two statements are equivalent: + +```swift +Alamofire.request("https://httpbin.org/get") +``` + +```swift +let sessionManager = Alamofire.SessionManager.default +sessionManager.request("https://httpbin.org/get") +``` + +Applications can create session managers for background and ephemeral sessions, as well as new managers that customize the default session configuration, such as for default headers (`httpAdditionalHeaders`) or timeout interval (`timeoutIntervalForRequest`). + +#### Creating a Session Manager with Default Configuration + +```swift +let configuration = URLSessionConfiguration.default +let sessionManager = Alamofire.SessionManager(configuration: configuration) +``` + +#### Creating a Session Manager with Background Configuration + +```swift +let configuration = URLSessionConfiguration.background(withIdentifier: "com.example.app.background") +let sessionManager = Alamofire.SessionManager(configuration: configuration) +``` + +#### Creating a Session Manager with Ephemeral Configuration + +```swift +let configuration = URLSessionConfiguration.ephemeral +let sessionManager = Alamofire.SessionManager(configuration: configuration) +``` + +#### Modifying the Session Configuration + +```swift +var defaultHeaders = Alamofire.SessionManager.defaultHTTPHeaders +defaultHeaders["DNT"] = "1 (Do Not Track Enabled)" + +let configuration = URLSessionConfiguration.default +configuration.httpAdditionalHeaders = defaultHeaders + +let sessionManager = Alamofire.SessionManager(configuration: configuration) +``` + +> This is **not** recommended for `Authorization` or `Content-Type` headers. Instead, use the `headers` parameter in the top-level `Alamofire.request` APIs, `URLRequestConvertible` and `ParameterEncoding`, respectively. + +### Session Delegate + +By default, an Alamofire `SessionManager` instance creates a `SessionDelegate` object to handle all the various types of delegate callbacks that are generated by the underlying `URLSession`. The implementations of each delegate method handle the most common use cases for these types of calls abstracting the complexity away from the top-level APIs. However, advanced users may find the need to override the default functionality for various reasons. + +#### Override Closures + +The first way to customize the `SessionDelegate` behavior is through the use of the override closures. Each closure gives you the ability to override the implementation of the matching `SessionDelegate` API, yet still use the default implementation for all other APIs. This makes it easy to customize subsets of the delegate functionality. Here are a few examples of some of the override closures available: + +```swift +/// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`. +open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + +/// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`. +open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)? + +/// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`. +open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? + +/// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`. +open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? +``` + +The following is a short example of how to use the `taskWillPerformHTTPRedirection` to avoid following redirects to any `apple.com` domains. + +```swift +let sessionManager = Alamofire.SessionManager(configuration: URLSessionConfiguration.default) +let delegate: Alamofire.SessionDelegate = sessionManager.delegate + +delegate.taskWillPerformHTTPRedirection = { session, task, response, request in + var finalRequest = request + + if + let originalRequest = task.originalRequest, + let urlString = originalRequest.url?.urlString, + urlString.contains("apple.com") + { + finalRequest = originalRequest + } + + return finalRequest +} +``` + +#### Subclassing + +Another way to override the default implementation of the `SessionDelegate` is to subclass it. Subclassing allows you completely customize the behavior of the API or to create a proxy for the API and still use the default implementation. Creating a proxy allows you to log events, emit notifications, provide pre and post hook implementations, etc. Here's a quick example of subclassing the `SessionDelegate` and logging a message when a redirect occurs. + +```swift +class LoggingSessionDelegate: SessionDelegate { + override func urlSession( + _ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) + { + print("URLSession will perform HTTP redirection to request: \(request)") + + super.urlSession( + session, + task: task, + willPerformHTTPRedirection: response, + newRequest: request, + completionHandler: completionHandler + ) + } +} +``` + +Generally speaking, either the default implementation or the override closures should provide the necessary functionality required. Subclassing should only be used as a last resort. + +> It is important to keep in mind that the `subdelegates` are initialized and destroyed in the default implementation. Be careful when subclassing to not introduce memory leaks. + +### Request + +The result of a `request`, `download`, `upload` or `stream` methods are a `DataRequest`, `DownloadRequest`, `UploadRequest` and `StreamRequest` which all inherit from `Request`. All `Request` instances are always created by an owning session manager, and never initialized directly. + +Each subclass has specialized methods such as `authenticate`, `validate`, `responseJSON` and `uploadProgress` that each return the caller instance in order to facilitate method chaining. + +Requests can be suspended, resumed and cancelled: + +- `suspend()`: Suspends the underlying task and dispatch queue. +- `resume()`: Resumes the underlying task and dispatch queue. If the owning manager does not have `startRequestsImmediately` set to `true`, the request must call `resume()` in order to start. +- `cancel()`: Cancels the underlying task, producing an error that is passed to any registered response handlers. + +### Routing Requests + +As apps grow in size, it's important to adopt common patterns as you build out your network stack. An important part of that design is how to route your requests. The Alamofire `URLConvertible` and `URLRequestConvertible` protocols along with the `Router` design pattern are here to help. + +#### URLConvertible + +Types adopting the `URLConvertible` protocol can be used to construct URLs, which are then used to construct URL requests internally. `String`, `URL`, and `URLComponents` conform to `URLConvertible` by default, allowing any of them to be passed as `url` parameters to the `request`, `upload`, and `download` methods: + +```swift +let urlString = "https://httpbin.org/post" +Alamofire.request(urlString, method: .post) + +let url = URL(string: urlString)! +Alamofire.request(url, method: .post) + +let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true)! +Alamofire.request(urlComponents, method: .post) +``` + +Applications interacting with web applications in a significant manner are encouraged to have custom types conform to `URLConvertible` as a convenient way to map domain-specific models to server resources. + +##### Type-Safe Routing + +```swift +extension User: URLConvertible { + static let baseURLString = "https://example.com" + + func asURL() throws -> URL { + let urlString = User.baseURLString + "/users/\(username)/" + return try urlString.asURL() + } +} +``` + +```swift +let user = User(username: "mattt") +Alamofire.request(user) // https://example.com/users/mattt +``` + +#### URLRequestConvertible + +Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. `URLRequest` conforms to `URLRequestConvertible` by default, allowing it to be passed into `request`, `upload`, and `download` methods directly (this is the recommended way to specify custom HTTP body for individual requests): + +```swift +let url = URL(string: "https://httpbin.org/post")! +var urlRequest = URLRequest(url: url) +urlRequest.httpMethod = "POST" + +let parameters = ["foo": "bar"] + +do { + urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: []) +} catch { + // No-op +} + +urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + +Alamofire.request(urlRequest) +``` + +Applications interacting with web applications in a significant manner are encouraged to have custom types conform to `URLRequestConvertible` as a way to ensure consistency of requested endpoints. Such an approach can be used to abstract away server-side inconsistencies and provide type-safe routing, as well as manage authentication credentials and other state. + +##### API Parameter Abstraction + +```swift +enum Router: URLRequestConvertible { + case search(query: String, page: Int) + + static let baseURLString = "https://example.com" + static let perPage = 50 + + // MARK: URLRequestConvertible + + func asURLRequest() throws -> URLRequest { + let result: (path: String, parameters: Parameters) = { + switch self { + case let .search(query, page) where page > 0: + return ("/search", ["q": query, "offset": Router.perPage * page]) + case let .search(query, _): + return ("/search", ["q": query]) + } + }() + + let url = try Router.baseURLString.asURL() + let urlRequest = URLRequest(url: url.appendingPathComponent(result.path)) + + return try URLEncoding.default.encode(urlRequest, with: result.parameters) + } +} +``` + +```swift +Alamofire.request(Router.search(query: "foo bar", page: 1)) // https://example.com/search?q=foo%20bar&offset=50 +``` + +##### CRUD & Authorization + +```swift +import Alamofire + +enum Router: URLRequestConvertible { + case createUser(parameters: Parameters) + case readUser(username: String) + case updateUser(username: String, parameters: Parameters) + case destroyUser(username: String) + + static let baseURLString = "https://example.com" + + var method: HTTPMethod { + switch self { + case .createUser: + return .post + case .readUser: + return .get + case .updateUser: + return .put + case .destroyUser: + return .delete + } + } + + var path: String { + switch self { + case .createUser: + return "/users" + case .readUser(let username): + return "/users/\(username)" + case .updateUser(let username, _): + return "/users/\(username)" + case .destroyUser(let username): + return "/users/\(username)" + } + } + + // MARK: URLRequestConvertible + + func asURLRequest() throws -> URLRequest { + let url = try Router.baseURLString.asURL() + + var urlRequest = URLRequest(url: url.appendingPathComponent(path)) + urlRequest.httpMethod = method.rawValue + + switch self { + case .createUser(let parameters): + urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters) + case .updateUser(_, let parameters): + urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters) + default: + break + } + + return urlRequest + } +} +``` + +```swift +Alamofire.request(Router.readUser("mattt")) // GET https://example.com/users/mattt +``` + +### Adapting and Retrying Requests + +Most web services these days are behind some sort of authentication system. One of the more common ones today is OAuth. This generally involves generating an access token authorizing your application or user to call the various supported web services. While creating these initial access tokens can be laborsome, it can be even more complicated when your access token expires and you need to fetch a new one. There are many thread-safety issues that need to be considered. + +The `RequestAdapter` and `RequestRetrier` protocols were created to make it much easier to create a thread-safe authentication system for a specific set of web services. + +#### RequestAdapter + +The `RequestAdapter` protocol allows each `Request` made on a `SessionManager` to be inspected and adapted before being created. One very specific way to use an adapter is to append an `Authorization` header to requests behind a certain type of authentication. + +```swift +class AccessTokenAdapter: RequestAdapter { + private let accessToken: String + + init(accessToken: String) { + self.accessToken = accessToken + } + + func adapt(_ urlRequest: URLRequest) throws -> URLRequest { + var urlRequest = urlRequest + + if let urlString = urlRequest.url?.absoluteString, urlString.hasPrefix("https://httpbin.org") { + urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization") + } + + return urlRequest + } +} +``` + +```swift +let sessionManager = SessionManager() +sessionManager.adapter = AccessTokenAdapter(accessToken: "1234") + +sessionManager.request("https://httpbin.org/get") +``` + +#### RequestRetrier + +The `RequestRetrier` protocol allows a `Request` that encountered an `Error` while being executed to be retried. When using both the `RequestAdapter` and `RequestRetrier` protocols together, you can create credential refresh systems for OAuth1, OAuth2, Basic Auth and even exponential backoff retry policies. The possibilities are endless. Here's an example of how you could implement a refresh flow for OAuth2 access tokens. + +> **DISCLAIMER:** This is **NOT** a global `OAuth2` solution. It is merely an example demonstrating how one could use the `RequestAdapter` in conjunction with the `RequestRetrier` to create a thread-safe refresh system. + +> To reiterate, **do NOT copy** this sample code and drop it into a production application. This is merely an example. Each authentication system must be tailored to a particular platform and authentication type. + +```swift +class OAuth2Handler: RequestAdapter, RequestRetrier { + private typealias RefreshCompletion = (_ succeeded: Bool, _ accessToken: String?, _ refreshToken: String?) -> Void + + private let sessionManager: SessionManager = { + let configuration = URLSessionConfiguration.default + configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders + + return SessionManager(configuration: configuration) + }() + + private let lock = NSLock() + + private var clientID: String + private var baseURLString: String + private var accessToken: String + private var refreshToken: String + + private var isRefreshing = false + private var requestsToRetry: [RequestRetryCompletion] = [] + + // MARK: - Initialization + + public init(clientID: String, baseURLString: String, accessToken: String, refreshToken: String) { + self.clientID = clientID + self.baseURLString = baseURLString + self.accessToken = accessToken + self.refreshToken = refreshToken + } + + // MARK: - RequestAdapter + + func adapt(_ urlRequest: URLRequest) throws -> URLRequest { + if let urlString = urlRequest.url?.absoluteString, urlString.hasPrefix(baseURLString) { + var urlRequest = urlRequest + urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization") + return urlRequest + } + + return urlRequest + } + + // MARK: - RequestRetrier + + func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) { + lock.lock() ; defer { lock.unlock() } + + if let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401 { + requestsToRetry.append(completion) + + if !isRefreshing { + refreshTokens { [weak self] succeeded, accessToken, refreshToken in + guard let strongSelf = self else { return } + + strongSelf.lock.lock() ; defer { strongSelf.lock.unlock() } + + if let accessToken = accessToken, let refreshToken = refreshToken { + strongSelf.accessToken = accessToken + strongSelf.refreshToken = refreshToken + } + + strongSelf.requestsToRetry.forEach { $0(succeeded, 0.0) } + strongSelf.requestsToRetry.removeAll() + } + } + } else { + completion(false, 0.0) + } + } + + // MARK: - Private - Refresh Tokens + + private func refreshTokens(completion: @escaping RefreshCompletion) { + guard !isRefreshing else { return } + + isRefreshing = true + + let urlString = "\(baseURLString)/oauth2/token" + + let parameters: [String: Any] = [ + "access_token": accessToken, + "refresh_token": refreshToken, + "client_id": clientID, + "grant_type": "refresh_token" + ] + + sessionManager.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default) + .responseJSON { [weak self] response in + guard let strongSelf = self else { return } + + if + let json = response.result.value as? [String: Any], + let accessToken = json["access_token"] as? String, + let refreshToken = json["refresh_token"] as? String + { + completion(true, accessToken, refreshToken) + } else { + completion(false, nil, nil) + } + + strongSelf.isRefreshing = false + } + } +} +``` + +```swift +let baseURLString = "https://some.domain-behind-oauth2.com" + +let oauthHandler = OAuth2Handler( + clientID: "12345678", + baseURLString: baseURLString, + accessToken: "abcd1234", + refreshToken: "ef56789a" +) + +let sessionManager = SessionManager() +sessionManager.adapter = oauthHandler +sessionManager.retrier = oauthHandler + +let urlString = "\(baseURLString)/some/endpoint" + +sessionManager.request(urlString).validate().responseJSON { response in + debugPrint(response) +} +``` + +Once the `OAuth2Handler` is applied as both the `adapter` and `retrier` for the `SessionManager`, it will handle an invalid access token error by automatically refreshing the access token and retrying all failed requests in the same order they failed. + +> If you needed them to execute in the same order they were created, you could sort them by their task identifiers. + +The example above only checks for a `401` response code which is not nearly robust enough, but does demonstrate how one could check for an invalid access token error. In a production application, one would want to check the `realm` and most likely the `www-authenticate` header response although it depends on the OAuth2 implementation. + +Another important note is that this authentication system could be shared between multiple session managers. For example, you may need to use both a `default` and `ephemeral` session configuration for the same set of web services. The example above allows the same `oauthHandler` instance to be shared across multiple session managers to manage the single refresh flow. + +### Custom Response Serialization + +Alamofire provides built-in response serialization for data, strings, JSON, and property lists: + +```swift +Alamofire.request(...).responseData { (resp: DataResponse) in ... } +Alamofire.request(...).responseString { (resp: DataResponse) in ... } +Alamofire.request(...).responseJSON { (resp: DataResponse) in ... } +Alamofire.request(...).responsePropertyList { resp: DataResponse) in ... } +``` + +Those responses wrap deserialized *values* (Data, String, Any) or *errors* (network, validation errors), as well as *meta-data* (URL request, HTTP headers, status code, [metrics](#statistical-metrics), ...). + +You have several ways to customize all of those response elements: + +- [Response Mapping](#response-mapping) +- [Handling Errors](#handling-errors) +- [Creating a Custom Response Serializer](#creating-a-custom-response-serializer) +- [Generic Response Object Serialization](#generic-response-object-serialization) + +#### Response Mapping + +Response mapping is the simplest way to produce customized responses. It transforms the value of a response, while preserving eventual errors and meta-data. For example, you can turn a json response `DataResponse` into a response that holds an application model, such as `DataResponse`. You perform response mapping with the `DataResponse.map` method: + +```swift +Alamofire.request("https://example.com/users/mattt").responseJSON { (response: DataResponse) in + let userResponse = response.map { json in + // We assume an existing User(json: Any) initializer + return User(json: json) + } + + // Process userResponse, of type DataResponse: + if let user = userResponse.value { + print("User: { username: \(user.username), name: \(user.name) }") + } +} +``` + +When the transformation may throw an error, use `flatMap` instead: + +```swift +Alamofire.request("https://example.com/users/mattt").responseJSON { response in + let userResponse = response.flatMap { json in + try User(json: json) + } +} +``` + +Response mapping is a good fit for your custom completion handlers: + +```swift +@discardableResult +func loadUser(completionHandler: @escaping (DataResponse) -> Void) -> Alamofire.DataRequest { + return Alamofire.request("https://example.com/users/mattt").responseJSON { response in + let userResponse = response.flatMap { json in + try User(json: json) + } + + completionHandler(userResponse) + } +} + +loadUser { response in + if let user = response.value { + print("User: { username: \(user.username), name: \(user.name) }") + } +} +``` + +When the map/flatMap closure may process a big amount of data, make sure you execute it outside of the main thread: + +```swift +@discardableResult +func loadUser(completionHandler: @escaping (DataResponse) -> Void) -> Alamofire.DataRequest { + let utilityQueue = DispatchQueue.global(qos: .utility) + + return Alamofire.request("https://example.com/users/mattt").responseJSON(queue: utilityQueue) { response in + let userResponse = response.flatMap { json in + try User(json: json) + } + + DispatchQueue.main.async { + completionHandler(userResponse) + } + } +} +``` + +`map` and `flatMap` are also available for [download responses](#downloading-data-to-a-file). + +#### Handling Errors + +Before implementing custom response serializers or object serialization methods, it's important to consider how to handle any errors that may occur. There are two basic options: passing existing errors along unmodified, to be dealt with at response time; or, wrapping all errors in an `Error` type specific to your app. + +For example, here's a simple `BackendError` enum which will be used in later examples: + +```swift +enum BackendError: Error { + case network(error: Error) // Capture any underlying Error from the URLSession API + case dataSerialization(error: Error) + case jsonSerialization(error: Error) + case xmlSerialization(error: Error) + case objectSerialization(reason: String) +} +``` + +#### Creating a Custom Response Serializer + +Alamofire provides built-in response serialization for strings, JSON, and property lists, but others can be added in extensions on `Alamofire.DataRequest` and / or `Alamofire.DownloadRequest`. + +For example, here's how a response handler using [Ono](https://github.com/mattt/Ono) might be implemented: + +```swift +extension DataRequest { + static func xmlResponseSerializer() -> DataResponseSerializer { + return DataResponseSerializer { request, response, data, error in + // Pass through any underlying URLSession error to the .network case. + guard error == nil else { return .failure(BackendError.network(error: error!)) } + + // Use Alamofire's existing data serializer to extract the data, passing the error as nil, as it has + // already been handled. + let result = Request.serializeResponseData(response: response, data: data, error: nil) + + guard case let .success(validData) = result else { + return .failure(BackendError.dataSerialization(error: result.error! as! AFError)) + } + + do { + let xml = try ONOXMLDocument(data: validData) + return .success(xml) + } catch { + return .failure(BackendError.xmlSerialization(error: error)) + } + } + } + + @discardableResult + func responseXMLDocument( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.xmlResponseSerializer(), + completionHandler: completionHandler + ) + } +} +``` + +#### Generic Response Object Serialization + +Generics can be used to provide automatic, type-safe response object serialization. + +```swift +protocol ResponseObjectSerializable { + init?(response: HTTPURLResponse, representation: Any) +} + +extension DataRequest { + func responseObject( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + let responseSerializer = DataResponseSerializer { request, response, data, error in + guard error == nil else { return .failure(BackendError.network(error: error!)) } + + let jsonResponseSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments) + let result = jsonResponseSerializer.serializeResponse(request, response, data, nil) + + guard case let .success(jsonObject) = result else { + return .failure(BackendError.jsonSerialization(error: result.error!)) + } + + guard let response = response, let responseObject = T(response: response, representation: jsonObject) else { + return .failure(BackendError.objectSerialization(reason: "JSON could not be serialized: \(jsonObject)")) + } + + return .success(responseObject) + } + + return response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) + } +} +``` + +```swift +struct User: ResponseObjectSerializable, CustomStringConvertible { + let username: String + let name: String + + var description: String { + return "User: { username: \(username), name: \(name) }" + } + + init?(response: HTTPURLResponse, representation: Any) { + guard + let username = response.url?.lastPathComponent, + let representation = representation as? [String: Any], + let name = representation["name"] as? String + else { return nil } + + self.username = username + self.name = name + } +} +``` + +```swift +Alamofire.request("https://example.com/users/mattt").responseObject { (response: DataResponse) in + debugPrint(response) + + if let user = response.result.value { + print("User: { username: \(user.username), name: \(user.name) }") + } +} +``` + +The same approach can also be used to handle endpoints that return a representation of a collection of objects: + +```swift +protocol ResponseCollectionSerializable { + static func collection(from response: HTTPURLResponse, withRepresentation representation: Any) -> [Self] +} + +extension ResponseCollectionSerializable where Self: ResponseObjectSerializable { + static func collection(from response: HTTPURLResponse, withRepresentation representation: Any) -> [Self] { + var collection: [Self] = [] + + if let representation = representation as? [[String: Any]] { + for itemRepresentation in representation { + if let item = Self(response: response, representation: itemRepresentation) { + collection.append(item) + } + } + } + + return collection + } +} +``` + +```swift +extension DataRequest { + @discardableResult + func responseCollection( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DataResponse<[T]>) -> Void) -> Self + { + let responseSerializer = DataResponseSerializer<[T]> { request, response, data, error in + guard error == nil else { return .failure(BackendError.network(error: error!)) } + + let jsonSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments) + let result = jsonSerializer.serializeResponse(request, response, data, nil) + + guard case let .success(jsonObject) = result else { + return .failure(BackendError.jsonSerialization(error: result.error!)) + } + + guard let response = response else { + let reason = "Response collection could not be serialized due to nil response." + return .failure(BackendError.objectSerialization(reason: reason)) + } + + return .success(T.collection(from: response, withRepresentation: jsonObject)) + } + + return response(responseSerializer: responseSerializer, completionHandler: completionHandler) + } +} +``` + +```swift +struct User: ResponseObjectSerializable, ResponseCollectionSerializable, CustomStringConvertible { + let username: String + let name: String + + var description: String { + return "User: { username: \(username), name: \(name) }" + } + + init?(response: HTTPURLResponse, representation: Any) { + guard + let username = response.url?.lastPathComponent, + let representation = representation as? [String: Any], + let name = representation["name"] as? String + else { return nil } + + self.username = username + self.name = name + } +} +``` + +```swift +Alamofire.request("https://example.com/users").responseCollection { (response: DataResponse<[User]>) in + debugPrint(response) + + if let users = response.result.value { + users.forEach { print("- \($0)") } + } +} +``` + +### Security + +Using a secure HTTPS connection when communicating with servers and web services is an important step in securing sensitive data. By default, Alamofire will evaluate the certificate chain provided by the server using Apple's built in validation provided by the Security framework. While this guarantees the certificate chain is valid, it does not prevent man-in-the-middle (MITM) attacks or other potential vulnerabilities. In order to mitigate MITM attacks, applications dealing with sensitive customer data or financial information should use certificate or public key pinning provided by the `ServerTrustPolicy`. + +#### ServerTrustPolicy + +The `ServerTrustPolicy` enumeration evaluates the server trust generally provided by an `URLAuthenticationChallenge` when connecting to a server over a secure HTTPS connection. + +```swift +let serverTrustPolicy = ServerTrustPolicy.pinCertificates( + certificates: ServerTrustPolicy.certificates(), + validateCertificateChain: true, + validateHost: true +) +``` + +There are many different cases of server trust evaluation giving you complete control over the validation process: + +* `performDefaultEvaluation`: Uses the default server trust evaluation while allowing you to control whether to validate the host provided by the challenge. +* `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. +* `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. +* `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 thus giving you complete control over the validation process. Use with caution. + +#### Server Trust Policy Manager + +The `ServerTrustPolicyManager` is responsible for storing an internal mapping of server trust policies to a particular host. This allows Alamofire to evaluate each host against a different server trust policy. + +```swift +let serverTrustPolicies: [String: ServerTrustPolicy] = [ + "test.example.com": .pinCertificates( + certificates: ServerTrustPolicy.certificates(), + validateCertificateChain: true, + validateHost: true + ), + "insecure.expired-apis.com": .disableEvaluation +] + +let sessionManager = SessionManager( + serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies) +) +``` + +> Make sure to keep a reference to the new `SessionManager` instance, otherwise your requests will all get cancelled when your `sessionManager` is deallocated. + +These server trust policies will result in the following behavior: + +- `test.example.com` will always use certificate pinning with certificate chain and host validation enabled thus requiring the following criteria to be met to allow the TLS handshake to succeed: + - Certificate chain MUST be valid. + - Certificate chain MUST include one of the pinned certificates. + - Challenge host MUST match the host in the certificate chain's leaf certificate. +- `insecure.expired-apis.com` will never evaluate the certificate chain and will always allow the TLS handshake to succeed. +- All other hosts will use the default evaluation provided by Apple. + +##### Subclassing Server Trust Policy Manager + +If you find yourself needing more flexible server trust policy matching behavior (i.e. wildcarded domains), then subclass the `ServerTrustPolicyManager` and override the `serverTrustPolicyForHost` method with your own custom implementation. + +```swift +class CustomServerTrustPolicyManager: ServerTrustPolicyManager { + override func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? { + var policy: ServerTrustPolicy? + + // Implement your custom domain matching behavior... + + return policy + } +} +``` + +#### Validating the Host + +The `.performDefaultEvaluation`, `.pinCertificates` and `.pinPublicKeys` server trust policies all take a `validateHost` parameter. Setting the value to `true` will cause the server trust evaluation to verify that hostname in the certificate matches the hostname of the challenge. If they do not match, evaluation will fail. A `validateHost` value of `false` will still evaluate the full certificate chain, but will not validate the hostname of the leaf certificate. + +> It is recommended that `validateHost` always be set to `true` in production environments. + +#### Validating the Certificate Chain + +Pinning certificates and public keys both have the option of validating the certificate chain using the `validateCertificateChain` parameter. By setting this value to `true`, the full certificate chain will be evaluated in addition to performing a byte equality check against the pinned certificates or public keys. A value of `false` will skip the certificate chain validation, but will still perform the byte equality check. + +There are several cases where it may make sense to disable certificate chain validation. The most common use cases for disabling validation are self-signed and expired certificates. The evaluation would always fail in both of these cases, but the byte equality check will still ensure you are receiving the certificate you expect from the server. + +> It is recommended that `validateCertificateChain` always be set to `true` in production environments. + +#### App Transport Security + +With the addition of App Transport Security (ATS) in iOS 9, it is possible that using a custom `ServerTrustPolicyManager` with several `ServerTrustPolicy` objects will have no effect. If you continuously see `CFNetwork SSLHandshake failed (-9806)` errors, you have probably run into this problem. Apple's ATS system overrides the entire challenge system unless you configure the ATS settings in your app's plist to disable enough of it to allow your app to evaluate the server trust. + +If you run into this problem (high probability with self-signed certificates), you can work around this issue by adding the following to your `Info.plist`. + +```xml + + NSAppTransportSecurity + + NSExceptionDomains + + example.com + + NSExceptionAllowsInsecureHTTPLoads + + NSExceptionRequiresForwardSecrecy + + NSIncludesSubdomains + + + NSTemporaryExceptionMinimumTLSVersion + TLSv1.2 + + + + +``` + +Whether you need to set the `NSExceptionRequiresForwardSecrecy` to `NO` depends on whether your TLS connection is using an allowed cipher suite. In certain cases, it will need to be set to `NO`. The `NSExceptionAllowsInsecureHTTPLoads` MUST be set to `YES` in order to allow the `SessionDelegate` to receive challenge callbacks. Once the challenge callbacks are being called, the `ServerTrustPolicyManager` will take over the server trust evaluation. You may also need to specify the `NSTemporaryExceptionMinimumTLSVersion` if you're trying to connect to a host that only supports TLS versions less than `1.2`. + +> It is recommended to always use valid certificates in production environments. + +### Network Reachability + +The `NetworkReachabilityManager` listens for reachability changes of hosts and addresses for both WWAN and WiFi network interfaces. + +```swift +let manager = NetworkReachabilityManager(host: "www.apple.com") + +manager?.listener = { status in + print("Network Status Changed: \(status)") +} + +manager?.startListening() +``` + +> Make sure to remember to retain the `manager` in the above example, or no status changes will be reported. +> Also, do not include the scheme in the `host` string or reachability won't function correctly. + +There are some important things to remember when using network reachability to determine what to do next. + +- **Do NOT** use Reachability to determine if a network request should be sent. + - You should **ALWAYS** send it. +- When Reachability is restored, use the event to retry failed network requests. + - Even though the network requests may still fail, this is a good moment to retry them. +- The network reachability status can be useful for determining why a network request may have failed. + - If a network request fails, it is more useful to tell the user that the network request failed due to being offline rather than a more technical error, such as "request timed out." + +> It is recommended to check out [WWDC 2012 Session 706, "Networking Best Practices"](https://developer.apple.com/videos/play/wwdc2012-706/) for more info. + +--- + +## Open Radars + +The following radars have some effect on the current implementation of Alamofire. + +- [`rdar://21349340`](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case +- [`rdar://26761490`](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage +- `rdar://26870455` - Background URL Session Configurations do not work in the simulator +- `rdar://26849668` - Some URLProtocol APIs do not properly handle `URLRequest` + +## FAQ + +### What's the origin of the name Alamofire? + +Alamofire is named after the [Alamo Fire flower](https://aggie-horticulture.tamu.edu/wildseed/alamofire.html), a hybrid variant of the Bluebonnet, the official state flower of Texas. + +### What logic belongs in a Router vs. a Request Adapter? + +Simple, static data such as paths, parameters and common headers belong in the `Router`. Dynamic data such as an `Authorization` header whose value can changed based on an authentication system belongs in a `RequestAdapter`. + +The reason the dynamic data MUST be placed into the `RequestAdapter` is to support retry operations. When a `Request` is retried, the original request is not rebuilt meaning the `Router` will not be called again. The `RequestAdapter` is called again allowing the dynamic data to be updated on the original request before retrying the `Request`. + +--- + +## Credits + +Alamofire is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). You can follow them on Twitter at [@AlamofireSF](https://twitter.com/AlamofireSF) for project updates and releases. + +### Security Disclosure + +If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. + +## Donations + +The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise money to officially register as a federal non-profit organization. Registering will allow us members to gain some legal protections and also allow us to put donations to use, tax free. Donating to the ASF will enable us to: + +- Pay our legal fees to register as a federal non-profit organization +- Pay our yearly legal fees to keep the non-profit in good status +- Pay for our mail servers to help us stay on top of all questions and security issues +- Potentially fund test servers to make it easier for us to test the edge cases +- Potentially fund developers to work on one of our projects full-time + +The community adoption of the ASF libraries has been amazing. We are greatly humbled by your enthusiasm around the projects, and want to continue to do everything we can to move the needle forward. With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. If you use any of our libraries for work, see if your employers would be interested in donating. Our initial goal is to raise $1000 to get all our legal ducks in a row and kickstart this campaign. Any amount you can donate today to help us reach our goal would be greatly appreciated. + +Click here to lend your support to: Alamofire Software Foundation and make a donation at pledgie.com ! + +## License + +Alamofire is released under the MIT license. [See LICENSE](https://github.com/Alamofire/Alamofire/blob/master/LICENSE) for details. diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/AFError.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/AFError.swift new file mode 100644 index 0000000000..f047695b6d --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/AFError.swift @@ -0,0 +1,460 @@ +// +// AFError.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 + +/// `AFError` is the error type returned by Alamofire. It encompasses a few different types of errors, each with +/// their own associated reasons. +/// +/// - invalidURL: Returned when a `URLConvertible` type fails to create a valid `URL`. +/// - parameterEncodingFailed: Returned when a parameter encoding object throws an error during the encoding process. +/// - multipartEncodingFailed: Returned when some step in the multipart encoding process fails. +/// - responseValidationFailed: Returned when a `validate()` call fails. +/// - responseSerializationFailed: Returned when a response serializer encounters an error in the serialization process. +public enum AFError: Error { + /// The underlying reason the parameter encoding error occurred. + /// + /// - missingURL: The URL request did not have a URL to encode. + /// - jsonEncodingFailed: JSON serialization failed with an underlying system error during the + /// encoding process. + /// - propertyListEncodingFailed: Property list serialization failed with an underlying system error during + /// encoding process. + public enum ParameterEncodingFailureReason { + case missingURL + case jsonEncodingFailed(error: Error) + case propertyListEncodingFailed(error: Error) + } + + /// The underlying reason the multipart encoding error occurred. + /// + /// - bodyPartURLInvalid: The `fileURL` provided for reading an encodable body part isn't a + /// file URL. + /// - bodyPartFilenameInvalid: The filename of the `fileURL` provided has either an empty + /// `lastPathComponent` or `pathExtension. + /// - bodyPartFileNotReachable: The file at the `fileURL` provided was not reachable. + /// - bodyPartFileNotReachableWithError: Attempting to check the reachability of the `fileURL` provided threw + /// an error. + /// - bodyPartFileIsDirectory: The file at the `fileURL` provided is actually a directory. + /// - bodyPartFileSizeNotAvailable: The size of the file at the `fileURL` provided was not returned by + /// the system. + /// - bodyPartFileSizeQueryFailedWithError: The attempt to find the size of the file at the `fileURL` provided + /// threw an error. + /// - bodyPartInputStreamCreationFailed: An `InputStream` could not be created for the provided `fileURL`. + /// - outputStreamCreationFailed: An `OutputStream` could not be created when attempting to write the + /// encoded data to disk. + /// - outputStreamFileAlreadyExists: The encoded body data could not be writtent disk because a file + /// already exists at the provided `fileURL`. + /// - outputStreamURLInvalid: The `fileURL` provided for writing the encoded body data to disk is + /// not a file URL. + /// - outputStreamWriteFailed: The attempt to write the encoded body data to disk failed with an + /// underlying error. + /// - inputStreamReadFailed: The attempt to read an encoded body part `InputStream` failed with + /// underlying system error. + public enum MultipartEncodingFailureReason { + case bodyPartURLInvalid(url: URL) + case bodyPartFilenameInvalid(in: URL) + case bodyPartFileNotReachable(at: URL) + case bodyPartFileNotReachableWithError(atURL: URL, error: Error) + case bodyPartFileIsDirectory(at: URL) + case bodyPartFileSizeNotAvailable(at: URL) + case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error) + case bodyPartInputStreamCreationFailed(for: URL) + + case outputStreamCreationFailed(for: URL) + case outputStreamFileAlreadyExists(at: URL) + case outputStreamURLInvalid(url: URL) + case outputStreamWriteFailed(error: Error) + + case inputStreamReadFailed(error: Error) + } + + /// The underlying reason the response validation error occurred. + /// + /// - dataFileNil: The data file containing the server response did not exist. + /// - dataFileReadFailed: The data file containing the server response could not be read. + /// - missingContentType: The response did not contain a `Content-Type` and the `acceptableContentTypes` + /// provided did not contain wildcard type. + /// - unacceptableContentType: The response `Content-Type` did not match any type in the provided + /// `acceptableContentTypes`. + /// - unacceptableStatusCode: The response status code was not acceptable. + public enum ResponseValidationFailureReason { + case dataFileNil + case dataFileReadFailed(at: URL) + case missingContentType(acceptableContentTypes: [String]) + case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String) + case unacceptableStatusCode(code: Int) + } + + /// The underlying reason the response serialization error occurred. + /// + /// - inputDataNil: The server response contained no data. + /// - inputDataNilOrZeroLength: The server response contained no data or the data was zero length. + /// - inputFileNil: The file containing the server response did not exist. + /// - inputFileReadFailed: The file containing the server response could not be read. + /// - stringSerializationFailed: String serialization failed using the provided `String.Encoding`. + /// - jsonSerializationFailed: JSON serialization failed with an underlying system error. + /// - propertyListSerializationFailed: Property list serialization failed with an underlying system error. + public enum ResponseSerializationFailureReason { + case inputDataNil + case inputDataNilOrZeroLength + case inputFileNil + case inputFileReadFailed(at: URL) + case stringSerializationFailed(encoding: String.Encoding) + case jsonSerializationFailed(error: Error) + case propertyListSerializationFailed(error: Error) + } + + case invalidURL(url: URLConvertible) + case parameterEncodingFailed(reason: ParameterEncodingFailureReason) + case multipartEncodingFailed(reason: MultipartEncodingFailureReason) + case responseValidationFailed(reason: ResponseValidationFailureReason) + case responseSerializationFailed(reason: ResponseSerializationFailureReason) +} + +// MARK: - Adapt Error + +struct AdaptError: Error { + let error: Error +} + +extension Error { + var underlyingAdaptError: Error? { return (self as? AdaptError)?.error } +} + +// MARK: - Error Booleans + +extension AFError { + /// Returns whether the AFError is an invalid URL error. + public var isInvalidURLError: Bool { + if case .invalidURL = self { return true } + return false + } + + /// Returns whether the AFError is a parameter encoding error. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isParameterEncodingError: Bool { + if case .parameterEncodingFailed = self { return true } + return false + } + + /// Returns whether the AFError is a multipart encoding error. When `true`, the `url` and `underlyingError` properties + /// will contain the associated values. + public var isMultipartEncodingError: Bool { + if case .multipartEncodingFailed = self { return true } + return false + } + + /// Returns whether the `AFError` is a response validation error. When `true`, the `acceptableContentTypes`, + /// `responseContentType`, and `responseCode` properties will contain the associated values. + public var isResponseValidationError: Bool { + if case .responseValidationFailed = self { return true } + return false + } + + /// Returns whether the `AFError` is a response serialization error. When `true`, the `failedStringEncoding` and + /// `underlyingError` properties will contain the associated values. + public var isResponseSerializationError: Bool { + if case .responseSerializationFailed = self { return true } + return false + } +} + +// MARK: - Convenience Properties + +extension AFError { + /// The `URLConvertible` associated with the error. + public var urlConvertible: URLConvertible? { + switch self { + case .invalidURL(let url): + return url + default: + return nil + } + } + + /// The `URL` associated with the error. + public var url: URL? { + switch self { + case .multipartEncodingFailed(let reason): + return reason.url + default: + return nil + } + } + + /// The `Error` returned by a system framework associated with a `.parameterEncodingFailed`, + /// `.multipartEncodingFailed` or `.responseSerializationFailed` error. + public var underlyingError: Error? { + switch self { + case .parameterEncodingFailed(let reason): + return reason.underlyingError + case .multipartEncodingFailed(let reason): + return reason.underlyingError + case .responseSerializationFailed(let reason): + return reason.underlyingError + default: + return nil + } + } + + /// The acceptable `Content-Type`s of a `.responseValidationFailed` error. + public var acceptableContentTypes: [String]? { + switch self { + case .responseValidationFailed(let reason): + return reason.acceptableContentTypes + default: + return nil + } + } + + /// The response `Content-Type` of a `.responseValidationFailed` error. + public var responseContentType: String? { + switch self { + case .responseValidationFailed(let reason): + return reason.responseContentType + default: + return nil + } + } + + /// The response code of a `.responseValidationFailed` error. + public var responseCode: Int? { + switch self { + case .responseValidationFailed(let reason): + return reason.responseCode + default: + return nil + } + } + + /// The `String.Encoding` associated with a failed `.stringResponse()` call. + public var failedStringEncoding: String.Encoding? { + switch self { + case .responseSerializationFailed(let reason): + return reason.failedStringEncoding + default: + return nil + } + } +} + +extension AFError.ParameterEncodingFailureReason { + var underlyingError: Error? { + switch self { + case .jsonEncodingFailed(let error), .propertyListEncodingFailed(let error): + return error + default: + return nil + } + } +} + +extension AFError.MultipartEncodingFailureReason { + var url: URL? { + switch self { + case .bodyPartURLInvalid(let url), .bodyPartFilenameInvalid(let url), .bodyPartFileNotReachable(let url), + .bodyPartFileIsDirectory(let url), .bodyPartFileSizeNotAvailable(let url), + .bodyPartInputStreamCreationFailed(let url), .outputStreamCreationFailed(let url), + .outputStreamFileAlreadyExists(let url), .outputStreamURLInvalid(let url), + .bodyPartFileNotReachableWithError(let url, _), .bodyPartFileSizeQueryFailedWithError(let url, _): + return url + default: + return nil + } + } + + var underlyingError: Error? { + switch self { + case .bodyPartFileNotReachableWithError(_, let error), .bodyPartFileSizeQueryFailedWithError(_, let error), + .outputStreamWriteFailed(let error), .inputStreamReadFailed(let error): + return error + default: + return nil + } + } +} + +extension AFError.ResponseValidationFailureReason { + var acceptableContentTypes: [String]? { + switch self { + case .missingContentType(let types), .unacceptableContentType(let types, _): + return types + default: + return nil + } + } + + var responseContentType: String? { + switch self { + case .unacceptableContentType(_, let responseType): + return responseType + default: + return nil + } + } + + var responseCode: Int? { + switch self { + case .unacceptableStatusCode(let code): + return code + default: + return nil + } + } +} + +extension AFError.ResponseSerializationFailureReason { + var failedStringEncoding: String.Encoding? { + switch self { + case .stringSerializationFailed(let encoding): + return encoding + default: + return nil + } + } + + var underlyingError: Error? { + switch self { + case .jsonSerializationFailed(let error), .propertyListSerializationFailed(let error): + return error + default: + return nil + } + } +} + +// MARK: - Error Descriptions + +extension AFError: LocalizedError { + public var errorDescription: String? { + switch self { + case .invalidURL(let url): + return "URL is not valid: \(url)" + case .parameterEncodingFailed(let reason): + return reason.localizedDescription + case .multipartEncodingFailed(let reason): + return reason.localizedDescription + case .responseValidationFailed(let reason): + return reason.localizedDescription + case .responseSerializationFailed(let reason): + return reason.localizedDescription + } + } +} + +extension AFError.ParameterEncodingFailureReason { + var localizedDescription: String { + switch self { + case .missingURL: + return "URL request to encode was missing a URL" + case .jsonEncodingFailed(let error): + return "JSON could not be encoded because of error:\n\(error.localizedDescription)" + case .propertyListEncodingFailed(let error): + return "PropertyList could not be encoded because of error:\n\(error.localizedDescription)" + } + } +} + +extension AFError.MultipartEncodingFailureReason { + var localizedDescription: String { + switch self { + case .bodyPartURLInvalid(let url): + return "The URL provided is not a file URL: \(url)" + case .bodyPartFilenameInvalid(let url): + return "The URL provided does not have a valid filename: \(url)" + case .bodyPartFileNotReachable(let url): + return "The URL provided is not reachable: \(url)" + case .bodyPartFileNotReachableWithError(let url, let error): + return ( + "The system returned an error while checking the provided URL for " + + "reachability.\nURL: \(url)\nError: \(error)" + ) + case .bodyPartFileIsDirectory(let url): + return "The URL provided is a directory: \(url)" + case .bodyPartFileSizeNotAvailable(let url): + return "Could not fetch the file size from the provided URL: \(url)" + case .bodyPartFileSizeQueryFailedWithError(let url, let error): + return ( + "The system returned an error while attempting to fetch the file size from the " + + "provided URL.\nURL: \(url)\nError: \(error)" + ) + case .bodyPartInputStreamCreationFailed(let url): + return "Failed to create an InputStream for the provided URL: \(url)" + case .outputStreamCreationFailed(let url): + return "Failed to create an OutputStream for URL: \(url)" + case .outputStreamFileAlreadyExists(let url): + return "A file already exists at the provided URL: \(url)" + case .outputStreamURLInvalid(let url): + return "The provided OutputStream URL is invalid: \(url)" + case .outputStreamWriteFailed(let error): + return "OutputStream write failed with error: \(error)" + case .inputStreamReadFailed(let error): + return "InputStream read failed with error: \(error)" + } + } +} + +extension AFError.ResponseSerializationFailureReason { + var localizedDescription: String { + switch self { + case .inputDataNil: + return "Response could not be serialized, input data was nil." + case .inputDataNilOrZeroLength: + return "Response could not be serialized, input data was nil or zero length." + case .inputFileNil: + return "Response could not be serialized, input file was nil." + case .inputFileReadFailed(let url): + return "Response could not be serialized, input file could not be read: \(url)." + case .stringSerializationFailed(let encoding): + return "String could not be serialized with encoding: \(encoding)." + case .jsonSerializationFailed(let error): + return "JSON could not be serialized because of error:\n\(error.localizedDescription)" + case .propertyListSerializationFailed(let error): + return "PropertyList could not be serialized because of error:\n\(error.localizedDescription)" + } + } +} + +extension AFError.ResponseValidationFailureReason { + var localizedDescription: String { + switch self { + case .dataFileNil: + return "Response could not be validated, data file was nil." + case .dataFileReadFailed(let url): + return "Response could not be validated, data file could not be read: \(url)." + case .missingContentType(let types): + return ( + "Response Content-Type was missing and acceptable content types " + + "(\(types.joined(separator: ","))) do not match \"*/*\"." + ) + case .unacceptableContentType(let acceptableTypes, let responseType): + return ( + "Response Content-Type \"\(responseType)\" does not match any acceptable types: " + + "\(acceptableTypes.joined(separator: ","))." + ) + case .unacceptableStatusCode(let code): + return "Response status code was unacceptable: \(code)." + } + } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift new file mode 100644 index 0000000000..edcf717ca9 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift @@ -0,0 +1,465 @@ +// +// 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 + +/// Types adopting the `URLConvertible` protocol can be used to construct URLs, which are then used to construct +/// URL requests. +public protocol URLConvertible { + /// Returns a URL that conforms to RFC 2396 or throws an `Error`. + /// + /// - throws: An `Error` if the type cannot be converted to a `URL`. + /// + /// - returns: A URL or throws an `Error`. + func asURL() throws -> URL +} + +extension String: URLConvertible { + /// Returns a URL if `self` represents a valid URL string that conforms to RFC 2396 or throws an `AFError`. + /// + /// - throws: An `AFError.invalidURL` if `self` is not a valid URL string. + /// + /// - returns: A URL or throws an `AFError`. + public func asURL() throws -> URL { + guard let url = URL(string: self) else { throw AFError.invalidURL(url: self) } + return url + } +} + +extension URL: URLConvertible { + /// Returns self. + public func asURL() throws -> URL { return self } +} + +extension URLComponents: URLConvertible { + /// Returns a URL if `url` is not nil, otherwise throws an `Error`. + /// + /// - throws: An `AFError.invalidURL` if `url` is `nil`. + /// + /// - returns: A URL or throws an `AFError`. + public func asURL() throws -> URL { + guard let url = url else { throw AFError.invalidURL(url: self) } + return url + } +} + +// MARK: - + +/// Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. +public protocol URLRequestConvertible { + /// Returns a URL request or throws if an `Error` was encountered. + /// + /// - throws: An `Error` if the underlying `URLRequest` is `nil`. + /// + /// - returns: A URL request. + func asURLRequest() throws -> URLRequest +} + +extension URLRequestConvertible { + /// The URL request. + public var urlRequest: URLRequest? { return try? asURLRequest() } +} + +extension URLRequest: URLRequestConvertible { + /// Returns a URL request or throws if an `Error` was encountered. + public func asURLRequest() throws -> URLRequest { return self } +} + +// MARK: - + +extension URLRequest { + /// Creates an instance with the specified `method`, `urlString` and `headers`. + /// + /// - parameter url: The URL. + /// - parameter method: The HTTP method. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The new `URLRequest` instance. + public init(url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws { + let url = try url.asURL() + + self.init(url: url) + + httpMethod = method.rawValue + + if let headers = headers { + for (headerField, headerValue) in headers { + setValue(headerValue, forHTTPHeaderField: headerField) + } + } + } + + func adapt(using adapter: RequestAdapter?) throws -> URLRequest { + guard let adapter = adapter else { return self } + return try adapter.adapt(self) + } +} + +// MARK: - Data Request + +/// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, +/// `method`, `parameters`, `encoding` and `headers`. +/// +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.get` by default. +/// - parameter parameters: The parameters. `nil` by default. +/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `DataRequest`. +@discardableResult +public func request( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil) + -> DataRequest +{ + return SessionManager.default.request( + url, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers + ) +} + +/// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of a URL based on the +/// specified `urlRequest`. +/// +/// - parameter urlRequest: The URL request +/// +/// - returns: The created `DataRequest`. +@discardableResult +public func request(_ urlRequest: URLRequestConvertible) -> DataRequest { + return SessionManager.default.request(urlRequest) +} + +// MARK: - Download Request + +// MARK: URL Request + +/// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, +/// `method`, `parameters`, `encoding`, `headers` and save them to the `destination`. +/// +/// If `destination` is not specified, the contents will remain in the temporary location determined by the +/// underlying URL session. +/// +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.get` by default. +/// - parameter parameters: The parameters. `nil` by default. +/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. +/// +/// - returns: The created `DownloadRequest`. +@discardableResult +public func download( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest +{ + return SessionManager.default.download( + url, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers, + to: destination + ) +} + +/// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of a URL based on the +/// specified `urlRequest` and save them to the `destination`. +/// +/// If `destination` is not specified, the contents will remain in the temporary location determined by the +/// underlying URL session. +/// +/// - parameter urlRequest: The URL request. +/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. +/// +/// - returns: The created `DownloadRequest`. +@discardableResult +public func download( + _ urlRequest: URLRequestConvertible, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest +{ + return SessionManager.default.download(urlRequest, to: destination) +} + +// MARK: Resume Data + +/// Creates a `DownloadRequest` using the default `SessionManager` from the `resumeData` produced from a +/// previous request cancellation to retrieve the contents of the original request and save them to the `destination`. +/// +/// If `destination` is not specified, the contents will remain in the temporary location determined by the +/// underlying URL session. +/// +/// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken +/// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the +/// data is written incorrectly and will always fail to resume the download. For more information about the bug and +/// possible workarounds, please refer to the following Stack Overflow post: +/// +/// - http://stackoverflow.com/a/39347461/1342462 +/// +/// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` +/// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for additional +/// information. +/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. +/// +/// - returns: The created `DownloadRequest`. +@discardableResult +public func download( + resumingWith resumeData: Data, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest +{ + return SessionManager.default.download(resumingWith: resumeData, to: destination) +} + +// MARK: - Upload Request + +// MARK: File + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` +/// for uploading the `file`. +/// +/// - parameter file: The file to upload. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload( + _ fileURL: URL, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest +{ + return SessionManager.default.upload(fileURL, to: url, method: method, headers: headers) +} + +/// Creates a `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for +/// uploading the `file`. +/// +/// - parameter file: The file to upload. +/// - parameter urlRequest: The URL request. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { + return SessionManager.default.upload(fileURL, with: urlRequest) +} + +// MARK: Data + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` +/// for uploading the `data`. +/// +/// - parameter data: The data to upload. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload( + _ data: Data, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest +{ + return SessionManager.default.upload(data, to: url, method: method, headers: headers) +} + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for +/// uploading the `data`. +/// +/// - parameter data: The data to upload. +/// - parameter urlRequest: The URL request. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { + return SessionManager.default.upload(data, with: urlRequest) +} + +// MARK: InputStream + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` +/// for uploading the `stream`. +/// +/// - parameter stream: The stream to upload. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload( + _ stream: InputStream, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest +{ + return SessionManager.default.upload(stream, to: url, method: method, headers: headers) +} + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for +/// uploading the `stream`. +/// +/// - parameter urlRequest: The URL request. +/// - parameter stream: The stream to upload. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { + return SessionManager.default.upload(stream, with: urlRequest) +} + +// MARK: MultipartFormData + +/// Encodes `multipartFormData` using `encodingMemoryThreshold` with the default `SessionManager` and calls +/// `encodingCompletion` with new `UploadRequest` using the `url`, `method` and `headers`. +/// +/// 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. +/// +/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. +/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. +/// `multipartFormDataEncodingMemoryThreshold` by default. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. +public func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) +{ + return SessionManager.default.upload( + multipartFormData: multipartFormData, + usingThreshold: encodingMemoryThreshold, + to: url, + method: method, + headers: headers, + encodingCompletion: encodingCompletion + ) +} + +/// Encodes `multipartFormData` using `encodingMemoryThreshold` and the default `SessionManager` and +/// calls `encodingCompletion` with new `UploadRequest` using the `urlRequest`. +/// +/// 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. +/// +/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. +/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. +/// `multipartFormDataEncodingMemoryThreshold` by default. +/// - parameter urlRequest: The URL request. +/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. +public func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + with urlRequest: URLRequestConvertible, + encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) +{ + return SessionManager.default.upload( + multipartFormData: multipartFormData, + usingThreshold: encodingMemoryThreshold, + with: urlRequest, + encodingCompletion: encodingCompletion + ) +} + +#if !os(watchOS) + +// MARK: - Stream Request + +// MARK: Hostname and Port + +/// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `hostname` +/// and `port`. +/// +/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. +/// +/// - parameter hostName: The hostname of the server to connect to. +/// - parameter port: The port of the server to connect to. +/// +/// - returns: The created `StreamRequest`. +@discardableResult +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +public func stream(withHostName hostName: String, port: Int) -> StreamRequest { + return SessionManager.default.stream(withHostName: hostName, port: port) +} + +// MARK: NetService + +/// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `netService`. +/// +/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. +/// +/// - parameter netService: The net service used to identify the endpoint. +/// +/// - returns: The created `StreamRequest`. +@discardableResult +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +public func stream(with netService: NetService) -> StreamRequest { + return SessionManager.default.stream(with: netService) +} + +#endif diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift new file mode 100644 index 0000000000..78e214ea17 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift @@ -0,0 +1,37 @@ +// +// DispatchQueue+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 Dispatch +import Foundation + +extension DispatchQueue { + static var userInteractive: DispatchQueue { return DispatchQueue.global(qos: .userInteractive) } + static var userInitiated: DispatchQueue { return DispatchQueue.global(qos: .userInitiated) } + static var utility: DispatchQueue { return DispatchQueue.global(qos: .utility) } + static var background: DispatchQueue { return DispatchQueue.global(qos: .background) } + + func after(_ delay: TimeInterval, execute closure: @escaping () -> Void) { + asyncAfter(deadline: .now() + delay, execute: closure) + } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift new file mode 100644 index 0000000000..c5093f9f85 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift @@ -0,0 +1,580 @@ +// +// 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(macOS) +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 +open 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(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data { + 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.data(using: String.Encoding.utf8, allowLossyConversion: false)! + } + } + + class BodyPart { + let headers: HTTPHeaders + let bodyStream: InputStream + let bodyContentLength: UInt64 + var hasInitialBoundary = false + var hasFinalBoundary = false + + init(headers: HTTPHeaders, bodyStream: InputStream, 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`. + open lazy var contentType: String = "multipart/form-data; boundary=\(self.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: AFError? + 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 append(_ data: Data, withName name: String) { + let headers = contentHeaders(withName: name) + let stream = InputStream(data: data) + let length = UInt64(data.count) + + append(stream, withLength: 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 append(_ data: Data, withName name: String, mimeType: String) { + let headers = contentHeaders(withName: name, mimeType: mimeType) + let stream = InputStream(data: data) + let length = UInt64(data.count) + + append(stream, withLength: 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 append(_ data: Data, withName name: String, fileName: String, mimeType: String) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + let stream = InputStream(data: data) + let length = UInt64(data.count) + + append(stream, withLength: 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 append(_ fileURL: URL, withName name: String) { + let fileName = fileURL.lastPathComponent + let pathExtension = fileURL.pathExtension + + if !fileName.isEmpty && !pathExtension.isEmpty { + let mime = mimeType(forPathExtension: pathExtension) + append(fileURL, withName: name, fileName: fileName, mimeType: mime) + } else { + setBodyPartError(withReason: .bodyPartFilenameInvalid(in: fileURL)) + } + } + + /// 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 append(_ fileURL: URL, withName name: String, fileName: String, mimeType: String) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + + //============================================================ + // Check 1 - is file URL? + //============================================================ + + guard fileURL.isFileURL else { + setBodyPartError(withReason: .bodyPartURLInvalid(url: fileURL)) + return + } + + //============================================================ + // Check 2 - is file URL reachable? + //============================================================ + + do { + let isReachable = try fileURL.checkPromisedItemIsReachable() + guard isReachable else { + setBodyPartError(withReason: .bodyPartFileNotReachable(at: fileURL)) + return + } + } catch { + setBodyPartError(withReason: .bodyPartFileNotReachableWithError(atURL: fileURL, error: error)) + return + } + + //============================================================ + // Check 3 - is file URL a directory? + //============================================================ + + var isDirectory: ObjCBool = false + let path = fileURL.path + + guard FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) && !isDirectory.boolValue else { + setBodyPartError(withReason: .bodyPartFileIsDirectory(at: fileURL)) + return + } + + //============================================================ + // Check 4 - can the file size be extracted? + //============================================================ + + let bodyContentLength: UInt64 + + do { + guard let fileSize = try FileManager.default.attributesOfItem(atPath: path)[.size] as? NSNumber else { + setBodyPartError(withReason: .bodyPartFileSizeNotAvailable(at: fileURL)) + return + } + + bodyContentLength = fileSize.uint64Value + } + catch { + setBodyPartError(withReason: .bodyPartFileSizeQueryFailedWithError(forURL: fileURL, error: error)) + return + } + + //============================================================ + // Check 5 - can a stream be created from file URL? + //============================================================ + + guard let stream = InputStream(url: fileURL) else { + setBodyPartError(withReason: .bodyPartInputStreamCreationFailed(for: fileURL)) + return + } + + append(stream, withLength: bodyContentLength, 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 append( + _ stream: InputStream, + withLength length: UInt64, + name: String, + fileName: String, + mimeType: String) + { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + append(stream, withLength: 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 append(_ stream: InputStream, withLength length: UInt64, headers: HTTPHeaders) { + let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length) + bodyParts.append(bodyPart) + } + + // MARK: - Data Encoding + + /// Encodes all the appended body parts into a single `Data` value. + /// + /// 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 `AFError` if encoding encounters an error. + /// + /// - returns: The encoded `Data` if encoding is successful. + public func encode() throws -> Data { + if let bodyPartError = bodyPartError { + throw bodyPartError + } + + var encoded = Data() + + bodyParts.first?.hasInitialBoundary = true + bodyParts.last?.hasFinalBoundary = true + + for bodyPart in bodyParts { + let encodedData = try encode(bodyPart) + encoded.append(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 `AFError` if encoding encounters an error. + public func writeEncodedData(to fileURL: URL) throws { + if let bodyPartError = bodyPartError { + throw bodyPartError + } + + if FileManager.default.fileExists(atPath: fileURL.path) { + throw AFError.multipartEncodingFailed(reason: .outputStreamFileAlreadyExists(at: fileURL)) + } else if !fileURL.isFileURL { + throw AFError.multipartEncodingFailed(reason: .outputStreamURLInvalid(url: fileURL)) + } + + guard let outputStream = OutputStream(url: fileURL, append: false) else { + throw AFError.multipartEncodingFailed(reason: .outputStreamCreationFailed(for: fileURL)) + } + + outputStream.open() + defer { outputStream.close() } + + self.bodyParts.first?.hasInitialBoundary = true + self.bodyParts.last?.hasFinalBoundary = true + + for bodyPart in self.bodyParts { + try write(bodyPart, to: outputStream) + } + } + + // MARK: - Private - Body Part Encoding + + private func encode(_ bodyPart: BodyPart) throws -> Data { + var encoded = Data() + + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + encoded.append(initialData) + + let headerData = encodeHeaders(for: bodyPart) + encoded.append(headerData) + + let bodyStreamData = try encodeBodyStream(for: bodyPart) + encoded.append(bodyStreamData) + + if bodyPart.hasFinalBoundary { + encoded.append(finalBoundaryData()) + } + + return encoded + } + + private func encodeHeaders(for bodyPart: BodyPart) -> Data { + var headerText = "" + + for (key, value) in bodyPart.headers { + headerText += "\(key): \(value)\(EncodingCharacters.crlf)" + } + headerText += EncodingCharacters.crlf + + return headerText.data(using: String.Encoding.utf8, allowLossyConversion: false)! + } + + private func encodeBodyStream(for bodyPart: BodyPart) throws -> Data { + let inputStream = bodyPart.bodyStream + inputStream.open() + defer { inputStream.close() } + + var encoded = Data() + + while inputStream.hasBytesAvailable { + var buffer = [UInt8](repeating: 0, count: streamBufferSize) + let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) + + if let error = inputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error)) + } + + if bytesRead > 0 { + encoded.append(buffer, count: bytesRead) + } else { + break + } + } + + return encoded + } + + // MARK: - Private - Writing Body Part to Output Stream + + private func write(_ bodyPart: BodyPart, to outputStream: OutputStream) throws { + try writeInitialBoundaryData(for: bodyPart, to: outputStream) + try writeHeaderData(for: bodyPart, to: outputStream) + try writeBodyStream(for: bodyPart, to: outputStream) + try writeFinalBoundaryData(for: bodyPart, to: outputStream) + } + + private func writeInitialBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + return try write(initialData, to: outputStream) + } + + private func writeHeaderData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let headerData = encodeHeaders(for: bodyPart) + return try write(headerData, to: outputStream) + } + + private func writeBodyStream(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let inputStream = bodyPart.bodyStream + + inputStream.open() + defer { inputStream.close() } + + while inputStream.hasBytesAvailable { + var buffer = [UInt8](repeating: 0, count: streamBufferSize) + let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) + + if let streamError = inputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: streamError)) + } + + if bytesRead > 0 { + if buffer.count != bytesRead { + buffer = Array(buffer[0.. 0, outputStream.hasSpaceAvailable { + let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite) + + if let error = outputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .outputStreamWriteFailed(error: error)) + } + + bytesToWrite -= bytesWritten + + if bytesToWrite > 0 { + buffer = Array(buffer[bytesWritten.. String { + if + let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), + let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() + { + return contentType as String + } + + return "application/octet-stream" + } + + // MARK: - Private - Content Headers + + private func contentHeaders(withName name: String, fileName: String? = nil, mimeType: String? = nil) -> [String: String] { + var disposition = "form-data; name=\"\(name)\"" + if let fileName = fileName { disposition += "; filename=\"\(fileName)\"" } + + var headers = ["Content-Disposition": disposition] + if let mimeType = mimeType { headers["Content-Type"] = mimeType } + + return headers + } + + // MARK: - Private - Boundary Encoding + + private func initialBoundaryData() -> Data { + return BoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary) + } + + private func encapsulatedBoundaryData() -> Data { + return BoundaryGenerator.boundaryData(forBoundaryType: .encapsulated, boundary: boundary) + } + + private func finalBoundaryData() -> Data { + return BoundaryGenerator.boundaryData(forBoundaryType: .final, boundary: boundary) + } + + // MARK: - Private - Errors + + private func setBodyPartError(withReason reason: AFError.MultipartEncodingFailureReason) { + guard bodyPartError == nil else { return } + bodyPartError = AFError.multipartEncodingFailed(reason: reason) + } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/NetworkReachabilityManager.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/NetworkReachabilityManager.swift new file mode 100644 index 0000000000..30443b99b2 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/NetworkReachabilityManager.swift @@ -0,0 +1,233 @@ +// +// NetworkReachabilityManager.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#if !os(watchOS) + +import Foundation +import SystemConfiguration + +/// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and +/// WiFi network interfaces. +/// +/// Reachability can be used to determine background information about why a network operation failed, or to retry +/// network requests when a connection is established. It should not be used to prevent a user from initiating a network +/// request, as it's possible that an initial request may be required to establish reachability. +public class NetworkReachabilityManager { + /// Defines the various states of network reachability. + /// + /// - unknown: It is unknown whether the network is reachable. + /// - notReachable: The network is not reachable. + /// - reachable: The network is reachable. + public enum NetworkReachabilityStatus { + case unknown + case notReachable + case reachable(ConnectionType) + } + + /// Defines the various connection types detected by reachability flags. + /// + /// - ethernetOrWiFi: The connection type is either over Ethernet or WiFi. + /// - wwan: The connection type is a WWAN connection. + public enum ConnectionType { + case ethernetOrWiFi + case wwan + } + + /// A closure executed when the network reachability status changes. The closure takes a single argument: the + /// network reachability status. + public typealias Listener = (NetworkReachabilityStatus) -> Void + + // MARK: - Properties + + /// Whether the network is currently reachable. + public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi } + + /// Whether the network is currently reachable over the WWAN interface. + public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .reachable(.wwan) } + + /// Whether the network is currently reachable over Ethernet or WiFi interface. + public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .reachable(.ethernetOrWiFi) } + + /// The current network reachability status. + public var networkReachabilityStatus: NetworkReachabilityStatus { + guard let flags = self.flags else { return .unknown } + return networkReachabilityStatusForFlags(flags) + } + + /// The dispatch queue to execute the `listener` closure on. + public var listenerQueue: DispatchQueue = DispatchQueue.main + + /// A closure executed when the network reachability status changes. + public var listener: Listener? + + private var flags: SCNetworkReachabilityFlags? { + var flags = SCNetworkReachabilityFlags() + + if SCNetworkReachabilityGetFlags(reachability, &flags) { + return flags + } + + return nil + } + + private let reachability: SCNetworkReachability + private var previousFlags: SCNetworkReachabilityFlags + + // MARK: - Initialization + + /// Creates a `NetworkReachabilityManager` instance with the specified host. + /// + /// - parameter host: The host used to evaluate network reachability. + /// + /// - returns: The new `NetworkReachabilityManager` instance. + public convenience init?(host: String) { + guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } + self.init(reachability: reachability) + } + + /// Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0. + /// + /// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing + /// status of the device, both IPv4 and IPv6. + /// + /// - returns: The new `NetworkReachabilityManager` instance. + public convenience init?() { + var address = sockaddr_in() + address.sin_len = UInt8(MemoryLayout.size) + address.sin_family = sa_family_t(AF_INET) + + guard let reachability = withUnsafePointer(to: &address, { pointer in + return pointer.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout.size) { + return SCNetworkReachabilityCreateWithAddress(nil, $0) + } + }) else { return nil } + + self.init(reachability: reachability) + } + + private init(reachability: SCNetworkReachability) { + self.reachability = reachability + self.previousFlags = SCNetworkReachabilityFlags() + } + + deinit { + stopListening() + } + + // MARK: - Listening + + /// Starts listening for changes in network reachability status. + /// + /// - returns: `true` if listening was started successfully, `false` otherwise. + @discardableResult + public func startListening() -> Bool { + var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) + context.info = Unmanaged.passUnretained(self).toOpaque() + + let callbackEnabled = SCNetworkReachabilitySetCallback( + reachability, + { (_, flags, info) in + let reachability = Unmanaged.fromOpaque(info!).takeUnretainedValue() + reachability.notifyListener(flags) + }, + &context + ) + + let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue) + + listenerQueue.async { + self.previousFlags = SCNetworkReachabilityFlags() + self.notifyListener(self.flags ?? SCNetworkReachabilityFlags()) + } + + return callbackEnabled && queueEnabled + } + + /// Stops listening for changes in network reachability status. + public func stopListening() { + SCNetworkReachabilitySetCallback(reachability, nil, nil) + SCNetworkReachabilitySetDispatchQueue(reachability, nil) + } + + // MARK: - Internal - Listener Notification + + func notifyListener(_ flags: SCNetworkReachabilityFlags) { + guard previousFlags != flags else { return } + previousFlags = flags + + listener?(networkReachabilityStatusForFlags(flags)) + } + + // MARK: - Internal - Network Reachability Status + + func networkReachabilityStatusForFlags(_ flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus { + guard isNetworkReachable(with: flags) else { return .notReachable } + + var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi) + + #if os(iOS) + if flags.contains(.isWWAN) { networkStatus = .reachable(.wwan) } + #endif + + return networkStatus + } + + func isNetworkReachable(with flags: SCNetworkReachabilityFlags) -> Bool { + let isReachable = flags.contains(.reachable) + let needsConnection = flags.contains(.connectionRequired) + let canConnectAutomatically = flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic) + let canConnectWithoutUserInteraction = canConnectAutomatically && !flags.contains(.interventionRequired) + + return isReachable && (!needsConnection || canConnectWithoutUserInteraction) + } +} + +// MARK: - + +extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} + +/// Returns whether the two network reachability status values are equal. +/// +/// - parameter lhs: The left-hand side value to compare. +/// - parameter rhs: The right-hand side value to compare. +/// +/// - returns: `true` if the two values are equal, `false` otherwise. +public func ==( + lhs: NetworkReachabilityManager.NetworkReachabilityStatus, + rhs: NetworkReachabilityManager.NetworkReachabilityStatus) + -> Bool +{ + switch (lhs, rhs) { + case (.unknown, .unknown): + return true + case (.notReachable, .notReachable): + return true + case let (.reachable(lhsConnectionType), .reachable(rhsConnectionType)): + return lhsConnectionType == rhsConnectionType + default: + return false + } +} + +#endif diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Notifications.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Notifications.swift new file mode 100644 index 0000000000..81f6e378c8 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Notifications.swift @@ -0,0 +1,52 @@ +// +// Notifications.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension Notification.Name { + /// Used as a namespace for all `URLSessionTask` related notifications. + public struct Task { + /// Posted when a `URLSessionTask` is resumed. The notification `object` contains the resumed `URLSessionTask`. + public static let DidResume = Notification.Name(rawValue: "org.alamofire.notification.name.task.didResume") + + /// Posted when a `URLSessionTask` is suspended. The notification `object` contains the suspended `URLSessionTask`. + public static let DidSuspend = Notification.Name(rawValue: "org.alamofire.notification.name.task.didSuspend") + + /// Posted when a `URLSessionTask` is cancelled. The notification `object` contains the cancelled `URLSessionTask`. + public static let DidCancel = Notification.Name(rawValue: "org.alamofire.notification.name.task.didCancel") + + /// Posted when a `URLSessionTask` is completed. The notification `object` contains the completed `URLSessionTask`. + public static let DidComplete = Notification.Name(rawValue: "org.alamofire.notification.name.task.didComplete") + } +} + +// MARK: - + +extension Notification { + /// Used as a namespace for all `Notification` user info dictionary keys. + public struct Key { + /// User info dictionary key representing the `URLSessionTask` associated with the notification. + public static let Task = "org.alamofire.notification.key.task" + } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift new file mode 100644 index 0000000000..959af6f936 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift @@ -0,0 +1,436 @@ +// +// 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 HTTPMethod: String { + case options = "OPTIONS" + case get = "GET" + case head = "HEAD" + case post = "POST" + case put = "PUT" + case patch = "PATCH" + case delete = "DELETE" + case trace = "TRACE" + case connect = "CONNECT" +} + +// MARK: - + +/// A dictionary of parameters to apply to a `URLRequest`. +public typealias Parameters = [String: Any] + +/// A type used to define how a set of parameters are applied to a `URLRequest`. +public protocol ParameterEncoding { + /// 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. + /// + /// - throws: An `AFError.parameterEncodingFailed` error if encoding fails. + /// + /// - returns: The encoded request. + func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest +} + +// MARK: - + +/// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP +/// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as +/// the HTTP body depends on the destination of the encoding. +/// +/// 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`). +public struct URLEncoding: ParameterEncoding { + + // MARK: Helper Types + + /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the + /// resulting URL request. + /// + /// - methodDependent: Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` + /// requests and sets as the HTTP body for requests with any other HTTP method. + /// - queryString: Sets or appends encoded query string result to existing query string. + /// - httpBody: Sets encoded query string result as the HTTP body of the URL request. + public enum Destination { + case methodDependent, queryString, httpBody + } + + // MARK: Properties + + /// Returns a default `URLEncoding` instance. + public static var `default`: URLEncoding { return URLEncoding() } + + /// Returns a `URLEncoding` instance with a `.methodDependent` destination. + public static var methodDependent: URLEncoding { return URLEncoding() } + + /// Returns a `URLEncoding` instance with a `.queryString` destination. + public static var queryString: URLEncoding { return URLEncoding(destination: .queryString) } + + /// Returns a `URLEncoding` instance with an `.httpBody` destination. + public static var httpBody: URLEncoding { return URLEncoding(destination: .httpBody) } + + /// The destination defining where the encoded query string is to be applied to the URL request. + public let destination: Destination + + // MARK: Initialization + + /// Creates a `URLEncoding` instance using the specified destination. + /// + /// - parameter destination: The destination defining where the encoded query string is to be applied. + /// + /// - returns: The new `URLEncoding` instance. + public init(destination: Destination = .methodDependent) { + self.destination = destination + } + + // MARK: Encoding + + /// 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. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters = parameters else { return urlRequest } + + if let method = HTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: method) { + guard let url = urlRequest.url else { + throw AFError.parameterEncodingFailed(reason: .missingURL) + } + + if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { + let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) + urlComponents.percentEncodedQuery = percentEncodedQuery + urlRequest.url = urlComponents.url + } + } else { + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false) + } + + return urlRequest + } + + /// 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(fromKey key: String, value: Any) -> [(String, String)] { + var components: [(String, String)] = [] + + if let dictionary = value as? [String: Any] { + for (nestedKey, value) in dictionary { + components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value) + } + } else if let array = value as? [Any] { + for value in array { + components += queryComponents(fromKey: "\(key)[]", value: value) + } + } else if let value = value as? NSNumber { + if value.isBool { + components.append((escape(key), escape((value.boolValue ? "1" : "0")))) + } else { + components.append((escape(key), escape("\(value)"))) + } + } else if let bool = value as? Bool { + components.append((escape(key), escape((bool ? "1" : "0")))) + } 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 = "!$&'()*+,;=" + + var allowedCharacterSet = CharacterSet.urlQueryAllowed + allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") + + var escaped = "" + + //========================================================================================================== + // + // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few + // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no + // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more + // info, please refer to: + // + // - https://github.com/Alamofire/Alamofire/issues/206 + // + //========================================================================================================== + + if #available(iOS 8.3, *) { + escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string + } else { + let batchSize = 50 + var index = string.startIndex + + while index != string.endIndex { + let startIndex = index + let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex + let range = startIndex.. String { + var components: [(String, String)] = [] + + for key in parameters.keys.sorted(by: <) { + let value = parameters[key]! + components += queryComponents(fromKey: key, value: value) + } + #if swift(>=4.0) + return components.map { "\($0.0)=\($0.1)" }.joined(separator: "&") + #else + return components.map { "\($0)=\($1)" }.joined(separator: "&") + #endif + } + + private func encodesParametersInURL(with method: HTTPMethod) -> Bool { + switch destination { + case .queryString: + return true + case .httpBody: + return false + default: + break + } + + switch method { + case .get, .head, .delete: + return true + default: + return false + } + } +} + +// MARK: - + +/// Uses `JSONSerialization` 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`. +public struct JSONEncoding: ParameterEncoding { + + // MARK: Properties + + /// Returns a `JSONEncoding` instance with default writing options. + public static var `default`: JSONEncoding { return JSONEncoding() } + + /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options. + public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) } + + /// The options for writing the parameters as JSON data. + public let options: JSONSerialization.WritingOptions + + // MARK: Initialization + + /// Creates a `JSONEncoding` instance using the specified options. + /// + /// - parameter options: The options for writing the parameters as JSON data. + /// + /// - returns: The new `JSONEncoding` instance. + public init(options: JSONSerialization.WritingOptions = []) { + self.options = options + } + + // MARK: Encoding + + /// 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. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters = parameters else { return urlRequest } + + do { + let data = try JSONSerialization.data(withJSONObject: parameters, options: options) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return urlRequest + } + + /// Creates a URL request by encoding the JSON object and setting the resulting data on the HTTP body. + /// + /// - parameter urlRequest: The request to apply the JSON object to. + /// - parameter jsonObject: The JSON object to apply to the request. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let jsonObject = jsonObject else { return urlRequest } + + do { + let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return urlRequest + } +} + +// MARK: - + +/// Uses `PropertyListSerialization` 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`. +public struct PropertyListEncoding: ParameterEncoding { + + // MARK: Properties + + /// Returns a default `PropertyListEncoding` instance. + public static var `default`: PropertyListEncoding { return PropertyListEncoding() } + + /// Returns a `PropertyListEncoding` instance with xml formatting and default writing options. + public static var xml: PropertyListEncoding { return PropertyListEncoding(format: .xml) } + + /// Returns a `PropertyListEncoding` instance with binary formatting and default writing options. + public static var binary: PropertyListEncoding { return PropertyListEncoding(format: .binary) } + + /// The property list serialization format. + public let format: PropertyListSerialization.PropertyListFormat + + /// The options for writing the parameters as plist data. + public let options: PropertyListSerialization.WriteOptions + + // MARK: Initialization + + /// Creates a `PropertyListEncoding` instance using the specified format and options. + /// + /// - parameter format: The property list serialization format. + /// - parameter options: The options for writing the parameters as plist data. + /// + /// - returns: The new `PropertyListEncoding` instance. + public init( + format: PropertyListSerialization.PropertyListFormat = .xml, + options: PropertyListSerialization.WriteOptions = 0) + { + self.format = format + self.options = options + } + + // MARK: Encoding + + /// 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. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters = parameters else { return urlRequest } + + do { + let data = try PropertyListSerialization.data( + fromPropertyList: parameters, + format: format, + options: options + ) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .propertyListEncodingFailed(error: error)) + } + + return urlRequest + } +} + +// MARK: - + +extension NSNumber { + fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Request.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Request.swift new file mode 100644 index 0000000000..4f6350c5bf --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Request.swift @@ -0,0 +1,647 @@ +// +// 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 + +/// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary. +public protocol RequestAdapter { + /// Inspects and adapts the specified `URLRequest` in some manner if necessary and returns the result. + /// + /// - parameter urlRequest: The URL request to adapt. + /// + /// - throws: An `Error` if the adaptation encounters an error. + /// + /// - returns: The adapted `URLRequest`. + func adapt(_ urlRequest: URLRequest) throws -> URLRequest +} + +// MARK: - + +/// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not. +public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void + +/// A type that determines whether a request should be retried after being executed by the specified session manager +/// and encountering an error. +public protocol RequestRetrier { + /// Determines whether the `Request` should be retried by calling the `completion` closure. + /// + /// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs + /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly + /// cleaned up after. + /// + /// - parameter manager: The session manager the request was executed on. + /// - parameter request: The request that failed due to the encountered error. + /// - parameter error: The error encountered when executing the request. + /// - parameter completion: The completion closure to be executed when retry decision has been determined. + func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) +} + +// MARK: - + +protocol TaskConvertible { + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask +} + +/// A dictionary of headers to apply to a `URLRequest`. +public typealias HTTPHeaders = [String: String] + +// MARK: - + +/// Responsible for sending a request and receiving the response and associated data from the server, as well as +/// managing its underlying `URLSessionTask`. +open class Request { + + // MARK: Helper Types + + /// A closure executed when monitoring upload or download progress of a request. + public typealias ProgressHandler = (Progress) -> Void + + enum RequestTask { + case data(TaskConvertible?, URLSessionTask?) + case download(TaskConvertible?, URLSessionTask?) + case upload(TaskConvertible?, URLSessionTask?) + case stream(TaskConvertible?, URLSessionTask?) + } + + // MARK: Properties + + /// The delegate for the underlying task. + open internal(set) var delegate: TaskDelegate { + get { + taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } + return taskDelegate + } + set { + taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } + taskDelegate = newValue + } + } + + /// The underlying task. + open var task: URLSessionTask? { return delegate.task } + + /// The session belonging to the underlying task. + open let session: URLSession + + /// The request sent or to be sent to the server. + open var request: URLRequest? { return task?.originalRequest } + + /// The response received from the server, if any. + open var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse } + + /// The number of times the request has been retried. + open internal(set) var retryCount: UInt = 0 + + let originalTask: TaskConvertible? + + var startTime: CFAbsoluteTime? + var endTime: CFAbsoluteTime? + + var validations: [() -> Void] = [] + + private var taskDelegate: TaskDelegate + private var taskDelegateLock = NSLock() + + // MARK: Lifecycle + + init(session: URLSession, requestTask: RequestTask, error: Error? = nil) { + self.session = session + + switch requestTask { + case .data(let originalTask, let task): + taskDelegate = DataTaskDelegate(task: task) + self.originalTask = originalTask + case .download(let originalTask, let task): + taskDelegate = DownloadTaskDelegate(task: task) + self.originalTask = originalTask + case .upload(let originalTask, let task): + taskDelegate = UploadTaskDelegate(task: task) + self.originalTask = originalTask + case .stream(let originalTask, let task): + taskDelegate = TaskDelegate(task: task) + self.originalTask = originalTask + } + + delegate.error = error + delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() } + } + + // MARK: Authentication + + /// Associates an HTTP Basic credential with the request. + /// + /// - parameter user: The user. + /// - parameter password: The password. + /// - parameter persistence: The URL credential persistence. `.ForSession` by default. + /// + /// - returns: The request. + @discardableResult + open func authenticate( + user: String, + password: String, + persistence: URLCredential.Persistence = .forSession) + -> Self + { + let credential = URLCredential(user: user, password: password, persistence: persistence) + return authenticate(usingCredential: credential) + } + + /// Associates a specified credential with the request. + /// + /// - parameter credential: The credential. + /// + /// - returns: The request. + @discardableResult + open func authenticate(usingCredential credential: URLCredential) -> Self { + delegate.credential = credential + return self + } + + /// Returns a base64 encoded basic authentication credential as an authorization header tuple. + /// + /// - parameter user: The user. + /// - parameter password: The password. + /// + /// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise. + open static func authorizationHeader(user: String, password: String) -> (key: String, value: String)? { + guard let data = "\(user):\(password)".data(using: .utf8) else { return nil } + + let credential = data.base64EncodedString(options: []) + + return (key: "Authorization", value: "Basic \(credential)") + } + + // MARK: State + + /// Resumes the request. + open func resume() { + guard let task = task else { delegate.queue.isSuspended = false ; return } + + if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } + + task.resume() + + NotificationCenter.default.post( + name: Notification.Name.Task.DidResume, + object: self, + userInfo: [Notification.Key.Task: task] + ) + } + + /// Suspends the request. + open func suspend() { + guard let task = task else { return } + + task.suspend() + + NotificationCenter.default.post( + name: Notification.Name.Task.DidSuspend, + object: self, + userInfo: [Notification.Key.Task: task] + ) + } + + /// Cancels the request. + open func cancel() { + guard let task = task else { return } + + task.cancel() + + NotificationCenter.default.post( + name: Notification.Name.Task.DidCancel, + object: self, + userInfo: [Notification.Key.Task: task] + ) + } +} + +// 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. + open 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.joined(separator: " ") + } +} + +// MARK: - CustomDebugStringConvertible + +extension Request: CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, in the form of a cURL command. + open var debugDescription: String { + return cURLRepresentation() + } + + func cURLRepresentation() -> String { + var components = ["$ curl -v"] + + guard let request = self.request, + let url = request.url, + let host = url.host + else { + return "$ curl command could not be created" + } + + if let httpMethod = request.httpMethod, httpMethod != "GET" { + components.append("-X \(httpMethod)") + } + + if let credentialStorage = self.session.configuration.urlCredentialStorage { + let protectionSpace = URLProtectionSpace( + host: host, + port: url.port ?? 0, + protocol: url.scheme, + realm: host, + authenticationMethod: NSURLAuthenticationMethodHTTPBasic + ) + + if let credentials = credentialStorage.credentials(for: 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, + let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty + { + let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" } + components.append("-b \"\(string.substring(to: string.characters.index(before: string.endIndex)))\"") + } + } + + var headers: [AnyHashable: Any] = [:] + + if let additionalHeaders = session.configuration.httpAdditionalHeaders { + for (field, value) in additionalHeaders where field != AnyHashable("Cookie") { + headers[field] = value + } + } + + if let headerFields = request.allHTTPHeaderFields { + for (field, value) in headerFields where field != "Cookie" { + headers[field] = value + } + } + + for (field, value) in headers { + components.append("-H \"\(field): \(value)\"") + } + + if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) { + var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"") + escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"") + + components.append("-d \"\(escapedBody)\"") + } + + components.append("\"\(url.absoluteString)\"") + + return components.joined(separator: " \\\n\t") + } +} + +// MARK: - + +/// Specific type of `Request` that manages an underlying `URLSessionDataTask`. +open class DataRequest: Request { + + // MARK: Helper Types + + struct Requestable: TaskConvertible { + let urlRequest: URLRequest + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + do { + let urlRequest = try self.urlRequest.adapt(using: adapter) + return queue.sync { session.dataTask(with: urlRequest) } + } catch { + throw AdaptError(error: error) + } + } + } + + // MARK: Properties + + /// The request sent or to be sent to the server. + open override var request: URLRequest? { + if let request = super.request { return request } + if let requestable = originalTask as? Requestable { return requestable.urlRequest } + + return nil + } + + /// The progress of fetching the response data from the server for the request. + open var progress: Progress { return dataDelegate.progress } + + var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate } + + // MARK: Stream + + /// 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 server data in any `Response` object will be `nil`. + /// + /// - parameter closure: The code to be executed periodically during the lifecycle of the request. + /// + /// - returns: The request. + @discardableResult + open func stream(closure: ((Data) -> Void)? = nil) -> Self { + dataDelegate.dataStream = closure + return self + } + + // MARK: Progress + + /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. + /// + /// - parameter queue: The dispatch queue to execute the closure on. + /// - parameter closure: The code to be executed periodically as data is read from the server. + /// + /// - returns: The request. + @discardableResult + open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { + dataDelegate.progressHandler = (closure, queue) + return self + } +} + +// MARK: - + +/// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`. +open class DownloadRequest: Request { + + // MARK: Helper Types + + /// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the + /// destination URL. + public struct DownloadOptions: OptionSet { + /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol. + public let rawValue: UInt + + /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified. + public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0) + + /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified. + public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1) + + /// Creates a `DownloadFileDestinationOptions` instance with the specified raw value. + /// + /// - parameter rawValue: The raw bitmask value for the option. + /// + /// - returns: A new log level instance. + public init(rawValue: UInt) { + self.rawValue = rawValue + } + } + + /// A closure executed once a download 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 two arguments: the file URL where the temporary file should be moved and + /// the options defining how the file should be moved. + public typealias DownloadFileDestination = ( + _ temporaryURL: URL, + _ response: HTTPURLResponse) + -> (destinationURL: URL, options: DownloadOptions) + + enum Downloadable: TaskConvertible { + case request(URLRequest) + case resumeData(Data) + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + do { + let task: URLSessionTask + + switch self { + case let .request(urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.downloadTask(with: urlRequest) } + case let .resumeData(resumeData): + task = queue.sync { session.downloadTask(withResumeData: resumeData) } + } + + return task + } catch { + throw AdaptError(error: error) + } + } + } + + // MARK: Properties + + /// The request sent or to be sent to the server. + open override var request: URLRequest? { + if let request = super.request { return request } + + if let downloadable = originalTask as? Downloadable, case let .request(urlRequest) = downloadable { + return urlRequest + } + + return nil + } + + /// The resume data of the underlying download task if available after a failure. + open var resumeData: Data? { return downloadDelegate.resumeData } + + /// The progress of downloading the response data from the server for the request. + open var progress: Progress { return downloadDelegate.progress } + + var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate } + + // MARK: State + + /// Cancels the request. + open override func cancel() { + downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 } + + NotificationCenter.default.post( + name: Notification.Name.Task.DidCancel, + object: self, + userInfo: [Notification.Key.Task: task as Any] + ) + } + + // MARK: Progress + + /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. + /// + /// - parameter queue: The dispatch queue to execute the closure on. + /// - parameter closure: The code to be executed periodically as data is read from the server. + /// + /// - returns: The request. + @discardableResult + open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { + downloadDelegate.progressHandler = (closure, queue) + return self + } + + // MARK: Destination + + /// 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. + open class func suggestedDownloadDestination( + for directory: FileManager.SearchPathDirectory = .documentDirectory, + in domain: FileManager.SearchPathDomainMask = .userDomainMask) + -> DownloadFileDestination + { + return { temporaryURL, response in + let directoryURLs = FileManager.default.urls(for: directory, in: domain) + + if !directoryURLs.isEmpty { + return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), []) + } + + return (temporaryURL, []) + } + } +} + +// MARK: - + +/// Specific type of `Request` that manages an underlying `URLSessionUploadTask`. +open class UploadRequest: DataRequest { + + // MARK: Helper Types + + enum Uploadable: TaskConvertible { + case data(Data, URLRequest) + case file(URL, URLRequest) + case stream(InputStream, URLRequest) + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + do { + let task: URLSessionTask + + switch self { + case let .data(data, urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.uploadTask(with: urlRequest, from: data) } + case let .file(url, urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.uploadTask(with: urlRequest, fromFile: url) } + case let .stream(_, urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.uploadTask(withStreamedRequest: urlRequest) } + } + + return task + } catch { + throw AdaptError(error: error) + } + } + } + + // MARK: Properties + + /// The request sent or to be sent to the server. + open override var request: URLRequest? { + if let request = super.request { return request } + + guard let uploadable = originalTask as? Uploadable else { return nil } + + switch uploadable { + case .data(_, let urlRequest), .file(_, let urlRequest), .stream(_, let urlRequest): + return urlRequest + } + } + + /// The progress of uploading the payload to the server for the upload request. + open var uploadProgress: Progress { return uploadDelegate.uploadProgress } + + var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate } + + // MARK: Upload Progress + + /// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to + /// the server. + /// + /// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress + /// of data being read from the server. + /// + /// - parameter queue: The dispatch queue to execute the closure on. + /// - parameter closure: The code to be executed periodically as data is sent to the server. + /// + /// - returns: The request. + @discardableResult + open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { + uploadDelegate.uploadProgressHandler = (closure, queue) + return self + } +} + +// MARK: - + +#if !os(watchOS) + +/// Specific type of `Request` that manages an underlying `URLSessionStreamTask`. +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +open class StreamRequest: Request { + enum Streamable: TaskConvertible { + case stream(hostName: String, port: Int) + case netService(NetService) + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + let task: URLSessionTask + + switch self { + case let .stream(hostName, port): + task = queue.sync { session.streamTask(withHostName: hostName, port: port) } + case let .netService(netService): + task = queue.sync { session.streamTask(with: netService) } + } + + return task + } + } +} + +#endif diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Response.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Response.swift new file mode 100644 index 0000000000..5d3b6d2542 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Response.swift @@ -0,0 +1,465 @@ +// +// 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 data associated with an non-serialized response of a data or upload request. +public struct DefaultDataResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The data returned by the server. + public let data: Data? + + /// The error encountered while executing or validating the request. + public let error: Error? + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + var _metrics: AnyObject? + + /// Creates a `DefaultDataResponse` instance from the specified parameters. + /// + /// - Parameters: + /// - request: The URL request sent to the server. + /// - response: The server's response to the URL request. + /// - data: The data returned by the server. + /// - error: The error encountered while executing or validating the request. + /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. + /// - metrics: The task metrics containing the request / response statistics. `nil` by default. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + data: Data?, + error: Error?, + timeline: Timeline = Timeline(), + metrics: AnyObject? = nil) + { + self.request = request + self.response = response + self.data = data + self.error = error + self.timeline = timeline + } +} + +// MARK: - + +/// Used to store all data associated with a serialized response of a data or upload request. +public struct DataResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The data returned by the server. + public let data: Data? + + /// The result of response serialization. + public let result: Result + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + /// Returns the associated value of the result if it is a success, `nil` otherwise. + public var value: Value? { return result.value } + + /// Returns the associated error value if the result if it is a failure, `nil` otherwise. + public var error: Error? { return result.error } + + var _metrics: AnyObject? + + /// Creates a `DataResponse` instance with the specified parameters derived from response serialization. + /// + /// - parameter request: The URL request sent to the server. + /// - parameter response: The server's response to the URL request. + /// - parameter data: The data returned by the server. + /// - parameter result: The result of response serialization. + /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. + /// + /// - returns: The new `DataResponse` instance. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + data: Data?, + result: Result, + timeline: Timeline = Timeline()) + { + self.request = request + self.response = response + self.data = data + self.result = result + self.timeline = timeline + } +} + +// MARK: - + +extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible { + /// 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 + } + + /// The debug textual representation used when written to an output stream, which includes the URL request, the URL + /// response, the server data, the response serialization result and the timeline. + public var debugDescription: String { + var output: [String] = [] + + output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") + output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") + output.append("[Data]: \(data?.count ?? 0) bytes") + output.append("[Result]: \(result.debugDescription)") + output.append("[Timeline]: \(timeline.debugDescription)") + + return output.joined(separator: "\n") + } +} + +// MARK: - + +extension DataResponse { + /// Evaluates the specified closure when the result of this `DataResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `map` method with a closure that does not throw. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleInt = possibleData.map { $0.count } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A `DataResponse` whose result wraps the value returned by the given closure. If this instance's + /// result is a failure, returns a response wrapping the same failure. + public func map(_ transform: (Value) -> T) -> DataResponse { + var response = DataResponse( + request: request, + response: self.response, + data: data, + result: result.map(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result + /// value as a parameter. + /// + /// Use the `flatMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleObject = possibleData.flatMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A success or failure `DataResponse` depending on the result of the given closure. If this instance's + /// result is a failure, returns the same failure. + public func flatMap(_ transform: (Value) throws -> T) -> DataResponse { + var response = DataResponse( + request: request, + response: self.response, + data: data, + result: result.flatMap(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } +} + +// MARK: - + +/// Used to store all data associated with an non-serialized response of a download request. +public struct DefaultDownloadResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The temporary destination URL of the data returned from the server. + public let temporaryURL: URL? + + /// The final destination URL of the data returned from the server if it was moved. + public let destinationURL: URL? + + /// The resume data generated if the request was cancelled. + public let resumeData: Data? + + /// The error encountered while executing or validating the request. + public let error: Error? + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + var _metrics: AnyObject? + + /// Creates a `DefaultDownloadResponse` instance from the specified parameters. + /// + /// - Parameters: + /// - request: The URL request sent to the server. + /// - response: The server's response to the URL request. + /// - temporaryURL: The temporary destination URL of the data returned from the server. + /// - destinationURL: The final destination URL of the data returned from the server if it was moved. + /// - resumeData: The resume data generated if the request was cancelled. + /// - error: The error encountered while executing or validating the request. + /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. + /// - metrics: The task metrics containing the request / response statistics. `nil` by default. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + temporaryURL: URL?, + destinationURL: URL?, + resumeData: Data?, + error: Error?, + timeline: Timeline = Timeline(), + metrics: AnyObject? = nil) + { + self.request = request + self.response = response + self.temporaryURL = temporaryURL + self.destinationURL = destinationURL + self.resumeData = resumeData + self.error = error + self.timeline = timeline + } +} + +// MARK: - + +/// Used to store all data associated with a serialized response of a download request. +public struct DownloadResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The temporary destination URL of the data returned from the server. + public let temporaryURL: URL? + + /// The final destination URL of the data returned from the server if it was moved. + public let destinationURL: URL? + + /// The resume data generated if the request was cancelled. + public let resumeData: Data? + + /// The result of response serialization. + public let result: Result + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + /// Returns the associated value of the result if it is a success, `nil` otherwise. + public var value: Value? { return result.value } + + /// Returns the associated error value if the result if it is a failure, `nil` otherwise. + public var error: Error? { return result.error } + + var _metrics: AnyObject? + + /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization. + /// + /// - parameter request: The URL request sent to the server. + /// - parameter response: The server's response to the URL request. + /// - parameter temporaryURL: The temporary destination URL of the data returned from the server. + /// - parameter destinationURL: The final destination URL of the data returned from the server if it was moved. + /// - parameter resumeData: The resume data generated if the request was cancelled. + /// - parameter result: The result of response serialization. + /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. + /// + /// - returns: The new `DownloadResponse` instance. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + temporaryURL: URL?, + destinationURL: URL?, + resumeData: Data?, + result: Result, + timeline: Timeline = Timeline()) + { + self.request = request + self.response = response + self.temporaryURL = temporaryURL + self.destinationURL = destinationURL + self.resumeData = resumeData + self.result = result + self.timeline = timeline + } +} + +// MARK: - + +extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible { + /// 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 + } + + /// The debug textual representation used when written to an output stream, which includes the URL request, the URL + /// response, the temporary and destination URLs, the resume data, the response serialization result and the + /// timeline. + public var debugDescription: String { + var output: [String] = [] + + output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") + output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") + output.append("[TemporaryURL]: \(temporaryURL?.path ?? "nil")") + output.append("[DestinationURL]: \(destinationURL?.path ?? "nil")") + output.append("[ResumeData]: \(resumeData?.count ?? 0) bytes") + output.append("[Result]: \(result.debugDescription)") + output.append("[Timeline]: \(timeline.debugDescription)") + + return output.joined(separator: "\n") + } +} + +// MARK: - + +extension DownloadResponse { + /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `map` method with a closure that does not throw. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleInt = possibleData.map { $0.count } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's + /// result is a failure, returns a response wrapping the same failure. + public func map(_ transform: (Value) -> T) -> DownloadResponse { + var response = DownloadResponse( + request: request, + response: self.response, + temporaryURL: temporaryURL, + destinationURL: destinationURL, + resumeData: resumeData, + result: result.map(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `flatMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleObject = possibleData.flatMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this + /// instance's result is a failure, returns the same failure. + public func flatMap(_ transform: (Value) throws -> T) -> DownloadResponse { + var response = DownloadResponse( + request: request, + response: self.response, + temporaryURL: temporaryURL, + destinationURL: destinationURL, + resumeData: resumeData, + result: result.flatMap(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } +} + +// MARK: - + +protocol Response { + /// The task metrics containing the request / response statistics. + var _metrics: AnyObject? { get set } + mutating func add(_ metrics: AnyObject?) +} + +extension Response { + mutating func add(_ metrics: AnyObject?) { + #if !os(watchOS) + guard #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) else { return } + guard let metrics = metrics as? URLSessionTaskMetrics else { return } + + _metrics = metrics + #endif + } +} + +// MARK: - + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DefaultDataResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DataResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DefaultDownloadResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DownloadResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift new file mode 100644 index 0000000000..1a59da550a --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift @@ -0,0 +1,715 @@ +// +// 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 + +/// The type in which all data response serializers must conform to in order to serialize a response. +public protocol DataResponseSerializerProtocol { + /// The type of serialized object to be created by this `DataResponseSerializerType`. + associatedtype SerializedObject + + /// A closure used by response handlers that takes a request, response, data and error and returns a result. + var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result { get } +} + +// MARK: - + +/// A generic `DataResponseSerializerType` used to serialize a request, response, and data into a serialized object. +public struct DataResponseSerializer: DataResponseSerializerProtocol { + /// The type of serialized object to be created by this `DataResponseSerializer`. + public typealias SerializedObject = Value + + /// A closure used by response handlers that takes a request, response, data and error and returns a result. + public var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result + + /// 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: @escaping (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result) { + self.serializeResponse = serializeResponse + } +} + +// MARK: - + +/// The type in which all download response serializers must conform to in order to serialize a response. +public protocol DownloadResponseSerializerProtocol { + /// The type of serialized object to be created by this `DownloadResponseSerializerType`. + associatedtype SerializedObject + + /// A closure used by response handlers that takes a request, response, url and error and returns a result. + var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result { get } +} + +// MARK: - + +/// A generic `DownloadResponseSerializerType` used to serialize a request, response, and data into a serialized object. +public struct DownloadResponseSerializer: DownloadResponseSerializerProtocol { + /// The type of serialized object to be created by this `DownloadResponseSerializer`. + public typealias SerializedObject = Value + + /// A closure used by response handlers that takes a request, response, url and error and returns a result. + public var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result + + /// 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: @escaping (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result) { + self.serializeResponse = serializeResponse + } +} + +// MARK: - Timeline + +extension Request { + var timeline: Timeline { + let requestStartTime = self.startTime ?? CFAbsoluteTimeGetCurrent() + let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent() + let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime + + return Timeline( + requestStartTime: requestStartTime, + initialResponseTime: initialResponseTime, + requestCompletedTime: requestCompletedTime, + serializationCompletedTime: CFAbsoluteTimeGetCurrent() + ) + } +} + +// MARK: - Default + +extension DataRequest { + /// 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. + @discardableResult + public func response(queue: DispatchQueue? = nil, completionHandler: @escaping (DefaultDataResponse) -> Void) -> Self { + delegate.queue.addOperation { + (queue ?? DispatchQueue.main).async { + var dataResponse = DefaultDataResponse( + request: self.request, + response: self.response, + data: self.delegate.data, + error: self.delegate.error, + timeline: self.timeline + ) + + dataResponse.add(self.delegate.metrics) + + completionHandler(dataResponse) + } + } + + 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. + @discardableResult + public func response( + queue: DispatchQueue? = nil, + responseSerializer: T, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + delegate.queue.addOperation { + let result = responseSerializer.serializeResponse( + self.request, + self.response, + self.delegate.data, + self.delegate.error + ) + + var dataResponse = DataResponse( + request: self.request, + response: self.response, + data: self.delegate.data, + result: result, + timeline: self.timeline + ) + + dataResponse.add(self.delegate.metrics) + + (queue ?? DispatchQueue.main).async { completionHandler(dataResponse) } + } + + return self + } +} + +extension DownloadRequest { + /// 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. + @discardableResult + public func response( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DefaultDownloadResponse) -> Void) + -> Self + { + delegate.queue.addOperation { + (queue ?? DispatchQueue.main).async { + var downloadResponse = DefaultDownloadResponse( + request: self.request, + response: self.response, + temporaryURL: self.downloadDelegate.temporaryURL, + destinationURL: self.downloadDelegate.destinationURL, + resumeData: self.downloadDelegate.resumeData, + error: self.downloadDelegate.error, + timeline: self.timeline + ) + + downloadResponse.add(self.delegate.metrics) + + completionHandler(downloadResponse) + } + } + + 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 contained in the destination url. + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func response( + queue: DispatchQueue? = nil, + responseSerializer: T, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + delegate.queue.addOperation { + let result = responseSerializer.serializeResponse( + self.request, + self.response, + self.downloadDelegate.fileURL, + self.downloadDelegate.error + ) + + var downloadResponse = DownloadResponse( + request: self.request, + response: self.response, + temporaryURL: self.downloadDelegate.temporaryURL, + destinationURL: self.downloadDelegate.destinationURL, + resumeData: self.downloadDelegate.resumeData, + result: result, + timeline: self.timeline + ) + + downloadResponse.add(self.delegate.metrics) + + (queue ?? DispatchQueue.main).async { completionHandler(downloadResponse) } + } + + return self + } +} + +// MARK: - Data + +extension Request { + /// Returns a result data type that contains the response data as-is. + /// + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponseData(response: HTTPURLResponse?, data: Data?, error: Error?) -> Result { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(Data()) } + + guard let validData = data else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) + } + + return .success(validData) + } +} + +extension DataRequest { + /// Creates a response serializer that returns the associated data as-is. + /// + /// - returns: A data response serializer. + public static func dataResponseSerializer() -> DataResponseSerializer { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponseData(response: response, data: data, error: error) + } + } + + /// 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. + @discardableResult + public func responseData( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.dataResponseSerializer(), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns the associated data as-is. + /// + /// - returns: A data response serializer. + public static func dataResponseSerializer() -> DownloadResponseSerializer { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponseData(response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// 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. + @discardableResult + public func responseData( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.dataResponseSerializer(), + completionHandler: completionHandler + ) + } +} + +// MARK: - String + +extension Request { + /// Returns a result string type 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. + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponseString( + encoding: String.Encoding?, + response: HTTPURLResponse?, + data: Data?, + error: Error?) + -> Result + { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success("") } + + guard let validData = data else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) + } + + var convertedEncoding = encoding + + if let encodingName = response?.textEncodingName as CFString!, convertedEncoding == nil { + convertedEncoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding( + CFStringConvertIANACharSetNameToEncoding(encodingName)) + ) + } + + let actualEncoding = convertedEncoding ?? String.Encoding.isoLatin1 + + if let string = String(data: validData, encoding: actualEncoding) { + return .success(string) + } else { + return .failure(AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding))) + } + } +} + +extension DataRequest { + /// Creates a response serializer that returns a result string type initialized from the response data with + /// the specified string encoding. + /// + /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server + /// response, falling back to the default HTTP default character set, ISO-8859-1. + /// + /// - returns: A string response serializer. + public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DataResponseSerializer { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: 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. + @discardableResult + public func responseString( + queue: DispatchQueue? = nil, + encoding: String.Encoding? = nil, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.stringResponseSerializer(encoding: encoding), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns a result string type initialized from the response data with + /// the specified string encoding. + /// + /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server + /// response, falling back to the default HTTP default character set, ISO-8859-1. + /// + /// - returns: A string response serializer. + public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DownloadResponseSerializer { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// 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. + @discardableResult + public func responseString( + queue: DispatchQueue? = nil, + encoding: String.Encoding? = nil, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.stringResponseSerializer(encoding: encoding), + completionHandler: completionHandler + ) + } +} + +// MARK: - JSON + +extension Request { + /// Returns a JSON object contained in a result type constructed from the response data using `JSONSerialization` + /// with the specified reading options. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponseJSON( + options: JSONSerialization.ReadingOptions, + response: HTTPURLResponse?, + data: Data?, + error: Error?) + -> Result + { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } + + guard let validData = data, validData.count > 0 else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) + } + + do { + let json = try JSONSerialization.jsonObject(with: validData, options: options) + return .success(json) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error))) + } + } +} + +extension DataRequest { + /// Creates a response serializer that returns a JSON object result type constructed from the response data using + /// `JSONSerialization` with the specified reading options. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// + /// - returns: A JSON object response serializer. + public static func jsonResponseSerializer( + options: JSONSerialization.ReadingOptions = .allowFragments) + -> DataResponseSerializer + { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseJSON( + queue: DispatchQueue? = nil, + options: JSONSerialization.ReadingOptions = .allowFragments, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.jsonResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns a JSON object result type constructed from the response data using + /// `JSONSerialization` with the specified reading options. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// + /// - returns: A JSON object response serializer. + public static func jsonResponseSerializer( + options: JSONSerialization.ReadingOptions = .allowFragments) + -> DownloadResponseSerializer + { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseJSON( + queue: DispatchQueue? = nil, + options: JSONSerialization.ReadingOptions = .allowFragments, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.jsonResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +// MARK: - Property List + +extension Request { + /// Returns a plist object contained in a result type constructed from the response data using + /// `PropertyListSerialization` with the specified reading options. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponsePropertyList( + options: PropertyListSerialization.ReadOptions, + response: HTTPURLResponse?, + data: Data?, + error: Error?) + -> Result + { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } + + guard let validData = data, validData.count > 0 else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) + } + + do { + let plist = try PropertyListSerialization.propertyList(from: validData, options: options, format: nil) + return .success(plist) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .propertyListSerializationFailed(error: error))) + } + } +} + +extension DataRequest { + /// Creates a response serializer that returns an object constructed from the response data using + /// `PropertyListSerialization` with the specified reading options. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// + /// - returns: A property list object response serializer. + public static func propertyListResponseSerializer( + options: PropertyListSerialization.ReadOptions = []) + -> DataResponseSerializer + { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responsePropertyList( + queue: DispatchQueue? = nil, + options: PropertyListSerialization.ReadOptions = [], + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.propertyListResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns an object constructed from the response data using + /// `PropertyListSerialization` with the specified reading options. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// + /// - returns: A property list object response serializer. + public static func propertyListResponseSerializer( + options: PropertyListSerialization.ReadOptions = []) + -> DownloadResponseSerializer + { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responsePropertyList( + queue: DispatchQueue? = nil, + options: PropertyListSerialization.ReadOptions = [], + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.propertyListResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +/// A set of HTTP response status code that do not contain response data. +private let emptyDataStatusCodes: Set = [204, 205] diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Result.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Result.swift new file mode 100644 index 0000000000..bf7e70255b --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Result.swift @@ -0,0 +1,300 @@ +// +// 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 { + 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)" + } + } +} + +// MARK: - Functional APIs + +extension Result { + /// Creates a `Result` instance from the result of a closure. + /// + /// A failure result is created when the closure throws, and a success result is created when the closure + /// succeeds without throwing an error. + /// + /// func someString() throws -> String { ... } + /// + /// let result = Result(value: { + /// return try someString() + /// }) + /// + /// // The type of result is Result + /// + /// The trailing closure syntax is also supported: + /// + /// let result = Result { try someString() } + /// + /// - parameter value: The closure to execute and create the result for. + public init(value: () throws -> Value) { + do { + self = try .success(value()) + } catch { + self = .failure(error) + } + } + + /// Returns the success value, or throws the failure error. + /// + /// let possibleString: Result = .success("success") + /// try print(possibleString.unwrap()) + /// // Prints "success" + /// + /// let noString: Result = .failure(error) + /// try print(noString.unwrap()) + /// // Throws error + public func unwrap() throws -> Value { + switch self { + case .success(let value): + return value + case .failure(let error): + throw error + } + } + + /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. + /// + /// Use the `map` method with a closure that does not throw. For example: + /// + /// let possibleData: Result = .success(Data()) + /// let possibleInt = possibleData.map { $0.count } + /// try print(possibleInt.unwrap()) + /// // Prints "0" + /// + /// let noData: Result = .failure(error) + /// let noInt = noData.map { $0.count } + /// try print(noInt.unwrap()) + /// // Throws error + /// + /// - parameter transform: A closure that takes the success value of the `Result` instance. + /// + /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the + /// same failure. + public func map(_ transform: (Value) -> T) -> Result { + switch self { + case .success(let value): + return .success(transform(value)) + case .failure(let error): + return .failure(error) + } + } + + /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. + /// + /// Use the `flatMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: Result = .success(Data(...)) + /// let possibleObject = possibleData.flatMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance. + /// + /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the + /// same failure. + public func flatMap(_ transform: (Value) throws -> T) -> Result { + switch self { + case .success(let value): + do { + return try .success(transform(value)) + } catch { + return .failure(error) + } + case .failure(let error): + return .failure(error) + } + } + + /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `mapError` function with a closure that does not throw. For example: + /// + /// let possibleData: Result = .failure(someError) + /// let withMyError: Result = possibleData.mapError { MyError.error($0) } + /// + /// - Parameter transform: A closure that takes the error of the instance. + /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns + /// the same instance. + public func mapError(_ transform: (Error) -> T) -> Result { + switch self { + case .failure(let error): + return .failure(transform(error)) + case .success: + return self + } + } + + /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `flatMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: Result = .success(Data(...)) + /// let possibleObject = possibleData.flatMapError { + /// try someFailableFunction(taking: $0) + /// } + /// + /// - Parameter transform: A throwing closure that takes the error of the instance. + /// + /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns + /// the same instance. + public func flatMapError(_ transform: (Error) throws -> T) -> Result { + switch self { + case .failure(let error): + do { + return try .failure(transform(error)) + } catch { + return .failure(error) + } + case .success: + return self + } + } + + /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. + /// + /// Use the `withValue` function to evaluate the passed closure without modifying the `Result` instance. + /// + /// - Parameter closure: A closure that takes the success value of this instance. + /// - Returns: This `Result` instance, unmodified. + @discardableResult + public func withValue(_ closure: (Value) -> Void) -> Result { + if case let .success(value) = self { closure(value) } + + return self + } + + /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `withError` function to evaluate the passed closure without modifying the `Result` instance. + /// + /// - Parameter closure: A closure that takes the success value of this instance. + /// - Returns: This `Result` instance, unmodified. + @discardableResult + public func withError(_ closure: (Error) -> Void) -> Result { + if case let .failure(error) = self { closure(error) } + + return self + } + + /// Evaluates the specified closure when the `Result` is a success. + /// + /// Use the `ifSuccess` function to evaluate the passed closure without modifying the `Result` instance. + /// + /// - Parameter closure: A `Void` closure. + /// - Returns: This `Result` instance, unmodified. + @discardableResult + public func ifSuccess(_ closure: () -> Void) -> Result { + if isSuccess { closure() } + + return self + } + + /// Evaluates the specified closure when the `Result` is a failure. + /// + /// Use the `ifFailure` function to evaluate the passed closure without modifying the `Result` instance. + /// + /// - Parameter closure: A `Void` closure. + /// - Returns: This `Result` instance, unmodified. + @discardableResult + public func ifFailure(_ closure: () -> Void) -> Result { + if isFailure { closure() } + + return self + } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift new file mode 100644 index 0000000000..9c0e7c8d50 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift @@ -0,0 +1,307 @@ +// +// 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. +open class ServerTrustPolicyManager { + /// The dictionary of policies mapped to a particular host. + open 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. + open func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? { + return policies[host] + } +} + +// MARK: - + +extension URLSession { + private struct AssociatedKeys { + static var managerKey = "URLSession.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. +/// +/// - performRevokedEvaluation: Uses the default and revoked server trust evaluations allowing you to control whether to +/// validate the host provided by the challenge as well as specify the revocation flags for +/// testing for revoked certificates. Apple platforms did not start testing for revoked +/// certificates automatically until iOS 10.1, macOS 10.12 and tvOS 10.1 which is +/// demonstrated in our TLS tests. 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 performRevokedEvaluation(validateHost: Bool, revocationFlags: CFOptionFlags) + 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 certificates(in bundle: Bundle = Bundle.main) -> [SecCertificate] { + var certificates: [SecCertificate] = [] + + let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in + bundle.paths(forResourcesOfType: fileExtension, inDirectory: nil) + }.joined()) + + for path in paths { + if + let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData, + let 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 publicKeys(in bundle: Bundle = Bundle.main) -> [SecKey] { + var publicKeys: [SecKey] = [] + + for certificate in certificates(in: bundle) { + if let publicKey = publicKey(for: 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 evaluate(_ serverTrust: SecTrust, forHost 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 .performRevokedEvaluation(validateHost, revocationFlags): + let defaultPolicy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + let revokedPolicy = SecPolicyCreateRevocation(revocationFlags) + SecTrustSetPolicies(serverTrust, [defaultPolicy, revokedPolicy] as CFTypeRef) + + 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 as CFArray) + SecTrustSetAnchorCertificatesOnly(serverTrust, true) + + serverTrustIsValid = trustIsValid(serverTrust) + } else { + let serverCertificatesDataArray = certificateData(for: serverTrust) + let pinnedCertificatesDataArray = certificateData(for: pinnedCertificates) + + outerLoop: for serverCertificateData in serverCertificatesDataArray { + for pinnedCertificateData in pinnedCertificatesDataArray { + if serverCertificateData == 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.publicKeys(for: 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, host) + } + + return serverTrustIsValid + } + + // MARK: - Private - Trust Validation + + private func trustIsValid(_ trust: SecTrust) -> Bool { + var isValid = false + + var result = SecTrustResultType.invalid + let status = SecTrustEvaluate(trust, &result) + + if status == errSecSuccess { + let unspecified = SecTrustResultType.unspecified + let proceed = SecTrustResultType.proceed + + + isValid = result == unspecified || result == proceed + } + + return isValid + } + + // MARK: - Private - Certificate Data + + private func certificateData(for trust: SecTrust) -> [Data] { + var certificates: [SecCertificate] = [] + + for index in 0.. [Data] { + return certificates.map { SecCertificateCopyData($0) as Data } + } + + // MARK: - Private - Public Key Extraction + + private static func publicKeys(for trust: SecTrust) -> [SecKey] { + var publicKeys: [SecKey] = [] + + for index in 0.. SecKey? { + var publicKey: SecKey? + + let policy = SecPolicyCreateBasicX509() + var trust: SecTrust? + let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust) + + if let trust = trust, trustCreationStatus == errSecSuccess { + publicKey = SecTrustCopyPublicKey(trust) + } + + return publicKey + } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/SessionDelegate.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/SessionDelegate.swift new file mode 100644 index 0000000000..8edb492b69 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/SessionDelegate.swift @@ -0,0 +1,719 @@ +// +// SessionDelegate.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 handling all delegate callbacks for the underlying session. +open class SessionDelegate: NSObject { + + // MARK: URLSessionDelegate Overrides + + /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didBecomeInvalidWithError:)`. + open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)? + + /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`. + open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + + /// Overrides all behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)` and requires the caller to call the `completionHandler`. + open var sessionDidReceiveChallengeWithCompletion: ((URLSession, URLAuthenticationChallenge, @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`. + open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)? + + // MARK: URLSessionTaskDelegate Overrides + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`. + open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? + + /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` and + /// requires the caller to call the `completionHandler`. + open var taskWillPerformHTTPRedirectionWithCompletion: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest, @escaping (URLRequest?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)`. + open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + + /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)` and + /// requires the caller to call the `completionHandler`. + open var taskDidReceiveChallengeWithCompletion: ((URLSession, URLSessionTask, URLAuthenticationChallenge, @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)`. + open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? + + /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)` and + /// requires the caller to call the `completionHandler`. + open var taskNeedNewBodyStreamWithCompletion: ((URLSession, URLSessionTask, @escaping (InputStream?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)`. + open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didCompleteWithError:)`. + open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)? + + // MARK: URLSessionDataDelegate Overrides + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)`. + open var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? + + /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)` and + /// requires caller to call the `completionHandler`. + open var dataTaskDidReceiveResponseWithCompletion: ((URLSession, URLSessionDataTask, URLResponse, @escaping (URLSession.ResponseDisposition) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didBecome:)`. + open var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:)`. + open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`. + open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? + + /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)` and + /// requires caller to call the `completionHandler`. + open var dataTaskWillCacheResponseWithCompletion: ((URLSession, URLSessionDataTask, CachedURLResponse, @escaping (CachedURLResponse?) -> Void) -> Void)? + + // MARK: URLSessionDownloadDelegate Overrides + + /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didFinishDownloadingTo:)`. + open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)? + + /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)`. + open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + + /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)`. + open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? + + // MARK: URLSessionStreamDelegate Overrides + +#if !os(watchOS) + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:readClosedFor:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskReadClosed: ((URLSession, URLSessionStreamTask) -> Void)? { + get { + return _streamTaskReadClosed as? (URLSession, URLSessionStreamTask) -> Void + } + set { + _streamTaskReadClosed = newValue + } + } + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:writeClosedFor:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskWriteClosed: ((URLSession, URLSessionStreamTask) -> Void)? { + get { + return _streamTaskWriteClosed as? (URLSession, URLSessionStreamTask) -> Void + } + set { + _streamTaskWriteClosed = newValue + } + } + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:betterRouteDiscoveredFor:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskBetterRouteDiscovered: ((URLSession, URLSessionStreamTask) -> Void)? { + get { + return _streamTaskBetterRouteDiscovered as? (URLSession, URLSessionStreamTask) -> Void + } + set { + _streamTaskBetterRouteDiscovered = newValue + } + } + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:streamTask:didBecome:outputStream:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskDidBecomeInputAndOutputStreams: ((URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void)? { + get { + return _streamTaskDidBecomeInputStream as? (URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void + } + set { + _streamTaskDidBecomeInputStream = newValue + } + } + + var _streamTaskReadClosed: Any? + var _streamTaskWriteClosed: Any? + var _streamTaskBetterRouteDiscovered: Any? + var _streamTaskDidBecomeInputStream: Any? + +#endif + + // MARK: Properties + + var retrier: RequestRetrier? + weak var sessionManager: SessionManager? + + private var requests: [Int: Request] = [:] + private let lock = NSLock() + + /// Access the task delegate for the specified task in a thread-safe manner. + open subscript(task: URLSessionTask) -> Request? { + get { + lock.lock() ; defer { lock.unlock() } + return requests[task.taskIdentifier] + } + set { + lock.lock() ; defer { lock.unlock() } + requests[task.taskIdentifier] = newValue + } + } + + // MARK: Lifecycle + + /// Initializes the `SessionDelegate` instance. + /// + /// - returns: The new `SessionDelegate` instance. + public override init() { + super.init() + } + + // MARK: NSObject Overrides + + /// Returns a `Bool` indicating whether the `SessionDelegate` implements or inherits a method that can respond + /// to a specified message. + /// + /// - parameter selector: A selector that identifies a message. + /// + /// - returns: `true` if the receiver implements or inherits a method that can respond to selector, otherwise `false`. + open override func responds(to selector: Selector) -> Bool { + #if !os(macOS) + if selector == #selector(URLSessionDelegate.urlSessionDidFinishEvents(forBackgroundURLSession:)) { + return sessionDidFinishEventsForBackgroundURLSession != nil + } + #endif + + #if !os(watchOS) + if #available(iOS 9.0, macOS 10.11, tvOS 9.0, *) { + switch selector { + case #selector(URLSessionStreamDelegate.urlSession(_:readClosedFor:)): + return streamTaskReadClosed != nil + case #selector(URLSessionStreamDelegate.urlSession(_:writeClosedFor:)): + return streamTaskWriteClosed != nil + case #selector(URLSessionStreamDelegate.urlSession(_:betterRouteDiscoveredFor:)): + return streamTaskBetterRouteDiscovered != nil + case #selector(URLSessionStreamDelegate.urlSession(_:streamTask:didBecome:outputStream:)): + return streamTaskDidBecomeInputAndOutputStreams != nil + default: + break + } + } + #endif + + switch selector { + case #selector(URLSessionDelegate.urlSession(_:didBecomeInvalidWithError:)): + return sessionDidBecomeInvalidWithError != nil + case #selector(URLSessionDelegate.urlSession(_:didReceive:completionHandler:)): + return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil) + case #selector(URLSessionTaskDelegate.urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)): + return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil) + case #selector(URLSessionDataDelegate.urlSession(_:dataTask:didReceive:completionHandler:)): + return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil) + default: + return type(of: self).instancesRespond(to: selector) + } + } +} + +// MARK: - URLSessionDelegate + +extension SessionDelegate: URLSessionDelegate { + /// 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. + open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { + 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. + open func urlSession( + _ session: URLSession, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + guard sessionDidReceiveChallengeWithCompletion == nil else { + sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler) + return + } + + var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling + var credential: URLCredential? + + 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?.serverTrustPolicy(forHost: host), + let serverTrust = challenge.protectionSpace.serverTrust + { + if serverTrustPolicy.evaluate(serverTrust, forHost: host) { + disposition = .useCredential + credential = URLCredential(trust: serverTrust) + } else { + disposition = .cancelAuthenticationChallenge + } + } + } + + completionHandler(disposition, credential) + } + +#if !os(macOS) + + /// Tells the delegate that all messages enqueued for a session have been delivered. + /// + /// - parameter session: The session that no longer has any outstanding requests. + open func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { + sessionDidFinishEventsForBackgroundURLSession?(session) + } + +#endif +} + +// MARK: - URLSessionTaskDelegate + +extension SessionDelegate: URLSessionTaskDelegate { + /// 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. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) + { + guard taskWillPerformHTTPRedirectionWithCompletion == nil else { + taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler) + return + } + + var redirectRequest: URLRequest? = 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. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + guard taskDidReceiveChallengeWithCompletion == nil else { + taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler) + return + } + + if let taskDidReceiveChallenge = taskDidReceiveChallenge { + let result = taskDidReceiveChallenge(session, task, challenge) + completionHandler(result.0, result.1) + } else if let delegate = self[task]?.delegate { + delegate.urlSession( + session, + task: task, + didReceive: challenge, + completionHandler: completionHandler + ) + } else { + urlSession(session, didReceive: 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. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) + { + guard taskNeedNewBodyStreamWithCompletion == nil else { + taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler) + return + } + + if let taskNeedNewBodyStream = taskNeedNewBodyStream { + completionHandler(taskNeedNewBodyStream(session, task)) + } else if let delegate = self[task]?.delegate { + 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. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) + { + if let taskDidSendBodyData = taskDidSendBodyData { + taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) + } else if let delegate = self[task]?.delegate as? UploadTaskDelegate { + delegate.URLSession( + session, + task: task, + didSendBodyData: bytesSent, + totalBytesSent: totalBytesSent, + totalBytesExpectedToSend: totalBytesExpectedToSend + ) + } + } + +#if !os(watchOS) + + /// Tells the delegate that the session finished collecting metrics for the task. + /// + /// - parameter session: The session collecting the metrics. + /// - parameter task: The task whose metrics have been collected. + /// - parameter metrics: The collected metrics. + @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) + @objc(URLSession:task:didFinishCollectingMetrics:) + open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { + self[task]?.delegate.metrics = metrics + } + +#endif + + /// 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. + open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + /// Executed after it is determined that the request is not going to be retried + let completeTask: (URLSession, URLSessionTask, Error?) -> Void = { [weak self] session, task, error in + guard let strongSelf = self else { return } + + strongSelf.taskDidComplete?(session, task, error) + + strongSelf[task]?.delegate.urlSession(session, task: task, didCompleteWithError: error) + + NotificationCenter.default.post( + name: Notification.Name.Task.DidComplete, + object: strongSelf, + userInfo: [Notification.Key.Task: task] + ) + + strongSelf[task] = nil + } + + guard let request = self[task], let sessionManager = sessionManager else { + completeTask(session, task, error) + return + } + + // Run all validations on the request before checking if an error occurred + request.validations.forEach { $0() } + + // Determine whether an error has occurred + var error: Error? = error + + if request.delegate.error != nil { + error = request.delegate.error + } + + /// If an error occurred and the retrier is set, asynchronously ask the retrier if the request + /// should be retried. Otherwise, complete the task by notifying the task delegate. + if let retrier = retrier, let error = error { + retrier.should(sessionManager, retry: request, with: error) { [weak self] shouldRetry, timeDelay in + guard shouldRetry else { completeTask(session, task, error) ; return } + + DispatchQueue.utility.after(timeDelay) { [weak self] in + guard let strongSelf = self else { return } + + let retrySucceeded = strongSelf.sessionManager?.retry(request) ?? false + + if retrySucceeded, let task = request.task { + strongSelf[task] = request + return + } else { + completeTask(session, task, error) + } + } + } + } else { + completeTask(session, task, error) + } + } +} + +// MARK: - URLSessionDataDelegate + +extension SessionDelegate: URLSessionDataDelegate { + /// 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. + open func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didReceive response: URLResponse, + completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) + { + guard dataTaskDidReceiveResponseWithCompletion == nil else { + dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler) + return + } + + var disposition: URLSession.ResponseDisposition = .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. + open func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didBecome downloadTask: URLSessionDownloadTask) + { + if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask { + dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask) + } else { + self[downloadTask]?.delegate = DownloadTaskDelegate(task: downloadTask) + } + } + + /// 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. + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + if let dataTaskDidReceiveData = dataTaskDidReceiveData { + dataTaskDidReceiveData(session, dataTask, data) + } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { + delegate.urlSession(session, dataTask: dataTask, didReceive: 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. + open func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse, + completionHandler: @escaping (CachedURLResponse?) -> Void) + { + guard dataTaskWillCacheResponseWithCompletion == nil else { + dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler) + return + } + + if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { + completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) + } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { + delegate.urlSession( + session, + dataTask: dataTask, + willCacheResponse: proposedResponse, + completionHandler: completionHandler + ) + } else { + completionHandler(proposedResponse) + } + } +} + +// MARK: - URLSessionDownloadDelegate + +extension SessionDelegate: URLSessionDownloadDelegate { + /// 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. + open func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didFinishDownloadingTo location: URL) + { + if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { + downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) + } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { + delegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: 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`. + open func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) + { + if let downloadTaskDidWriteData = downloadTaskDidWriteData { + downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) + } else if let delegate = self[downloadTask]?.delegate as? 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. + open func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) + { + if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { + downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) + } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { + delegate.urlSession( + session, + downloadTask: downloadTask, + didResumeAtOffset: fileOffset, + expectedTotalBytes: expectedTotalBytes + ) + } + } +} + +// MARK: - URLSessionStreamDelegate + +#if !os(watchOS) + +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +extension SessionDelegate: URLSessionStreamDelegate { + /// Tells the delegate that the read side of the connection has been closed. + /// + /// - parameter session: The session. + /// - parameter streamTask: The stream task. + open func urlSession(_ session: URLSession, readClosedFor streamTask: URLSessionStreamTask) { + 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. + open func urlSession(_ session: URLSession, writeClosedFor streamTask: URLSessionStreamTask) { + 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. + open func urlSession(_ session: URLSession, betterRouteDiscoveredFor streamTask: URLSessionStreamTask) { + 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. + open func urlSession( + _ session: URLSession, + streamTask: URLSessionStreamTask, + didBecome inputStream: InputStream, + outputStream: OutputStream) + { + streamTaskDidBecomeInputAndOutputStreams?(session, streamTask, inputStream, outputStream) + } +} + +#endif diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/SessionManager.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/SessionManager.swift new file mode 100644 index 0000000000..493ce29cb4 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/SessionManager.swift @@ -0,0 +1,899 @@ +// +// SessionManager.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`. +open class SessionManager { + + // MARK: - Helper Types + + /// 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 `UploadRequest` 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: UploadRequest, streamingFromDisk: Bool, streamFileURL: URL?) + case failure(Error) + } + + // MARK: - Properties + + /// A default instance of `SessionManager`, used by top-level Alamofire request methods, and suitable for use + /// directly for any ad hoc requests. + open static let `default`: SessionManager = { + let configuration = URLSessionConfiguration.default + configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders + + return SessionManager(configuration: configuration) + }() + + /// Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. + open static let defaultHTTPHeaders: HTTPHeaders = { + // 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 + #if swift(>=4.0) + let acceptLanguage = Locale.preferredLanguages.prefix(6).enumerated().map { enumeratedLanguage in + let (index, languageCode) = enumeratedLanguage + let quality = 1.0 - (Double(index) * 0.1) + return "\(languageCode);q=\(quality)" + }.joined(separator: ", ") + #else + let acceptLanguage = Locale.preferredLanguages.prefix(6).enumerated().map { index, languageCode in + let quality = 1.0 - (Double(index) * 0.1) + return "\(languageCode);q=\(quality)" + }.joined(separator: ", ") + #endif + + // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 + // Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0` + let userAgent: String = { + if let info = Bundle.main.infoDictionary { + let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" + let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" + let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown" + let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown" + + let osNameVersion: String = { + let version = ProcessInfo.processInfo.operatingSystemVersion + let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" + + let osName: String = { + #if os(iOS) + return "iOS" + #elseif os(watchOS) + return "watchOS" + #elseif os(tvOS) + return "tvOS" + #elseif os(macOS) + return "OS X" + #elseif os(Linux) + return "Linux" + #else + return "Unknown" + #endif + }() + + return "\(osName) \(versionString)" + }() + + let alamofireVersion: String = { + guard + let afInfo = Bundle(for: SessionManager.self).infoDictionary, + let build = afInfo["CFBundleShortVersionString"] + else { return "Unknown" } + + return "Alamofire/\(build)" + }() + + return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)" + } + + return "Alamofire" + }() + + return [ + "Accept-Encoding": acceptEncoding, + "Accept-Language": acceptLanguage, + "User-Agent": userAgent + ] + }() + + /// Default memory threshold used when encoding `MultipartFormData` in bytes. + open static let multipartFormDataEncodingMemoryThreshold: UInt64 = 10_000_000 + + /// The underlying session. + open let session: URLSession + + /// The session delegate handling all the task and session delegate callbacks. + open let delegate: SessionDelegate + + /// Whether to start requests immediately after being constructed. `true` by default. + open var startRequestsImmediately: Bool = true + + /// The request adapter called each time a new request is created. + open var adapter: RequestAdapter? + + /// The request retrier called each time a request encounters an error to determine whether to retry the request. + open var retrier: RequestRetrier? { + get { return delegate.retrier } + set { delegate.retrier = newValue } + } + + /// 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. + open var backgroundCompletionHandler: (() -> Void)? + + let queue = DispatchQueue(label: "org.alamofire.session-manager." + UUID().uuidString) + + // MARK: - Lifecycle + + /// Creates an instance with the specified `configuration`, `delegate` and `serverTrustPolicyManager`. + /// + /// - parameter configuration: The configuration used to construct the managed session. + /// `URLSessionConfiguration.default` 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 `SessionManager` instance. + public init( + configuration: URLSessionConfiguration = URLSessionConfiguration.default, + delegate: SessionDelegate = SessionDelegate(), + serverTrustPolicyManager: ServerTrustPolicyManager? = nil) + { + self.delegate = delegate + self.session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) + + commonInit(serverTrustPolicyManager: serverTrustPolicyManager) + } + + /// Creates an instance with the specified `session`, `delegate` and `serverTrustPolicyManager`. + /// + /// - 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 `SessionManager` instance if the URL session's delegate matches; `nil` otherwise. + public init?( + session: URLSession, + delegate: SessionDelegate, + serverTrustPolicyManager: ServerTrustPolicyManager? = nil) + { + guard delegate === session.delegate else { return nil } + + self.delegate = delegate + self.session = session + + commonInit(serverTrustPolicyManager: serverTrustPolicyManager) + } + + private func commonInit(serverTrustPolicyManager: ServerTrustPolicyManager?) { + session.serverTrustPolicyManager = serverTrustPolicyManager + + delegate.sessionManager = self + + delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in + guard let strongSelf = self else { return } + DispatchQueue.main.async { strongSelf.backgroundCompletionHandler?() } + } + } + + deinit { + session.invalidateAndCancel() + } + + // MARK: - Data Request + + /// Creates a `DataRequest` to retrieve the contents of the specified `url`, `method`, `parameters`, `encoding` + /// and `headers`. + /// + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.get` by default. + /// - parameter parameters: The parameters. `nil` by default. + /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `DataRequest`. + @discardableResult + open func request( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil) + -> DataRequest + { + var originalRequest: URLRequest? + + do { + originalRequest = try URLRequest(url: url, method: method, headers: headers) + let encodedURLRequest = try encoding.encode(originalRequest!, with: parameters) + return request(encodedURLRequest) + } catch { + return request(originalRequest, failedWith: error) + } + } + + /// Creates a `DataRequest` to retrieve the contents of a URL based on the specified `urlRequest`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `DataRequest`. + open func request(_ urlRequest: URLRequestConvertible) -> DataRequest { + var originalRequest: URLRequest? + + do { + originalRequest = try urlRequest.asURLRequest() + let originalTask = DataRequest.Requestable(urlRequest: originalRequest!) + + let task = try originalTask.task(session: session, adapter: adapter, queue: queue) + let request = DataRequest(session: session, requestTask: .data(originalTask, task)) + + delegate[task] = request + + if startRequestsImmediately { request.resume() } + + return request + } catch { + return request(originalRequest, failedWith: error) + } + } + + // MARK: Private - Request Implementation + + private func request(_ urlRequest: URLRequest?, failedWith error: Error) -> DataRequest { + var requestTask: Request.RequestTask = .data(nil, nil) + + if let urlRequest = urlRequest { + let originalTask = DataRequest.Requestable(urlRequest: urlRequest) + requestTask = .data(originalTask, nil) + } + + let underlyingError = error.underlyingAdaptError ?? error + let request = DataRequest(session: session, requestTask: requestTask, error: underlyingError) + + if let retrier = retrier, error is AdaptError { + allowRetrier(retrier, toRetry: request, with: underlyingError) + } else { + if startRequestsImmediately { request.resume() } + } + + return request + } + + // MARK: - Download Request + + // MARK: URL Request + + /// Creates a `DownloadRequest` to retrieve the contents the specified `url`, `method`, `parameters`, `encoding`, + /// `headers` and save them to the `destination`. + /// + /// If `destination` is not specified, the contents will remain in the temporary location determined by the + /// underlying URL session. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.get` by default. + /// - parameter parameters: The parameters. `nil` by default. + /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. + /// + /// - returns: The created `DownloadRequest`. + @discardableResult + open func download( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + let encodedURLRequest = try encoding.encode(urlRequest, with: parameters) + return download(encodedURLRequest, to: destination) + } catch { + return download(nil, to: destination, failedWith: error) + } + } + + /// Creates a `DownloadRequest` to retrieve the contents of a URL based on the specified `urlRequest` and save + /// them to the `destination`. + /// + /// If `destination` is not specified, the contents will remain in the temporary location determined by the + /// underlying URL session. + /// + /// 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. `nil` by default. + /// + /// - returns: The created `DownloadRequest`. + @discardableResult + open func download( + _ urlRequest: URLRequestConvertible, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest + { + do { + let urlRequest = try urlRequest.asURLRequest() + return download(.request(urlRequest), to: destination) + } catch { + return download(nil, to: destination, failedWith: error) + } + } + + // MARK: Resume Data + + /// Creates a `DownloadRequest` from the `resumeData` produced from a previous request cancellation to retrieve + /// the contents of the original request and save them to the `destination`. + /// + /// If `destination` is not specified, the contents will remain in the temporary location determined by the + /// underlying URL session. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken + /// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the + /// data is written incorrectly and will always fail to resume the download. For more information about the bug and + /// possible workarounds, please refer to the following Stack Overflow post: + /// + /// - http://stackoverflow.com/a/39347461/1342462 + /// + /// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` + /// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for + /// additional information. + /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. + /// + /// - returns: The created `DownloadRequest`. + @discardableResult + open func download( + resumingWith resumeData: Data, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest + { + return download(.resumeData(resumeData), to: destination) + } + + // MARK: Private - Download Implementation + + private func download( + _ downloadable: DownloadRequest.Downloadable, + to destination: DownloadRequest.DownloadFileDestination?) + -> DownloadRequest + { + do { + let task = try downloadable.task(session: session, adapter: adapter, queue: queue) + let download = DownloadRequest(session: session, requestTask: .download(downloadable, task)) + + download.downloadDelegate.destination = destination + + delegate[task] = download + + if startRequestsImmediately { download.resume() } + + return download + } catch { + return download(downloadable, to: destination, failedWith: error) + } + } + + private func download( + _ downloadable: DownloadRequest.Downloadable?, + to destination: DownloadRequest.DownloadFileDestination?, + failedWith error: Error) + -> DownloadRequest + { + var downloadTask: Request.RequestTask = .download(nil, nil) + + if let downloadable = downloadable { + downloadTask = .download(downloadable, nil) + } + + let underlyingError = error.underlyingAdaptError ?? error + + let download = DownloadRequest(session: session, requestTask: downloadTask, error: underlyingError) + download.downloadDelegate.destination = destination + + if let retrier = retrier, error is AdaptError { + allowRetrier(retrier, toRetry: download, with: underlyingError) + } else { + if startRequestsImmediately { download.resume() } + } + + return download + } + + // MARK: - Upload Request + + // MARK: File + + /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `file`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter file: The file to upload. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload( + _ fileURL: URL, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + return upload(fileURL, with: urlRequest) + } catch { + return upload(nil, failedWith: error) + } + } + + /// Creates a `UploadRequest` from the specified `urlRequest` for uploading the `file`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter file: The file to upload. + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { + do { + let urlRequest = try urlRequest.asURLRequest() + return upload(.file(fileURL, urlRequest)) + } catch { + return upload(nil, failedWith: error) + } + } + + // MARK: Data + + /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `data`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter data: The data to upload. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload( + _ data: Data, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + return upload(data, with: urlRequest) + } catch { + return upload(nil, failedWith: error) + } + } + + /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `data`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter data: The data to upload. + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { + do { + let urlRequest = try urlRequest.asURLRequest() + return upload(.data(data, urlRequest)) + } catch { + return upload(nil, failedWith: error) + } + } + + // MARK: InputStream + + /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `stream`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter stream: The stream to upload. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload( + _ stream: InputStream, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + return upload(stream, with: urlRequest) + } catch { + return upload(nil, failedWith: error) + } + } + + /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `stream`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter stream: The stream to upload. + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { + do { + let urlRequest = try urlRequest.asURLRequest() + return upload(.stream(stream, urlRequest)) + } catch { + return upload(nil, failedWith: error) + } + } + + // MARK: MultipartFormData + + /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new + /// `UploadRequest` using the `url`, `method` and `headers`. + /// + /// 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 multipartFormData: The closure used to append body parts to the `MultipartFormData`. + /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + /// `multipartFormDataEncodingMemoryThreshold` by default. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. + open func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + + return upload( + multipartFormData: multipartFormData, + usingThreshold: encodingMemoryThreshold, + with: urlRequest, + encodingCompletion: encodingCompletion + ) + } catch { + DispatchQueue.main.async { encodingCompletion?(.failure(error)) } + } + } + + /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new + /// `UploadRequest` using the `urlRequest`. + /// + /// 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 multipartFormData: The closure used to append body parts to the `MultipartFormData`. + /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + /// `multipartFormDataEncodingMemoryThreshold` by default. + /// - parameter urlRequest: The URL request. + /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. + open func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + with urlRequest: URLRequestConvertible, + encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) + { + DispatchQueue.global(qos: .utility).async { + let formData = MultipartFormData() + multipartFormData(formData) + + var tempFileURL: URL? + + do { + var urlRequestWithContentType = try urlRequest.asURLRequest() + urlRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type") + + let isBackgroundSession = self.session.configuration.identifier != nil + + if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession { + let data = try formData.encode() + + let encodingResult = MultipartFormDataEncodingResult.success( + request: self.upload(data, with: urlRequestWithContentType), + streamingFromDisk: false, + streamFileURL: nil + ) + + DispatchQueue.main.async { encodingCompletion?(encodingResult) } + } else { + let fileManager = FileManager.default + let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory()) + let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data") + let fileName = UUID().uuidString + let fileURL = directoryURL.appendingPathComponent(fileName) + + tempFileURL = fileURL + + var directoryError: Error? + + // Create directory inside serial queue to ensure two threads don't do this in parallel + self.queue.sync { + do { + try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) + } catch { + directoryError = error + } + } + + if let directoryError = directoryError { throw directoryError } + + try formData.writeEncodedData(to: fileURL) + + let upload = self.upload(fileURL, with: urlRequestWithContentType) + + // Cleanup the temp file once the upload is complete + upload.delegate.queue.addOperation { + do { + try FileManager.default.removeItem(at: fileURL) + } catch { + // No-op + } + } + + DispatchQueue.main.async { + let encodingResult = MultipartFormDataEncodingResult.success( + request: upload, + streamingFromDisk: true, + streamFileURL: fileURL + ) + + encodingCompletion?(encodingResult) + } + } + } catch { + // Cleanup the temp file in the event that the multipart form data encoding failed + if let tempFileURL = tempFileURL { + do { + try FileManager.default.removeItem(at: tempFileURL) + } catch { + // No-op + } + } + + DispatchQueue.main.async { encodingCompletion?(.failure(error)) } + } + } + } + + // MARK: Private - Upload Implementation + + private func upload(_ uploadable: UploadRequest.Uploadable) -> UploadRequest { + do { + let task = try uploadable.task(session: session, adapter: adapter, queue: queue) + let upload = UploadRequest(session: session, requestTask: .upload(uploadable, task)) + + if case let .stream(inputStream, _) = uploadable { + upload.delegate.taskNeedNewBodyStream = { _, _ in inputStream } + } + + delegate[task] = upload + + if startRequestsImmediately { upload.resume() } + + return upload + } catch { + return upload(uploadable, failedWith: error) + } + } + + private func upload(_ uploadable: UploadRequest.Uploadable?, failedWith error: Error) -> UploadRequest { + var uploadTask: Request.RequestTask = .upload(nil, nil) + + if let uploadable = uploadable { + uploadTask = .upload(uploadable, nil) + } + + let underlyingError = error.underlyingAdaptError ?? error + let upload = UploadRequest(session: session, requestTask: uploadTask, error: underlyingError) + + if let retrier = retrier, error is AdaptError { + allowRetrier(retrier, toRetry: upload, with: underlyingError) + } else { + if startRequestsImmediately { upload.resume() } + } + + return upload + } + +#if !os(watchOS) + + // MARK: - Stream Request + + // MARK: Hostname and Port + + /// Creates a `StreamRequest` for bidirectional streaming using the `hostname` and `port`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter hostName: The hostname of the server to connect to. + /// - parameter port: The port of the server to connect to. + /// + /// - returns: The created `StreamRequest`. + @discardableResult + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open func stream(withHostName hostName: String, port: Int) -> StreamRequest { + return stream(.stream(hostName: hostName, port: port)) + } + + // MARK: NetService + + /// Creates a `StreamRequest` for bidirectional streaming using the `netService`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter netService: The net service used to identify the endpoint. + /// + /// - returns: The created `StreamRequest`. + @discardableResult + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open func stream(with netService: NetService) -> StreamRequest { + return stream(.netService(netService)) + } + + // MARK: Private - Stream Implementation + + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + private func stream(_ streamable: StreamRequest.Streamable) -> StreamRequest { + do { + let task = try streamable.task(session: session, adapter: adapter, queue: queue) + let request = StreamRequest(session: session, requestTask: .stream(streamable, task)) + + delegate[task] = request + + if startRequestsImmediately { request.resume() } + + return request + } catch { + return stream(failedWith: error) + } + } + + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + private func stream(failedWith error: Error) -> StreamRequest { + let stream = StreamRequest(session: session, requestTask: .stream(nil, nil), error: error) + if startRequestsImmediately { stream.resume() } + return stream + } + +#endif + + // MARK: - Internal - Retry Request + + func retry(_ request: Request) -> Bool { + guard let originalTask = request.originalTask else { return false } + + do { + let task = try originalTask.task(session: session, adapter: adapter, queue: queue) + + request.delegate.task = task // resets all task delegate data + + request.retryCount += 1 + request.startTime = CFAbsoluteTimeGetCurrent() + request.endTime = nil + + task.resume() + + return true + } catch { + request.delegate.error = error.underlyingAdaptError ?? error + return false + } + } + + private func allowRetrier(_ retrier: RequestRetrier, toRetry request: Request, with error: Error) { + DispatchQueue.utility.async { [weak self] in + guard let strongSelf = self else { return } + + retrier.should(strongSelf, retry: request, with: error) { shouldRetry, timeDelay in + guard let strongSelf = self else { return } + + guard shouldRetry else { + if strongSelf.startRequestsImmediately { request.resume() } + return + } + + DispatchQueue.utility.after(timeDelay) { + guard let strongSelf = self else { return } + + let retrySucceeded = strongSelf.retry(request) + + if retrySucceeded, let task = request.task { + strongSelf.delegate[task] = request + } else { + if strongSelf.startRequestsImmediately { request.resume() } + } + } + } + } + } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/TaskDelegate.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/TaskDelegate.swift new file mode 100644 index 0000000000..d4fd2163c1 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/TaskDelegate.swift @@ -0,0 +1,453 @@ +// +// TaskDelegate.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 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. +open class TaskDelegate: NSObject { + + // MARK: Properties + + /// The serial operation queue used to execute all operations after the task completes. + open let queue: OperationQueue + + /// The data returned by the server. + public var data: Data? { return nil } + + /// The error generated throughout the lifecyle of the task. + public var error: Error? + + var task: URLSessionTask? { + didSet { reset() } + } + + var initialResponseTime: CFAbsoluteTime? + var credential: URLCredential? + var metrics: AnyObject? // URLSessionTaskMetrics + + // MARK: Lifecycle + + init(task: URLSessionTask?) { + self.task = task + + self.queue = { + let operationQueue = OperationQueue() + + operationQueue.maxConcurrentOperationCount = 1 + operationQueue.isSuspended = true + operationQueue.qualityOfService = .utility + + return operationQueue + }() + } + + func reset() { + error = nil + initialResponseTime = nil + } + + // MARK: URLSessionTaskDelegate + + var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? + var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? + var taskDidCompleteWithError: ((URLSession, URLSessionTask, Error?) -> Void)? + + @objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:) + func urlSession( + _ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) + { + var redirectRequest: URLRequest? = request + + if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { + redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) + } + + completionHandler(redirectRequest) + } + + @objc(URLSession:task:didReceiveChallenge:completionHandler:) + func urlSession( + _ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling + var credential: URLCredential? + + 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?.serverTrustPolicy(forHost: host), + let serverTrust = challenge.protectionSpace.serverTrust + { + if serverTrustPolicy.evaluate(serverTrust, forHost: host) { + disposition = .useCredential + credential = URLCredential(trust: serverTrust) + } else { + disposition = .cancelAuthenticationChallenge + } + } + } else { + if challenge.previousFailureCount > 0 { + disposition = .rejectProtectionSpace + } else { + credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace) + + if credential != nil { + disposition = .useCredential + } + } + } + + completionHandler(disposition, credential) + } + + @objc(URLSession:task:needNewBodyStream:) + func urlSession( + _ session: URLSession, + task: URLSessionTask, + needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) + { + var bodyStream: InputStream? + + if let taskNeedNewBodyStream = taskNeedNewBodyStream { + bodyStream = taskNeedNewBodyStream(session, task) + } + + completionHandler(bodyStream) + } + + @objc(URLSession:task:didCompleteWithError:) + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + if let taskDidCompleteWithError = taskDidCompleteWithError { + taskDidCompleteWithError(session, task, error) + } else { + if let error = error { + if self.error == nil { self.error = error } + + if + let downloadDelegate = self as? DownloadTaskDelegate, + let resumeData = (error as NSError).userInfo[NSURLSessionDownloadTaskResumeData] as? Data + { + downloadDelegate.resumeData = resumeData + } + } + + queue.isSuspended = false + } + } +} + +// MARK: - + +class DataTaskDelegate: TaskDelegate, URLSessionDataDelegate { + + // MARK: Properties + + var dataTask: URLSessionDataTask { return task as! URLSessionDataTask } + + override var data: Data? { + if dataStream != nil { + return nil + } else { + return mutableData + } + } + + var progress: Progress + var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? + + var dataStream: ((_ data: Data) -> Void)? + + private var totalBytesReceived: Int64 = 0 + private var mutableData: Data + + private var expectedContentLength: Int64? + + // MARK: Lifecycle + + override init(task: URLSessionTask?) { + mutableData = Data() + progress = Progress(totalUnitCount: 0) + + super.init(task: task) + } + + override func reset() { + super.reset() + + progress = Progress(totalUnitCount: 0) + totalBytesReceived = 0 + mutableData = Data() + expectedContentLength = nil + } + + // MARK: URLSessionDataDelegate + + var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? + var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? + var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? + var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? + + func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didReceive response: URLResponse, + completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) + { + var disposition: URLSession.ResponseDisposition = .allow + + expectedContentLength = response.expectedContentLength + + if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { + disposition = dataTaskDidReceiveResponse(session, dataTask, response) + } + + completionHandler(disposition) + } + + func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didBecome downloadTask: URLSessionDownloadTask) + { + dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask) + } + + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + + if let dataTaskDidReceiveData = dataTaskDidReceiveData { + dataTaskDidReceiveData(session, dataTask, data) + } else { + if let dataStream = dataStream { + dataStream(data) + } else { + mutableData.append(data) + } + + let bytesReceived = Int64(data.count) + totalBytesReceived += bytesReceived + let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown + + progress.totalUnitCount = totalBytesExpected + progress.completedUnitCount = totalBytesReceived + + if let progressHandler = progressHandler { + progressHandler.queue.async { progressHandler.closure(self.progress) } + } + } + } + + func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse, + completionHandler: @escaping (CachedURLResponse?) -> Void) + { + var cachedResponse: CachedURLResponse? = proposedResponse + + if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { + cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse) + } + + completionHandler(cachedResponse) + } +} + +// MARK: - + +class DownloadTaskDelegate: TaskDelegate, URLSessionDownloadDelegate { + + // MARK: Properties + + var downloadTask: URLSessionDownloadTask { return task as! URLSessionDownloadTask } + + var progress: Progress + var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? + + var resumeData: Data? + override var data: Data? { return resumeData } + + var destination: DownloadRequest.DownloadFileDestination? + + var temporaryURL: URL? + var destinationURL: URL? + + var fileURL: URL? { return destination != nil ? destinationURL : temporaryURL } + + // MARK: Lifecycle + + override init(task: URLSessionTask?) { + progress = Progress(totalUnitCount: 0) + super.init(task: task) + } + + override func reset() { + super.reset() + + progress = Progress(totalUnitCount: 0) + resumeData = nil + } + + // MARK: URLSessionDownloadDelegate + + var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> URL)? + var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? + + func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didFinishDownloadingTo location: URL) + { + temporaryURL = location + + guard + let destination = destination, + let response = downloadTask.response as? HTTPURLResponse + else { return } + + let result = destination(location, response) + let destinationURL = result.destinationURL + let options = result.options + + self.destinationURL = destinationURL + + do { + if options.contains(.removePreviousFile), FileManager.default.fileExists(atPath: destinationURL.path) { + try FileManager.default.removeItem(at: destinationURL) + } + + if options.contains(.createIntermediateDirectories) { + let directory = destinationURL.deletingLastPathComponent() + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + + try FileManager.default.moveItem(at: location, to: destinationURL) + } catch { + self.error = error + } + } + + func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) + { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + + if let downloadTaskDidWriteData = downloadTaskDidWriteData { + downloadTaskDidWriteData( + session, + downloadTask, + bytesWritten, + totalBytesWritten, + totalBytesExpectedToWrite + ) + } else { + progress.totalUnitCount = totalBytesExpectedToWrite + progress.completedUnitCount = totalBytesWritten + + if let progressHandler = progressHandler { + progressHandler.queue.async { progressHandler.closure(self.progress) } + } + } + } + + func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) + { + if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { + downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) + } else { + progress.totalUnitCount = expectedTotalBytes + progress.completedUnitCount = fileOffset + } + } +} + +// MARK: - + +class UploadTaskDelegate: DataTaskDelegate { + + // MARK: Properties + + var uploadTask: URLSessionUploadTask { return task as! URLSessionUploadTask } + + var uploadProgress: Progress + var uploadProgressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? + + // MARK: Lifecycle + + override init(task: URLSessionTask?) { + uploadProgress = Progress(totalUnitCount: 0) + super.init(task: task) + } + + override func reset() { + super.reset() + uploadProgress = Progress(totalUnitCount: 0) + } + + // MARK: URLSessionTaskDelegate + + var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? + + func URLSession( + _ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) + { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + + if let taskDidSendBodyData = taskDidSendBodyData { + taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) + } else { + uploadProgress.totalUnitCount = totalBytesExpectedToSend + uploadProgress.completedUnitCount = totalBytesSent + + if let uploadProgressHandler = uploadProgressHandler { + uploadProgressHandler.queue.async { uploadProgressHandler.closure(self.uploadProgress) } + } + } + } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Timeline.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Timeline.swift new file mode 100644 index 0000000000..1440989d5f --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Timeline.swift @@ -0,0 +1,136 @@ +// +// Timeline.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Responsible for computing the timing metrics for the complete lifecycle of a `Request`. +public struct Timeline { + /// The time the request was initialized. + public let requestStartTime: CFAbsoluteTime + + /// The time the first bytes were received from or sent to the server. + public let initialResponseTime: CFAbsoluteTime + + /// The time when the request was completed. + public let requestCompletedTime: CFAbsoluteTime + + /// The time when the response serialization was completed. + public let serializationCompletedTime: CFAbsoluteTime + + /// The time interval in seconds from the time the request started to the initial response from the server. + public let latency: TimeInterval + + /// The time interval in seconds from the time the request started to the time the request completed. + public let requestDuration: TimeInterval + + /// The time interval in seconds from the time the request completed to the time response serialization completed. + public let serializationDuration: TimeInterval + + /// The time interval in seconds from the time the request started to the time response serialization completed. + public let totalDuration: TimeInterval + + /// Creates a new `Timeline` instance with the specified request times. + /// + /// - parameter requestStartTime: The time the request was initialized. Defaults to `0.0`. + /// - parameter initialResponseTime: The time the first bytes were received from or sent to the server. + /// Defaults to `0.0`. + /// - parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`. + /// - parameter serializationCompletedTime: The time when the response serialization was completed. Defaults + /// to `0.0`. + /// + /// - returns: The new `Timeline` instance. + public init( + requestStartTime: CFAbsoluteTime = 0.0, + initialResponseTime: CFAbsoluteTime = 0.0, + requestCompletedTime: CFAbsoluteTime = 0.0, + serializationCompletedTime: CFAbsoluteTime = 0.0) + { + self.requestStartTime = requestStartTime + self.initialResponseTime = initialResponseTime + self.requestCompletedTime = requestCompletedTime + self.serializationCompletedTime = serializationCompletedTime + + self.latency = initialResponseTime - requestStartTime + self.requestDuration = requestCompletedTime - requestStartTime + self.serializationDuration = serializationCompletedTime - requestCompletedTime + self.totalDuration = serializationCompletedTime - requestStartTime + } +} + +// MARK: - CustomStringConvertible + +extension Timeline: CustomStringConvertible { + /// The textual representation used when written to an output stream, which includes the latency, the request + /// duration and the total duration. + public var description: String { + let latency = String(format: "%.3f", self.latency) + let requestDuration = String(format: "%.3f", self.requestDuration) + let serializationDuration = String(format: "%.3f", self.serializationDuration) + let totalDuration = String(format: "%.3f", self.totalDuration) + + // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is + // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. + let timings = [ + "\"Latency\": " + latency + " secs", + "\"Request Duration\": " + requestDuration + " secs", + "\"Serialization Duration\": " + serializationDuration + " secs", + "\"Total Duration\": " + totalDuration + " secs" + ] + + return "Timeline: { " + timings.joined(separator: ", ") + " }" + } +} + +// MARK: - CustomDebugStringConvertible + +extension Timeline: CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes the request start time, the + /// initial response time, the request completed time, the serialization completed time, the latency, the request + /// duration and the total duration. + public var debugDescription: String { + let requestStartTime = String(format: "%.3f", self.requestStartTime) + let initialResponseTime = String(format: "%.3f", self.initialResponseTime) + let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime) + let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime) + let latency = String(format: "%.3f", self.latency) + let requestDuration = String(format: "%.3f", self.requestDuration) + let serializationDuration = String(format: "%.3f", self.serializationDuration) + let totalDuration = String(format: "%.3f", self.totalDuration) + + // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is + // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. + let timings = [ + "\"Request Start Time\": " + requestStartTime, + "\"Initial Response Time\": " + initialResponseTime, + "\"Request Completed Time\": " + requestCompletedTime, + "\"Serialization Completed Time\": " + serializationCompletedTime, + "\"Latency\": " + latency + " secs", + "\"Request Duration\": " + requestDuration + " secs", + "\"Serialization Duration\": " + serializationDuration + " secs", + "\"Total Duration\": " + totalDuration + " secs" + ] + + return "Timeline: { " + timings.joined(separator: ", ") + " }" + } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift new file mode 100644 index 0000000000..c405d02af1 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift @@ -0,0 +1,309 @@ +// +// 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 { + + // MARK: Helper Types + + fileprivate typealias ErrorReason = AFError.ResponseValidationFailureReason + + /// 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(Error) + } + + fileprivate struct MIMEType { + let type: String + let subtype: String + + var isWildcard: Bool { return type == "*" && subtype == "*" } + + init?(_ string: String) { + let components: [String] = { + let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines) + let split = stripped.substring(to: stripped.range(of: ";")?.lowerBound ?? stripped.endIndex) + return split.components(separatedBy: "/") + }() + + if let type = components.first, let 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 + } + } + } + + // MARK: Properties + + fileprivate var acceptableStatusCodes: [Int] { return Array(200..<300) } + + fileprivate var acceptableContentTypes: [String] { + if let accept = request?.value(forHTTPHeaderField: "Accept") { + return accept.components(separatedBy: ",") + } + + return ["*/*"] + } + + // MARK: Status Code + + fileprivate func validate( + statusCode acceptableStatusCodes: S, + response: HTTPURLResponse) + -> ValidationResult + where S.Iterator.Element == Int + { + if acceptableStatusCodes.contains(response.statusCode) { + return .success + } else { + let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode) + return .failure(AFError.responseValidationFailed(reason: reason)) + } + } + + // MARK: Content Type + + fileprivate func validate( + contentType acceptableContentTypes: S, + response: HTTPURLResponse, + data: Data?) + -> ValidationResult + where S.Iterator.Element == String + { + guard let data = data, data.count > 0 else { return .success } + + guard + let responseContentType = response.mimeType, + let responseMIMEType = MIMEType(responseContentType) + else { + for contentType in acceptableContentTypes { + if let mimeType = MIMEType(contentType), mimeType.isWildcard { + return .success + } + } + + let error: AFError = { + let reason: ErrorReason = .missingContentType(acceptableContentTypes: Array(acceptableContentTypes)) + return AFError.responseValidationFailed(reason: reason) + }() + + return .failure(error) + } + + for contentType in acceptableContentTypes { + if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) { + return .success + } + } + + let error: AFError = { + let reason: ErrorReason = .unacceptableContentType( + acceptableContentTypes: Array(acceptableContentTypes), + responseContentType: responseContentType + ) + + return AFError.responseValidationFailed(reason: reason) + }() + + return .failure(error) + } +} + +// MARK: - + +extension DataRequest { + /// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the + /// request was valid. + public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> 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. + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validationExecution: () -> Void = { [unowned self] in + if + let response = self.response, + self.delegate.error == nil, + case let .failure(error) = validation(self.request, response, self.delegate.data) + { + self.delegate.error = error + } + } + + validations.append(validationExecution) + + return self + } + + /// Validates that the response has a status code in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter range: The range of acceptable status codes. + /// + /// - returns: The request. + @discardableResult + public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { + return validate { [unowned self] _, response, _ in + return self.validate(statusCode: acceptableStatusCodes, response: response) + } + } + + /// Validates that the response has a content type in the specified sequence. + /// + /// 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. + @discardableResult + public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { + return validate { [unowned self] _, response, data in + return self.validate(contentType: acceptableContentTypes, response: response, data: data) + } + } + + /// 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. + @discardableResult + public func validate() -> Self { + return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes) + } +} + +// MARK: - + +extension DownloadRequest { + /// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a + /// destination URL, and returns whether the request was valid. + public typealias Validation = ( + _ request: URLRequest?, + _ response: HTTPURLResponse, + _ temporaryURL: URL?, + _ destinationURL: URL?) + -> 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. + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validationExecution: () -> Void = { [unowned self] in + let request = self.request + let temporaryURL = self.downloadDelegate.temporaryURL + let destinationURL = self.downloadDelegate.destinationURL + + if + let response = self.response, + self.delegate.error == nil, + case let .failure(error) = validation(request, response, temporaryURL, destinationURL) + { + self.delegate.error = error + } + } + + validations.append(validationExecution) + + return self + } + + /// Validates that the response has a status code in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter range: The range of acceptable status codes. + /// + /// - returns: The request. + @discardableResult + public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { + return validate { [unowned self] _, response, _, _ in + return self.validate(statusCode: acceptableStatusCodes, response: response) + } + } + + /// Validates that the response has a content type in the specified sequence. + /// + /// 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. + @discardableResult + public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { + return validate { [unowned self] _, response, _, _ in + let fileURL = self.downloadDelegate.fileURL + + guard let validFileURL = fileURL else { + return .failure(AFError.responseValidationFailed(reason: .dataFileNil)) + } + + do { + let data = try Data(contentsOf: validFileURL) + return self.validate(contentType: acceptableContentTypes, response: response, data: data) + } catch { + return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL))) + } + } + } + + /// 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. + @discardableResult + public func validate() -> Self { + return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes) + } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json new file mode 100644 index 0000000000..e171d31513 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json @@ -0,0 +1,25 @@ +{ + "name": "PetstoreClient", + "platforms": { + "ios": "9.0", + "osx": "10.11" + }, + "version": "0.0.1", + "source": { + "git": "git@github.com:swagger-api/swagger-mustache.git", + "tag": "v1.0.0" + }, + "authors": "", + "license": "Proprietary", + "homepage": "https://github.com/swagger-api/swagger-codegen", + "summary": "PetstoreClient", + "source_files": "PetstoreClient/Classes/Swaggers/**/*.swift", + "dependencies": { + "PromiseKit": [ + "~> 4.2.2" + ], + "Alamofire": [ + "~> 4.5" + ] + } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Manifest.lock b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Manifest.lock new file mode 100644 index 0000000000..2ecaf7a82b --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Manifest.lock @@ -0,0 +1,32 @@ +PODS: + - Alamofire (4.5.0) + - PetstoreClient (0.0.1): + - Alamofire (~> 4.5) + - PromiseKit (~> 4.2.2) + - PromiseKit (4.2.2): + - PromiseKit/Foundation (= 4.2.2) + - PromiseKit/QuartzCore (= 4.2.2) + - PromiseKit/UIKit (= 4.2.2) + - PromiseKit/CorePromise (4.2.2) + - PromiseKit/Foundation (4.2.2): + - PromiseKit/CorePromise + - PromiseKit/QuartzCore (4.2.2): + - PromiseKit/CorePromise + - PromiseKit/UIKit (4.2.2): + - PromiseKit/CorePromise + +DEPENDENCIES: + - PetstoreClient (from `../`) + +EXTERNAL SOURCES: + PetstoreClient: + :path: ../ + +SPEC CHECKSUMS: + Alamofire: f28cdffd29de33a7bfa022cbd63ae95a27fae140 + PetstoreClient: dd4a9f18265468d1f25e14ed1651245c668448c3 + PromiseKit: 00e8886881f151c7e573d06b437915b0bb2970ec + +PODFILE CHECKSUM: da9f5a7ad6086f2c7abb73cf2c35cefce04a9a30 + +COCOAPODS: 1.1.1 diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj new file mode 100644 index 0000000000..4d0503356d --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj @@ -0,0 +1,1604 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 0000257E6138186889F38B8A7F797C33 /* AlamofireImplementations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1024470B7B0142DFF1DF7E009ED9260D /* AlamofireImplementations.swift */; }; + 003F98B2C041FC1DE84490CDB4598F89 /* UIViewController+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = BFD4C386443F3A9950AA00E1C6127C2B /* UIViewController+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0097805BEFC942B10049FCF37ED24E0D /* OuterComposite.swift in Sources */ = {isa = PBXBuildFile; fileRef = 749C03CC31823CCADA2EFFFD06BF9E98 /* OuterComposite.swift */; }; + 0298FFF35BEF4948A42E55756D7C81A8 /* FormatTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8DD5A1187D47A6FFAC34F927DA186750 /* FormatTest.swift */; }; + 0323E3530C2A481A0C10B0EBB7DCD2E4 /* NSURLSession+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = BA71549EA391E3A6799E5E2083D51179 /* NSURLSession+Promise.swift */; }; + 032C9FCA8EA6C8553275B1F7641A1CD8 /* EnumArrays.swift in Sources */ = {isa = PBXBuildFile; fileRef = 249B8C876D70EDBA1D831123AE8EE0F8 /* EnumArrays.swift */; }; + 04364ACE71EDEA482E970EDC82ED01B9 /* when.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1EA0E986221EEA08549F8CA73563FE27 /* when.swift */; }; + 050D8EBD37B9EBC551614518F5C70CF2 /* race.swift in Sources */ = {isa = PBXBuildFile; fileRef = 16F53B93392AAECDF2A786BC34DEE42B /* race.swift */; }; + 0AF188BAD0E51575891ACE80B0BA6AE9 /* List.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3BD1A4B33356A3CDF1DC77EE6C70D752 /* List.swift */; }; + 0DF2F6645EE3AB16827B6212F6DEDFDA /* SpecialModelName.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2AC757CC02124D5B17B6867095DBB70D /* SpecialModelName.swift */; }; + 109135A9E832B6E00D3258B9A7A95D2E /* ArrayOfArrayOfNumberOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = 81632F006BE1334AB9EE06329318FE60 /* ArrayOfArrayOfNumberOnly.swift */; }; + 10EB23E9ECC4B33E16933BB1EA560B6A /* Timeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = F738520F03FD7B756BB4DF21CF3DF1DC /* Timeline.swift */; }; + 14FA5791C21B38B5D90017F182AA77C6 /* AdditionalPropertiesClass.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F54BE613A3988D2B9B506E8E6BEE157 /* AdditionalPropertiesClass.swift */; }; + 173A377B378B75AADE06A397128BC8AB /* AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 0720785FA765917D0C03A126E07CB2C5 /* AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1870983702DCF95885BECDBF3E5757E3 /* MixedPropertiesAndAdditionalPropertiesClass.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4EE549F80BAFEF84BF212F0C315BC9BF /* MixedPropertiesAndAdditionalPropertiesClass.swift */; }; + 18F9B7517B71D53CC011E7F88676B527 /* User.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83A7AB2A1DA3632E843B3336E8D41A8E /* User.swift */; }; + 197CBB45FF699E91B3E8DEDFCD596612 /* NSNotificationCenter+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 3BF219E6163D01FB1E793CA0AE97EF67 /* NSNotificationCenter+AnyPromise.m */; }; + 1B50D83C35A942533A18AA3AF0A80421 /* UIView+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 69AAB5FB4A56193E40C41542AAAFD310 /* UIView+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1B9EDEDC964E6B08F78920B4F4B9DB84 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 6C7ACDC625BF00A435AF4AB3554CDDF0 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1D3E8E496572E1D4244811D5A3973171 /* NSURLSession+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 99A593C5CAA9E46E3EA8A5F0A3A5E892 /* NSURLSession+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1D670869022E7C0EA2DEE5155BD1864A /* DispatchQueue+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 103847E55D2DB836C4726FD119FCFA4F /* DispatchQueue+Promise.swift */; }; + 1DA594AF0F2972E05DF99942E216377A /* UIView+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8461ED3F533CF9C212A6A3F024CC8F5A /* UIView+Promise.swift */; }; + 1EFA4EB14D39ED739309A086ECEA8906 /* URLDataPromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 707A13EC65734755A4354861F095D56B /* URLDataPromise.swift */; }; + 1F6BD2584EF72ECAA323B94528BE7992 /* Models.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C877E250DAECFEE1CDABF476EF2B25C /* Models.swift */; }; + 1FB6E55D4CD4F11D4D7C8722E8C33A42 /* PromiseKit-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = B2D46CA33667445037B49DB2E4682861 /* PromiseKit-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 20E2CC1FD887EC3DA74724A32DDA1132 /* Pods-SwaggerClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 22980ADB7D228364F99E8EA145509B4F /* Client.swift in Sources */ = {isa = PBXBuildFile; fileRef = E2FCD5F3D2C6621D4355CACB49530DB3 /* Client.swift */; }; + 2642DF6CB39C87B120397F5C178010F9 /* NSObject+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = E6880118613493912D876F6EDAC620D3 /* NSObject+Promise.swift */; }; + 286FDA09B99338DDAE8AEEAF3D2769FA /* UserAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC87361174534D6D1655DD60071A3D83 /* UserAPI.swift */; }; + 3064A0BD79720BAD39B0F3ECD5C93FFA /* EnumClass.swift in Sources */ = {isa = PBXBuildFile; fileRef = 03597C306A2FB3B657BCFF572F74F4D4 /* EnumClass.swift */; }; + 30B8557D047D60B5F8332BCE95DD693E /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2141FBF0CC0A4A8349C016ECD4ABBEE2 /* QuartzCore.framework */; }; + 31F8B86E3672D0B828B6352C875649C4 /* Pods-SwaggerClientTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3312221F642766FE185B9B697A8BAE4B /* Pet.swift in Sources */ = {isa = PBXBuildFile; fileRef = DE081085EBFE0D670AAC85E74ACFDE8D /* Pet.swift */; }; + 33457D935182159E14829CE7BEEBDD6D /* StoreAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10156F0F886EC2F50651B704A3A6D742 /* StoreAPI.swift */; }; + 3440FB38AAE8B9EA4CDCEE98B931B524 /* Zalgo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 827F697F6F7FF65D0850AF04A0CC3806 /* Zalgo.swift */; }; + 3626B94094672CB1C9DEA32B9F9502E1 /* TaskDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 641D30DAD8B334C67D53DB9FE3E1156F /* TaskDelegate.swift */; }; + 3DAA524BB89E475536B71207F5F2C0F5 /* ArrayTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 53AFC29FAA23E6156D43BCDE6F4EFEF7 /* ArrayTest.swift */; }; + 3F034997ED7849F2C6CC86D5B8C50BC1 /* CALayer+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 3DB83DEE18EB958220B42D26A726EA74 /* CALayer+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 465DC8B52B3D7D0585D772ED29683D3E /* NSNotificationCenter+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 86FB9D88F32EB25214615C461AC6C432 /* NSNotificationCenter+Promise.swift */; }; + 468BB42B90797F64A371FDE8C7185AF4 /* State.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7CB03045DB10F7089377C70AF5B3F670 /* State.swift */; }; + 4E482819CF1AD28A5960095805A803ED /* FakeAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6815FAC9A7B1782239E161DEEF54357F /* FakeAPI.swift */; }; + 508395CE75541C444206B78E2E94F435 /* MapTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0C11B4AA97BB6048B4FFD944AEE16E85 /* MapTest.swift */; }; + 5387216E723A3C68E851CA15573CDD71 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F0DEFA8B8F894D4BFC00D53E40611EC /* Request.swift */; }; + 53A8D9F8E089D32918F3A5843ADDC26A /* PMKFoundation.h in Headers */ = {isa = PBXBuildFile; fileRef = C31B213B335DFB715738D846C9799EC8 /* PMKFoundation.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 545C5A303A209C2C009E242F9D310001 /* EnumTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4199B3084AC46DC42D15500A1C964ECC /* EnumTest.swift */; }; + 57451FA0255A49DEBAEB885DD0658750 /* hang.m in Sources */ = {isa = PBXBuildFile; fileRef = 0E0D7BCA2C0C3C6ABB215B192FE61633 /* hang.m */; }; + 5765C7B9F6084011161DA2267C2A0B57 /* PromiseKit.h in Headers */ = {isa = PBXBuildFile; fileRef = A1F75405F0BABFF928C6618F11B55DD2 /* PromiseKit.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 578E746892610EA4B83D264A05D6FC60 /* APIHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 14FA6FDDB70F2EFB58DE7D635F6946D4 /* APIHelper.swift */; }; + 5909B4BACAF8557FE13B325FA529BE57 /* FakeclassnametagsAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 09F0396C30B906DB9EFEFBE97E091406 /* FakeclassnametagsAPI.swift */; }; + 5BE1865A8083F6AD7AE7DCFE51E58891 /* afterlife.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E15893D6DA076F151391488D212E3FE /* afterlife.swift */; }; + 5CBC2597C5EED08A74430DD6E8C3C9C5 /* GlobalState.m in Sources */ = {isa = PBXBuildFile; fileRef = 2174DBFD409F34598A78447BBC01DB23 /* GlobalState.m */; }; + 5D63858F4E9812FAAF772FFDCB4ACE45 /* ApiResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26189A4CE9006C2C9BB1AAE144CB191F /* ApiResponse.swift */; }; + 6084F899BF2E35FD09D072A5C0394BD3 /* CALayer+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = BAF01D809260F177266BCDEB5D85A6F4 /* CALayer+AnyPromise.m */; }; + 61200D01A1855D7920CEF835C8BE00B0 /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7C414EFC68CF0C5DB0E5D9E33863B44 /* DispatchQueue+Alamofire.swift */; }; + 622B5DBF5E128A33315BE8EFF05792EA /* AnimalFarm.swift in Sources */ = {isa = PBXBuildFile; fileRef = 688103EFA108516ADBACAFEF5DF33690 /* AnimalFarm.swift */; }; + 62F65AD8DC4F0F9610F4B8B4738EC094 /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 19B892C7CE6610E1CA2ADC23C7B1C5B9 /* ServerTrustPolicy.swift */; }; + 6A47436E31CAD703E4ABB641F80FC7DF /* Category.swift in Sources */ = {isa = PBXBuildFile; fileRef = F69BC1C993ED1722CE6D63E07381785E /* Category.swift */; }; + 6CE003919AF6139793694D58ADFAF9E6 /* after.m in Sources */ = {isa = PBXBuildFile; fileRef = 2CD0480A6F4D769F6CE8B6BEC16F5CFE /* after.m */; }; + 6DCD351570B86AADFD4BF754096A2DAE /* OuterBoolean.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1365D135EB77F78D4ED50CB4CEA2BA76 /* OuterBoolean.swift */; }; + 6FA5895264E0223B0A016644C59C6046 /* HasOnlyReadOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A2DACCC87696D352D52090A939EE230 /* HasOnlyReadOnly.swift */; }; + 77F4CFE0094EBDC63B49257B074C936B /* OuterNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = E6E0984D5B0599817A4E48CBAE9AAB9A /* OuterNumber.swift */; }; + 7878FCD0D2F00BCD00002F6BD6E297A7 /* Return.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F57C400928D9344121036AC8E4220D /* Return.swift */; }; + 7B5FE28C7EA4122B0598738E54DBEBD8 /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = A4AECF8B352819D57BE253B02387B58E /* SessionDelegate.swift */; }; + 7D8CC01E8C9EFFF9F4D65406CDE0AB66 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 475A72056C770A5978AB453E7DC5B3AE /* Result.swift */; }; + 7E40C3A7DBC7306738AC9E27C734C25E /* Dog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 975DAA5E04C557E1AA63DD67304C3466 /* Dog.swift */; }; + 7E60F24604C0F467F63D451E410390D8 /* JSONEncodingHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 25616A3E91482393BFD64C92FE312F0E /* JSONEncodingHelper.swift */; }; + 7F1456C9A2A6684F13FD1B5A1DFD7E74 /* dispatch_promise.m in Sources */ = {isa = PBXBuildFile; fileRef = F57895C0FD129E4ACA6D2DF8C5C960BC /* dispatch_promise.m */; }; + 7F4DA286C82EE5687AFC2FE1B7C60292 /* PromiseKit-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 7B8FB736CDFAAADBDB70EA060535FFEB /* PromiseKit-dummy.m */; }; + 81DF78F6697313B98D66D012475E8067 /* NSNotificationCenter+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 7DEB18C435BF545F4290754BD12ACA89 /* NSNotificationCenter+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 825645C19A9BDB1D138D5DFDF69C143A /* fwd.h in Headers */ = {isa = PBXBuildFile; fileRef = 501CB163DE7B7F59F59C62C76F13A1E3 /* fwd.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 86463DE0FB886D57EFACE9747D72E1E6 /* PetstoreClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */; }; + 8740BC8B595A54E9C973D7110740D43F /* Pods-SwaggerClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */; }; + 897985FA042CD12B825C3032898FAB26 /* Pods-SwaggerClientTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */; }; + 8C1BEB026BACC90CE05F5DA21C8CFF67 /* PMKAlertController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A1934708EF63D8175858BE77D4CC707 /* PMKAlertController.swift */; }; + 908D609C8BB8E370E1A3C03D05F0A23C /* UIViewController+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E47C91B82D7EF2401C4A7D2DA4F7B72 /* UIViewController+Promise.swift */; }; + 95630631BB8BFEB5540B6CF0C5D029E2 /* AnyPromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 706B5E9B8BA544EE1CCA46D4A1F29216 /* AnyPromise.swift */; }; + 960FAEEAEDD7034D1E1B0D5B5AB43088 /* after.swift in Sources */ = {isa = PBXBuildFile; fileRef = F05F43847135C8DA403312FBEDB1F49F /* after.swift */; }; + 99C82D0F8CF5B60591EF533A62F0E10A /* Order.swift in Sources */ = {isa = PBXBuildFile; fileRef = E80F4034540947434A69B02246F8ABBD /* Order.swift */; }; + 9CBC2DEF8C73F54A32071F82D8F12DF5 /* join.swift in Sources */ = {isa = PBXBuildFile; fileRef = E92EF227AB7E7DD3F054096F5CC1A430 /* join.swift */; }; + 9ED2BB2981896E0A39EFA365503F58CE /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = F35E3788DA69834B7CF86EC61FEB453C /* AFError.swift */; }; + 9F31C123624CA2B1C281D5F975EDE616 /* Name.swift in Sources */ = {isa = PBXBuildFile; fileRef = 237AE2907A722F87C756BCE4EF772C4C /* Name.swift */; }; + A04BFC558D69E7DBB68023C80A9CFE4E /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C8F4E041B8F062D0E58498A365070ED8 /* Foundation.framework */; }; + A04DA97EEE7A057FC4EDA1D95309E9A3 /* wrap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B83848569669227892C0BF2A5CE1835 /* wrap.swift */; }; + A22E02C8FB1A44C7AAFED7E121904807 /* APIs.swift in Sources */ = {isa = PBXBuildFile; fileRef = 798454EC551811276A6837CFCD4ADC8A /* APIs.swift */; }; + A2A6F71B727312BD45CC7A4AAD7B0AB7 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 68757F29FA6F6C42DBA6342A3E62044D /* NetworkReachabilityManager.swift */; }; + A81AD325D55AF5D8972809300D8F36E5 /* Animal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 44E7AE2E18EA6D3B341C419A4B2813F3 /* Animal.swift */; }; + A9EEEA7477981DEEBC72432DE9990A4B /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = F20826EF67AE5149D903E774F67507DD /* Alamofire-dummy.m */; }; + AA72696A13BD17947CAEDA22B0C89372 /* Tag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A3C1EDF28A8B80DB140B65CDE450E09 /* Tag.swift */; }; + AB0054D02002325BD7DF0BE3FD742D9C /* JSONEncodableEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F07EB5B38222CE6DB8CC7EC894E9E73 /* JSONEncodableEncoding.swift */; }; + ADF417E7FD14C452F475C4328B1661C3 /* PMKUIKit.h in Headers */ = {isa = PBXBuildFile; fileRef = 475705EF39C1CD6FEAE0873C0353F9A7 /* PMKUIKit.h */; settings = {ATTRIBUTES = (Public, ); }; }; + AE1EF48399533730D0066E04B22CA2D6 /* SessionManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3227553C2F6B960B53F2DADD2091E856 /* SessionManager.swift */; }; + B0D0A8D9EB7248222E444C3004709BB4 /* PetstoreClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B2CF10965316B20D0BB59BDEC2AB0131 /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F53D6FE99858297507D97FCDF5F0F461 /* Alamofire.framework */; }; + B65FCF589DA398C3EFE0128064E510EC /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = CF7474663A857DD4540585C7AABD1E42 /* MultipartFormData.swift */; }; + BBEFE2F9CEB73DC7BD97FFA66A0D9D4F /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 943618599D753D3CF9CEA416875D6417 /* Validation.swift */; }; + BC1063342B57CB4A07D50F277CAC4783 /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1194146F3B5CFFECFE93B4E1DBB369BA /* Configuration.swift */; }; + BD80FDBAC0BA32059AE47295D91CA7D5 /* AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 0296C2154D0CAB4EE1AF3AD456C7207F /* AnyPromise.m */; }; + BDEA72204E0F3D235E5B0950762CC3DF /* when.m in Sources */ = {isa = PBXBuildFile; fileRef = 152E92E58DF288044CE0369CD8522B52 /* when.m */; }; + BE5C67A07E289FE1F9BE27335B159997 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51E0E750323BD31207928C6D05DBA443 /* ParameterEncoding.swift */; }; + BFAD00B3B746E0E08E9155FF4E84F24A /* NSTask+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 6B5E5BE3E3FECE0F54F54CE7C4EDBF6F /* NSTask+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + C0C4450B687C7F4706A5E8ADD7826A85 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C8F4E041B8F062D0E58498A365070ED8 /* Foundation.framework */; }; + C0D858800E557D0A38D2E61CB98523F3 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C8F4E041B8F062D0E58498A365070ED8 /* Foundation.framework */; }; + C2432D8D7746A8E8DCA5B602151C42E4 /* join.m in Sources */ = {isa = PBXBuildFile; fileRef = 64849EF7FCD1A24F508478A6B82F15B4 /* join.m */; }; + C764F495BF6DFEBE52AFD13FDFB8E77F /* Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 074AB602E0D52FDEFEAC391A71BE362C /* Extensions.swift */; }; + C80991D67ADACC9C48704248AC151933 /* Capitalization.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE4C2705D4C3B913D44B4F26C6817A9C /* Capitalization.swift */; }; + C8DC229B790728AF1D8DBE1C9DBC4149 /* UIView+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 607DB4D4E14EB20C4DE0C6BD2FA4A922 /* UIView+AnyPromise.m */; }; + C9D7613956EB06CD6E42B97ABEC9B673 /* PMKQuartzCore.h in Headers */ = {isa = PBXBuildFile; fileRef = 584464ED8CD0D083C3125CBCE3F07BA1 /* PMKQuartzCore.h */; settings = {ATTRIBUTES = (Public, ); }; }; + CA4691ACA6280C902F0B1EA26C33A367 /* Promise+Properties.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3C42CC2D632364C7CA8BB4857F2F9C6F /* Promise+Properties.swift */; }; + CB6D60925223897FFA2662667DF83E8A /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = D5021828D3563560F50658622F55322A /* Response.swift */; }; + CFFAD4C93D9A9D8455B4D4C18FFE8055 /* PetAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A0B8917069F5E9591DD17A113737986 /* PetAPI.swift */; }; + D2451BD00C9ED3883D70BDDE178EAE89 /* NumberOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = 076A25934936127AC03A2B855ACCDF5E /* NumberOnly.swift */; }; + D32130A2C8AC5B1FF21AF43BCC2B5217 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C8F4E041B8F062D0E58498A365070ED8 /* Foundation.framework */; }; + D67D0F8EB46ED3C4256F87DF09186EEA /* CodableHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = C387A09BFC4D29F2B2C308F55CD2BFB7 /* CodableHelper.swift */; }; + DA76C2A4D3AB587E749A0F66577E9304 /* NSURLSession+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = E470520443CDA5BBDA7D716E9AFEF14C /* NSURLSession+AnyPromise.m */; }; + DBDF86E562197D5CD9642080A12A5BE4 /* NSTask+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = A583E04FA44E6EB8B13CFBD3C4BC1016 /* NSTask+AnyPromise.m */; }; + DC594EF39ADAFC9B59E1DE1A9BE58D97 /* Cat.swift in Sources */ = {isa = PBXBuildFile; fileRef = C21C617FCA30726E782E8A67D0149138 /* Cat.swift */; }; + DDEE5C6AA270829DE886561F304A4824 /* Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = AAC0733365F6A9BF565156D2FFA419ED /* Promise.swift */; }; + E3EC746788D5F275062D0285A256889F /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4655B4C1707E9902435774C9B1981618 /* Error.swift */; }; + E58EC13E8E0CD973265C55501616B315 /* Process+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 06FB2C2C487F62C8E234E5F309EE50EE /* Process+Promise.swift */; }; + E59910F3BA3F43E74B24DC9AE4612B88 /* ArrayOfNumberOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D9891D7095BE60AF5240E9C34D72085 /* ArrayOfNumberOnly.swift */; }; + E76FE98378C097EE9C5A718F5BD2F581 /* Model200Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = C82495B2E8EC7A268E3C9F068458102B /* Model200Response.swift */; }; + E856B555D4283924AE496FB9A447189A /* OuterString.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA8F6D8048F257672069D2008983C66D /* OuterString.swift */; }; + E9709BDE6A967F82A034B01DD832123C /* ReadOnlyFirst.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1DF0A17DD1DCF7B53BFC5E09C07C84B1 /* ReadOnlyFirst.swift */; }; + EB1F02E78667DE59E495E496FFEFC8CB /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2ABF01CA3A8264BCD945D29D45416B97 /* UIKit.framework */; }; + EFD264FC408EBF3BA2528E70B08DDD94 /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2DE0CB8D9EE8A56D63B991586247B70A /* Notifications.swift */; }; + F08AFEBD1802D01C74266BF23F184138 /* OuterEnum.swift in Sources */ = {isa = PBXBuildFile; fileRef = C2A49053FD4226BD3513549F61A5944F /* OuterEnum.swift */; }; + F45D65E76C21F99D26C25A71AE5566DD /* ClassModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = D679EE988B8B8734D2AAAAAFD25CDB9B /* ClassModel.swift */; }; + F4FD458A3DA6D643C08F837463C11B79 /* PromiseKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 31D680492464F6D65F2FAFA3D645CFFC /* PromiseKit.framework */; }; + F6BECD98B97CBFEBE2C96F0E9E72A6C0 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 82CFB52B2B1C4E72218F01A4034E11C4 /* ResponseSerialization.swift */; }; + F8B3D3092ED0417E8CDF32033F6122F5 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3DD4689CB744B566DA645A762474D50 /* Alamofire.swift */; }; + F9A79B29AC1077DE04896B7C0ED7FEF7 /* UIViewController+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 4DD1AADF1F309F00ABA66EF864526D79 /* UIViewController+AnyPromise.m */; }; + FC3CD5AA2DA8A499EB23571E14325F13 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C8F4E041B8F062D0E58498A365070ED8 /* Foundation.framework */; }; + FD795A688F4488A09DC07632E6280D8C /* Promise+AnyPromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = CAFBFC23A6A4DB2974DAB9A6FADE9E11 /* Promise+AnyPromise.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + B173CFF2A1174933D7851E8CE1CA77AB /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = CD79A5D6FCA04E079B656EC73E0CF0A9; + remoteInfo = PetstoreClient; + }; + BBE116AAF20C2D98E0CC5B0D86765D22 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 88E9EC28B8B46C3631E6B242B50F4442; + remoteInfo = Alamofire; + }; + CB26706D98170EB16B463236FA3B7559 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 88E9EC28B8B46C3631E6B242B50F4442; + remoteInfo = Alamofire; + }; + D74571BD294009BB075CA105B3BA8274 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = C7C5ED0DB8AF8EA86EC1631F79346F2C; + remoteInfo = PromiseKit; + }; + F4F5C9A84714BE23040A5FB7588DA6BD /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = C7C5ED0DB8AF8EA86EC1631F79346F2C; + remoteInfo = PromiseKit; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 00ACB4396DD1B4E4539E4E81C1D7A14E /* Pods-SwaggerClientTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = "Pods-SwaggerClientTests.modulemap"; sourceTree = ""; }; + 0296C2154D0CAB4EE1AF3AD456C7207F /* AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AnyPromise.m; path = Sources/AnyPromise.m; sourceTree = ""; }; + 02F28E719AA874BE9213D6CF8CE7E36B /* Pods-SwaggerClientTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClientTests-acknowledgements.plist"; sourceTree = ""; }; + 03597C306A2FB3B657BCFF572F74F4D4 /* EnumClass.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = EnumClass.swift; sourceTree = ""; }; + 06FB2C2C487F62C8E234E5F309EE50EE /* Process+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Process+Promise.swift"; path = "Extensions/Foundation/Sources/Process+Promise.swift"; sourceTree = ""; }; + 0720785FA765917D0C03A126E07CB2C5 /* AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AnyPromise.h; path = Sources/AnyPromise.h; sourceTree = ""; }; + 074AB602E0D52FDEFEAC391A71BE362C /* Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Extensions.swift; sourceTree = ""; }; + 076A25934936127AC03A2B855ACCDF5E /* NumberOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = NumberOnly.swift; sourceTree = ""; }; + 08BC2EAEE303ADCEB346C66DA76C7B56 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 09F0396C30B906DB9EFEFBE97E091406 /* FakeclassnametagsAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = FakeclassnametagsAPI.swift; sourceTree = ""; }; + 0A0A7AF3E4D82A790BC8A16BB4972FA7 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 0B4A4A4EB2DBD6F56B1383E53763FD1B /* PetstoreClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = PetstoreClient.framework; path = PetstoreClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 0B83848569669227892C0BF2A5CE1835 /* wrap.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = wrap.swift; path = Sources/wrap.swift; sourceTree = ""; }; + 0C11B4AA97BB6048B4FFD944AEE16E85 /* MapTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MapTest.swift; sourceTree = ""; }; + 0E0D7BCA2C0C3C6ABB215B192FE61633 /* hang.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = hang.m; path = Sources/hang.m; sourceTree = ""; }; + 10156F0F886EC2F50651B704A3A6D742 /* StoreAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = StoreAPI.swift; sourceTree = ""; }; + 1024470B7B0142DFF1DF7E009ED9260D /* AlamofireImplementations.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AlamofireImplementations.swift; sourceTree = ""; }; + 103847E55D2DB836C4726FD119FCFA4F /* DispatchQueue+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Promise.swift"; path = "Sources/DispatchQueue+Promise.swift"; sourceTree = ""; }; + 1194146F3B5CFFECFE93B4E1DBB369BA /* Configuration.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Configuration.swift; sourceTree = ""; }; + 1365D135EB77F78D4ED50CB4CEA2BA76 /* OuterBoolean.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterBoolean.swift; sourceTree = ""; }; + 14FA6FDDB70F2EFB58DE7D635F6946D4 /* APIHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIHelper.swift; sourceTree = ""; }; + 152E92E58DF288044CE0369CD8522B52 /* when.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = when.m; path = Sources/when.m; sourceTree = ""; }; + 16F53B93392AAECDF2A786BC34DEE42B /* race.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = race.swift; path = Sources/race.swift; sourceTree = ""; }; + 19B892C7CE6610E1CA2ADC23C7B1C5B9 /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; + 1DF0A17DD1DCF7B53BFC5E09C07C84B1 /* ReadOnlyFirst.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ReadOnlyFirst.swift; sourceTree = ""; }; + 1EA0E986221EEA08549F8CA73563FE27 /* when.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = when.swift; path = Sources/when.swift; sourceTree = ""; }; + 2141FBF0CC0A4A8349C016ECD4ABBEE2 /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.0.sdk/System/Library/Frameworks/QuartzCore.framework; sourceTree = DEVELOPER_DIR; }; + 2174DBFD409F34598A78447BBC01DB23 /* GlobalState.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GlobalState.m; path = Sources/GlobalState.m; sourceTree = ""; }; + 237AE2907A722F87C756BCE4EF772C4C /* Name.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Name.swift; sourceTree = ""; }; + 249B8C876D70EDBA1D831123AE8EE0F8 /* EnumArrays.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = EnumArrays.swift; sourceTree = ""; }; + 25616A3E91482393BFD64C92FE312F0E /* JSONEncodingHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = JSONEncodingHelper.swift; sourceTree = ""; }; + 26189A4CE9006C2C9BB1AAE144CB191F /* ApiResponse.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ApiResponse.swift; sourceTree = ""; }; + 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClient-dummy.m"; sourceTree = ""; }; + 2A1934708EF63D8175858BE77D4CC707 /* PMKAlertController.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PMKAlertController.swift; path = Extensions/UIKit/Sources/PMKAlertController.swift; sourceTree = ""; }; + 2A2DACCC87696D352D52090A939EE230 /* HasOnlyReadOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HasOnlyReadOnly.swift; sourceTree = ""; }; + 2ABF01CA3A8264BCD945D29D45416B97 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.0.sdk/System/Library/Frameworks/UIKit.framework; sourceTree = DEVELOPER_DIR; }; + 2AC757CC02124D5B17B6867095DBB70D /* SpecialModelName.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = SpecialModelName.swift; sourceTree = ""; }; + 2C877E250DAECFEE1CDABF476EF2B25C /* Models.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Models.swift; sourceTree = ""; }; + 2CD0480A6F4D769F6CE8B6BEC16F5CFE /* after.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = after.m; path = Sources/after.m; sourceTree = ""; }; + 2DE0CB8D9EE8A56D63B991586247B70A /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; + 2F0DEFA8B8F894D4BFC00D53E40611EC /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; + 2FF17440CCD2E1A69791A4AA23325AD5 /* Pods-SwaggerClient-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClient-acknowledgements.markdown"; sourceTree = ""; }; + 31D680492464F6D65F2FAFA3D645CFFC /* PromiseKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PromiseKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 3227553C2F6B960B53F2DADD2091E856 /* SessionManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionManager.swift; path = Source/SessionManager.swift; sourceTree = ""; }; + 333A9E9802CC9090A44946166799777F /* PromiseKit.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = PromiseKit.modulemap; sourceTree = ""; }; + 3BD1A4B33356A3CDF1DC77EE6C70D752 /* List.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = List.swift; sourceTree = ""; }; + 3BF219E6163D01FB1E793CA0AE97EF67 /* NSNotificationCenter+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSNotificationCenter+AnyPromise.m"; path = "Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.m"; sourceTree = ""; }; + 3C42CC2D632364C7CA8BB4857F2F9C6F /* Promise+Properties.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Properties.swift"; path = "Sources/Promise+Properties.swift"; sourceTree = ""; }; + 3DB83DEE18EB958220B42D26A726EA74 /* CALayer+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "CALayer+AnyPromise.h"; path = "Extensions/QuartzCore/Sources/CALayer+AnyPromise.h"; sourceTree = ""; }; + 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClient-umbrella.h"; sourceTree = ""; }; + 3F16B43ABD2C8CD4A311AA1AB3B6C02F /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 4199B3084AC46DC42D15500A1C964ECC /* EnumTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = EnumTest.swift; sourceTree = ""; }; + 43FC49AA70D3E2A84CAED9C37BE9C4B5 /* Pods-SwaggerClientTests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-frameworks.sh"; sourceTree = ""; }; + 44E7AE2E18EA6D3B341C419A4B2813F3 /* Animal.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Animal.swift; sourceTree = ""; }; + 4655B4C1707E9902435774C9B1981618 /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Sources/Error.swift; sourceTree = ""; }; + 46A00B403166BEF9EE215F6CB59BE9A6 /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_SwaggerClient.framework; path = "Pods-SwaggerClient.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PetstoreClient-dummy.m"; sourceTree = ""; }; + 475705EF39C1CD6FEAE0873C0353F9A7 /* PMKUIKit.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PMKUIKit.h; path = Extensions/UIKit/Sources/PMKUIKit.h; sourceTree = ""; }; + 475A72056C770A5978AB453E7DC5B3AE /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; + 4C1356040CC9A1CCCED79A1A510AF74E /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; + 4DD1AADF1F309F00ABA66EF864526D79 /* UIViewController+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIViewController+AnyPromise.m"; path = "Extensions/UIKit/Sources/UIViewController+AnyPromise.m"; sourceTree = ""; }; + 4E15893D6DA076F151391488D212E3FE /* afterlife.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = afterlife.swift; path = Extensions/Foundation/Sources/afterlife.swift; sourceTree = ""; }; + 4EE549F80BAFEF84BF212F0C315BC9BF /* MixedPropertiesAndAdditionalPropertiesClass.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MixedPropertiesAndAdditionalPropertiesClass.swift; sourceTree = ""; }; + 501CB163DE7B7F59F59C62C76F13A1E3 /* fwd.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = fwd.h; path = Sources/fwd.h; sourceTree = ""; }; + 51E0E750323BD31207928C6D05DBA443 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; + 53AFC29FAA23E6156D43BCDE6F4EFEF7 /* ArrayTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ArrayTest.swift; sourceTree = ""; }; + 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; + 56F57C400928D9344121036AC8E4220D /* Return.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Return.swift; sourceTree = ""; }; + 584464ED8CD0D083C3125CBCE3F07BA1 /* PMKQuartzCore.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PMKQuartzCore.h; path = Extensions/QuartzCore/Sources/PMKQuartzCore.h; sourceTree = ""; }; + 5F54BE613A3988D2B9B506E8E6BEE157 /* AdditionalPropertiesClass.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AdditionalPropertiesClass.swift; sourceTree = ""; }; + 607DB4D4E14EB20C4DE0C6BD2FA4A922 /* UIView+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIView+AnyPromise.m"; path = "Extensions/UIKit/Sources/UIView+AnyPromise.m"; sourceTree = ""; }; + 641D30DAD8B334C67D53DB9FE3E1156F /* TaskDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TaskDelegate.swift; path = Source/TaskDelegate.swift; sourceTree = ""; }; + 64849EF7FCD1A24F508478A6B82F15B4 /* join.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = join.m; path = Sources/join.m; sourceTree = ""; }; + 650FB90BA05FD8D3E51FE82393B780C8 /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; + 6815FAC9A7B1782239E161DEEF54357F /* FakeAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = FakeAPI.swift; sourceTree = ""; }; + 68757F29FA6F6C42DBA6342A3E62044D /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; + 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClientTests-dummy.m"; sourceTree = ""; }; + 688103EFA108516ADBACAFEF5DF33690 /* AnimalFarm.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AnimalFarm.swift; sourceTree = ""; }; + 69AAB5FB4A56193E40C41542AAAFD310 /* UIView+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIView+AnyPromise.h"; path = "Extensions/UIKit/Sources/UIView+AnyPromise.h"; sourceTree = ""; }; + 6B5E5BE3E3FECE0F54F54CE7C4EDBF6F /* NSTask+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSTask+AnyPromise.h"; path = "Extensions/Foundation/Sources/NSTask+AnyPromise.h"; sourceTree = ""; }; + 6C7ACDC625BF00A435AF4AB3554CDDF0 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; + 6D9891D7095BE60AF5240E9C34D72085 /* ArrayOfNumberOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ArrayOfNumberOnly.swift; sourceTree = ""; }; + 706B5E9B8BA544EE1CCA46D4A1F29216 /* AnyPromise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnyPromise.swift; path = Sources/AnyPromise.swift; sourceTree = ""; }; + 707A13EC65734755A4354861F095D56B /* URLDataPromise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = URLDataPromise.swift; path = Extensions/Foundation/Sources/URLDataPromise.swift; sourceTree = ""; }; + 749C03CC31823CCADA2EFFFD06BF9E98 /* OuterComposite.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterComposite.swift; sourceTree = ""; }; + 776D1D6E37D1EF4B16870DB0A90BD5B6 /* PromiseKit-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PromiseKit-prefix.pch"; sourceTree = ""; }; + 798454EC551811276A6837CFCD4ADC8A /* APIs.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIs.swift; sourceTree = ""; }; + 7A0B8917069F5E9591DD17A113737986 /* PetAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PetAPI.swift; sourceTree = ""; }; + 7B8FB736CDFAAADBDB70EA060535FFEB /* PromiseKit-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PromiseKit-dummy.m"; sourceTree = ""; }; + 7C8E63660D346FD8ED2A97242E74EA09 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 7CB03045DB10F7089377C70AF5B3F670 /* State.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = State.swift; path = Sources/State.swift; sourceTree = ""; }; + 7DEB18C435BF545F4290754BD12ACA89 /* NSNotificationCenter+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSNotificationCenter+AnyPromise.h"; path = "Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.h"; sourceTree = ""; }; + 81632F006BE1334AB9EE06329318FE60 /* ArrayOfArrayOfNumberOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ArrayOfArrayOfNumberOnly.swift; sourceTree = ""; }; + 827F697F6F7FF65D0850AF04A0CC3806 /* Zalgo.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Zalgo.swift; path = Sources/Zalgo.swift; sourceTree = ""; }; + 82CFB52B2B1C4E72218F01A4034E11C4 /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; + 83A7AB2A1DA3632E843B3336E8D41A8E /* User.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = User.swift; sourceTree = ""; }; + 8461ED3F533CF9C212A6A3F024CC8F5A /* UIView+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIView+Promise.swift"; path = "Extensions/UIKit/Sources/UIView+Promise.swift"; sourceTree = ""; }; + 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; + 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; + 86FB9D88F32EB25214615C461AC6C432 /* NSNotificationCenter+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSNotificationCenter+Promise.swift"; path = "Extensions/Foundation/Sources/NSNotificationCenter+Promise.swift"; sourceTree = ""; }; + 8A3C1EDF28A8B80DB140B65CDE450E09 /* Tag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Tag.swift; sourceTree = ""; }; + 8BBF3490280C4ED53738743F84C890BC /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_SwaggerClientTests.framework; path = "Pods-SwaggerClientTests.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + 8DD5A1187D47A6FFAC34F927DA186750 /* FormatTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = FormatTest.swift; sourceTree = ""; }; + 8E47C91B82D7EF2401C4A7D2DA4F7B72 /* UIViewController+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIViewController+Promise.swift"; path = "Extensions/UIKit/Sources/UIViewController+Promise.swift"; sourceTree = ""; }; + 8F07EB5B38222CE6DB8CC7EC894E9E73 /* JSONEncodableEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = JSONEncodableEncoding.swift; sourceTree = ""; }; + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 943618599D753D3CF9CEA416875D6417 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; + 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; + 975DAA5E04C557E1AA63DD67304C3466 /* Dog.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Dog.swift; sourceTree = ""; }; + 99A593C5CAA9E46E3EA8A5F0A3A5E892 /* NSURLSession+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSURLSession+AnyPromise.h"; path = "Extensions/Foundation/Sources/NSURLSession+AnyPromise.h"; sourceTree = ""; }; + 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-umbrella.h"; sourceTree = ""; }; + A1F75405F0BABFF928C6618F11B55DD2 /* PromiseKit.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PromiseKit.h; path = Sources/PromiseKit.h; sourceTree = ""; }; + A4AECF8B352819D57BE253B02387B58E /* SessionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDelegate.swift; path = Source/SessionDelegate.swift; sourceTree = ""; }; + A583E04FA44E6EB8B13CFBD3C4BC1016 /* NSTask+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSTask+AnyPromise.m"; path = "Extensions/Foundation/Sources/NSTask+AnyPromise.m"; sourceTree = ""; }; + AAC0733365F6A9BF565156D2FFA419ED /* Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Promise.swift; path = Sources/Promise.swift; sourceTree = ""; }; + AD3B511F5C43568AAFBA2714468F9FD5 /* PromiseKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = PromiseKit.framework; path = PromiseKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + B2D46CA33667445037B49DB2E4682861 /* PromiseKit-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PromiseKit-umbrella.h"; sourceTree = ""; }; + B3A144887C8B13FD888B76AB096B0CA1 /* PetstoreClient-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-prefix.pch"; sourceTree = ""; }; + BA71549EA391E3A6799E5E2083D51179 /* NSURLSession+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSURLSession+Promise.swift"; path = "Extensions/Foundation/Sources/NSURLSession+Promise.swift"; sourceTree = ""; }; + BAF01D809260F177266BCDEB5D85A6F4 /* CALayer+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "CALayer+AnyPromise.m"; path = "Extensions/QuartzCore/Sources/CALayer+AnyPromise.m"; sourceTree = ""; }; + BCF2D4DFF08D2A18E8C8FE4C4B4633FB /* Pods-SwaggerClient-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-frameworks.sh"; sourceTree = ""; }; + BE4C2705D4C3B913D44B4F26C6817A9C /* Capitalization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Capitalization.swift; sourceTree = ""; }; + BFD4C386443F3A9950AA00E1C6127C2B /* UIViewController+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIViewController+AnyPromise.h"; path = "Extensions/UIKit/Sources/UIViewController+AnyPromise.h"; sourceTree = ""; }; + C0C4B8ED879AE799525B69F4E8C51B1E /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = Alamofire.modulemap; sourceTree = ""; }; + C21C617FCA30726E782E8A67D0149138 /* Cat.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Cat.swift; sourceTree = ""; }; + C2A49053FD4226BD3513549F61A5944F /* OuterEnum.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterEnum.swift; sourceTree = ""; }; + C31B213B335DFB715738D846C9799EC8 /* PMKFoundation.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PMKFoundation.h; path = Extensions/Foundation/Sources/PMKFoundation.h; sourceTree = ""; }; + C387A09BFC4D29F2B2C308F55CD2BFB7 /* CodableHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CodableHelper.swift; sourceTree = ""; }; + C3DD4689CB744B566DA645A762474D50 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; + C82495B2E8EC7A268E3C9F068458102B /* Model200Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Model200Response.swift; sourceTree = ""; }; + C8F4E041B8F062D0E58498A365070ED8 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + CAFBFC23A6A4DB2974DAB9A6FADE9E11 /* Promise+AnyPromise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+AnyPromise.swift"; path = "Sources/Promise+AnyPromise.swift"; sourceTree = ""; }; + CC87361174534D6D1655DD60071A3D83 /* UserAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = UserAPI.swift; sourceTree = ""; }; + CF7474663A857DD4540585C7AABD1E42 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; + D2841E5E2183846280B97F6E660DA26C /* Pods-SwaggerClient-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-resources.sh"; sourceTree = ""; }; + D5021828D3563560F50658622F55322A /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; + D679EE988B8B8734D2AAAAAFD25CDB9B /* ClassModel.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ClassModel.swift; sourceTree = ""; }; + D6C0428DC253F416C26670E1A755E6C7 /* PromiseKit.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PromiseKit.xcconfig; sourceTree = ""; }; + DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PetstoreClient.xcconfig; sourceTree = ""; }; + DE081085EBFE0D670AAC85E74ACFDE8D /* Pet.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Pet.swift; sourceTree = ""; }; + DE164497A94DD3215ED4D1AE0D4703B1 /* Pods-SwaggerClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = "Pods-SwaggerClient.modulemap"; sourceTree = ""; }; + E1E4BCB344D3C100253B24B79421F00A /* Pods-SwaggerClient-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClient-acknowledgements.plist"; sourceTree = ""; }; + E2FCD5F3D2C6621D4355CACB49530DB3 /* Client.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Client.swift; sourceTree = ""; }; + E3D1141B63DF38660CD6F3AC588A782B /* PetstoreClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = PetstoreClient.modulemap; sourceTree = ""; }; + E470520443CDA5BBDA7D716E9AFEF14C /* NSURLSession+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSURLSession+AnyPromise.m"; path = "Extensions/Foundation/Sources/NSURLSession+AnyPromise.m"; sourceTree = ""; }; + E4E6F4A58FE7868CA2177D3AC79AD2FA /* Pods-SwaggerClientTests-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-resources.sh"; sourceTree = ""; }; + E6880118613493912D876F6EDAC620D3 /* NSObject+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSObject+Promise.swift"; path = "Extensions/Foundation/Sources/NSObject+Promise.swift"; sourceTree = ""; }; + E6E0984D5B0599817A4E48CBAE9AAB9A /* OuterNumber.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterNumber.swift; sourceTree = ""; }; + E80A16C989615AAE419866DB4FD10185 /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Alamofire.framework; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + E80F4034540947434A69B02246F8ABBD /* Order.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Order.swift; sourceTree = ""; }; + E92EF227AB7E7DD3F054096F5CC1A430 /* join.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = join.swift; path = Sources/join.swift; sourceTree = ""; }; + EA8F6D8048F257672069D2008983C66D /* OuterString.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterString.swift; sourceTree = ""; }; + F05F43847135C8DA403312FBEDB1F49F /* after.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = after.swift; path = Sources/after.swift; sourceTree = ""; }; + F0D4E00A8974E74325E9E53D456F9AD4 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + F20826EF67AE5149D903E774F67507DD /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; + F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClientTests-umbrella.h"; sourceTree = ""; }; + F35E3788DA69834B7CF86EC61FEB453C /* AFError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AFError.swift; path = Source/AFError.swift; sourceTree = ""; }; + F53D6FE99858297507D97FCDF5F0F461 /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + F57895C0FD129E4ACA6D2DF8C5C960BC /* dispatch_promise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = dispatch_promise.m; path = Sources/dispatch_promise.m; sourceTree = ""; }; + F69BC1C993ED1722CE6D63E07381785E /* Category.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Category.swift; sourceTree = ""; }; + F738520F03FD7B756BB4DF21CF3DF1DC /* Timeline.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeline.swift; path = Source/Timeline.swift; sourceTree = ""; }; + F7C414EFC68CF0C5DB0E5D9E33863B44 /* DispatchQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Alamofire.swift"; path = "Source/DispatchQueue+Alamofire.swift"; sourceTree = ""; }; + FB170EFD14935F121CDE3211DB4C5CA3 /* Pods-SwaggerClientTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClientTests-acknowledgements.markdown"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 1D8C8B25D2467630E50174D221B39B90 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + C0C4450B687C7F4706A5E8ADD7826A85 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4B4E3FA81CA094AF6C75A1E6C915869B /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + C0D858800E557D0A38D2E61CB98523F3 /* Foundation.framework in Frameworks */, + 30B8557D047D60B5F8332BCE95DD693E /* QuartzCore.framework in Frameworks */, + EB1F02E78667DE59E495E496FFEFC8CB /* UIKit.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 87AF7EC7404199AC8C5D22375A6059BF /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + D32130A2C8AC5B1FF21AF43BCC2B5217 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 99195E4207764744AEC07ECCBCD550EB /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + A04BFC558D69E7DBB68023C80A9CFE4E /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + D6F457FE461B17076A16F6175AFC7647 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + B2CF10965316B20D0BB59BDEC2AB0131 /* Alamofire.framework in Frameworks */, + FC3CD5AA2DA8A499EB23571E14325F13 /* Foundation.framework in Frameworks */, + F4FD458A3DA6D643C08F837463C11B79 /* PromiseKit.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 02E57F930C8EDC9AD0C9932B5CAD1DC8 /* Classes */ = { + isa = PBXGroup; + children = ( + 6D8231D013B59DBC75D89B4D4FC1781D /* Swaggers */, + ); + name = Classes; + path = Classes; + sourceTree = ""; + }; + 07B4ADF8C410B092809517B0BAB36E30 /* Foundation */ = { + isa = PBXGroup; + children = ( + 4E15893D6DA076F151391488D212E3FE /* afterlife.swift */, + 7DEB18C435BF545F4290754BD12ACA89 /* NSNotificationCenter+AnyPromise.h */, + 3BF219E6163D01FB1E793CA0AE97EF67 /* NSNotificationCenter+AnyPromise.m */, + 86FB9D88F32EB25214615C461AC6C432 /* NSNotificationCenter+Promise.swift */, + E6880118613493912D876F6EDAC620D3 /* NSObject+Promise.swift */, + 6B5E5BE3E3FECE0F54F54CE7C4EDBF6F /* NSTask+AnyPromise.h */, + A583E04FA44E6EB8B13CFBD3C4BC1016 /* NSTask+AnyPromise.m */, + 99A593C5CAA9E46E3EA8A5F0A3A5E892 /* NSURLSession+AnyPromise.h */, + E470520443CDA5BBDA7D716E9AFEF14C /* NSURLSession+AnyPromise.m */, + BA71549EA391E3A6799E5E2083D51179 /* NSURLSession+Promise.swift */, + C31B213B335DFB715738D846C9799EC8 /* PMKFoundation.h */, + 06FB2C2C487F62C8E234E5F309EE50EE /* Process+Promise.swift */, + 707A13EC65734755A4354861F095D56B /* URLDataPromise.swift */, + ); + name = Foundation; + sourceTree = ""; + }; + 22F52349E1BE90FC6E064DAAC9EA9612 /* Development Pods */ = { + isa = PBXGroup; + children = ( + E9F8459055B900A58FB97600A53E5D1C /* PetstoreClient */, + ); + name = "Development Pods"; + sourceTree = ""; + }; + 27454559852AC8B9DDF3F084C1E09F22 /* PromiseKit */ = { + isa = PBXGroup; + children = ( + 6B8BED723E1865D5B9F1AC8B17FF7035 /* CorePromise */, + 07B4ADF8C410B092809517B0BAB36E30 /* Foundation */, + ADEB788C7842BDA6F8D266DFB6B6D00D /* QuartzCore */, + 8349D367FE0957C4AFA12D8CA5EA5B44 /* Support Files */, + 4C35F42FA9EA91ABFFA7ECEDDFB2E61A /* UIKit */, + ); + name = PromiseKit; + path = PromiseKit; + sourceTree = ""; + }; + 470B2EC4B502506F1DCAE0EE7E194226 /* Support Files */ = { + isa = PBXGroup; + children = ( + C0C4B8ED879AE799525B69F4E8C51B1E /* Alamofire.modulemap */, + 650FB90BA05FD8D3E51FE82393B780C8 /* Alamofire.xcconfig */, + F20826EF67AE5149D903E774F67507DD /* Alamofire-dummy.m */, + 4C1356040CC9A1CCCED79A1A510AF74E /* Alamofire-prefix.pch */, + 6C7ACDC625BF00A435AF4AB3554CDDF0 /* Alamofire-umbrella.h */, + 0A0A7AF3E4D82A790BC8A16BB4972FA7 /* Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/Alamofire"; + sourceTree = ""; + }; + 4C35F42FA9EA91ABFFA7ECEDDFB2E61A /* UIKit */ = { + isa = PBXGroup; + children = ( + 2A1934708EF63D8175858BE77D4CC707 /* PMKAlertController.swift */, + 475705EF39C1CD6FEAE0873C0353F9A7 /* PMKUIKit.h */, + 69AAB5FB4A56193E40C41542AAAFD310 /* UIView+AnyPromise.h */, + 607DB4D4E14EB20C4DE0C6BD2FA4A922 /* UIView+AnyPromise.m */, + 8461ED3F533CF9C212A6A3F024CC8F5A /* UIView+Promise.swift */, + BFD4C386443F3A9950AA00E1C6127C2B /* UIViewController+AnyPromise.h */, + 4DD1AADF1F309F00ABA66EF864526D79 /* UIViewController+AnyPromise.m */, + 8E47C91B82D7EF2401C4A7D2DA4F7B72 /* UIViewController+Promise.swift */, + ); + name = UIKit; + sourceTree = ""; + }; + 6B8BED723E1865D5B9F1AC8B17FF7035 /* CorePromise */ = { + isa = PBXGroup; + children = ( + 2CD0480A6F4D769F6CE8B6BEC16F5CFE /* after.m */, + F05F43847135C8DA403312FBEDB1F49F /* after.swift */, + 0720785FA765917D0C03A126E07CB2C5 /* AnyPromise.h */, + 0296C2154D0CAB4EE1AF3AD456C7207F /* AnyPromise.m */, + 706B5E9B8BA544EE1CCA46D4A1F29216 /* AnyPromise.swift */, + F57895C0FD129E4ACA6D2DF8C5C960BC /* dispatch_promise.m */, + 103847E55D2DB836C4726FD119FCFA4F /* DispatchQueue+Promise.swift */, + 4655B4C1707E9902435774C9B1981618 /* Error.swift */, + 501CB163DE7B7F59F59C62C76F13A1E3 /* fwd.h */, + 2174DBFD409F34598A78447BBC01DB23 /* GlobalState.m */, + 0E0D7BCA2C0C3C6ABB215B192FE61633 /* hang.m */, + 64849EF7FCD1A24F508478A6B82F15B4 /* join.m */, + E92EF227AB7E7DD3F054096F5CC1A430 /* join.swift */, + AAC0733365F6A9BF565156D2FFA419ED /* Promise.swift */, + CAFBFC23A6A4DB2974DAB9A6FADE9E11 /* Promise+AnyPromise.swift */, + 3C42CC2D632364C7CA8BB4857F2F9C6F /* Promise+Properties.swift */, + A1F75405F0BABFF928C6618F11B55DD2 /* PromiseKit.h */, + 16F53B93392AAECDF2A786BC34DEE42B /* race.swift */, + 7CB03045DB10F7089377C70AF5B3F670 /* State.swift */, + 152E92E58DF288044CE0369CD8522B52 /* when.m */, + 1EA0E986221EEA08549F8CA73563FE27 /* when.swift */, + 0B83848569669227892C0BF2A5CE1835 /* wrap.swift */, + 827F697F6F7FF65D0850AF04A0CC3806 /* Zalgo.swift */, + ); + name = CorePromise; + sourceTree = ""; + }; + 6D8231D013B59DBC75D89B4D4FC1781D /* Swaggers */ = { + isa = PBXGroup; + children = ( + 1024470B7B0142DFF1DF7E009ED9260D /* AlamofireImplementations.swift */, + 14FA6FDDB70F2EFB58DE7D635F6946D4 /* APIHelper.swift */, + 798454EC551811276A6837CFCD4ADC8A /* APIs.swift */, + C387A09BFC4D29F2B2C308F55CD2BFB7 /* CodableHelper.swift */, + 1194146F3B5CFFECFE93B4E1DBB369BA /* Configuration.swift */, + 074AB602E0D52FDEFEAC391A71BE362C /* Extensions.swift */, + 8F07EB5B38222CE6DB8CC7EC894E9E73 /* JSONEncodableEncoding.swift */, + 25616A3E91482393BFD64C92FE312F0E /* JSONEncodingHelper.swift */, + 2C877E250DAECFEE1CDABF476EF2B25C /* Models.swift */, + 79B0B5EF51D76393D11143FD83D1F224 /* APIs */, + BDF2B05EE3EDF246153D7BDD1A3D065A /* Models */, + ); + name = Swaggers; + path = Swaggers; + sourceTree = ""; + }; + 79B0B5EF51D76393D11143FD83D1F224 /* APIs */ = { + isa = PBXGroup; + children = ( + 6815FAC9A7B1782239E161DEEF54357F /* FakeAPI.swift */, + 09F0396C30B906DB9EFEFBE97E091406 /* FakeclassnametagsAPI.swift */, + 7A0B8917069F5E9591DD17A113737986 /* PetAPI.swift */, + 10156F0F886EC2F50651B704A3A6D742 /* StoreAPI.swift */, + CC87361174534D6D1655DD60071A3D83 /* UserAPI.swift */, + ); + name = APIs; + path = APIs; + sourceTree = ""; + }; + 7DB346D0F39D3F0E887471402A8071AB = { + isa = PBXGroup; + children = ( + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, + 22F52349E1BE90FC6E064DAAC9EA9612 /* Development Pods */, + E1A132DCFF79A96DE3636D6C3ED161C5 /* Frameworks */, + E3012ACC12C4AE1521338E1834D7BDF0 /* Pods */, + D2A28169658A67F83CC3B568D7E0E6A1 /* Products */, + C1A60D10CED0E61146591438999C7502 /* Targets Support Files */, + ); + sourceTree = ""; + }; + 8349D367FE0957C4AFA12D8CA5EA5B44 /* Support Files */ = { + isa = PBXGroup; + children = ( + 08BC2EAEE303ADCEB346C66DA76C7B56 /* Info.plist */, + 333A9E9802CC9090A44946166799777F /* PromiseKit.modulemap */, + D6C0428DC253F416C26670E1A755E6C7 /* PromiseKit.xcconfig */, + 7B8FB736CDFAAADBDB70EA060535FFEB /* PromiseKit-dummy.m */, + 776D1D6E37D1EF4B16870DB0A90BD5B6 /* PromiseKit-prefix.pch */, + B2D46CA33667445037B49DB2E4682861 /* PromiseKit-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/PromiseKit"; + sourceTree = ""; + }; + 88CE2B3F08C34DDB098AD8A5DCC1DF1E /* Pods-SwaggerClient */ = { + isa = PBXGroup; + children = ( + 7C8E63660D346FD8ED2A97242E74EA09 /* Info.plist */, + DE164497A94DD3215ED4D1AE0D4703B1 /* Pods-SwaggerClient.modulemap */, + 2FF17440CCD2E1A69791A4AA23325AD5 /* Pods-SwaggerClient-acknowledgements.markdown */, + E1E4BCB344D3C100253B24B79421F00A /* Pods-SwaggerClient-acknowledgements.plist */, + 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */, + BCF2D4DFF08D2A18E8C8FE4C4B4633FB /* Pods-SwaggerClient-frameworks.sh */, + D2841E5E2183846280B97F6E660DA26C /* Pods-SwaggerClient-resources.sh */, + 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */, + 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */, + 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */, + ); + name = "Pods-SwaggerClient"; + path = "Target Support Files/Pods-SwaggerClient"; + sourceTree = ""; + }; + 8D4D0246A623990315CCCFC95C6D7152 /* iOS */ = { + isa = PBXGroup; + children = ( + C8F4E041B8F062D0E58498A365070ED8 /* Foundation.framework */, + 2141FBF0CC0A4A8349C016ECD4ABBEE2 /* QuartzCore.framework */, + 2ABF01CA3A8264BCD945D29D45416B97 /* UIKit.framework */, + ); + name = iOS; + sourceTree = ""; + }; + 8F6D133867EE63820DFB7E83F4C51252 /* Support Files */ = { + isa = PBXGroup; + children = ( + F0D4E00A8974E74325E9E53D456F9AD4 /* Info.plist */, + E3D1141B63DF38660CD6F3AC588A782B /* PetstoreClient.modulemap */, + DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */, + 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */, + B3A144887C8B13FD888B76AB096B0CA1 /* PetstoreClient-prefix.pch */, + 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */, + ); + name = "Support Files"; + path = "SwaggerClientTests/Pods/Target Support Files/PetstoreClient"; + sourceTree = ""; + }; + ADEB788C7842BDA6F8D266DFB6B6D00D /* QuartzCore */ = { + isa = PBXGroup; + children = ( + 3DB83DEE18EB958220B42D26A726EA74 /* CALayer+AnyPromise.h */, + BAF01D809260F177266BCDEB5D85A6F4 /* CALayer+AnyPromise.m */, + 584464ED8CD0D083C3125CBCE3F07BA1 /* PMKQuartzCore.h */, + ); + name = QuartzCore; + sourceTree = ""; + }; + BDF2B05EE3EDF246153D7BDD1A3D065A /* Models */ = { + isa = PBXGroup; + children = ( + 5F54BE613A3988D2B9B506E8E6BEE157 /* AdditionalPropertiesClass.swift */, + 44E7AE2E18EA6D3B341C419A4B2813F3 /* Animal.swift */, + 688103EFA108516ADBACAFEF5DF33690 /* AnimalFarm.swift */, + 26189A4CE9006C2C9BB1AAE144CB191F /* ApiResponse.swift */, + 81632F006BE1334AB9EE06329318FE60 /* ArrayOfArrayOfNumberOnly.swift */, + 6D9891D7095BE60AF5240E9C34D72085 /* ArrayOfNumberOnly.swift */, + 53AFC29FAA23E6156D43BCDE6F4EFEF7 /* ArrayTest.swift */, + BE4C2705D4C3B913D44B4F26C6817A9C /* Capitalization.swift */, + C21C617FCA30726E782E8A67D0149138 /* Cat.swift */, + F69BC1C993ED1722CE6D63E07381785E /* Category.swift */, + D679EE988B8B8734D2AAAAAFD25CDB9B /* ClassModel.swift */, + E2FCD5F3D2C6621D4355CACB49530DB3 /* Client.swift */, + 975DAA5E04C557E1AA63DD67304C3466 /* Dog.swift */, + 249B8C876D70EDBA1D831123AE8EE0F8 /* EnumArrays.swift */, + 03597C306A2FB3B657BCFF572F74F4D4 /* EnumClass.swift */, + 4199B3084AC46DC42D15500A1C964ECC /* EnumTest.swift */, + 8DD5A1187D47A6FFAC34F927DA186750 /* FormatTest.swift */, + 2A2DACCC87696D352D52090A939EE230 /* HasOnlyReadOnly.swift */, + 3BD1A4B33356A3CDF1DC77EE6C70D752 /* List.swift */, + 0C11B4AA97BB6048B4FFD944AEE16E85 /* MapTest.swift */, + 4EE549F80BAFEF84BF212F0C315BC9BF /* MixedPropertiesAndAdditionalPropertiesClass.swift */, + C82495B2E8EC7A268E3C9F068458102B /* Model200Response.swift */, + 237AE2907A722F87C756BCE4EF772C4C /* Name.swift */, + 076A25934936127AC03A2B855ACCDF5E /* NumberOnly.swift */, + E80F4034540947434A69B02246F8ABBD /* Order.swift */, + 1365D135EB77F78D4ED50CB4CEA2BA76 /* OuterBoolean.swift */, + 749C03CC31823CCADA2EFFFD06BF9E98 /* OuterComposite.swift */, + C2A49053FD4226BD3513549F61A5944F /* OuterEnum.swift */, + E6E0984D5B0599817A4E48CBAE9AAB9A /* OuterNumber.swift */, + EA8F6D8048F257672069D2008983C66D /* OuterString.swift */, + DE081085EBFE0D670AAC85E74ACFDE8D /* Pet.swift */, + 1DF0A17DD1DCF7B53BFC5E09C07C84B1 /* ReadOnlyFirst.swift */, + 56F57C400928D9344121036AC8E4220D /* Return.swift */, + 2AC757CC02124D5B17B6867095DBB70D /* SpecialModelName.swift */, + 8A3C1EDF28A8B80DB140B65CDE450E09 /* Tag.swift */, + 83A7AB2A1DA3632E843B3336E8D41A8E /* User.swift */, + ); + name = Models; + path = Models; + sourceTree = ""; + }; + C1A60D10CED0E61146591438999C7502 /* Targets Support Files */ = { + isa = PBXGroup; + children = ( + 88CE2B3F08C34DDB098AD8A5DCC1DF1E /* Pods-SwaggerClient */, + D6D0CD30E3EAF2ED10AE0CBC07506C5A /* Pods-SwaggerClientTests */, + ); + name = "Targets Support Files"; + sourceTree = ""; + }; + D2A28169658A67F83CC3B568D7E0E6A1 /* Products */ = { + isa = PBXGroup; + children = ( + E80A16C989615AAE419866DB4FD10185 /* Alamofire.framework */, + 0B4A4A4EB2DBD6F56B1383E53763FD1B /* PetstoreClient.framework */, + 46A00B403166BEF9EE215F6CB59BE9A6 /* Pods_SwaggerClient.framework */, + 8BBF3490280C4ED53738743F84C890BC /* Pods_SwaggerClientTests.framework */, + AD3B511F5C43568AAFBA2714468F9FD5 /* PromiseKit.framework */, + ); + name = Products; + sourceTree = ""; + }; + D630949B04477DB25A8CE685790D41CD /* Alamofire */ = { + isa = PBXGroup; + children = ( + F35E3788DA69834B7CF86EC61FEB453C /* AFError.swift */, + C3DD4689CB744B566DA645A762474D50 /* Alamofire.swift */, + F7C414EFC68CF0C5DB0E5D9E33863B44 /* DispatchQueue+Alamofire.swift */, + CF7474663A857DD4540585C7AABD1E42 /* MultipartFormData.swift */, + 68757F29FA6F6C42DBA6342A3E62044D /* NetworkReachabilityManager.swift */, + 2DE0CB8D9EE8A56D63B991586247B70A /* Notifications.swift */, + 51E0E750323BD31207928C6D05DBA443 /* ParameterEncoding.swift */, + 2F0DEFA8B8F894D4BFC00D53E40611EC /* Request.swift */, + D5021828D3563560F50658622F55322A /* Response.swift */, + 82CFB52B2B1C4E72218F01A4034E11C4 /* ResponseSerialization.swift */, + 475A72056C770A5978AB453E7DC5B3AE /* Result.swift */, + 19B892C7CE6610E1CA2ADC23C7B1C5B9 /* ServerTrustPolicy.swift */, + A4AECF8B352819D57BE253B02387B58E /* SessionDelegate.swift */, + 3227553C2F6B960B53F2DADD2091E856 /* SessionManager.swift */, + 641D30DAD8B334C67D53DB9FE3E1156F /* TaskDelegate.swift */, + F738520F03FD7B756BB4DF21CF3DF1DC /* Timeline.swift */, + 943618599D753D3CF9CEA416875D6417 /* Validation.swift */, + 470B2EC4B502506F1DCAE0EE7E194226 /* Support Files */, + ); + name = Alamofire; + path = Alamofire; + sourceTree = ""; + }; + D6D0CD30E3EAF2ED10AE0CBC07506C5A /* Pods-SwaggerClientTests */ = { + isa = PBXGroup; + children = ( + 3F16B43ABD2C8CD4A311AA1AB3B6C02F /* Info.plist */, + 00ACB4396DD1B4E4539E4E81C1D7A14E /* Pods-SwaggerClientTests.modulemap */, + FB170EFD14935F121CDE3211DB4C5CA3 /* Pods-SwaggerClientTests-acknowledgements.markdown */, + 02F28E719AA874BE9213D6CF8CE7E36B /* Pods-SwaggerClientTests-acknowledgements.plist */, + 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */, + 43FC49AA70D3E2A84CAED9C37BE9C4B5 /* Pods-SwaggerClientTests-frameworks.sh */, + E4E6F4A58FE7868CA2177D3AC79AD2FA /* Pods-SwaggerClientTests-resources.sh */, + F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */, + 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */, + 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */, + ); + name = "Pods-SwaggerClientTests"; + path = "Target Support Files/Pods-SwaggerClientTests"; + sourceTree = ""; + }; + E1A132DCFF79A96DE3636D6C3ED161C5 /* Frameworks */ = { + isa = PBXGroup; + children = ( + F53D6FE99858297507D97FCDF5F0F461 /* Alamofire.framework */, + 31D680492464F6D65F2FAFA3D645CFFC /* PromiseKit.framework */, + 8D4D0246A623990315CCCFC95C6D7152 /* iOS */, + ); + name = Frameworks; + sourceTree = ""; + }; + E3012ACC12C4AE1521338E1834D7BDF0 /* Pods */ = { + isa = PBXGroup; + children = ( + D630949B04477DB25A8CE685790D41CD /* Alamofire */, + 27454559852AC8B9DDF3F084C1E09F22 /* PromiseKit */, + ); + name = Pods; + sourceTree = ""; + }; + E73D9BF152C59F341559DE62A3143721 /* PetstoreClient */ = { + isa = PBXGroup; + children = ( + 02E57F930C8EDC9AD0C9932B5CAD1DC8 /* Classes */, + ); + name = PetstoreClient; + path = PetstoreClient; + sourceTree = ""; + }; + E9F8459055B900A58FB97600A53E5D1C /* PetstoreClient */ = { + isa = PBXGroup; + children = ( + E73D9BF152C59F341559DE62A3143721 /* PetstoreClient */, + 8F6D133867EE63820DFB7E83F4C51252 /* Support Files */, + ); + name = PetstoreClient; + path = ../..; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 1353AC7A6419F876B294A55E5550D1E4 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 31F8B86E3672D0B828B6352C875649C4 /* Pods-SwaggerClientTests-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 8C605DB733F0B4EC31CC50556BD08B92 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + B0D0A8D9EB7248222E444C3004709BB4 /* PetstoreClient-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A99DB1B2B8050CD5EEC454140260FB13 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 173A377B378B75AADE06A397128BC8AB /* AnyPromise.h in Headers */, + 3F034997ED7849F2C6CC86D5B8C50BC1 /* CALayer+AnyPromise.h in Headers */, + 825645C19A9BDB1D138D5DFDF69C143A /* fwd.h in Headers */, + 81DF78F6697313B98D66D012475E8067 /* NSNotificationCenter+AnyPromise.h in Headers */, + BFAD00B3B746E0E08E9155FF4E84F24A /* NSTask+AnyPromise.h in Headers */, + 1D3E8E496572E1D4244811D5A3973171 /* NSURLSession+AnyPromise.h in Headers */, + 53A8D9F8E089D32918F3A5843ADDC26A /* PMKFoundation.h in Headers */, + C9D7613956EB06CD6E42B97ABEC9B673 /* PMKQuartzCore.h in Headers */, + ADF417E7FD14C452F475C4328B1661C3 /* PMKUIKit.h in Headers */, + 1FB6E55D4CD4F11D4D7C8722E8C33A42 /* PromiseKit-umbrella.h in Headers */, + 5765C7B9F6084011161DA2267C2A0B57 /* PromiseKit.h in Headers */, + 1B50D83C35A942533A18AA3AF0A80421 /* UIView+AnyPromise.h in Headers */, + 003F98B2C041FC1DE84490CDB4598F89 /* UIViewController+AnyPromise.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + AEF06A413F97A6E5233398FAC3F25335 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 20E2CC1FD887EC3DA74724A32DDA1132 /* Pods-SwaggerClient-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + B4002B6E97835FDCCAA5963EFE09A3E0 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 1B9EDEDC964E6B08F78920B4F4B9DB84 /* Alamofire-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */ = { + isa = PBXNativeTarget; + buildConfigurationList = 419E5D95491847CD79841B971A8A3277 /* Build configuration list for PBXNativeTarget "Alamofire" */; + buildPhases = ( + 32B9974868188C4803318E36329C87FE /* Sources */, + 99195E4207764744AEC07ECCBCD550EB /* Frameworks */, + B4002B6E97835FDCCAA5963EFE09A3E0 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Alamofire; + productName = Alamofire; + productReference = E80A16C989615AAE419866DB4FD10185 /* Alamofire.framework */; + productType = "com.apple.product-type.framework"; + }; + C7C5ED0DB8AF8EA86EC1631F79346F2C /* PromiseKit */ = { + isa = PBXNativeTarget; + buildConfigurationList = 02482B3666DC12E2ABD164F8C86F2B54 /* Build configuration list for PBXNativeTarget "PromiseKit" */; + buildPhases = ( + F11C32C4518B2E95254C966B5EC111FA /* Sources */, + 4B4E3FA81CA094AF6C75A1E6C915869B /* Frameworks */, + A99DB1B2B8050CD5EEC454140260FB13 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = PromiseKit; + productName = PromiseKit; + productReference = AD3B511F5C43568AAFBA2714468F9FD5 /* PromiseKit.framework */; + productType = "com.apple.product-type.framework"; + }; + CD79A5D6FCA04E079B656EC73E0CF0A9 /* PetstoreClient */ = { + isa = PBXNativeTarget; + buildConfigurationList = B1A4CABC9A5EAB96E49E2FD508880661 /* Build configuration list for PBXNativeTarget "PetstoreClient" */; + buildPhases = ( + BC392AC4415A71BAD9D8AAC1DCE30B0E /* Sources */, + D6F457FE461B17076A16F6175AFC7647 /* Frameworks */, + 8C605DB733F0B4EC31CC50556BD08B92 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + 1EDC13795DA36DC88CF1A4EB19B00C27 /* PBXTargetDependency */, + F49B4E5A7446788D16D901B71DE002E8 /* PBXTargetDependency */, + ); + name = PetstoreClient; + productName = PetstoreClient; + productReference = 0B4A4A4EB2DBD6F56B1383E53763FD1B /* PetstoreClient.framework */; + productType = "com.apple.product-type.framework"; + }; + E5B96E99C219DDBC57BC27EE9DF5EC22 /* Pods-SwaggerClient */ = { + isa = PBXNativeTarget; + buildConfigurationList = 607382BCFF2B60BA932C95EC3C22A69F /* Build configuration list for PBXNativeTarget "Pods-SwaggerClient" */; + buildPhases = ( + FA262994DA85648A45EB39519AF3D0E3 /* Sources */, + 1D8C8B25D2467630E50174D221B39B90 /* Frameworks */, + AEF06A413F97A6E5233398FAC3F25335 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + 1C76F9E08AAB9400CF7937D3DBF4E272 /* PBXTargetDependency */, + 405120CD9D9120CBBC452E54C91FA485 /* PBXTargetDependency */, + 328C6C7DF03199CFF8F5B47C39DEE2BC /* PBXTargetDependency */, + ); + name = "Pods-SwaggerClient"; + productName = "Pods-SwaggerClient"; + productReference = 46A00B403166BEF9EE215F6CB59BE9A6 /* Pods_SwaggerClient.framework */; + productType = "com.apple.product-type.framework"; + }; + F3DF8DD6DBDCB07B04D7B1CC8A462562 /* Pods-SwaggerClientTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = B462F7329881FF6565EF44016BE2B959 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClientTests" */; + buildPhases = ( + BDFDEE831A91E115AA482B4E9E9B5CC8 /* Sources */, + 87AF7EC7404199AC8C5D22375A6059BF /* Frameworks */, + 1353AC7A6419F876B294A55E5550D1E4 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "Pods-SwaggerClientTests"; + productName = "Pods-SwaggerClientTests"; + productReference = 8BBF3490280C4ED53738743F84C890BC /* Pods_SwaggerClientTests.framework */; + productType = "com.apple.product-type.framework"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + D41D8CD98F00B204E9800998ECF8427E /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0730; + LastUpgradeCheck = 0700; + }; + buildConfigurationList = 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = 7DB346D0F39D3F0E887471402A8071AB; + productRefGroup = D2A28169658A67F83CC3B568D7E0E6A1 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */, + CD79A5D6FCA04E079B656EC73E0CF0A9 /* PetstoreClient */, + E5B96E99C219DDBC57BC27EE9DF5EC22 /* Pods-SwaggerClient */, + F3DF8DD6DBDCB07B04D7B1CC8A462562 /* Pods-SwaggerClientTests */, + C7C5ED0DB8AF8EA86EC1631F79346F2C /* PromiseKit */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXSourcesBuildPhase section */ + 32B9974868188C4803318E36329C87FE /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 9ED2BB2981896E0A39EFA365503F58CE /* AFError.swift in Sources */, + A9EEEA7477981DEEBC72432DE9990A4B /* Alamofire-dummy.m in Sources */, + F8B3D3092ED0417E8CDF32033F6122F5 /* Alamofire.swift in Sources */, + 61200D01A1855D7920CEF835C8BE00B0 /* DispatchQueue+Alamofire.swift in Sources */, + B65FCF589DA398C3EFE0128064E510EC /* MultipartFormData.swift in Sources */, + A2A6F71B727312BD45CC7A4AAD7B0AB7 /* NetworkReachabilityManager.swift in Sources */, + EFD264FC408EBF3BA2528E70B08DDD94 /* Notifications.swift in Sources */, + BE5C67A07E289FE1F9BE27335B159997 /* ParameterEncoding.swift in Sources */, + 5387216E723A3C68E851CA15573CDD71 /* Request.swift in Sources */, + CB6D60925223897FFA2662667DF83E8A /* Response.swift in Sources */, + F6BECD98B97CBFEBE2C96F0E9E72A6C0 /* ResponseSerialization.swift in Sources */, + 7D8CC01E8C9EFFF9F4D65406CDE0AB66 /* Result.swift in Sources */, + 62F65AD8DC4F0F9610F4B8B4738EC094 /* ServerTrustPolicy.swift in Sources */, + 7B5FE28C7EA4122B0598738E54DBEBD8 /* SessionDelegate.swift in Sources */, + AE1EF48399533730D0066E04B22CA2D6 /* SessionManager.swift in Sources */, + 3626B94094672CB1C9DEA32B9F9502E1 /* TaskDelegate.swift in Sources */, + 10EB23E9ECC4B33E16933BB1EA560B6A /* Timeline.swift in Sources */, + BBEFE2F9CEB73DC7BD97FFA66A0D9D4F /* Validation.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + BC392AC4415A71BAD9D8AAC1DCE30B0E /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 14FA5791C21B38B5D90017F182AA77C6 /* AdditionalPropertiesClass.swift in Sources */, + 0000257E6138186889F38B8A7F797C33 /* AlamofireImplementations.swift in Sources */, + A81AD325D55AF5D8972809300D8F36E5 /* Animal.swift in Sources */, + 622B5DBF5E128A33315BE8EFF05792EA /* AnimalFarm.swift in Sources */, + 578E746892610EA4B83D264A05D6FC60 /* APIHelper.swift in Sources */, + 5D63858F4E9812FAAF772FFDCB4ACE45 /* ApiResponse.swift in Sources */, + A22E02C8FB1A44C7AAFED7E121904807 /* APIs.swift in Sources */, + 109135A9E832B6E00D3258B9A7A95D2E /* ArrayOfArrayOfNumberOnly.swift in Sources */, + E59910F3BA3F43E74B24DC9AE4612B88 /* ArrayOfNumberOnly.swift in Sources */, + 3DAA524BB89E475536B71207F5F2C0F5 /* ArrayTest.swift in Sources */, + C80991D67ADACC9C48704248AC151933 /* Capitalization.swift in Sources */, + DC594EF39ADAFC9B59E1DE1A9BE58D97 /* Cat.swift in Sources */, + 6A47436E31CAD703E4ABB641F80FC7DF /* Category.swift in Sources */, + F45D65E76C21F99D26C25A71AE5566DD /* ClassModel.swift in Sources */, + 22980ADB7D228364F99E8EA145509B4F /* Client.swift in Sources */, + D67D0F8EB46ED3C4256F87DF09186EEA /* CodableHelper.swift in Sources */, + BC1063342B57CB4A07D50F277CAC4783 /* Configuration.swift in Sources */, + 7E40C3A7DBC7306738AC9E27C734C25E /* Dog.swift in Sources */, + 032C9FCA8EA6C8553275B1F7641A1CD8 /* EnumArrays.swift in Sources */, + 3064A0BD79720BAD39B0F3ECD5C93FFA /* EnumClass.swift in Sources */, + 545C5A303A209C2C009E242F9D310001 /* EnumTest.swift in Sources */, + C764F495BF6DFEBE52AFD13FDFB8E77F /* Extensions.swift in Sources */, + 4E482819CF1AD28A5960095805A803ED /* FakeAPI.swift in Sources */, + 5909B4BACAF8557FE13B325FA529BE57 /* FakeclassnametagsAPI.swift in Sources */, + 0298FFF35BEF4948A42E55756D7C81A8 /* FormatTest.swift in Sources */, + 6FA5895264E0223B0A016644C59C6046 /* HasOnlyReadOnly.swift in Sources */, + AB0054D02002325BD7DF0BE3FD742D9C /* JSONEncodableEncoding.swift in Sources */, + 7E60F24604C0F467F63D451E410390D8 /* JSONEncodingHelper.swift in Sources */, + 0AF188BAD0E51575891ACE80B0BA6AE9 /* List.swift in Sources */, + 508395CE75541C444206B78E2E94F435 /* MapTest.swift in Sources */, + 1870983702DCF95885BECDBF3E5757E3 /* MixedPropertiesAndAdditionalPropertiesClass.swift in Sources */, + E76FE98378C097EE9C5A718F5BD2F581 /* Model200Response.swift in Sources */, + 1F6BD2584EF72ECAA323B94528BE7992 /* Models.swift in Sources */, + 9F31C123624CA2B1C281D5F975EDE616 /* Name.swift in Sources */, + D2451BD00C9ED3883D70BDDE178EAE89 /* NumberOnly.swift in Sources */, + 99C82D0F8CF5B60591EF533A62F0E10A /* Order.swift in Sources */, + 6DCD351570B86AADFD4BF754096A2DAE /* OuterBoolean.swift in Sources */, + 0097805BEFC942B10049FCF37ED24E0D /* OuterComposite.swift in Sources */, + F08AFEBD1802D01C74266BF23F184138 /* OuterEnum.swift in Sources */, + 77F4CFE0094EBDC63B49257B074C936B /* OuterNumber.swift in Sources */, + E856B555D4283924AE496FB9A447189A /* OuterString.swift in Sources */, + 3312221F642766FE185B9B697A8BAE4B /* Pet.swift in Sources */, + CFFAD4C93D9A9D8455B4D4C18FFE8055 /* PetAPI.swift in Sources */, + 86463DE0FB886D57EFACE9747D72E1E6 /* PetstoreClient-dummy.m in Sources */, + E9709BDE6A967F82A034B01DD832123C /* ReadOnlyFirst.swift in Sources */, + 7878FCD0D2F00BCD00002F6BD6E297A7 /* Return.swift in Sources */, + 0DF2F6645EE3AB16827B6212F6DEDFDA /* SpecialModelName.swift in Sources */, + 33457D935182159E14829CE7BEEBDD6D /* StoreAPI.swift in Sources */, + AA72696A13BD17947CAEDA22B0C89372 /* Tag.swift in Sources */, + 18F9B7517B71D53CC011E7F88676B527 /* User.swift in Sources */, + 286FDA09B99338DDAE8AEEAF3D2769FA /* UserAPI.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + BDFDEE831A91E115AA482B4E9E9B5CC8 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 897985FA042CD12B825C3032898FAB26 /* Pods-SwaggerClientTests-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + F11C32C4518B2E95254C966B5EC111FA /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 6CE003919AF6139793694D58ADFAF9E6 /* after.m in Sources */, + 960FAEEAEDD7034D1E1B0D5B5AB43088 /* after.swift in Sources */, + 5BE1865A8083F6AD7AE7DCFE51E58891 /* afterlife.swift in Sources */, + BD80FDBAC0BA32059AE47295D91CA7D5 /* AnyPromise.m in Sources */, + 95630631BB8BFEB5540B6CF0C5D029E2 /* AnyPromise.swift in Sources */, + 6084F899BF2E35FD09D072A5C0394BD3 /* CALayer+AnyPromise.m in Sources */, + 7F1456C9A2A6684F13FD1B5A1DFD7E74 /* dispatch_promise.m in Sources */, + 1D670869022E7C0EA2DEE5155BD1864A /* DispatchQueue+Promise.swift in Sources */, + E3EC746788D5F275062D0285A256889F /* Error.swift in Sources */, + 5CBC2597C5EED08A74430DD6E8C3C9C5 /* GlobalState.m in Sources */, + 57451FA0255A49DEBAEB885DD0658750 /* hang.m in Sources */, + C2432D8D7746A8E8DCA5B602151C42E4 /* join.m in Sources */, + 9CBC2DEF8C73F54A32071F82D8F12DF5 /* join.swift in Sources */, + 197CBB45FF699E91B3E8DEDFCD596612 /* NSNotificationCenter+AnyPromise.m in Sources */, + 465DC8B52B3D7D0585D772ED29683D3E /* NSNotificationCenter+Promise.swift in Sources */, + 2642DF6CB39C87B120397F5C178010F9 /* NSObject+Promise.swift in Sources */, + DBDF86E562197D5CD9642080A12A5BE4 /* NSTask+AnyPromise.m in Sources */, + DA76C2A4D3AB587E749A0F66577E9304 /* NSURLSession+AnyPromise.m in Sources */, + 0323E3530C2A481A0C10B0EBB7DCD2E4 /* NSURLSession+Promise.swift in Sources */, + 8C1BEB026BACC90CE05F5DA21C8CFF67 /* PMKAlertController.swift in Sources */, + E58EC13E8E0CD973265C55501616B315 /* Process+Promise.swift in Sources */, + FD795A688F4488A09DC07632E6280D8C /* Promise+AnyPromise.swift in Sources */, + CA4691ACA6280C902F0B1EA26C33A367 /* Promise+Properties.swift in Sources */, + DDEE5C6AA270829DE886561F304A4824 /* Promise.swift in Sources */, + 7F4DA286C82EE5687AFC2FE1B7C60292 /* PromiseKit-dummy.m in Sources */, + 050D8EBD37B9EBC551614518F5C70CF2 /* race.swift in Sources */, + 468BB42B90797F64A371FDE8C7185AF4 /* State.swift in Sources */, + C8DC229B790728AF1D8DBE1C9DBC4149 /* UIView+AnyPromise.m in Sources */, + 1DA594AF0F2972E05DF99942E216377A /* UIView+Promise.swift in Sources */, + F9A79B29AC1077DE04896B7C0ED7FEF7 /* UIViewController+AnyPromise.m in Sources */, + 908D609C8BB8E370E1A3C03D05F0A23C /* UIViewController+Promise.swift in Sources */, + 1EFA4EB14D39ED739309A086ECEA8906 /* URLDataPromise.swift in Sources */, + BDEA72204E0F3D235E5B0950762CC3DF /* when.m in Sources */, + 04364ACE71EDEA482E970EDC82ED01B9 /* when.swift in Sources */, + A04DA97EEE7A057FC4EDA1D95309E9A3 /* wrap.swift in Sources */, + 3440FB38AAE8B9EA4CDCEE98B931B524 /* Zalgo.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FA262994DA85648A45EB39519AF3D0E3 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 8740BC8B595A54E9C973D7110740D43F /* Pods-SwaggerClient-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 1C76F9E08AAB9400CF7937D3DBF4E272 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */; + targetProxy = BBE116AAF20C2D98E0CC5B0D86765D22 /* PBXContainerItemProxy */; + }; + 1EDC13795DA36DC88CF1A4EB19B00C27 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */; + targetProxy = CB26706D98170EB16B463236FA3B7559 /* PBXContainerItemProxy */; + }; + 328C6C7DF03199CFF8F5B47C39DEE2BC /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = PromiseKit; + target = C7C5ED0DB8AF8EA86EC1631F79346F2C /* PromiseKit */; + targetProxy = F4F5C9A84714BE23040A5FB7588DA6BD /* PBXContainerItemProxy */; + }; + 405120CD9D9120CBBC452E54C91FA485 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = PetstoreClient; + target = CD79A5D6FCA04E079B656EC73E0CF0A9 /* PetstoreClient */; + targetProxy = B173CFF2A1174933D7851E8CE1CA77AB /* PBXContainerItemProxy */; + }; + F49B4E5A7446788D16D901B71DE002E8 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = PromiseKit; + target = C7C5ED0DB8AF8EA86EC1631F79346F2C /* PromiseKit */; + targetProxy = D74571BD294009BB075CA105B3BA8274 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 0A29B6F510198AF64EFD762EF6FA97A5 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 650FB90BA05FD8D3E51FE82393B780C8 /* Alamofire.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 2623EA9399E8F15FA92D7B9FD57C4FC9 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = D6C0428DC253F416C26670E1A755E6C7 /* PromiseKit.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/PromiseKit/PromiseKit-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/PromiseKit/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/PromiseKit/PromiseKit.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = PromiseKit; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 8DFCF8B61E8E87BEC121F13D463ED5A5 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/PetstoreClient/PetstoreClient-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/PetstoreClient/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/PetstoreClient/PetstoreClient.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = PetstoreClient; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 91B7FF0075884FD652BE3D081577D6B0 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClient/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.2; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClient; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + A658260C69CC5FE8D2D4A6E6D37E820A /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClientTests/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.2; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClientTests; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + A8D7EB2B9C6028C3CFF700992765BA91 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = D6C0428DC253F416C26670E1A755E6C7 /* PromiseKit.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/PromiseKit/PromiseKit-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/PromiseKit/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/PromiseKit/PromiseKit.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = PromiseKit; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + AA6E8122A0F8D71757B2807B2041E880 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClient/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.2; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClient; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + AADB9822762AD81BBAE83335B2AB1EB0 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGNING_REQUIRED = NO; + COPY_PHASE_STRIP = YES; + ENABLE_NS_ASSERTIONS = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_RELEASE=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.2; + PROVISIONING_PROFILE_SPECIFIER = NO_SIGNING/; + STRIP_INSTALLED_PRODUCT = NO; + SYMROOT = "${SRCROOT}/../build"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + B1B5EB0850F98CB5AECDB015B690777F /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGNING_REQUIRED = NO; + COPY_PHASE_STRIP = NO; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_DEBUG=1", + "DEBUG=1", + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.2; + ONLY_ACTIVE_ARCH = YES; + PROVISIONING_PROFILE_SPECIFIER = NO_SIGNING/; + STRIP_INSTALLED_PRODUCT = NO; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Debug; + }; + B6E0752FFEEE096B03BB77B7B0A0AD3F /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/PetstoreClient/PetstoreClient-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/PetstoreClient/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/PetstoreClient/PetstoreClient.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = PetstoreClient; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + EFA70F2EAB610CE73EB4B75FFD679D69 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClientTests/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.2; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClientTests; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + F383079BFBF927813EA3613CFB679FDE /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 650FB90BA05FD8D3E51FE82393B780C8 /* Alamofire.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 02482B3666DC12E2ABD164F8C86F2B54 /* Build configuration list for PBXNativeTarget "PromiseKit" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 2623EA9399E8F15FA92D7B9FD57C4FC9 /* Debug */, + A8D7EB2B9C6028C3CFF700992765BA91 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + B1B5EB0850F98CB5AECDB015B690777F /* Debug */, + AADB9822762AD81BBAE83335B2AB1EB0 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 419E5D95491847CD79841B971A8A3277 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + F383079BFBF927813EA3613CFB679FDE /* Debug */, + 0A29B6F510198AF64EFD762EF6FA97A5 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 607382BCFF2B60BA932C95EC3C22A69F /* Build configuration list for PBXNativeTarget "Pods-SwaggerClient" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 91B7FF0075884FD652BE3D081577D6B0 /* Debug */, + AA6E8122A0F8D71757B2807B2041E880 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + B1A4CABC9A5EAB96E49E2FD508880661 /* Build configuration list for PBXNativeTarget "PetstoreClient" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + B6E0752FFEEE096B03BB77B7B0A0AD3F /* Debug */, + 8DFCF8B61E8E87BEC121F13D463ED5A5 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + B462F7329881FF6565EF44016BE2B959 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClientTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + EFA70F2EAB610CE73EB4B75FFD679D69 /* Debug */, + A658260C69CC5FE8D2D4A6E6D37E820A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = D41D8CD98F00B204E9800998ECF8427E /* Project object */; +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.h b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.h new file mode 100644 index 0000000000..351a93b97e --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.h @@ -0,0 +1,44 @@ +#import +#import + + +/** + To import the `NSNotificationCenter` category: + + use_frameworks! + pod "PromiseKit/Foundation" + + Or `NSNotificationCenter` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + #import +*/ +@interface NSNotificationCenter (PromiseKit) +/** + Observe the named notification once. + + [NSNotificationCenter once:UIKeyboardWillShowNotification].then(^(id note, id userInfo){ + UIViewAnimationCurve curve = [userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue]; + CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue]; + + return [UIView promiseWithDuration:duration delay:0.0 options:(curve << 16) animations:^{ + + }]; + }); + + @warning *Important* Promises only resolve once. If you need your block to execute more than once then use `-addObserverForName:object:queue:usingBlock:`. + + @param notificationName The name of the notification for which to register the observer. + + @return A promise that fulfills with two parameters: + + 1. The NSNotification object. + 2. The NSNotification’s userInfo property. +*/ ++ (AnyPromise *)once:(NSString *)notificationName NS_REFINED_FOR_SWIFT; + +@end diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.m b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.m new file mode 100644 index 0000000000..a3b8baf507 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.m @@ -0,0 +1,16 @@ +#import +#import +#import "PMKFoundation.h" + +@implementation NSNotificationCenter (PromiseKit) + ++ (AnyPromise *)once:(NSString *)name { + return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { + __block id identifier = [[NSNotificationCenter defaultCenter] addObserverForName:name object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) { + [[NSNotificationCenter defaultCenter] removeObserver:identifier name:name object:nil]; + resolve(PMKManifold(note, note.userInfo)); + }]; + }]; +} + +@end diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+Promise.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+Promise.swift new file mode 100644 index 0000000000..6fa08cde3b --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+Promise.swift @@ -0,0 +1,45 @@ +import Foundation.NSNotification +#if !COCOAPODS +import PromiseKit +#endif + +/** + To import the `NSNotificationCenter` category: + + use_frameworks! + pod "PromiseKit/Foundation" + + Or `NSNotificationCenter` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + import PromiseKit +*/ +extension NotificationCenter { + /// Observe the named notification once + public func observe(once name: Notification.Name, object: Any? = nil) -> NotificationPromise { + let (promise, fulfill) = NotificationPromise.go() + let id = addObserver(forName: name, object: object, queue: nil, using: fulfill) + _ = promise.always { self.removeObserver(id) } + return promise + } +} + +/// The promise returned by `NotificationCenter.observe(once:)` +public class NotificationPromise: Promise<[AnyHashable: Any]> { + private let pending = Promise.pending() + + public func asNotification() -> Promise { + return pending.promise + } + + fileprivate class func go() -> (NotificationPromise, (Notification) -> Void) { + let (p, fulfill, _) = NotificationPromise.pending() + let promise = p as! NotificationPromise + _ = promise.pending.promise.then { fulfill($0.userInfo ?? [:]) } + return (promise, promise.pending.fulfill) + } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/NSObject+Promise.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/NSObject+Promise.swift new file mode 100644 index 0000000000..48d8133375 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/NSObject+Promise.swift @@ -0,0 +1,64 @@ +import Foundation +#if !COCOAPODS +import PromiseKit +#endif + +/** + To import the `NSObject` category: + + use_frameworks! + pod "PromiseKit/Foundation" + + Or `NSObject` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + import PromiseKit +*/ +extension NSObject { + /** + - Returns: A promise that resolves when the provided keyPath changes. + - Warning: *Important* The promise must not outlive the object under observation. + - SeeAlso: Apple’s KVO documentation. + */ + public func observe(keyPath: String) -> Promise { + let (promise, fulfill, reject) = Promise.pending() + let proxy = KVOProxy(observee: self, keyPath: keyPath) { obj in + if let obj = obj as? T { + fulfill(obj) + } else { + reject(PMKError.castError(T.self)) + } + } + proxy.retainCycle = proxy + return promise + } +} + +private class KVOProxy: NSObject { + var retainCycle: KVOProxy? + let fulfill: (Any?) -> Void + + init(observee: NSObject, keyPath: String, resolve: @escaping (Any?) -> Void) { + fulfill = resolve + super.init() + observee.addObserver(self, forKeyPath: keyPath, options: NSKeyValueObservingOptions.new, context: pointer) + } + + fileprivate override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { + if let change = change, context == pointer { + defer { retainCycle = nil } + fulfill(change[NSKeyValueChangeKey.newKey]) + if let object = object as? NSObject, let keyPath = keyPath { + object.removeObserver(self, forKeyPath: keyPath) + } + } + } + + private lazy var pointer: UnsafeMutableRawPointer = { + return Unmanaged.passUnretained(self).toOpaque() + }() +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/NSTask+AnyPromise.h b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/NSTask+AnyPromise.h new file mode 100644 index 0000000000..29c2c0389e --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/NSTask+AnyPromise.h @@ -0,0 +1,53 @@ +#if TARGET_OS_MAC && !TARGET_OS_EMBEDDED && !TARGET_OS_SIMULATOR + +#import +#import + +#define PMKTaskErrorLaunchPathKey @"PMKTaskErrorLaunchPathKey" +#define PMKTaskErrorArgumentsKey @"PMKTaskErrorArgumentsKey" +#define PMKTaskErrorStandardOutputKey @"PMKTaskErrorStandardOutputKey" +#define PMKTaskErrorStandardErrorKey @"PMKTaskErrorStandardErrorKey" +#define PMKTaskErrorExitStatusKey @"PMKTaskErrorExitStatusKey" + +/** + To import the `NSTask` category: + + use_frameworks! + pod "PromiseKit/Foundation" + + Or `NSTask` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + #import +*/ +@interface NSTask (PromiseKit) + +/** + Launches the receiver and resolves when it exits. + + If the task fails the promise is rejected with code `PMKTaskError`, and + `userInfo` keys: `PMKTaskErrorStandardOutputKey`, + `PMKTaskErrorStandardErrorKey` and `PMKTaskErrorExitStatusKey`. + + NSTask *task = [NSTask new]; + task.launchPath = @"/usr/bin/basename"; + task.arguments = @[@"/usr/bin/sleep"]; + [task promise].then(^(NSString *stdout){ + //… + }); + + @return A promise that fulfills with three parameters: + + 1) The stdout interpreted as a UTF8 string. + 2) The stderr interpreted as a UTF8 string. + 3) The stdout as `NSData`. +*/ +- (AnyPromise *)promise NS_REFINED_FOR_SWIFT; + +@end + +#endif diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/NSTask+AnyPromise.m b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/NSTask+AnyPromise.m new file mode 100644 index 0000000000..bfabd6157e --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/NSTask+AnyPromise.m @@ -0,0 +1,46 @@ +#import +#import +#import +#import +#import + +#if TARGET_OS_MAC && !TARGET_OS_EMBEDDED && !TARGET_OS_SIMULATOR + +#import "NSTask+AnyPromise.h" + +@implementation NSTask (PromiseKit) + +- (AnyPromise *)promise { + return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { + self.standardOutput = [NSPipe pipe]; + self.standardError = [NSPipe pipe]; + self.terminationHandler = ^(NSTask *task){ + id stdoutData = [[task.standardOutput fileHandleForReading] readDataToEndOfFile]; + id stdoutString = [[NSString alloc] initWithData:stdoutData encoding:NSUTF8StringEncoding]; + id stderrData = [[task.standardError fileHandleForReading] readDataToEndOfFile]; + id stderrString = [[NSString alloc] initWithData:stderrData encoding:NSUTF8StringEncoding]; + + if (task.terminationReason == NSTaskTerminationReasonExit && self.terminationStatus == 0) { + resolve(PMKManifold(stdoutString, stderrString, stdoutData)); + } else { + id cmd = [NSMutableArray arrayWithObject:task.launchPath]; + [cmd addObjectsFromArray:task.arguments]; + cmd = [cmd componentsJoinedByString:@" "]; + + id info = @{ + NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Failed executing: %@.", cmd], + PMKTaskErrorStandardOutputKey: stdoutString, + PMKTaskErrorStandardErrorKey: stderrString, + PMKTaskErrorExitStatusKey: @(task.terminationStatus), + }; + + resolve([NSError errorWithDomain:PMKErrorDomain code:PMKTaskError userInfo:info]); + } + }; + [self launch]; + }]; +} + +@end + +#endif diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+AnyPromise.h b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+AnyPromise.h new file mode 100644 index 0000000000..b71cf7e279 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+AnyPromise.h @@ -0,0 +1,66 @@ +#import +#import +#import +#import + +#define PMKURLErrorFailingURLResponseKey @"PMKURLErrorFailingURLResponseKey" +#define PMKURLErrorFailingDataKey @"PMKURLErrorFailingDataKey" +#define PMKURLErrorFailingStringKey @"PMKURLErrorFailingStringKey" +#define PMKJSONErrorJSONObjectKey @"PMKJSONErrorJSONObjectKey" + +/** + To import the `NSURLSession` category: + + use_frameworks! + pod "PromiseKit/Foundation" + + Or `NSURLConnection` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + #import +*/ +@interface NSURLSession (PromiseKit) + +/** + Creates a task that retrieves the contents of a URL based on the + specified URL request object. + + PromiseKit automatically deserializes the raw HTTP data response into the + appropriate rich data type based on the mime type the server provides. + Thus if the response is JSON you will get the deserialized JSON response. + PromiseKit supports decoding into strings, JSON and UIImages. + + However if your server does not provide a rich content-type, you will + just get `NSData`. This is rare, but a good example we came across was + downloading files from Dropbox. + + PromiseKit goes to quite some lengths to provide good `NSError` objects + for error conditions at all stages of the HTTP to rich-data type + pipeline. We provide the following additional `userInfo` keys as + appropriate: + + - `PMKURLErrorFailingDataKey` + - `PMKURLErrorFailingStringKey` + - `PMKURLErrorFailingURLResponseKey` + + [[NSURLConnection sharedSession] promiseDataTaskWithRequest:rq].then(^(id response){ + // response is probably an NSDictionary deserialized from JSON + }); + + @param request The URL request. + + @return A promise that fulfills with three parameters: + + 1) The deserialized data response. + 2) The `NSHTTPURLResponse`. + 3) The raw `NSData` response. + + @see https://github.com/mxcl/OMGHTTPURLRQ +*/ +- (AnyPromise *)promiseDataTaskWithRequest:(NSURLRequest *)request NS_REFINED_FOR_SWIFT; + +@end diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+AnyPromise.m b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+AnyPromise.m new file mode 100644 index 0000000000..91d4a067e2 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+AnyPromise.m @@ -0,0 +1,113 @@ +#import +#import +#import +#import "NSURLSession+AnyPromise.h" +#import +#import +#import +#import +#import +#import +#import +#import + +@implementation NSURLSession (PromiseKit) + +- (AnyPromise *)promiseDataTaskWithRequest:(NSURLRequest *)rq { + return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { + [[self dataTaskWithRequest:rq completionHandler:^(NSData *data, id rsp, NSError *urlError){ + assert(![NSThread isMainThread]); + + PMKResolver fulfiller = ^(id responseObject){ + resolve(PMKManifold(responseObject, rsp, data)); + }; + PMKResolver rejecter = ^(NSError *error){ + id userInfo = error.userInfo.mutableCopy ?: [NSMutableDictionary new]; + if (data) userInfo[PMKURLErrorFailingDataKey] = data; + if (rsp) userInfo[PMKURLErrorFailingURLResponseKey] = rsp; + error = [NSError errorWithDomain:error.domain code:error.code userInfo:userInfo]; + resolve(error); + }; + + NSStringEncoding (^stringEncoding)() = ^NSStringEncoding{ + id encodingName = [rsp textEncodingName]; + if (encodingName) { + CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)encodingName); + if (encoding != kCFStringEncodingInvalidId) + return CFStringConvertEncodingToNSStringEncoding(encoding); + } + return NSUTF8StringEncoding; + }; + + if (urlError) { + rejecter(urlError); + } else if (![rsp isKindOfClass:[NSHTTPURLResponse class]]) { + fulfiller(data); + } else if ([rsp statusCode] < 200 || [rsp statusCode] >= 300) { + id info = @{ + NSLocalizedDescriptionKey: @"The server returned a bad HTTP response code", + NSURLErrorFailingURLStringErrorKey: rq.URL.absoluteString, + NSURLErrorFailingURLErrorKey: rq.URL + }; + id err = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadServerResponse userInfo:info]; + rejecter(err); + } else if (PMKHTTPURLResponseIsJSON(rsp)) { + // work around ever-so-common Rails workaround: https://github.com/rails/rails/issues/1742 + if ([rsp expectedContentLength] == 1 && [data isEqualToData:[NSData dataWithBytes:" " length:1]]) + return fulfiller(nil); + + NSError *err = nil; + id json = [NSJSONSerialization JSONObjectWithData:data options:PMKJSONDeserializationOptions error:&err]; + if (!err) { + fulfiller(json); + } else { + id userInfo = err.userInfo.mutableCopy; + if (data) { + NSString *string = [[NSString alloc] initWithData:data encoding:stringEncoding()]; + if (string) + userInfo[PMKURLErrorFailingStringKey] = string; + } + long long length = [rsp expectedContentLength]; + id bytes = length <= 0 ? @"" : [NSString stringWithFormat:@"%lld bytes", length]; + id fmt = @"The server claimed a %@ JSON response, but decoding failed with: %@"; + userInfo[NSLocalizedDescriptionKey] = [NSString stringWithFormat:fmt, bytes, userInfo[NSLocalizedDescriptionKey]]; + err = [NSError errorWithDomain:err.domain code:err.code userInfo:userInfo]; + rejecter(err); + } + #ifdef UIKIT_EXTERN + } else if (PMKHTTPURLResponseIsImage(rsp)) { + UIImage *image = [[UIImage alloc] initWithData:data]; + image = [[UIImage alloc] initWithCGImage:[image CGImage] scale:image.scale orientation:image.imageOrientation]; + if (image) + fulfiller(image); + else { + id info = @{ + NSLocalizedDescriptionKey: @"The server returned invalid image data", + NSURLErrorFailingURLStringErrorKey: rq.URL.absoluteString, + NSURLErrorFailingURLErrorKey: rq.URL + }; + id err = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:info]; + rejecter(err); + } + #endif + } else if (PMKHTTPURLResponseIsText(rsp)) { + id str = [[NSString alloc] initWithData:data encoding:stringEncoding()]; + if (str) + fulfiller(str); + else { + id info = @{ + NSLocalizedDescriptionKey: @"The server returned invalid string data", + NSURLErrorFailingURLStringErrorKey: rq.URL.absoluteString, + NSURLErrorFailingURLErrorKey: rq.URL + }; + id err = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:info]; + rejecter(err); + } + } else { + fulfiller(data); + } + }] resume]; + }]; +} + +@end diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+Promise.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+Promise.swift new file mode 100644 index 0000000000..4789b84e24 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+Promise.swift @@ -0,0 +1,50 @@ +import Foundation +#if !COCOAPODS +import PromiseKit +#endif + +/** + To import the `NSURLSession` category: + + use_frameworks! + pod "PromiseKit/Foundation" + + Or `NSURLSession` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + import PromiseKit +*/ +extension URLSession { + /** + Makes an HTTP request using the parameters specified by the provided URL + request. + + We recommend the use of [OMGHTTPURLRQ] which allows you to construct correct REST requests. + + let rq = OMGHTTPURLRQ.POST(url, json: parameters) + NSURLSession.shared.dataTask(with: rq).asDictionary().then { json in + //… + } + + [We provide OMG extensions](https://github.com/PromiseKit/OMGHTTPURLRQ) + that allow eg: + + URLSession.shared.POST(url, json: ["a": "b"]) + + - Parameter request: The URL request. + - Returns: A promise that represents the URL request. + - SeeAlso: `URLDataPromise` + - SeeAlso: [OMGHTTPURLRQ] + + [OMGHTTPURLRQ]: https://github.com/mxcl/OMGHTTPURLRQ + */ + public func dataTask(with request: URLRequest) -> URLDataPromise { + return URLDataPromise.go(request) { completionHandler in + dataTask(with: request, completionHandler: completionHandler).resume() + } + } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/PMKFoundation.h b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/PMKFoundation.h new file mode 100644 index 0000000000..8796c0d11b --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/PMKFoundation.h @@ -0,0 +1,3 @@ +#import "NSNotificationCenter+AnyPromise.h" +#import "NSURLSession+AnyPromise.h" +#import "NSTask+AnyPromise.h" diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/Process+Promise.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/Process+Promise.swift new file mode 100644 index 0000000000..396b87ff58 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/Process+Promise.swift @@ -0,0 +1,146 @@ +import Foundation +#if !COCOAPODS +import PromiseKit +#endif + +#if os(macOS) + +/** + To import the `Process` category: + + use_frameworks! + pod "PromiseKit/Foundation" + + Or `Process` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + import PromiseKit + */ +extension Process { + /** + Launches the receiver and resolves when it exits. + + let proc = Process() + proc.launchPath = "/bin/ls" + proc.arguments = ["/bin"] + proc.promise().asStandardOutput(encoding: .utf8).then { str in + print(str) + } + */ + public func promise() -> ProcessPromise { + standardOutput = Pipe() + standardError = Pipe() + + launch() + + let (p, fulfill, reject) = ProcessPromise.pending() + let promise = p as! ProcessPromise + + promise.task = self + + waldo.async { + self.waitUntilExit() + + if self.terminationReason == .exit && self.terminationStatus == 0 { + fulfill() + } else { + reject(Error(.execution, promise, self)) + } + + promise.task = nil + } + + return promise + } + + /** + The error generated by PromiseKit’s `Process` extension + */ + public struct Error: Swift.Error, CustomStringConvertible { + public let exitStatus: Int + public let stdout: Data + public let stderr: Data + public let args: [String] + public let code: Code + public let cmd: String + + init(_ code: Code, _ promise: ProcessPromise, _ task: Process) { + stdout = promise.stdout + stderr = promise.stderr + exitStatus = Int(task.terminationStatus) + cmd = task.launchPath ?? "" + args = task.arguments ?? [] + self.code = code + } + + /// The type of `Process` error + public enum Code { + /// The data could not be converted to a UTF8 String + case encoding + /// The task execution failed + case execution + } + + /// A textual representation of the error + public var description: String { + switch code { + case .encoding: + return "Could not decode command output into string." + case .execution: + let str = ([cmd] + args).joined(separator: " ") + return "Failed executing: `\(str)`." + } + } + } +} + +final public class ProcessPromise: Promise { + fileprivate var task: Process! + + fileprivate var stdout: Data { + return (task.standardOutput! as! Pipe).fileHandleForReading.readDataToEndOfFile() + } + + fileprivate var stderr: Data { + return (task.standardError! as! Pipe).fileHandleForReading.readDataToEndOfFile() + } + + public func asStandardOutput() -> Promise { + return then(on: zalgo) { _ in self.stdout } + } + + public func asStandardError() -> Promise { + return then(on: zalgo) { _ in self.stderr } + } + + public func asStandardPair() -> Promise<(Data, Data)> { + return then(on: zalgo) { _ in (self.stderr, self.stdout) } + } + + private func decode(_ encoding: String.Encoding, _ data: Data) throws -> String { + guard let str = String(bytes: data, encoding: encoding) else { + throw Process.Error(.encoding, self, self.task) + } + return str + } + + public func asStandardPair(encoding: String.Encoding) -> Promise<(String, String)> { + return then(on: zalgo) { _ in + (try self.decode(encoding, self.stdout), try self.decode(encoding, self.stderr)) + } + } + + public func asStandardOutput(encoding: String.Encoding) -> Promise { + return then(on: zalgo) { _ in try self.decode(encoding, self.stdout) } + } + + public func asStandardError(encoding: String.Encoding) -> Promise { + return then(on: zalgo) { _ in try self.decode(encoding, self.stderr) } + } +} + +#endif diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/URLDataPromise.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/URLDataPromise.swift new file mode 100644 index 0000000000..2c380a5a92 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/URLDataPromise.swift @@ -0,0 +1,121 @@ +import Foundation +#if !COCOAPODS +import PromiseKit +#endif + +public enum Encoding { + /// Decode as JSON + case json(JSONSerialization.ReadingOptions) +} + +/** + A promise capable of decoding common Internet data types. + + Used by: + + - PromiseKit/Foundation + - PromiseKit/Social + - PromiseKit/OMGHTTPURLRQ + + But probably of general use to any promises that receive HTTP `Data`. + */ +public class URLDataPromise: Promise { + /// Convert the promise to a tuple of `(Data, URLResponse)` + public func asDataAndResponse() -> Promise<(Data, Foundation.URLResponse)> { + return then(on: zalgo) { ($0, self.URLResponse) } + } + + /// Decode the HTTP response to a String, the string encoding is read from the response. + public func asString() -> Promise { + return then(on: waldo) { data -> String in + guard let str = String(bytes: data, encoding: self.URLResponse.stringEncoding ?? .utf8) else { + throw PMKURLError.stringEncoding(self.URLRequest, data, self.URLResponse) + } + return str + } + } + + /// Decode the HTTP response as a JSON array + public func asArray(_ encoding: Encoding = .json(.allowFragments)) -> Promise { + return then(on: waldo) { data -> NSArray in + switch encoding { + case .json(let options): + guard !data.b0rkedEmptyRailsResponse else { return NSArray() } + let json = try JSONSerialization.jsonObject(with: data, options: options) + guard let array = json as? NSArray else { throw JSONError.unexpectedRootNode(json) } + return array + } + } + } + + /// Decode the HTTP response as a JSON dictionary + public func asDictionary(_ encoding: Encoding = .json(.allowFragments)) -> Promise { + return then(on: waldo) { data -> NSDictionary in + switch encoding { + case .json(let options): + guard !data.b0rkedEmptyRailsResponse else { return NSDictionary() } + let json = try JSONSerialization.jsonObject(with: data, options: options) + guard let dict = json as? NSDictionary else { throw JSONError.unexpectedRootNode(json) } + return dict + } + } + } + + fileprivate var URLRequest: Foundation.URLRequest! + fileprivate var URLResponse: Foundation.URLResponse! + + /// Internal + public class func go(_ request: URLRequest, body: (@escaping (Data?, URLResponse?, Error?) -> Void) -> Void) -> URLDataPromise { + let (p, fulfill, reject) = URLDataPromise.pending() + let promise = p as! URLDataPromise + + body { data, rsp, error in + promise.URLRequest = request + promise.URLResponse = rsp + + if let error = error { + reject(error) + } else if let data = data, let rsp = rsp as? HTTPURLResponse, (200..<300) ~= rsp.statusCode { + fulfill(data) + } else if let data = data, !(rsp is HTTPURLResponse) { + fulfill(data) + } else { + reject(PMKURLError.badResponse(request, data, rsp)) + } + } + + return promise + } +} + +#if os(iOS) + import UIKit.UIImage + + extension URLDataPromise { + /// Decode the HTTP response as a UIImage + public func asImage() -> Promise { + return then(on: waldo) { data -> UIImage in + guard let img = UIImage(data: data), let cgimg = img.cgImage else { + throw PMKURLError.invalidImageData(self.URLRequest, data) + } + // this way of decoding the image limits main thread impact when displaying the image + return UIImage(cgImage: cgimg, scale: img.scale, orientation: img.imageOrientation) + } + } + } +#endif + +extension URLResponse { + fileprivate var stringEncoding: String.Encoding? { + guard let encodingName = textEncodingName else { return nil } + let encoding = CFStringConvertIANACharSetNameToEncoding(encodingName as CFString) + guard encoding != kCFStringEncodingInvalidId else { return nil } + return String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(encoding)) + } +} + +extension Data { + fileprivate var b0rkedEmptyRailsResponse: Bool { + return count == 1 && withUnsafeBytes{ $0[0] == " " } + } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/afterlife.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/afterlife.swift new file mode 100644 index 0000000000..ecc9edd852 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/Foundation/Sources/afterlife.swift @@ -0,0 +1,26 @@ +import Foundation +#if !COCOAPODS +import PromiseKit +#endif + +/** + - Returns: A promise that resolves when the provided object deallocates + - Important: The promise is not guarenteed to resolve immediately when the provided object is deallocated. So you cannot write code that depends on exact timing. + */ +public func after(life object: NSObject) -> Promise { + var reaper = objc_getAssociatedObject(object, &handle) as? GrimReaper + if reaper == nil { + reaper = GrimReaper() + objc_setAssociatedObject(object, &handle, reaper, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + return reaper!.promise +} + +private var handle: UInt8 = 0 + +private class GrimReaper: NSObject { + deinit { + fulfill() + } + let (promise, fulfill, _) = Promise.pending() +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/QuartzCore/Sources/CALayer+AnyPromise.h b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/QuartzCore/Sources/CALayer+AnyPromise.h new file mode 100644 index 0000000000..0026d378cf --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/QuartzCore/Sources/CALayer+AnyPromise.h @@ -0,0 +1,40 @@ +// +// CALayer+AnyPromise.h +// +// Created by María Patricia Montalvo Dzib on 24/11/14. +// Copyright (c) 2014 Aluxoft SCP. All rights reserved. +// + +#import +#import + +/** + To import the `CALayer` category: + + use_frameworks! + pod "PromiseKit/QuartzCore" + + Or `CALayer` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + @import PromiseKit; +*/ +@interface CALayer (PromiseKit) + +/** + Add the specified animation object to the layer’s render tree. + + @return A promise that thens two parameters: + + 1. `@YES` if the animation progressed entirely to completion. + 2. The `CAAnimation` object. + + @see addAnimation:forKey +*/ +- (AnyPromise *)promiseAnimation:(CAAnimation *)animation forKey:(NSString *)key; + +@end diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/QuartzCore/Sources/CALayer+AnyPromise.m b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/QuartzCore/Sources/CALayer+AnyPromise.m new file mode 100644 index 0000000000..6ad7e2f13e --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/QuartzCore/Sources/CALayer+AnyPromise.m @@ -0,0 +1,36 @@ +// +// CALayer+PromiseKit.m +// +// Created by María Patricia Montalvo Dzib on 24/11/14. +// Copyright (c) 2014 Aluxoft SCP. All rights reserved. +// + +#import +#import "CALayer+AnyPromise.h" + +@interface PMKCAAnimationDelegate : NSObject { +@public + PMKResolver resolve; + CAAnimation *animation; +} +@end + +@implementation PMKCAAnimationDelegate + +- (void)animationDidStop:(CAAnimation *)ignoreOrRetainCycleHappens finished:(BOOL)flag { + resolve(PMKManifold(@(flag), animation)); + animation.delegate = nil; +} + +@end + +@implementation CALayer (PromiseKit) + +- (AnyPromise *)promiseAnimation:(CAAnimation *)animation forKey:(NSString *)key { + PMKCAAnimationDelegate *d = animation.delegate = [PMKCAAnimationDelegate new]; + d->animation = animation; + [self addAnimation:animation forKey:key]; + return [[AnyPromise alloc] initWithResolver:&d->resolve]; +} + +@end diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/QuartzCore/Sources/PMKQuartzCore.h b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/QuartzCore/Sources/PMKQuartzCore.h new file mode 100644 index 0000000000..585f7fddb6 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/QuartzCore/Sources/PMKQuartzCore.h @@ -0,0 +1 @@ +#import "CALayer+AnyPromise.h" diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/UIKit/Sources/PMKAlertController.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/UIKit/Sources/PMKAlertController.swift new file mode 100644 index 0000000000..3ebc5813a3 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/UIKit/Sources/PMKAlertController.swift @@ -0,0 +1,96 @@ +import UIKit +#if !COCOAPODS +import PromiseKit +#endif + +//TODO tests +//TODO NSCoding + +/** + A “promisable” UIAlertController. + + UIAlertController is not a suitable API for an extension; it has closure + handlers on its main API for each button and an extension would have to + either replace all these when the controller is presented or force you to + use an extended addAction method, which would be easy to forget part of + the time. Hence we provide a facade pattern that can be promised. + + let alert = PMKAlertController("OHAI") + let sup = alert.addActionWithTitle("SUP") + let bye = alert.addActionWithTitle("BYE") + promiseViewController(alert).then { action in + switch action { + case is sup: + //… + case is bye: + //… + } + } +*/ +public class PMKAlertController { + /// The title of the alert. + public var title: String? { return UIAlertController.title } + /// Descriptive text that provides more details about the reason for the alert. + public var message: String? { return UIAlertController.message } + /// The style of the alert controller. + public var preferredStyle: UIAlertControllerStyle { return UIAlertController.preferredStyle } + /// The actions that the user can take in response to the alert or action sheet. + public var actions: [UIAlertAction] { return UIAlertController.actions } + /// The array of text fields displayed by the alert. + public var textFields: [UITextField]? { return UIAlertController.textFields } + +#if !os(tvOS) + /// The nearest popover presentation controller that is managing the current view controller. + public var popoverPresentationController: UIPopoverPresentationController? { return UIAlertController.popoverPresentationController } +#endif + + /// Creates and returns a view controller for displaying an alert to the user. + public required init(title: String?, message: String? = nil, preferredStyle: UIAlertControllerStyle = .alert) { + UIAlertController = UIKit.UIAlertController(title: title, message: message, preferredStyle: preferredStyle) + } + + /// Attaches an action title to the alert or action sheet. + public func addActionWithTitle(title: String, style: UIAlertActionStyle = .default) -> UIAlertAction { + let action = UIAlertAction(title: title, style: style) { action in + if style != .cancel { + self.fulfill(action) + } else { + self.reject(Error.cancelled) + } + } + UIAlertController.addAction(action) + return action + } + + /// Adds a text field to an alert. + public func addTextFieldWithConfigurationHandler(configurationHandler: ((UITextField) -> Void)?) { + UIAlertController.addTextField(configurationHandler: configurationHandler) + } + + fileprivate let UIAlertController: UIKit.UIAlertController + fileprivate let (promise, fulfill, reject) = Promise.pending() + fileprivate var retainCycle: PMKAlertController? + + /// Errors that represent PMKAlertController failures + public enum Error: CancellableError { + /// The user cancelled the PMKAlertController. + case cancelled + + /// - Returns: true + public var isCancelled: Bool { + return self == .cancelled + } + } +} + +extension UIViewController { + /// Presents the PMKAlertController, resolving with the user action. + public func promise(_ vc: PMKAlertController, animated: Bool = true, completion: (() -> Void)? = nil) -> Promise { + vc.retainCycle = vc + present(vc.UIAlertController, animated: animated, completion: completion) + _ = vc.promise.always { _ -> Void in + vc.retainCycle = nil + } + return vc.promise + } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/UIKit/Sources/PMKUIKit.h b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/UIKit/Sources/PMKUIKit.h new file mode 100644 index 0000000000..5133264586 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/UIKit/Sources/PMKUIKit.h @@ -0,0 +1,2 @@ +#import "UIView+AnyPromise.h" +#import "UIViewController+AnyPromise.h" diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+AnyPromise.h b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+AnyPromise.h new file mode 100644 index 0000000000..0a19cd6fe1 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+AnyPromise.h @@ -0,0 +1,80 @@ +#import +#import + +// Created by Masafumi Yoshida on 2014/07/11. +// Copyright (c) 2014年 DeNA. All rights reserved. + +/** + To import the `UIView` category: + + use_frameworks! + pod "PromiseKit/UIKit" + + Or `UIKit` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + @import PromiseKit; +*/ +@interface UIView (PromiseKit) + +/** + Animate changes to one or more views using the specified duration. + + @param duration The total duration of the animations, measured in + seconds. If you specify a negative value or 0, the changes are made + without animating them. + + @param animations A block object containing the changes to commit to the + views. + + @return A promise that fulfills with a boolean NSNumber indicating + whether or not the animations actually finished. +*/ ++ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations NS_REFINED_FOR_SWIFT; + +/** + Animate changes to one or more views using the specified duration, delay, + options, and completion handler. + + @param duration The total duration of the animations, measured in + seconds. If you specify a negative value or 0, the changes are made + without animating them. + + @param delay The amount of time (measured in seconds) to wait before + beginning the animations. Specify a value of 0 to begin the animations + immediately. + + @param options A mask of options indicating how you want to perform the + animations. For a list of valid constants, see UIViewAnimationOptions. + + @param animations A block object containing the changes to commit to the + views. + + @return A promise that fulfills with a boolean NSNumber indicating + whether or not the animations actually finished. +*/ ++ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewAnimationOptions)options animations:(void (^)(void))animations NS_REFINED_FOR_SWIFT; + +/** + Performs a view animation using a timing curve corresponding to the + motion of a physical spring. + + @return A promise that fulfills with a boolean NSNumber indicating + whether or not the animations actually finished. +*/ ++ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay usingSpringWithDamping:(CGFloat)dampingRatio initialSpringVelocity:(CGFloat)velocity options:(UIViewAnimationOptions)options animations:(void (^)(void))animations NS_REFINED_FOR_SWIFT; + +/** + Creates an animation block object that can be used to set up + keyframe-based animations for the current view. + + @return A promise that fulfills with a boolean NSNumber indicating + whether or not the animations actually finished. +*/ ++ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewKeyframeAnimationOptions)options keyframeAnimations:(void (^)(void))animations NS_REFINED_FOR_SWIFT; + +@end diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+AnyPromise.m b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+AnyPromise.m new file mode 100644 index 0000000000..04ee940358 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+AnyPromise.m @@ -0,0 +1,64 @@ +// +// UIView+PromiseKit_UIAnimation.m +// YahooDenaStudy +// +// Created by Masafumi Yoshida on 2014/07/11. +// Copyright (c) 2014年 DeNA. All rights reserved. +// + +#import +#import "UIView+AnyPromise.h" + + +#define CopyPasta \ + NSAssert([NSThread isMainThread], @"UIKit animation must be performed on the main thread"); \ + \ + if (![NSThread isMainThread]) { \ + id error = [NSError errorWithDomain:PMKErrorDomain code:PMKInvalidUsageError userInfo:@{NSLocalizedDescriptionKey: @"Animation was attempted on a background thread"}]; \ + return [AnyPromise promiseWithValue:error]; \ + } \ + \ + PMKResolver resolve = nil; \ + AnyPromise *promise = [[AnyPromise alloc] initWithResolver:&resolve]; + + +@implementation UIView (PromiseKit) + ++ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations { + return [self promiseWithDuration:duration delay:0 options:0 animations:animations]; +} + ++ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewAnimationOptions)options animations:(void(^)(void))animations +{ + CopyPasta; + + [UIView animateWithDuration:duration delay:delay options:options animations:animations completion:^(BOOL finished) { + resolve(@(finished)); + }]; + + return promise; +} + ++ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay usingSpringWithDamping:(CGFloat)dampingRatio initialSpringVelocity:(CGFloat)velocity options:(UIViewAnimationOptions)options animations:(void(^)(void))animations +{ + CopyPasta; + + [UIView animateWithDuration:duration delay:delay usingSpringWithDamping:dampingRatio initialSpringVelocity:velocity options:options animations:animations completion:^(BOOL finished) { + resolve(@(finished)); + }]; + + return promise; +} + ++ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewKeyframeAnimationOptions)options keyframeAnimations:(void(^)(void))animations +{ + CopyPasta; + + [UIView animateKeyframesWithDuration:duration delay:delay options:options animations:animations completion:^(BOOL finished) { + resolve(@(finished)); + }]; + + return promise; +} + +@end diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+Promise.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+Promise.swift new file mode 100644 index 0000000000..5575e49077 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+Promise.swift @@ -0,0 +1,46 @@ +import UIKit.UIView +#if !COCOAPODS +import PromiseKit +#endif + +/** + To import the `UIView` category: + + use_frameworks! + pod "PromiseKit/UIKit" + + Or `UIKit` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + import PromiseKit +*/ +extension UIView { + /** + Animate changes to one or more views using the specified duration, delay, + options, and completion handler. + + - Parameter duration: The total duration of the animations, measured in + seconds. If you specify a negative value or 0, the changes are made + without animating them. + + - Parameter delay: The amount of time (measured in seconds) to wait before + beginning the animations. Specify a value of 0 to begin the animations + immediately. + + - Parameter options: A mask of options indicating how you want to perform the + animations. For a list of valid constants, see UIViewAnimationOptions. + + - Parameter animations: A block object containing the changes to commit to the + views. + + - Returns: A promise that fulfills with a boolean NSNumber indicating + whether or not the animations actually finished. + */ + public class func promise(animateWithDuration duration: TimeInterval, delay: TimeInterval = 0, options: UIViewAnimationOptions = [], animations: @escaping () -> Void) -> Promise { + return PromiseKit.wrap { animate(withDuration: duration, delay: delay, options: options, animations: animations, completion: $0) } + } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+AnyPromise.h b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+AnyPromise.h new file mode 100644 index 0000000000..0e60ca9e7f --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+AnyPromise.h @@ -0,0 +1,71 @@ +#import +#import + +/** + To import the `UIViewController` category: + + use_frameworks! + pod "PromiseKit/UIKit" + + Or `UIKit` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + @import PromiseKit; +*/ +@interface UIViewController (PromiseKit) + +/** + Presents a view controller modally. + + If the view controller is one of the following: + + - MFMailComposeViewController + - MFMessageComposeViewController + - UIImagePickerController + - SLComposeViewController + + Then PromiseKit presents the view controller returning a promise that is + resolved as per the documentation for those classes. Eg. if you present a + `UIImagePickerController` the view controller will be presented for you + and the returned promise will resolve with the media the user selected. + + [self promiseViewController:[MFMailComposeViewController new] animated:YES completion:nil].then(^{ + //… + }); + + Otherwise PromiseKit expects your view controller to implement a + `promise` property. This promise will be returned from this method and + presentation and dismissal of the presented view controller will be + managed for you. + + \@interface MyViewController: UIViewController + @property (readonly) AnyPromise *promise; + @end + + @implementation MyViewController { + PMKResolver resolve; + } + + - (void)viewDidLoad { + _promise = [[AnyPromise alloc] initWithResolver:&resolve]; + } + + - (void)later { + resolve(@"some fulfilled value"); + } + + @end + + [self promiseViewController:[MyViewController new] aniamted:YES completion:nil].then(^(id value){ + // value == @"some fulfilled value" + }); + + @return A promise that can be resolved by the presented view controller. +*/ +- (AnyPromise *)promiseViewController:(UIViewController *)vc animated:(BOOL)animated completion:(void (^)(void))block NS_REFINED_FOR_SWIFT; + +@end diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+AnyPromise.m b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+AnyPromise.m new file mode 100644 index 0000000000..93e7e00db6 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+AnyPromise.m @@ -0,0 +1,140 @@ +#import +#import "UIViewController+AnyPromise.h" +#import + +#if PMKImagePickerController +#import +#endif + +@interface PMKGenericDelegate : NSObject { +@public + PMKResolver resolve; +} ++ (instancetype)delegateWithPromise:(AnyPromise **)promise; +@end + +@interface UIViewController () +- (AnyPromise*) promise; +@end + +@implementation UIViewController (PromiseKit) + +- (AnyPromise *)promiseViewController:(UIViewController *)vc animated:(BOOL)animated completion:(void (^)(void))block { + __kindof UIViewController *vc2present = vc; + AnyPromise *promise = nil; + + if ([vc isKindOfClass:NSClassFromString(@"MFMailComposeViewController")]) { + PMKGenericDelegate *delegate = [PMKGenericDelegate delegateWithPromise:&promise]; + [vc setValue:delegate forKey:@"mailComposeDelegate"]; + } + else if ([vc isKindOfClass:NSClassFromString(@"MFMessageComposeViewController")]) { + PMKGenericDelegate *delegate = [PMKGenericDelegate delegateWithPromise:&promise]; + [vc setValue:delegate forKey:@"messageComposeDelegate"]; + } +#ifdef PMKImagePickerController + else if ([vc isKindOfClass:[UIImagePickerController class]]) { + PMKGenericDelegate *delegate = [PMKGenericDelegate delegateWithPromise:&promise]; + [vc setValue:delegate forKey:@"delegate"]; + } +#endif + else if ([vc isKindOfClass:NSClassFromString(@"SLComposeViewController")]) { + PMKResolver resolve; + promise = [[AnyPromise alloc] initWithResolver:&resolve]; + [vc setValue:^(NSInteger result){ + if (result == 0) { + resolve([NSError cancelledError]); + } else { + resolve(@(result)); + } + } forKey:@"completionHandler"]; + } + else if ([vc isKindOfClass:[UINavigationController class]]) + vc = [(id)vc viewControllers].firstObject; + + if (!vc) { + id userInfo = @{NSLocalizedDescriptionKey: @"nil or effective nil passed to promiseViewController"}; + id err = [NSError errorWithDomain:PMKErrorDomain code:PMKInvalidUsageError userInfo:userInfo]; + return [AnyPromise promiseWithValue:err]; + } + + if (!promise) { + if (![vc respondsToSelector:@selector(promise)]) { + id userInfo = @{NSLocalizedDescriptionKey: @"ViewController is not promisable"}; + id err = [NSError errorWithDomain:PMKErrorDomain code:PMKInvalidUsageError userInfo:userInfo]; + return [AnyPromise promiseWithValue:err]; + } + + promise = [vc valueForKey:@"promise"]; + + if (![promise isKindOfClass:[AnyPromise class]]) { + id userInfo = @{NSLocalizedDescriptionKey: @"The promise property is nil or not of type AnyPromise"}; + id err = [NSError errorWithDomain:PMKErrorDomain code:PMKInvalidUsageError userInfo:userInfo]; + return [AnyPromise promiseWithValue:err]; + } + } + + if (!promise.pending) + return promise; + + [self presentViewController:vc2present animated:animated completion:block]; + + promise.always(^{ + [vc2present.presentingViewController dismissViewControllerAnimated:animated completion:nil]; + }); + + return promise; +} + +@end + + + +@implementation PMKGenericDelegate { + id retainCycle; +} + ++ (instancetype)delegateWithPromise:(AnyPromise **)promise; { + PMKGenericDelegate *d = [PMKGenericDelegate new]; + d->retainCycle = d; + *promise = [[AnyPromise alloc] initWithResolver:&d->resolve]; + return d; +} + +- (void)mailComposeController:(id)controller didFinishWithResult:(int)result error:(NSError *)error { + if (error != nil) { + resolve(error); + } else if (result == 0) { + resolve([NSError cancelledError]); + } else { + resolve(@(result)); + } + retainCycle = nil; +} + +- (void)messageComposeViewController:(id)controller didFinishWithResult:(int)result { + if (result == 2) { + id userInfo = @{NSLocalizedDescriptionKey: @"The attempt to save or send the message was unsuccessful."}; + id error = [NSError errorWithDomain:PMKErrorDomain code:PMKOperationFailed userInfo:userInfo]; + resolve(error); + } else { + resolve(@(result)); + } + retainCycle = nil; +} + +#ifdef PMKImagePickerController + +- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { + id img = info[UIImagePickerControllerEditedImage] ?: info[UIImagePickerControllerOriginalImage]; + resolve(PMKManifold(img, info)); + retainCycle = nil; +} + +- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { + resolve([NSError cancelledError]); + retainCycle = nil; +} + +#endif + +@end diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+Promise.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+Promise.swift new file mode 100644 index 0000000000..f02b9e64bb --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+Promise.swift @@ -0,0 +1,111 @@ +import Foundation.NSError +import UIKit +#if !COCOAPODS +import PromiseKit +#endif + +/** + To import this `UIViewController` category: + + use_frameworks! + pod "PromiseKit/UIKit" + + Or `UIKit` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + import PromiseKit +*/ +extension UIViewController { + + public enum PMKError: Error { + case navigationControllerEmpty + case noImageFound + case notPromisable + case notGenericallyPromisable + case nilPromisable + } + + /// Configures when a UIViewController promise resolves + public enum FulfillmentType { + /// The promise resolves just after the view controller has disappeared. + case onceDisappeared + /// The promise resolves before the view controller has disappeared. + case beforeDismissal + } + + /// Presents the UIViewController, resolving with the user action. + public func promise(_ vc: UIViewController, animate animationOptions: PMKAnimationOptions = [.appear, .disappear], fulfills fulfillmentType: FulfillmentType = .onceDisappeared, completion: (() -> Void)? = nil) -> Promise { + let pvc: UIViewController + + switch vc { + case let nc as UINavigationController: + guard let vc = nc.viewControllers.first else { return Promise(error: PMKError.navigationControllerEmpty) } + pvc = vc + default: + pvc = vc + } + + let promise: Promise + + if !(pvc is Promisable) { + promise = Promise(error: PMKError.notPromisable) + } else if let p = pvc.value(forKeyPath: "promise") as? Promise { + promise = p + } else if let _ = pvc.value(forKeyPath: "promise") { + promise = Promise(error: PMKError.notGenericallyPromisable) + } else { + promise = Promise(error: PMKError.nilPromisable) + } + + if !promise.isPending { + return promise + } + + present(vc, animated: animationOptions.contains(.appear), completion: completion) + + let (wrappingPromise, fulfill, reject) = Promise.pending() + + switch fulfillmentType { + case .onceDisappeared: + promise.then { result in + vc.presentingViewController?.dismiss(animated: animationOptions.contains(.disappear), completion: { fulfill(result) }) + } + .catch(policy: .allErrors) { error in + vc.presentingViewController?.dismiss(animated: animationOptions.contains(.disappear), completion: { reject(error) }) + } + case .beforeDismissal: + promise.then { result -> Void in + fulfill(result) + vc.presentingViewController?.dismiss(animated: animationOptions.contains(.disappear), completion: nil) + } + .catch(policy: .allErrors) { error in + reject(error) + vc.presentingViewController?.dismiss(animated: animationOptions.contains(.disappear), completion: nil) + } + } + + return wrappingPromise + } + + @available(*, deprecated: 3.4, renamed: "promise(_:animate:fulfills:completion:)") + public func promiseViewController(_ vc: UIViewController, animated: Bool = true, completion: (() -> Void)? = nil) -> Promise { + return promise(vc, animate: animated ? [.appear, .disappear] : [], completion: completion) + } +} + +/// A protocol for UIViewControllers that can be promised. +@objc(Promisable) public protocol Promisable { + /** + Provide a promise for promiseViewController here. + + The resulting property must be annotated with @objc. + + Obviously return a Promise. There is an issue with generics and Swift and + protocols currently so we couldn't specify that. + */ + var promise: AnyObject! { get } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/LICENSE b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/LICENSE new file mode 100644 index 0000000000..c547fa8491 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/LICENSE @@ -0,0 +1,20 @@ +Copyright 2016, Max Howell; mxcl@me.com + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/README.md b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/README.md new file mode 100644 index 0000000000..0e2b93b139 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/README.md @@ -0,0 +1,247 @@ +![PromiseKit](http://promisekit.org/public/img/logo-tight.png) + +![badge-pod] ![badge-languages] ![badge-pms] ![badge-platforms] ![badge-mit] + +[繁體中文](README.zh_Hant.md) [简体中文](README.zh_CN.md) + +--- + +Modern development is highly asynchronous: isn’t it about time we had tools that +made programming asynchronously powerful, easy and delightful? + +```swift +UIApplication.shared.isNetworkActivityIndicatorVisible = true + +firstly { + when(URLSession.dataTask(with: url).asImage(), CLLocationManager.promise()) +}.then { image, location -> Void in + self.imageView.image = image + self.label.text = "\(location)" +}.always { + UIApplication.shared.isNetworkActivityIndicatorVisible = false +}.catch { error in + UIAlertView(/*…*/).show() +} +``` + +PromiseKit is a thoughtful and complete implementation of promises for any +platform with a `swiftc` (indeed, this includes *Linux*), it has *excellent* Objective-C bridging and +*delightful* specializations for iOS, macOS, tvOS and watchOS. + +# Quick Start + +We recommend [CocoaPods] or [Carthage], however you can just drop `PromiseKit.xcodeproj` into your project and add `PromiseKit.framework` to your app’s embedded frameworks. + +## Xcode 8 / Swift 3 + +```ruby +# CocoaPods >= 1.1.0-rc.2 +swift_version = "3.0" +pod "PromiseKit", "~> 4.0" + +# Carthage +github "mxcl/PromiseKit" ~> 4.0 + +# SwiftPM +let package = Package( + dependencies: [ + .Package(url: "https://github.com/mxcl/PromiseKit", majorVersion: 4) + ] +) +``` + +## Xcode 8 / Swift 2.3 or Xcode 7 + +```ruby +# CocoaPods +swift_version = "2.3" +pod "PromiseKit", "~> 3.5" + +# Carthage +github "mxcl/PromiseKit" ~> 3.5 +``` + +# Documentation + +We have thorough and complete documentation at [promisekit.org]. + +## Overview + +Promises are defined by the function `then`: + +```swift +login().then { json in + //… +} +``` + +They are chainable: + +```swift +login().then { json -> Promise in + return fetchAvatar(json["username"]) +}.then { avatarImage in + self.imageView.image = avatarImage +} +``` + +Errors cascade through chains: + +```swift +login().then { + return fetchAvatar() +}.then { avatarImage in + //… +}.catch { error in + UIAlertView(/*…*/).show() +} +``` + +They are composable: + +```swift +let username = login().then{ $0["username"] } + +when(username, CLLocationManager.promise()).then { user, location in + return fetchAvatar(user, location: location) +}.then { image in + //… +} +``` + +They are trivial to refactor: + +```swift +func avatar() -> Promise { + let username = login().then{ $0["username"] } + + return when(username, CLLocationManager.promise()).then { user, location in + return fetchAvatar(user, location: location) + } +} +``` + +You can easily create a new, pending promise. +```swift +func fetchAvatar(user: String) -> Promise { + return Promise { fulfill, reject in + MyWebHelper.GET("\(user)/avatar") { data, err in + guard let data = data else { return reject(err) } + guard let img = UIImage(data: data) else { return reject(MyError.InvalidImage) } + guard let img.size.width > 0 else { return reject(MyError.ImageTooSmall) } + fulfill(img) + } + } +} +``` + +## Continue Learning… + +Complete and progressive learning guide at [promisekit.org]. + +## PromiseKit vs. Xcode + +PromiseKit contains Swift, so we engage in an unending battle with Xcode: + +| Swift | Xcode | PromiseKit | CI Status | Release Notes | +| ----- | ----- | ---------- | ------------ | ----------------- | +| 3 | 8 | 4 | ![ci-master] | [2016/09][news-4] | +| 2 | 7/8 | 3 | ![ci-swift2] | [2015/10][news-3] | +| 1 | 7 | 3 | – | [2015/10][news-3] | +| *N/A* | * | 1† | ![ci-legacy] | – | + +† PromiseKit 1 is pure Objective-C and thus can be used with any Xcode, it is +also your only choice if you need to support iOS 7 or below. + +--- + +We also maintain some branches to aid migrating between Swift versions: + +| Xcode | Swift | PromiseKit | Branch | CI Status | +| ----- | ----- | -----------| --------------------------- | --------- | +| 8.0 | 2.3 | 2 | [swift-2.3-minimal-changes] | ![ci-23] | +| 7.3 | 2.2 | 2 | [swift-2.2-minimal-changes] | ![ci-22] | +| 7.2 | 2.2 | 2 | [swift-2.2-minimal-changes] | ![ci-22] | +| 7.1 | 2.1 | 2 | [swift-2.0-minimal-changes] | ![ci-20] | +| 7.0 | 2.0 | 2 | [swift-2.0-minimal-changes] | ![ci-20] | + +We do **not** usually backport fixes to these branches, but pull-requests are welcome. + +# Extensions + +Promises are only as useful as the asynchronous tasks they represent, thus we +have converted (almost) all of Apple’s APIs to Promises. The default CocoaPod +comes with promises UIKit and Foundation, the rest are accessed by specifying +additional subspecs in your `Podfile`, eg: + +```ruby +pod "PromiseKit/MapKit" # MKDirections().promise().then { /*…*/ } +pod "PromiseKit/CoreLocation" # CLLocationManager.promise().then { /*…*/ } +``` + +All our extensions are separate repositories at the [PromiseKit org ](https://github.com/PromiseKit). + +For Carthage specify the additional repositories in your `Cartfile`: + +```ruby +github "PromiseKit/MapKit" ~> 1.0 +``` + +## Choose Your Networking Library + +`NSURLSession` is typically inadequate; choose from [Alamofire] or [OMGHTTPURLRQ]: + +```swift +// pod 'PromiseKit/Alamofire' +Alamofire.request("http://example.com", withMethod: .GET).responseJSON().then { json in + //… +}.catch { error in + //… +} + +// pod 'PromiseKit/OMGHTTPURLRQ' +URLSession.GET("http://example.com").asDictionary().then { json in + +}.catch { error in + //… +} +``` + +For [AFNetworking] we recommend [csotiriou/AFNetworking]. + + +# Need to convert your codebase to Promises? + +From experience it really improves the robustness of your app, feel free to ask us how to go about it. + +# Support + +Ask your question at our [Gitter chat channel](https://gitter.im/mxcl/PromiseKit) or on +[our bug tracker](https://github.com/mxcl/PromiseKit/issues/new). + + +[travis]: https://travis-ci.org/mxcl/PromiseKit +[ci-master]: https://travis-ci.org/mxcl/PromiseKit.svg?branch=master +[ci-legacy]: https://travis-ci.org/mxcl/PromiseKit.svg?branch=legacy-1.x +[ci-swift2]: https://travis-ci.org/mxcl/PromiseKit.svg?branch=swift-2.x +[ci-23]: https://travis-ci.org/mxcl/PromiseKit.svg?branch=swift-2.3-minimal-changes +[ci-22]: https://travis-ci.org/mxcl/PromiseKit.svg?branch=swift-2.2-minimal-changes +[ci-20]: https://travis-ci.org/mxcl/PromiseKit.svg?branch=swift-2.0-minimal-changes +[news-2]: http://promisekit.org/news/2015/05/PromiseKit-2.0-Released/ +[news-3]: https://github.com/mxcl/PromiseKit/blob/master/CHANGELOG.markdown#300-oct-1st-2015 +[news-4]: http://promisekit.org/news/2016/09/PromiseKit-4.0-Released/ +[swift-2.3-minimal-changes]: https://github.com/mxcl/PromiseKit/tree/swift-2.3-minimal-changes +[swift-2.2-minimal-changes]: https://github.com/mxcl/PromiseKit/tree/swift-2.2-minimal-changes +[swift-2.0-minimal-changes]: https://github.com/mxcl/PromiseKit/tree/swift-2.0-minimal-changes +[promisekit.org]: http://promisekit.org/docs/ +[badge-pod]: https://img.shields.io/cocoapods/v/PromiseKit.svg?label=version +[badge-platforms]: https://img.shields.io/badge/platforms-macOS%20%7C%20iOS%20%7C%20watchOS%20%7C%20tvOS-lightgrey.svg +[badge-languages]: https://img.shields.io/badge/languages-Swift%20%7C%20ObjC-orange.svg +[badge-mit]: https://img.shields.io/badge/license-MIT-blue.svg +[badge-pms]: https://img.shields.io/badge/supports-CocoaPods%20%7C%20Carthage%20%7C%20SwiftPM-green.svg +[OMGHTTPURLRQ]: https://github.com/mxcl/OMGHTTPURLRQ +[Alamofire]: http://alamofire.org +[AFNetworking]: https://github.com/AFNetworking/AFNetworking +[csotiriou/AFNetworking]: https://github.com/csotiriou/AFNetworking-PromiseKit +[CocoaPods]: http://cocoapods.org +[Carthage]: 2016-09-05-PromiseKit-4.0-Released diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise+Private.h b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise+Private.h new file mode 100644 index 0000000000..efc2bcaba2 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise+Private.h @@ -0,0 +1,38 @@ +@import Foundation.NSError; +@import Foundation.NSPointerArray; + +#if TARGET_OS_IPHONE + #define NSPointerArrayMake(N) ({ \ + NSPointerArray *aa = [NSPointerArray strongObjectsPointerArray]; \ + aa.count = N; \ + aa; \ + }) +#else + static inline NSPointerArray * __nonnull NSPointerArrayMake(NSUInteger count) { + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wdeprecated-declarations" + NSPointerArray *aa = [[NSPointerArray class] respondsToSelector:@selector(strongObjectsPointerArray)] + ? [NSPointerArray strongObjectsPointerArray] + : [NSPointerArray pointerArrayWithStrongObjects]; + #pragma clang diagnostic pop + aa.count = count; + return aa; + } +#endif + +#define IsError(o) [o isKindOfClass:[NSError class]] +#define IsPromise(o) [o isKindOfClass:[AnyPromise class]] + +#import "AnyPromise.h" + +@interface AnyPromise (Swift) +- (AnyPromise * __nonnull)__thenOn:(__nonnull dispatch_queue_t)q execute:(id __nullable (^ __nonnull)(id __nullable))body; +- (AnyPromise * __nonnull)__catchWithPolicy:(PMKCatchPolicy)policy execute:(id __nullable (^ __nonnull)(id __nullable))body; +- (AnyPromise * __nonnull)__alwaysOn:(__nonnull dispatch_queue_t)q execute:(void (^ __nonnull)(void))body; +- (void)__pipe:(void(^ __nonnull)(__nullable id))body; +- (AnyPromise * __nonnull)initWithResolverBlock:(void (^ __nonnull)(PMKResolver __nonnull))resolver; +@end + +extern NSError * __nullable PMKProcessUnhandledException(id __nonnull thrown); + +@class PMKArray; diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.h b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.h new file mode 100644 index 0000000000..28806f2755 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.h @@ -0,0 +1,249 @@ +#import +#import +#import "fwd.h" + +typedef void (^PMKResolver)(id __nullable) NS_REFINED_FOR_SWIFT; + +typedef NS_ENUM(NSInteger, PMKCatchPolicy) { + PMKCatchPolicyAllErrors, + PMKCatchPolicyAllErrorsExceptCancellation +} NS_SWIFT_NAME(CatchPolicy); + + +#if __has_include("PromiseKit-Swift.h") + #pragma clang diagnostic push + #pragma clang diagnostic ignored"-Wdocumentation" + #import "PromiseKit-Swift.h" + #pragma clang diagnostic pop +#else + // this hack because `AnyPromise` is Swift, but we add + // our own methods via the below category. This hack is + // only required while building PromiseKit since, once + // built, the generated -Swift header exists. + + __attribute__((objc_subclassing_restricted)) __attribute__((objc_runtime_name("AnyPromise"))) + @interface AnyPromise : NSObject + @property (nonatomic, readonly) BOOL resolved; + @property (nonatomic, readonly) BOOL pending; + @property (nonatomic, readonly) __nullable id value; + + (instancetype __nonnull)promiseWithResolverBlock:(void (^ __nonnull)(__nonnull PMKResolver))resolveBlock; + + (instancetype __nonnull)promiseWithValue:(__nullable id)value; + @end +#endif + + +@interface AnyPromise (obj) + +@property (nonatomic, readonly) __nullable id value; + +/** + The provided block is executed when its receiver is resolved. + + If you provide a block that takes a parameter, the value of the receiver will be passed as that parameter. + + [NSURLSession GET:url].then(^(NSData *data){ + // do something with data + }); + + @return A new promise that is resolved with the value returned from the provided block. For example: + + [NSURLSession GET:url].then(^(NSData *data){ + return data.length; + }).then(^(NSNumber *number){ + //… + }); + + @warning *Important* The block passed to `then` may take zero, one, two or three arguments, and return an object or return nothing. This flexibility is why the method signature for then is `id`, which means you will not get completion for the block parameter, and must type it yourself. It is safe to type any block syntax here, so to start with try just: `^{}`. + + @warning *Important* If an `NSError` or `NSString` is thrown inside your block, or you return an `NSError` object the next `Promise` will be rejected. See `catch` for documentation on error handling. + + @warning *Important* `then` is always executed on the main queue. + + @see thenOn + @see thenInBackground +*/ +- (AnyPromise * __nonnull (^ __nonnull)(id __nonnull))then NS_REFINED_FOR_SWIFT; + + +/** + The provided block is executed on the default queue when the receiver is fulfilled. + + This method is provided as a convenience for `thenOn`. + + @see then + @see thenOn +*/ +- (AnyPromise * __nonnull(^ __nonnull)(id __nonnull))thenInBackground NS_REFINED_FOR_SWIFT; + +/** + The provided block is executed on the dispatch queue of your choice when the receiver is fulfilled. + + @see then + @see thenInBackground +*/ +- (AnyPromise * __nonnull(^ __nonnull)(dispatch_queue_t __nonnull, id __nonnull))thenOn NS_REFINED_FOR_SWIFT; + +#ifndef __cplusplus +/** + The provided block is executed when the receiver is rejected. + + Provide a block of form `^(NSError *){}` or simply `^{}`. The parameter has type `id` to give you the freedom to choose either. + + The provided block always runs on the main queue. + + @warning *Note* Cancellation errors are not caught. + + @warning *Note* Since catch is a c++ keyword, this method is not available in Objective-C++ files. Instead use catchWithPolicy. + + @see catchWithPolicy +*/ +- (AnyPromise * __nonnull(^ __nonnull)(id __nonnull))catch NS_REFINED_FOR_SWIFT; +#endif + +/** + The provided block is executed when the receiver is rejected with the specified policy. + + Specify the policy with which to catch as the first parameter to your block. Either for all errors, or all errors *except* cancellation errors. + + @see catch +*/ +- (AnyPromise * __nonnull(^ __nonnull)(PMKCatchPolicy, id __nonnull))catchWithPolicy NS_REFINED_FOR_SWIFT; + +/** + The provided block is executed when the receiver is resolved. + + The provided block always runs on the main queue. + + @see alwaysOn +*/ +- (AnyPromise * __nonnull(^ __nonnull)(dispatch_block_t __nonnull))always NS_REFINED_FOR_SWIFT; + +/** + The provided block is executed on the dispatch queue of your choice when the receiver is resolved. + + @see always + */ +- (AnyPromise * __nonnull(^ __nonnull)(dispatch_queue_t __nonnull, dispatch_block_t __nonnull))alwaysOn NS_REFINED_FOR_SWIFT; + +/// @see always +- (AnyPromise * __nonnull(^ __nonnull)(dispatch_block_t __nonnull))finally __attribute__((deprecated("Use always"))); +/// @see alwaysOn +- (AnyPromise * __nonnull(^ __nonnull)(dispatch_block_t __nonnull, dispatch_block_t __nonnull))finallyOn __attribute__((deprecated("Use always"))); + +/** + Create a new promise with an associated resolver. + + Use this method when wrapping asynchronous code that does *not* use + promises so that this code can be used in promise chains. Generally, + prefer `promiseWithResolverBlock:` as the resulting code is more elegant. + + PMKResolver resolve; + AnyPromise *promise = [[AnyPromise alloc] initWithResolver:&resolve]; + + // later + resolve(@"foo"); + + @param resolver A reference to a block pointer of PMKResolver type. + You can then call your resolver to resolve this promise. + + @return A new promise. + + @warning *Important* The resolver strongly retains the promise. + + @see promiseWithResolverBlock: +*/ +- (instancetype __nonnull)initWithResolver:(PMKResolver __strong __nonnull * __nonnull)resolver NS_REFINED_FOR_SWIFT; + +@end + + + +@interface AnyPromise (Unavailable) + +- (instancetype __nonnull)init __attribute__((unavailable("It is illegal to create an unresolvable promise."))); ++ (instancetype __nonnull)new __attribute__((unavailable("It is illegal to create an unresolvable promise."))); + +@end + + + +typedef void (^PMKAdapter)(id __nullable, NSError * __nullable) NS_REFINED_FOR_SWIFT; +typedef void (^PMKIntegerAdapter)(NSInteger, NSError * __nullable) NS_REFINED_FOR_SWIFT; +typedef void (^PMKBooleanAdapter)(BOOL, NSError * __nullable) NS_REFINED_FOR_SWIFT; + + +@interface AnyPromise (Adapters) + +/** + Create a new promise by adapting an existing asynchronous system. + + The pattern of a completion block that passes two parameters, the first + the result and the second an `NSError` object is so common that we + provide this convenience adapter to make wrapping such systems more + elegant. + + return [PMKPromise promiseWithAdapterBlock:^(PMKAdapter adapter){ + PFQuery *query = [PFQuery …]; + [query findObjectsInBackgroundWithBlock:adapter]; + }]; + + @warning *Important* If both parameters are nil, the promise fulfills, + if both are non-nil the promise rejects. This is per the convention. + + @see http://promisekit.org/sealing-your-own-promises/ + */ ++ (instancetype __nonnull)promiseWithAdapterBlock:(void (^ __nonnull)(PMKAdapter __nonnull adapter))block NS_REFINED_FOR_SWIFT; + +/** + Create a new promise by adapting an existing asynchronous system. + + Adapts asynchronous systems that complete with `^(NSInteger, NSError *)`. + NSInteger will cast to enums provided the enum has been wrapped with + `NS_ENUM`. All of Apple’s enums are, so if you find one that hasn’t you + may need to make a pull-request. + + @see promiseWithAdapter + */ ++ (instancetype __nonnull)promiseWithIntegerAdapterBlock:(void (^ __nonnull)(PMKIntegerAdapter __nonnull adapter))block NS_REFINED_FOR_SWIFT; + +/** + Create a new promise by adapting an existing asynchronous system. + + Adapts asynchronous systems that complete with `^(BOOL, NSError *)`. + + @see promiseWithAdapter + */ ++ (instancetype __nonnull)promiseWithBooleanAdapterBlock:(void (^ __nonnull)(PMKBooleanAdapter __nonnull adapter))block NS_REFINED_FOR_SWIFT; + +@end + + + +/** + Whenever resolving a promise you may resolve with a tuple, eg. + returning from a `then` or `catch` handler or resolving a new promise. + + Consumers of your Promise are not compelled to consume any arguments and + in fact will often only consume the first parameter. Thus ensure the + order of parameters is: from most-important to least-important. + + Currently PromiseKit limits you to THREE parameters to the manifold. +*/ +#define PMKManifold(...) __PMKManifold(__VA_ARGS__, 3, 2, 1) +#define __PMKManifold(_1, _2, _3, N, ...) __PMKArrayWithCount(N, _1, _2, _3) +extern id __nonnull __PMKArrayWithCount(NSUInteger, ...); + + + +@interface AnyPromise (Deprecations) + ++ (instancetype __nonnull)new:(__nullable id)resolvers __attribute__((unavailable("See +promiseWithResolverBlock:"))); ++ (instancetype __nonnull)when:(__nullable id)promises __attribute__((unavailable("See PMKWhen()"))); ++ (instancetype __nonnull)join:(__nullable id)promises __attribute__((unavailable("See PMKJoin()"))); + +@end + + +__attribute__((unavailable("See AnyPromise"))) +@interface PMKPromise +@end diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.m b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.m new file mode 100644 index 0000000000..184ac01562 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.m @@ -0,0 +1,117 @@ +#import "PMKCallVariadicBlock.m" +#import "AnyPromise+Private.h" + +extern dispatch_queue_t PMKDefaultDispatchQueue(); + +NSString *const PMKErrorDomain = @"PMKErrorDomain"; + + +@implementation AnyPromise (objc) + +- (instancetype)initWithResolver:(PMKResolver __strong *)resolver { + return [[self class] promiseWithResolverBlock:^(PMKResolver resolve){ + *resolver = resolve; + }]; +} + +- (AnyPromise *(^)(id))then { + return ^(id block) { + return [self __thenOn:PMKDefaultDispatchQueue() execute:^(id obj) { + return PMKCallVariadicBlock(block, obj); + }]; + }; +} + +- (AnyPromise *(^)(dispatch_queue_t, id))thenOn { + return ^(dispatch_queue_t queue, id block) { + return [self __thenOn:queue execute:^(id obj) { + return PMKCallVariadicBlock(block, obj); + }]; + }; +} + +- (AnyPromise *(^)(id))thenInBackground { + return ^(id block) { + return [self __thenOn:dispatch_get_global_queue(0, 0) execute:^(id obj) { + return PMKCallVariadicBlock(block, obj); + }]; + }; +} + +- (AnyPromise *(^)(id))catch { + return ^(id block) { + return [self __catchWithPolicy:PMKCatchPolicyAllErrorsExceptCancellation execute:^(id obj) { + return PMKCallVariadicBlock(block, obj); + }]; + }; +} + +- (AnyPromise *(^)(PMKCatchPolicy, id))catchWithPolicy { + return ^(PMKCatchPolicy policy, id block) { + return [self __catchWithPolicy:policy execute:^(id obj) { + return PMKCallVariadicBlock(block, obj); + }]; + }; +} + +- (AnyPromise *(^)(dispatch_block_t))always { + return ^(dispatch_block_t block) { + return [self __alwaysOn:PMKDefaultDispatchQueue() execute:block]; + }; +} + +- (AnyPromise *(^)(dispatch_queue_t, dispatch_block_t))alwaysOn { + return ^(dispatch_queue_t queue, dispatch_block_t block) { + return [self __alwaysOn:queue execute:block]; + }; +} + +@end + + + +@implementation AnyPromise (Adapters) + ++ (instancetype)promiseWithAdapterBlock:(void (^)(PMKAdapter))block { + return [self promiseWithResolverBlock:^(PMKResolver resolve) { + block(^(id value, id error){ + resolve(error ?: value); + }); + }]; +} + ++ (instancetype)promiseWithIntegerAdapterBlock:(void (^)(PMKIntegerAdapter))block { + return [self promiseWithResolverBlock:^(PMKResolver resolve) { + block(^(NSInteger value, id error){ + if (error) { + resolve(error); + } else { + resolve(@(value)); + } + }); + }]; +} + ++ (instancetype)promiseWithBooleanAdapterBlock:(void (^)(PMKBooleanAdapter adapter))block { + return [self promiseWithResolverBlock:^(PMKResolver resolve) { + block(^(BOOL value, id error){ + if (error) { + resolve(error); + } else { + resolve(@(value)); + } + }); + }]; +} + +- (id)value { + id obj = [self valueForKey:@"__value"]; + + if ([obj isKindOfClass:[PMKArray class]]) { + return obj[0]; + } else { + return obj; + } +} + +@end diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.swift new file mode 100644 index 0000000000..7fc7d0217e --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.swift @@ -0,0 +1,279 @@ +import Foundation + +/** + AnyPromise is an Objective-C compatible promise. +*/ +@objc(AnyPromise) public class AnyPromise: NSObject { + let state: State + + /** + - Returns: A new `AnyPromise` bound to a `Promise`. + */ + required public init(_ bridge: Promise) { + state = bridge.state + } + + /// hack to ensure Swift picks the right initializer for each of the below + private init(force: Promise) { + state = force.state + } + + /** + - Returns: A new `AnyPromise` bound to a `Promise`. + */ + public convenience init(_ bridge: Promise) { + self.init(force: bridge.then(on: zalgo) { $0 }) + } + + /** + - Returns: A new `AnyPromise` bound to a `Promise`. + */ + convenience public init(_ bridge: Promise) { + self.init(force: bridge.then(on: zalgo) { $0 }) + } + + /** + - Returns: A new `AnyPromise` bound to a `Promise`. + - Note: A “void” `AnyPromise` has a value of `nil`. + */ + convenience public init(_ bridge: Promise) { + self.init(force: bridge.then(on: zalgo) { nil }) + } + + /** + Bridges an `AnyPromise` to a `Promise`. + + - Note: AnyPromises fulfilled with `PMKManifold` lose all but the first fulfillment object. + - Remark: Could not make this an initializer of `Promise` due to generics issues. + */ + public func asPromise() -> Promise { + return Promise(sealant: { resolve in + state.pipe { resolution in + switch resolution { + case .rejected: + resolve(resolution) + case .fulfilled: + let obj = (self as AnyObject).value(forKey: "value") + resolve(.fulfilled(obj)) + } + } + }) + } + + /// - See: `Promise.then()` + public func then(on q: DispatchQueue = .default, execute body: @escaping (Any?) throws -> T) -> Promise { + return asPromise().then(on: q, execute: body) + } + + /// - See: `Promise.then()` + public func then(on q: DispatchQueue = .default, execute body: @escaping (Any?) throws -> AnyPromise) -> Promise { + return asPromise().then(on: q, execute: body) + } + + /// - See: `Promise.then()` + public func then(on q: DispatchQueue = .default, execute body: @escaping (Any?) throws -> Promise) -> Promise { + return asPromise().then(on: q, execute: body) + } + + /// - See: `Promise.always()` + public func always(on q: DispatchQueue = .default, execute body: @escaping () -> Void) -> Promise { + return asPromise().always(execute: body) + } + + /// - See: `Promise.tap()` + public func tap(on q: DispatchQueue = .default, execute body: @escaping (Result) -> Void) -> Promise { + return asPromise().tap(execute: body) + } + + /// - See: `Promise.recover()` + public func recover(on q: DispatchQueue = .default, policy: CatchPolicy = .allErrorsExceptCancellation, execute body: @escaping (Error) throws -> Promise) -> Promise { + return asPromise().recover(on: q, policy: policy, execute: body) + } + + /// - See: `Promise.recover()` + public func recover(on q: DispatchQueue = .default, policy: CatchPolicy = .allErrorsExceptCancellation, execute body: @escaping (Error) throws -> Any?) -> Promise { + return asPromise().recover(on: q, policy: policy, execute: body) + } + + /// - See: `Promise.catch()` + public func `catch`(on q: DispatchQueue = .default, policy: CatchPolicy = .allErrorsExceptCancellation, execute body: @escaping (Error) -> Void) { + state.catch(on: q, policy: policy, else: { _ in }, execute: body) + } + +//MARK: ObjC methods + + /** + A promise starts pending and eventually resolves. + - Returns: `true` if the promise has not yet resolved. + */ + @objc public var pending: Bool { + return state.get() == nil + } + + /** + A promise starts pending and eventually resolves. + - Returns: `true` if the promise has resolved. + */ + @objc public var resolved: Bool { + return !pending + } + + /** + The value of the asynchronous task this promise represents. + + A promise has `nil` value if the asynchronous task it represents has not finished. If the value is `nil` the promise is still `pending`. + + - Warning: *Note* Our Swift variant’s value property returns nil if the promise is rejected where AnyPromise will return the error object. This fits with the pattern where AnyPromise is not strictly typed and is more dynamic, but you should be aware of the distinction. + + - Note: If the AnyPromise was fulfilled with a `PMKManifold`, returns only the first fulfillment object. + + - Returns: The value with which this promise was resolved or `nil` if this promise is pending. + */ + @objc private var __value: Any? { + switch state.get() { + case nil: + return nil + case .rejected(let error, _)?: + return error + case .fulfilled(let obj)?: + return obj + } + } + + /** + Creates a resolved promise. + + When developing your own promise systems, it is occasionally useful to be able to return an already resolved promise. + + - Parameter value: The value with which to resolve this promise. Passing an `NSError` will cause the promise to be rejected, passing an AnyPromise will return a new AnyPromise bound to that promise, otherwise the promise will be fulfilled with the value passed. + + - Returns: A resolved promise. + */ + @objc public class func promiseWithValue(_ value: Any?) -> AnyPromise { + let state: State + switch value { + case let promise as AnyPromise: + state = promise.state + case let err as Error: + state = SealedState(resolution: Resolution(err)) + default: + state = SealedState(resolution: .fulfilled(value)) + } + return AnyPromise(state: state) + } + + private init(state: State) { + self.state = state + } + + /** + Create a new promise that resolves with the provided block. + + Use this method when wrapping asynchronous code that does *not* use promises so that this code can be used in promise chains. + + If `resolve` is called with an `NSError` object, the promise is rejected, otherwise the promise is fulfilled. + + Don’t use this method if you already have promises! Instead, just return your promise. + + Should you need to fulfill a promise but have no sensical value to use: your promise is a `void` promise: fulfill with `nil`. + + The block you pass is executed immediately on the calling thread. + + - Parameter block: The provided block is immediately executed, inside the block call `resolve` to resolve this promise and cause any attached handlers to execute. If you are wrapping a delegate-based system, we recommend instead to use: initWithResolver: + + - Returns: A new promise. + - Warning: Resolving a promise with `nil` fulfills it. + - SeeAlso: http://promisekit.org/sealing-your-own-promises/ + - SeeAlso: http://promisekit.org/wrapping-delegation/ + */ + @objc public class func promiseWithResolverBlock(_ body: (@escaping (Any?) -> Void) -> Void) -> AnyPromise { + return AnyPromise(sealant: { resolve in + body { obj in + makeHandler({ _ in obj }, resolve)(obj) + } + }) + } + + private init(sealant: (@escaping (Resolution) -> Void) -> Void) { + var resolve: ((Resolution) -> Void)! + state = UnsealedState(resolver: &resolve) + sealant(resolve) + } + + @objc func __thenOn(_ q: DispatchQueue, execute body: @escaping (Any?) -> Any?) -> AnyPromise { + return AnyPromise(sealant: { resolve in + state.then(on: q, else: resolve, execute: makeHandler(body, resolve)) + }) + } + + @objc func __catchWithPolicy(_ policy: CatchPolicy, execute body: @escaping (Any?) -> Any?) -> AnyPromise { + return AnyPromise(sealant: { resolve in + state.catch(on: .default, policy: policy, else: resolve) { err in + makeHandler(body, resolve)(err as NSError) + } + }) + } + + @objc func __alwaysOn(_ q: DispatchQueue, execute body: @escaping () -> Void) -> AnyPromise { + return AnyPromise(sealant: { resolve in + state.always(on: q) { resolution in + body() + resolve(resolution) + } + }) + } + + /** + Convert an `AnyPromise` to `Promise`. + + anyPromise.toPromise(T).then { (t: T) -> U in ... } + + - Returns: A `Promise` with the requested type. + - Throws: `CastingError.CastingAnyPromiseFailed(T)` if self's value cannot be downcasted to the given type. + */ + public func asPromise(type: T.Type) -> Promise { + return self.then(on: zalgo) { (value: Any?) -> T in + if let value = value as? T { + return value + } + throw PMKError.castError(type) + } + } + + /// used by PMKWhen and PMKJoin + @objc func __pipe(_ body: @escaping (Any?) -> Void) { + state.pipe { resolution in + switch resolution { + case .rejected(let error, let token): + token.consumed = true // when and join will create a new parent error that is unconsumed + body(error as NSError) + case .fulfilled(let value): + body(value) + } + } + } +} + + +extension AnyPromise { + /** + - Returns: A description of the state of this promise. + */ + override public var description: String { + return "AnyPromise: \(state)" + } +} + +private func makeHandler(_ body: @escaping (Any?) -> Any?, _ resolve: @escaping (Resolution) -> Void) -> (Any?) -> Void { + return { obj in + let obj = body(obj) + switch obj { + case let err as Error: + resolve(Resolution(err)) + case let promise as AnyPromise: + promise.state.pipe(resolve) + default: + resolve(.fulfilled(obj)) + } + } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/DispatchQueue+Promise.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/DispatchQueue+Promise.swift new file mode 100644 index 0000000000..2c912129e2 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/DispatchQueue+Promise.swift @@ -0,0 +1,53 @@ +import Dispatch + +extension DispatchQueue { + /** + Submits a block for asynchronous execution on a dispatch queue. + + DispatchQueue.global().promise { + try md5(input) + }.then { md5 in + //… + } + + - Parameter body: The closure that resolves this promise. + - Returns: A new promise resolved by the result of the provided closure. + + - SeeAlso: `DispatchQueue.async(group:qos:flags:execute:)` + - SeeAlso: `dispatch_promise()` + - SeeAlso: `dispatch_promise_on()` + */ + public final func promise(group: DispatchGroup? = nil, qos: DispatchQoS = .default, flags: DispatchWorkItemFlags = [], execute body: @escaping () throws -> T) -> Promise { + + return Promise(sealant: { resolve in + async(group: group, qos: qos, flags: flags) { + do { + resolve(.fulfilled(try body())) + } catch { + resolve(Resolution(error)) + } + } + }) + } + + /// Unavailable due to Swift compiler issues + @available(*, unavailable) + public final func promise(group: DispatchGroup? = nil, qos: DispatchQoS = .default, flags: DispatchWorkItemFlags = [], execute body: () throws -> Promise) -> Promise { fatalError() } + + /** + The default queue for all handlers. + + Defaults to `DispatchQueue.main`. + + - SeeAlso: `PMKDefaultDispatchQueue()` + - SeeAlso: `PMKSetDefaultDispatchQueue()` + */ + class public final var `default`: DispatchQueue { + get { + return __PMKDefaultDispatchQueue() + } + set { + __PMKSetDefaultDispatchQueue(newValue) + } + } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Error.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Error.swift new file mode 100644 index 0000000000..a447f29328 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Error.swift @@ -0,0 +1,171 @@ +import Foundation + +public enum PMKError: Error { + /** + The ErrorType for a rejected `join`. + - Parameter 0: The promises passed to this `join` that did not *all* fulfill. + - Note: The array is untyped because Swift generics are fussy with enums. + */ + case join([AnyObject]) + + /** + The completionHandler with form (T?, ErrorType?) was called with (nil, nil) + This is invalid as per Cocoa/Apple calling conventions. + */ + case invalidCallingConvention + + /** + A handler returned its own promise. 99% of the time, this is likely a + programming error. It is also invalid per Promises/A+. + */ + case returnedSelf + + /** `when()` was called with a concurrency of <= 0 */ + case whenConcurrentlyZero + + /** AnyPromise.toPromise failed to cast as requested */ + case castError(Any.Type) +} + +public enum PMKURLError: Error { + /** + The URLRequest succeeded but a valid UIImage could not be decoded from + the data that was received. + */ + case invalidImageData(URLRequest, Data) + + /** + The HTTP request returned a non-200 status code. + */ + case badResponse(URLRequest, Data?, URLResponse?) + + /** + The data could not be decoded using the encoding specified by the HTTP + response headers. + */ + case stringEncoding(URLRequest, Data, URLResponse) + + /** + Usually the `URLResponse` is actually an `HTTPURLResponse`, if so you + can access it using this property. Since it is returned as an unwrapped + optional: be sure. + */ + public var NSHTTPURLResponse: Foundation.HTTPURLResponse! { + switch self { + case .invalidImageData: + return nil + case .badResponse(_, _, let rsp): + return rsp as! Foundation.HTTPURLResponse + case .stringEncoding(_, _, let rsp): + return rsp as! Foundation.HTTPURLResponse + } + } +} + +extension PMKURLError: CustomStringConvertible { + public var description: String { + switch self { + case let .badResponse(rq, data, rsp): + if let data = data, let str = String(data: data, encoding: .utf8), let rsp = rsp { + return "PromiseKit: badResponse: \(rq): \(rsp)\n\(str)" + } else { + fallthrough + } + default: + return "\(self)" + } + } +} + +public enum JSONError: Error { + /// The JSON response was different to that requested + case unexpectedRootNode(Any) +} + + +//////////////////////////////////////////////////////////// Cancellation + +public protocol CancellableError: Error { + var isCancelled: Bool { get } +} + +#if !SWIFT_PACKAGE + +private struct ErrorPair: Hashable { + let domain: String + let code: Int + init(_ d: String, _ c: Int) { + domain = d; code = c + } + var hashValue: Int { + return "\(domain):\(code)".hashValue + } +} + +private func ==(lhs: ErrorPair, rhs: ErrorPair) -> Bool { + return lhs.domain == rhs.domain && lhs.code == rhs.code +} + +extension NSError { + @objc public class func cancelledError() -> NSError { + let info = [NSLocalizedDescriptionKey: "The operation was cancelled"] + return NSError(domain: PMKErrorDomain, code: PMKOperationCancelled, userInfo: info) + } + + /** + - Warning: You must call this method before any promises in your application are rejected. Failure to ensure this may lead to concurrency crashes. + - Warning: You must call this method on the main thread. Failure to do this may lead to concurrency crashes. + */ + @objc public class func registerCancelledErrorDomain(_ domain: String, code: Int) { + cancelledErrorIdentifiers.insert(ErrorPair(domain, code)) + } + + /// - Returns: true if the error represents cancellation. + @objc public var isCancelled: Bool { + return (self as Error).isCancelledError + } +} + +private var cancelledErrorIdentifiers = Set([ + ErrorPair(PMKErrorDomain, PMKOperationCancelled), + ErrorPair(NSURLErrorDomain, NSURLErrorCancelled), +]) + +#endif + + +extension Error { + public var isCancelledError: Bool { + if let ce = self as? CancellableError { + return ce.isCancelled + } else { + #if SWIFT_PACKAGE + return false + #else + let ne = self as NSError + return cancelledErrorIdentifiers.contains(ErrorPair(ne.domain, ne.code)) + #endif + } + } +} + + +//////////////////////////////////////////////////////// Unhandled Errors +class ErrorConsumptionToken { + var consumed = false + let error: Error + + init(_ error: Error) { + self.error = error + } + + deinit { + if !consumed { +#if os(Linux) + PMKUnhandledErrorHandler(error) +#else + PMKUnhandledErrorHandler(error as NSError) +#endif + } + } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/GlobalState.m b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/GlobalState.m new file mode 100644 index 0000000000..c156cde948 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/GlobalState.m @@ -0,0 +1,76 @@ +#import "PromiseKit.h" + +@interface NSError (PMK) +- (BOOL)isCancelled; +@end + +static dispatch_once_t __PMKDefaultDispatchQueueToken; +static dispatch_queue_t __PMKDefaultDispatchQueue; + +dispatch_queue_t PMKDefaultDispatchQueue() { + dispatch_once(&__PMKDefaultDispatchQueueToken, ^{ + if (__PMKDefaultDispatchQueue == nil) { + __PMKDefaultDispatchQueue = dispatch_get_main_queue(); + } + }); + return __PMKDefaultDispatchQueue; +} + +void PMKSetDefaultDispatchQueue(dispatch_queue_t newDefaultQueue) { + dispatch_once(&__PMKDefaultDispatchQueueToken, ^{ + __PMKDefaultDispatchQueue = newDefaultQueue; + }); +} + + +static dispatch_once_t __PMKErrorUnhandlerToken; +static void (^__PMKErrorUnhandler)(NSError *); + +void PMKUnhandledErrorHandler(NSError *error) { + dispatch_once(&__PMKErrorUnhandlerToken, ^{ + if (__PMKErrorUnhandler == nil) { + __PMKErrorUnhandler = ^(NSError *error){ + if (!error.isCancelled) { + NSLog(@"PromiseKit: unhandled error: %@", error); + } + }; + } + }); + return __PMKErrorUnhandler(error); +} + +void PMKSetUnhandledErrorHandler(void(^newHandler)(NSError *)) { + dispatch_once(&__PMKErrorUnhandlerToken, ^{ + __PMKErrorUnhandler = newHandler; + }); +} + + +static dispatch_once_t __PMKUnhandledExceptionHandlerToken; +static NSError *(^__PMKUnhandledExceptionHandler)(id); + +NSError *PMKProcessUnhandledException(id thrown) { + + dispatch_once(&__PMKUnhandledExceptionHandlerToken, ^{ + __PMKUnhandledExceptionHandler = ^id(id reason){ + if ([reason isKindOfClass:[NSError class]]) + return reason; + if ([reason isKindOfClass:[NSString class]]) + return [NSError errorWithDomain:PMKErrorDomain code:PMKUnexpectedError userInfo:@{NSLocalizedDescriptionKey: reason}]; + return nil; + }; + }); + + id err = __PMKUnhandledExceptionHandler(thrown); + if (!err) { + NSLog(@"PromiseKit no longer catches *all* exceptions. However you can change this behavior by setting a new PMKProcessUnhandledException handler."); + @throw thrown; + } + return err; +} + +void PMKSetUnhandledExceptionHandler(NSError *(^newHandler)(id)) { + dispatch_once(&__PMKUnhandledExceptionHandlerToken, ^{ + __PMKUnhandledExceptionHandler = newHandler; + }); +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/NSMethodSignatureForBlock.m b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/NSMethodSignatureForBlock.m new file mode 100644 index 0000000000..700c1b37ef --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/NSMethodSignatureForBlock.m @@ -0,0 +1,77 @@ +#import + +struct PMKBlockLiteral { + void *isa; // initialized to &_NSConcreteStackBlock or &_NSConcreteGlobalBlock + int flags; + int reserved; + void (*invoke)(void *, ...); + struct block_descriptor { + unsigned long int reserved; // NULL + unsigned long int size; // sizeof(struct Block_literal_1) + // optional helper functions + void (*copy_helper)(void *dst, void *src); // IFF (1<<25) + void (*dispose_helper)(void *src); // IFF (1<<25) + // required ABI.2010.3.16 + const char *signature; // IFF (1<<30) + } *descriptor; + // imported variables +}; + +typedef NS_OPTIONS(NSUInteger, PMKBlockDescriptionFlags) { + PMKBlockDescriptionFlagsHasCopyDispose = (1 << 25), + PMKBlockDescriptionFlagsHasCtor = (1 << 26), // helpers have C++ code + PMKBlockDescriptionFlagsIsGlobal = (1 << 28), + PMKBlockDescriptionFlagsHasStret = (1 << 29), // IFF BLOCK_HAS_SIGNATURE + PMKBlockDescriptionFlagsHasSignature = (1 << 30) +}; + +// It appears 10.7 doesn't support quotes in method signatures. Remove them +// via @rabovik's method. See https://github.com/OliverLetterer/SLObjectiveCRuntimeAdditions/pull/2 +#if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_8 +NS_INLINE static const char * pmk_removeQuotesFromMethodSignature(const char *str){ + char *result = malloc(strlen(str) + 1); + BOOL skip = NO; + char *to = result; + char c; + while ((c = *str++)) { + if ('"' == c) { + skip = !skip; + continue; + } + if (skip) continue; + *to++ = c; + } + *to = '\0'; + return result; +} +#endif + +static NSMethodSignature *NSMethodSignatureForBlock(id block) { + if (!block) + return nil; + + struct PMKBlockLiteral *blockRef = (__bridge struct PMKBlockLiteral *)block; + PMKBlockDescriptionFlags flags = (PMKBlockDescriptionFlags)blockRef->flags; + + if (flags & PMKBlockDescriptionFlagsHasSignature) { + void *signatureLocation = blockRef->descriptor; + signatureLocation += sizeof(unsigned long int); + signatureLocation += sizeof(unsigned long int); + + if (flags & PMKBlockDescriptionFlagsHasCopyDispose) { + signatureLocation += sizeof(void(*)(void *dst, void *src)); + signatureLocation += sizeof(void (*)(void *src)); + } + + const char *signature = (*(const char **)signatureLocation); +#if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_8 + signature = pmk_removeQuotesFromMethodSignature(signature); + NSMethodSignature *nsSignature = [NSMethodSignature signatureWithObjCTypes:signature]; + free((void *)signature); + + return nsSignature; +#endif + return [NSMethodSignature signatureWithObjCTypes:signature]; + } + return 0; +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/PMKCallVariadicBlock.m b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/PMKCallVariadicBlock.m new file mode 100644 index 0000000000..f89197ec04 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/PMKCallVariadicBlock.m @@ -0,0 +1,114 @@ +#import "NSMethodSignatureForBlock.m" +#import +#import +#import "AnyPromise+Private.h" +#import +#import +#import + +#ifndef PMKLog +#define PMKLog NSLog +#endif + +@interface PMKArray : NSObject { +@public + id objs[3]; + NSUInteger count; +} @end + +@implementation PMKArray + +- (id)objectAtIndexedSubscript:(NSUInteger)idx { + if (count <= idx) { + // this check is necessary due to lack of checks in `pmk_safely_call_block` + return nil; + } + return objs[idx]; +} + +@end + +id __PMKArrayWithCount(NSUInteger count, ...) { + PMKArray *this = [PMKArray new]; + this->count = count; + va_list args; + va_start(args, count); + for (NSUInteger x = 0; x < count; ++x) + this->objs[x] = va_arg(args, id); + va_end(args); + return this; +} + + +static inline id _PMKCallVariadicBlock(id frock, id result) { + NSCAssert(frock, @""); + + NSMethodSignature *sig = NSMethodSignatureForBlock(frock); + const NSUInteger nargs = sig.numberOfArguments; + const char rtype = sig.methodReturnType[0]; + + #define call_block_with_rtype(type) ({^type{ \ + switch (nargs) { \ + case 1: \ + return ((type(^)(void))frock)(); \ + case 2: { \ + const id arg = [result class] == [PMKArray class] ? result[0] : result; \ + return ((type(^)(id))frock)(arg); \ + } \ + case 3: { \ + type (^block)(id, id) = frock; \ + return [result class] == [PMKArray class] \ + ? block(result[0], result[1]) \ + : block(result, nil); \ + } \ + case 4: { \ + type (^block)(id, id, id) = frock; \ + return [result class] == [PMKArray class] \ + ? block(result[0], result[1], result[2]) \ + : block(result, nil, nil); \ + } \ + default: \ + @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"PromiseKit: The provided block’s argument count is unsupported." userInfo:nil]; \ + }}();}) + + switch (rtype) { + case 'v': + call_block_with_rtype(void); + return nil; + case '@': + return call_block_with_rtype(id) ?: nil; + case '*': { + char *str = call_block_with_rtype(char *); + return str ? @(str) : nil; + } + case 'c': return @(call_block_with_rtype(char)); + case 'i': return @(call_block_with_rtype(int)); + case 's': return @(call_block_with_rtype(short)); + case 'l': return @(call_block_with_rtype(long)); + case 'q': return @(call_block_with_rtype(long long)); + case 'C': return @(call_block_with_rtype(unsigned char)); + case 'I': return @(call_block_with_rtype(unsigned int)); + case 'S': return @(call_block_with_rtype(unsigned short)); + case 'L': return @(call_block_with_rtype(unsigned long)); + case 'Q': return @(call_block_with_rtype(unsigned long long)); + case 'f': return @(call_block_with_rtype(float)); + case 'd': return @(call_block_with_rtype(double)); + case 'B': return @(call_block_with_rtype(_Bool)); + case '^': + if (strcmp(sig.methodReturnType, "^v") == 0) { + call_block_with_rtype(void); + return nil; + } + // else fall through! + default: + @throw [NSException exceptionWithName:@"PromiseKit" reason:@"PromiseKit: Unsupported method signature." userInfo:nil]; + } +} + +static id PMKCallVariadicBlock(id frock, id result) { + @try { + return _PMKCallVariadicBlock(frock, result); + } @catch (id thrown) { + return PMKProcessUnhandledException(thrown); + } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Promise+AnyPromise.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Promise+AnyPromise.swift new file mode 100644 index 0000000000..5d77d4c833 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Promise+AnyPromise.swift @@ -0,0 +1,41 @@ +import class Dispatch.DispatchQueue + +extension Promise { + /** + The provided closure executes once this promise resolves. + + - Parameter on: The queue on which the provided closure executes. + - Parameter body: The closure that is executed when this promise fulfills. + - Returns: A new promise that resolves when the `AnyPromise` returned from the provided closure resolves. For example: + + URLSession.GET(url).then { (data: NSData) -> AnyPromise in + //… + return SCNetworkReachability() + }.then { _ in + //… + } + */ + public func then(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> AnyPromise) -> Promise { + return Promise(sealant: { resolve in + state.then(on: q, else: resolve) { value in + try body(value).state.pipe(resolve) + } + }) + } + + @available(*, unavailable, message: "unwrap the promise") + public func then(on: DispatchQueue = .default, execute body: (T) throws -> AnyPromise?) -> Promise { fatalError() } +} + +/** + `firstly` can make chains more readable. +*/ +public func firstly(execute body: () throws -> AnyPromise) -> Promise { + return Promise(sealant: { resolve in + do { + try body().state.pipe(resolve) + } catch { + resolve(Resolution(error)) + } + }) +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Promise+Properties.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Promise+Properties.swift new file mode 100644 index 0000000000..251ea6dcb4 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Promise+Properties.swift @@ -0,0 +1,57 @@ +extension Promise { + /** + - Returns: The error with which this promise was rejected; `nil` if this promise is not rejected. + */ + public var error: Error? { + switch state.get() { + case .none: + return nil + case .some(.fulfilled): + return nil + case .some(.rejected(let error, _)): + return error + } + } + + /** + - Returns: `true` if the promise has not yet resolved. + */ + public var isPending: Bool { + return state.get() == nil + } + + /** + - Returns: `true` if the promise has resolved. + */ + public var isResolved: Bool { + return !isPending + } + + /** + - Returns: `true` if the promise was fulfilled. + */ + public var isFulfilled: Bool { + return value != nil + } + + /** + - Returns: `true` if the promise was rejected. + */ + public var isRejected: Bool { + return error != nil + } + + /** + - Returns: The value with which this promise was fulfilled or `nil` if this promise is pending or rejected. + */ + public var value: T? { + switch state.get() { + case .none: + return nil + case .some(.fulfilled(let value)): + return value + case .some(.rejected): + return nil + } + } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Promise.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Promise.swift new file mode 100644 index 0000000000..ddbd6064aa --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Promise.swift @@ -0,0 +1,628 @@ +import class Dispatch.DispatchQueue +import class Foundation.NSError +import func Foundation.NSLog + + +/** + A *promise* represents the future value of a (usually) asynchronous task. + + To obtain the value of a promise we call `then`. + + Promises are chainable: `then` returns a promise, you can call `then` on + that promise, which returns a promise, you can call `then` on that + promise, et cetera. + + Promises start in a pending state and *resolve* with a value to become + *fulfilled* or an `Error` to become rejected. + + - SeeAlso: [PromiseKit `then` Guide](http://promisekit.org/docs/) + */ +open class Promise { + let state: State + + /** + Create a new, pending promise. + + func fetchAvatar(user: String) -> Promise { + return Promise { fulfill, reject in + MyWebHelper.GET("\(user)/avatar") { data, err in + guard let data = data else { return reject(err) } + guard let img = UIImage(data: data) else { return reject(MyError.InvalidImage) } + guard let img.size.width > 0 else { return reject(MyError.ImageTooSmall) } + fulfill(img) + } + } + } + + - Parameter resolvers: The provided closure is called immediately on the active thread; commence your asynchronous task, calling either fulfill or reject when it completes. + - Parameter fulfill: Fulfills this promise with the provided value. + - Parameter reject: Rejects this promise with the provided error. + + - Returns: A new promise. + + - Note: If you are wrapping a delegate-based system, we recommend + to use instead: `Promise.pending()` + + - SeeAlso: http://promisekit.org/docs/sealing-promises/ + - SeeAlso: http://promisekit.org/docs/cookbook/wrapping-delegation/ + - SeeAlso: pending() + */ + required public init(resolvers: (_ fulfill: @escaping (T) -> Void, _ reject: @escaping (Error) -> Void) throws -> Void) { + var resolve: ((Resolution) -> Void)! + do { + state = UnsealedState(resolver: &resolve) + try resolvers({ resolve(.fulfilled($0)) }, { error in + #if !PMKDisableWarnings + if self.isPending { + resolve(Resolution(error)) + } else { + NSLog("PromiseKit: warning: reject called on already rejected Promise: \(error)") + } + #else + resolve(Resolution(error)) + #endif + }) + } catch { + resolve(Resolution(error)) + } + } + + /** + Create an already fulfilled promise. + + To create a resolved `Void` promise, do: `Promise(value: ())` + */ + required public init(value: T) { + state = SealedState(resolution: .fulfilled(value)) + } + + /** + Create an already rejected promise. + */ + required public init(error: Error) { + state = SealedState(resolution: Resolution(error)) + } + + /** + Careful with this, it is imperative that sealant can only be called once + or you will end up with spurious unhandled-errors due to possible double + rejections and thus immediately deallocated ErrorConsumptionTokens. + */ + init(sealant: (@escaping (Resolution) -> Void) -> Void) { + var resolve: ((Resolution) -> Void)! + state = UnsealedState(resolver: &resolve) + sealant(resolve) + } + + /** + A `typealias` for the return values of `pending()`. Simplifies declaration of properties that reference the values' containing tuple when this is necessary. For example, when working with multiple `pendingPromise(value: ())`s within the same scope, or when the promise initialization must occur outside of the caller's initialization. + + class Foo: BarDelegate { + var task: Promise.PendingTuple? + } + + - SeeAlso: pending() + */ + public typealias PendingTuple = (promise: Promise, fulfill: (T) -> Void, reject: (Error) -> Void) + + /** + Making promises that wrap asynchronous delegation systems or other larger asynchronous systems without a simple completion handler is easier with pending. + + class Foo: BarDelegate { + let (promise, fulfill, reject) = Promise.pending() + + func barDidFinishWithResult(result: Int) { + fulfill(result) + } + + func barDidError(error: NSError) { + reject(error) + } + } + + - Returns: A tuple consisting of: + 1) A promise + 2) A function that fulfills that promise + 3) A function that rejects that promise + */ + public final class func pending() -> PendingTuple { + var fulfill: ((T) -> Void)! + var reject: ((Error) -> Void)! + let promise = self.init { fulfill = $0; reject = $1 } + return (promise, fulfill, reject) + } + + /** + The provided closure is executed when this promise is resolved. + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter body: The closure that is executed when this Promise is fulfilled. + - Returns: A new promise that is resolved with the value returned from the provided closure. For example: + + URLSession.GET(url).then { data -> Int in + //… + return data.length + }.then { length in + //… + } + */ + public func then(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> U) -> Promise { + return Promise { resolve in + state.then(on: q, else: resolve) { value in + resolve(.fulfilled(try body(value))) + } + } + } + + /** + The provided closure executes when this promise resolves. + + This variant of `then` allows chaining promises, the promise returned by the provided closure is resolved before the promise returned by this closure resolves. + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter execute: The closure that executes when this promise fulfills. + - Returns: A new promise that resolves when the promise returned from the provided closure resolves. For example: + + URLSession.GET(url1).then { data in + return CLLocationManager.promise() + }.then { location in + //… + } + */ + public func then(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> Promise) -> Promise { + var resolve: ((Resolution) -> Void)! + let rv = Promise{ resolve = $0 } + state.then(on: q, else: resolve) { value in + let promise = try body(value) + guard promise !== rv else { throw PMKError.returnedSelf } + promise.state.pipe(resolve) + } + return rv + } + + /** + The provided closure executes when this promise resolves. + + This variant of `then` allows returning a tuple of promises within provided closure. All of the returned + promises needs be fulfilled for this promise to be marked as resolved. + + - Note: At maximum 5 promises may be returned in a tuple + - Note: If *any* of the tuple-provided promises reject, the returned promise is immediately rejected with that error. + - Warning: In the event of rejection the other promises will continue to resolve and, as per any other promise, will either fulfill or reject. + - Parameter on: The queue to which the provided closure dispatches. + - Parameter execute: The closure that executes when this promise fulfills. + - Returns: A new promise that resolves when all promises returned from the provided closure resolve. For example: + + loginPromise.then { _ -> (Promise, Promise) + return (URLSession.GET(userUrl), URLSession.dataTask(with: avatarUrl).asImage()) + }.then { userData, avatarImage in + //… + } + */ + public func then(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> (Promise, Promise)) -> Promise<(U, V)> { + return then(on: q, execute: body) { when(fulfilled: $0.0, $0.1) } + } + + /// This variant of `then` allows returning a tuple of promises within provided closure. + public func then(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> (Promise, Promise, Promise)) -> Promise<(U, V, X)> { + return then(on: q, execute: body) { when(fulfilled: $0.0, $0.1, $0.2) } + } + + /// This variant of `then` allows returning a tuple of promises within provided closure. + public func then(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> (Promise, Promise, Promise, Promise)) -> Promise<(U, V, X, Y)> { + return then(on: q, execute: body) { when(fulfilled: $0.0, $0.1, $0.2, $0.3) } + } + + /// This variant of `then` allows returning a tuple of promises within provided closure. + public func then(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> (Promise, Promise, Promise, Promise, Promise)) -> Promise<(U, V, X, Y, Z)> { + return then(on: q, execute: body) { when(fulfilled: $0.0, $0.1, $0.2, $0.3, $0.4) } + } + + /// utility function to serve `then` implementations with `body` returning tuple of promises + private func then(on q: DispatchQueue, execute body: @escaping (T) throws -> V, when: @escaping (V) -> Promise) -> Promise { + return Promise { resolve in + state.then(on: q, else: resolve) { value in + let promise = try body(value) + + // since when(promise) switches to `zalgo`, we have to pipe back to `q` + when(promise).state.pipe(on: q, to: resolve) + } + } + } + + /** + The provided closure executes when this promise rejects. + + Rejecting a promise cascades: rejecting all subsequent promises (unless + recover is invoked) thus you will typically place your catch at the end + of a chain. Often utility promises will not have a catch, instead + delegating the error handling to the caller. + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter policy: The default policy does not execute your handler for cancellation errors. + - Parameter execute: The handler to execute if this promise is rejected. + - Returns: `self` + - SeeAlso: [Cancellation](http://promisekit.org/docs/) + - Important: The promise that is returned is `self`. `catch` cannot affect the chain, in PromiseKit 3 no promise was returned to strongly imply this, however for PromiseKit 4 we started returning a promise so that you can `always` after a catch or return from a function that has an error handler. + */ + @discardableResult + public func `catch`(on q: DispatchQueue = .default, policy: CatchPolicy = .allErrorsExceptCancellation, execute body: @escaping (Error) -> Void) -> Promise { + state.catch(on: q, policy: policy, else: { _ in }, execute: body) + return self + } + + /** + The provided closure executes when this promise rejects. + + Unlike `catch`, `recover` continues the chain provided the closure does not throw. Use `recover` in circumstances where recovering the chain from certain errors is a possibility. For example: + + CLLocationManager.promise().recover { error in + guard error == CLError.unknownLocation else { throw error } + return CLLocation.Chicago + } + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter policy: The default policy does not execute your handler for cancellation errors. + - Parameter execute: The handler to execute if this promise is rejected. + - SeeAlso: [Cancellation](http://promisekit.org/docs/) + */ + public func recover(on q: DispatchQueue = .default, policy: CatchPolicy = .allErrorsExceptCancellation, execute body: @escaping (Error) throws -> Promise) -> Promise { + var resolve: ((Resolution) -> Void)! + let rv = Promise{ resolve = $0 } + state.catch(on: q, policy: policy, else: resolve) { error in + let promise = try body(error) + guard promise !== rv else { throw PMKError.returnedSelf } + promise.state.pipe(resolve) + } + return rv + } + + /** + The provided closure executes when this promise rejects. + + Unlike `catch`, `recover` continues the chain provided the closure does not throw. Use `recover` in circumstances where recovering the chain from certain errors is a possibility. For example: + + CLLocationManager.promise().recover { error in + guard error == CLError.unknownLocation else { throw error } + return CLLocation.Chicago + } + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter policy: The default policy does not execute your handler for cancellation errors. + - Parameter execute: The handler to execute if this promise is rejected. + - SeeAlso: [Cancellation](http://promisekit.org/docs/) + */ + public func recover(on q: DispatchQueue = .default, policy: CatchPolicy = .allErrorsExceptCancellation, execute body: @escaping (Error) throws -> T) -> Promise { + return Promise { resolve in + state.catch(on: q, policy: policy, else: resolve) { error in + resolve(.fulfilled(try body(error))) + } + } + } + + /** + The provided closure executes when this promise resolves. + + firstly { + UIApplication.shared.networkActivityIndicatorVisible = true + }.then { + //… + }.always { + UIApplication.shared.networkActivityIndicatorVisible = false + }.catch { + //… + } + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter execute: The closure that executes when this promise resolves. + - Returns: A new promise, resolved with this promise’s resolution. + */ + @discardableResult + public func always(on q: DispatchQueue = .default, execute body: @escaping () -> Void) -> Promise { + state.always(on: q) { resolution in + body() + } + return self + } + + /** + Allows you to “tap” into a promise chain and inspect its result. + + The function you provide cannot mutate the chain. + + URLSession.GET(/*…*/).tap { result in + print(result) + } + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter execute: The closure that executes when this promise resolves. + - Returns: A new promise, resolved with this promise’s resolution. + */ + @discardableResult + public func tap(on q: DispatchQueue = .default, execute body: @escaping (Result) -> Void) -> Promise { + state.always(on: q) { resolution in + body(Result(resolution)) + } + return self + } + + /** + Void promises are less prone to generics-of-doom scenarios. + - SeeAlso: when.swift contains enlightening examples of using `Promise` to simplify your code. + */ + public func asVoid() -> Promise { + return then(on: zalgo) { _ in return } + } + +//MARK: deprecations + + @available(*, unavailable, renamed: "always()") + public func finally(on: DispatchQueue = DispatchQueue.main, execute body: () -> Void) -> Promise { fatalError() } + + @available(*, unavailable, renamed: "always()") + public func ensure(on: DispatchQueue = DispatchQueue.main, execute body: () -> Void) -> Promise { fatalError() } + + @available(*, unavailable, renamed: "pending()") + public class func `defer`() -> PendingTuple { fatalError() } + + @available(*, unavailable, renamed: "pending()") + public class func `pendingPromise`() -> PendingTuple { fatalError() } + + @available(*, unavailable, message: "deprecated: use then(on: .global())") + public func thenInBackground(execute body: (T) throws -> U) -> Promise { fatalError() } + + @available(*, unavailable, renamed: "catch") + public func onError(policy: CatchPolicy = .allErrors, execute body: (Error) -> Void) { fatalError() } + + @available(*, unavailable, renamed: "catch") + public func errorOnQueue(_ on: DispatchQueue, policy: CatchPolicy = .allErrors, execute body: (Error) -> Void) { fatalError() } + + @available(*, unavailable, renamed: "catch") + public func error(policy: CatchPolicy, execute body: (Error) -> Void) { fatalError() } + + @available(*, unavailable, renamed: "catch") + public func report(policy: CatchPolicy = .allErrors, execute body: (Error) -> Void) { fatalError() } + + @available(*, unavailable, renamed: "init(value:)") + public init(_ value: T) { fatalError() } + +//MARK: disallow `Promise` + + @available(*, unavailable, message: "cannot instantiate Promise") + public init(resolvers: (_ fulfill: (T) -> Void, _ reject: (Error) -> Void) throws -> Void) { fatalError() } + + @available(*, unavailable, message: "cannot instantiate Promise") + public class func pending() -> (promise: Promise, fulfill: (T) -> Void, reject: (Error) -> Void) { fatalError() } + +//MARK: disallow returning `Error` + + @available (*, unavailable, message: "instead of returning the error; throw") + public func then(on: DispatchQueue = .default, execute body: (T) throws -> U) -> Promise { fatalError() } + + @available (*, unavailable, message: "instead of returning the error; throw") + public func recover(on: DispatchQueue = .default, execute body: (Error) throws -> T) -> Promise { fatalError() } + +//MARK: disallow returning `Promise?` + + @available(*, unavailable, message: "unwrap the promise") + public func then(on: DispatchQueue = .default, execute body: (T) throws -> Promise?) -> Promise { fatalError() } + + @available(*, unavailable, message: "unwrap the promise") + public func recover(on: DispatchQueue = .default, execute body: (Error) throws -> Promise?) -> Promise { fatalError() } +} + +extension Promise: CustomStringConvertible { + public var description: String { + return "Promise: \(state)" + } +} + +/** + Judicious use of `firstly` *may* make chains more readable. + + Compare: + + URLSession.GET(url1).then { + URLSession.GET(url2) + }.then { + URLSession.GET(url3) + } + + With: + + firstly { + URLSession.GET(url1) + }.then { + URLSession.GET(url2) + }.then { + URLSession.GET(url3) + } + */ +public func firstly(execute body: () throws -> Promise) -> Promise { + return firstly(execute: body) { $0 } +} + +/** + Judicious use of `firstly` *may* make chains more readable. + Firstly allows to return tuple of promises + + Compare: + + when(fulfilled: URLSession.GET(url1), URLSession.GET(url2)).then { + URLSession.GET(url3) + }.then { + URLSession.GET(url4) + } + + With: + + firstly { + (URLSession.GET(url1), URLSession.GET(url2)) + }.then { _, _ in + URLSession.GET(url2) + }.then { + URLSession.GET(url3) + } + + - Note: At maximum 5 promises may be returned in a tuple + - Note: If *any* of the tuple-provided promises reject, the returned promise is immediately rejected with that error. + */ +public func firstly(execute body: () throws -> (Promise, Promise)) -> Promise<(T, U)> { + return firstly(execute: body) { when(fulfilled: $0.0, $0.1) } +} + +/// Firstly allows to return tuple of promises +public func firstly(execute body: () throws -> (Promise, Promise, Promise)) -> Promise<(T, U, V)> { + return firstly(execute: body) { when(fulfilled: $0.0, $0.1, $0.2) } +} + +/// Firstly allows to return tuple of promises +public func firstly(execute body: () throws -> (Promise, Promise, Promise, Promise)) -> Promise<(T, U, V, W)> { + return firstly(execute: body) { when(fulfilled: $0.0, $0.1, $0.2, $0.3) } +} + +/// Firstly allows to return tuple of promises +public func firstly(execute body: () throws -> (Promise, Promise, Promise, Promise, Promise)) -> Promise<(T, U, V, W, X)> { + return firstly(execute: body) { when(fulfilled: $0.0, $0.1, $0.2, $0.3, $0.4) } +} + +/// utility function to serve `firstly` implementations with `body` returning tuple of promises +fileprivate func firstly(execute body: () throws -> V, when: (V) -> Promise) -> Promise { + do { + return when(try body()) + } catch { + return Promise(error: error) + } +} + +@available(*, unavailable, message: "instead of returning the error; throw") +public func firstly(execute body: () throws -> T) -> Promise { fatalError() } + +@available(*, unavailable, message: "use DispatchQueue.promise") +public func firstly(on: DispatchQueue, execute body: () throws -> Promise) -> Promise { fatalError() } + +/** + - SeeAlso: `DispatchQueue.promise(group:qos:flags:execute:)` + */ +@available(*, deprecated: 4.0, renamed: "DispatchQueue.promise") +public func dispatch_promise(_ on: DispatchQueue, _ body: @escaping () throws -> T) -> Promise { + return Promise(value: ()).then(on: on, execute: body) +} + + +/** + The underlying resolved state of a promise. + - Remark: Same as `Resolution` but without the associated `ErrorConsumptionToken`. +*/ +public enum Result { + /// Fulfillment + case fulfilled(T) + /// Rejection + case rejected(Error) + + init(_ resolution: Resolution) { + switch resolution { + case .fulfilled(let value): + self = .fulfilled(value) + case .rejected(let error, _): + self = .rejected(error) + } + } + + /** + - Returns: `true` if the result is `fulfilled` or `false` if it is `rejected`. + */ + public var boolValue: Bool { + switch self { + case .fulfilled: + return true + case .rejected: + return false + } + } +} + +/** + An object produced by `Promise.joint()`, along with a promise to which it is bound. + + Joining with a promise via `Promise.join(_:)` will pipe the resolution of that promise to + the joint's bound promise. + + - SeeAlso: `Promise.joint()` + - SeeAlso: `Promise.join(_:)` + */ +public class PMKJoint { + fileprivate var resolve: ((Resolution) -> Void)! +} + +extension Promise { + /** + Provides a safe way to instantiate a `Promise` and resolve it later via its joint and another + promise. + + class Engine { + static func make() -> Promise { + let (enginePromise, joint) = Promise.joint() + let cylinder: Cylinder = Cylinder(explodeAction: { + + // We *could* use an IUO, but there are no guarantees about when + // this callback will be called. Having an actual promise is safe. + + enginePromise.then { engine in + engine.checkOilPressure() + } + }) + + firstly { + Ignition.default.start() + }.then { plugs in + Engine(cylinders: [cylinder], sparkPlugs: plugs) + }.join(joint) + + return enginePromise + } + } + + - Returns: A new promise and its joint. + - SeeAlso: `Promise.join(_:)` + */ + public final class func joint() -> (Promise, PMKJoint) { + let pipe = PMKJoint() + let promise = Promise(sealant: { pipe.resolve = $0 }) + return (promise, pipe) + } + + /** + Pipes the value of this promise to the promise created with the joint. + + - Parameter joint: The joint on which to join. + - SeeAlso: `Promise.joint()` + */ + public func join(_ joint: PMKJoint) { + state.pipe(joint.resolve) + } +} + + +extension Promise where T: Collection { + /** + Transforms a `Promise` where `T` is a `Collection` into a `Promise<[U]>` + + URLSession.shared.dataTask(url: /*…*/).asArray().map { result in + return download(result) + }.then { images in + // images is `[UIImage]` + } + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter transform: The closure that executes when this promise resolves. + - Returns: A new promise, resolved with this promise’s resolution. + */ + public func map(on: DispatchQueue = .default, transform: @escaping (T.Iterator.Element) throws -> Promise) -> Promise<[U]> { + return Promise<[U]> { resolve in + return state.then(on: zalgo, else: resolve) { tt in + when(fulfilled: try tt.map(transform)).state.pipe(resolve) + } + } + } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/PromiseKit.h b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/PromiseKit.h new file mode 100644 index 0000000000..2651530cbc --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/PromiseKit.h @@ -0,0 +1,7 @@ +#import "fwd.h" +#import "AnyPromise.h" + +#import // `FOUNDATION_EXPORT` + +FOUNDATION_EXPORT double PromiseKitVersionNumber; +FOUNDATION_EXPORT const unsigned char PromiseKitVersionString[]; diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/State.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/State.swift new file mode 100644 index 0000000000..cc1a19ce70 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/State.swift @@ -0,0 +1,219 @@ +import class Dispatch.DispatchQueue +import func Foundation.NSLog + +enum Seal { + case pending(Handlers) + case resolved(Resolution) +} + +enum Resolution { + case fulfilled(T) + case rejected(Error, ErrorConsumptionToken) + + init(_ error: Error) { + self = .rejected(error, ErrorConsumptionToken(error)) + } +} + +class State { + + // would be a protocol, but you can't have typed variables of “generic” + // protocols in Swift 2. That is, I couldn’t do var state: State when + // it was a protocol. There is no work around. Update: nor Swift 3 + + func get() -> Resolution? { fatalError("Abstract Base Class") } + func get(body: @escaping (Seal) -> Void) { fatalError("Abstract Base Class") } + + final func pipe(_ body: @escaping (Resolution) -> Void) { + get { seal in + switch seal { + case .pending(let handlers): + handlers.append(body) + case .resolved(let resolution): + body(resolution) + } + } + } + + final func pipe(on q: DispatchQueue, to body: @escaping (Resolution) -> Void) { + pipe { resolution in + contain_zalgo(q) { + body(resolution) + } + } + } + + final func then(on q: DispatchQueue, else rejecter: @escaping (Resolution) -> Void, execute body: @escaping (T) throws -> Void) { + pipe { resolution in + switch resolution { + case .fulfilled(let value): + contain_zalgo(q, rejecter: rejecter) { + try body(value) + } + case .rejected(let error, let token): + rejecter(.rejected(error, token)) + } + } + } + + final func always(on q: DispatchQueue, body: @escaping (Resolution) -> Void) { + pipe { resolution in + contain_zalgo(q) { + body(resolution) + } + } + } + + final func `catch`(on q: DispatchQueue, policy: CatchPolicy, else resolve: @escaping (Resolution) -> Void, execute body: @escaping (Error) throws -> Void) { + pipe { resolution in + switch (resolution, policy) { + case (.fulfilled, _): + resolve(resolution) + case (.rejected(let error, _), .allErrorsExceptCancellation) where error.isCancelledError: + resolve(resolution) + case (let .rejected(error, token), _): + contain_zalgo(q, rejecter: resolve) { + token.consumed = true + try body(error) + } + } + } + } +} + +class UnsealedState: State { + private let barrier = DispatchQueue(label: "org.promisekit.barrier", attributes: .concurrent) + private var seal: Seal + + /** + Quick return, but will not provide the handlers array because + it could be modified while you are using it by another thread. + If you need the handlers, use the second `get` variant. + */ + override func get() -> Resolution? { + var result: Resolution? + barrier.sync { + if case .resolved(let resolution) = self.seal { + result = resolution + } + } + return result + } + + override func get(body: @escaping (Seal) -> Void) { + var sealed = false + barrier.sync { + switch self.seal { + case .resolved: + sealed = true + case .pending: + sealed = false + } + } + if !sealed { + barrier.sync(flags: .barrier) { + switch (self.seal) { + case .pending: + body(self.seal) + case .resolved: + sealed = true // welcome to race conditions + } + } + } + if sealed { + body(seal) // as much as possible we do things OUTSIDE the barrier_sync + } + } + + required init(resolver: inout ((Resolution) -> Void)!) { + seal = .pending(Handlers()) + super.init() + resolver = { resolution in + var handlers: Handlers? + self.barrier.sync(flags: .barrier) { + if case .pending(let hh) = self.seal { + self.seal = .resolved(resolution) + handlers = hh + } + } + if let handlers = handlers { + for handler in handlers { + handler(resolution) + } + } + } + } +#if !PMKDisableWarnings + deinit { + if case .pending = seal { + NSLog("PromiseKit: Pending Promise deallocated! This is usually a bug") + } + } +#endif +} + +class SealedState: State { + fileprivate let resolution: Resolution + + init(resolution: Resolution) { + self.resolution = resolution + } + + override func get() -> Resolution? { + return resolution + } + + override func get(body: @escaping (Seal) -> Void) { + body(.resolved(resolution)) + } +} + + +class Handlers: Sequence { + var bodies: [(Resolution) -> Void] = [] + + func append(_ body: @escaping (Resolution) -> Void) { + bodies.append(body) + } + + func makeIterator() -> IndexingIterator<[(Resolution) -> Void]> { + return bodies.makeIterator() + } + + var count: Int { + return bodies.count + } +} + + +extension Resolution: CustomStringConvertible { + var description: String { + switch self { + case .fulfilled(let value): + return "Fulfilled with value: \(value)" + case .rejected(let error): + return "Rejected with error: \(error)" + } + } +} + +extension UnsealedState: CustomStringConvertible { + var description: String { + var rv: String! + get { seal in + switch seal { + case .pending(let handlers): + rv = "Pending with \(handlers.count) handlers" + case .resolved(let resolution): + rv = "\(resolution)" + } + } + return "UnsealedState: \(rv)" + } +} + +extension SealedState: CustomStringConvertible { + var description: String { + return "SealedState: \(resolution)" + } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Zalgo.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Zalgo.swift new file mode 100644 index 0000000000..e191df10d6 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Zalgo.swift @@ -0,0 +1,80 @@ +import class Dispatch.DispatchQueue +import class Foundation.Thread + +/** + `zalgo` causes your handlers to be executed as soon as their promise resolves. + + Usually all handlers are dispatched to a queue (the main queue by default); the `on:` parameter of `then` configures this. Its default value is `DispatchQueue.main`. + + - Important: `zalgo` is dangerous. + + Compare: + + var x = 0 + foo.then { + print(x) // => 1 + } + x++ + + With: + + var x = 0 + foo.then(on: zalgo) { + print(x) // => 0 or 1 + } + x++ + + In the latter case the value of `x` may be `0` or `1` depending on whether `foo` is resolved. This is a race-condition that is easily avoided by not using `zalgo`. + + - Important: you cannot control the queue that your handler executes if using `zalgo`. + + - Note: `zalgo` is provided for libraries providing promises that have good tests that prove “Unleashing Zalgo” is safe. You can also use it in your application code in situations where performance is critical, but be careful: read the essay liked below to understand the risks. + + - SeeAlso: [Designing APIs for Asynchrony](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) + - SeeAlso: `waldo` + */ +public let zalgo = DispatchQueue(label: "Zalgo") + +/** + `waldo` is dangerous. + + `waldo` is `zalgo`, unless the current queue is the main thread, in which + case we dispatch to the default background queue. + + If your block is likely to take more than a few milliseconds to execute, + then you should use waldo: 60fps means the main thread cannot hang longer + than 17 milliseconds: don’t contribute to UI lag. + + Conversely if your then block is trivial, use zalgo: GCD is not free and + for whatever reason you may already be on the main thread so just do what + you are doing quickly and pass on execution. + + It is considered good practice for asynchronous APIs to complete onto the + main thread. Apple do not always honor this, nor do other developers. + However, they *should*. In that respect waldo is a good choice if your + then is going to take some time and doesn’t interact with the UI. + + Please note (again) that generally you should not use `zalgo` or `waldo`. + The performance gains are negligible and we provide these functions only out + of a misguided sense that library code should be as optimized as possible. + If you use either without tests proving their correctness you may + unwillingly introduce horrendous, near-impossible-to-trace bugs. + + - SeeAlso: `zalgo` + */ +public let waldo = DispatchQueue(label: "Waldo") + + +@inline(__always) func contain_zalgo(_ q: DispatchQueue, body: @escaping () -> Void) { + if q === zalgo || q === waldo && !Thread.isMainThread { + body() + } else { + q.async(execute: body) + } +} + +@inline(__always) func contain_zalgo(_ q: DispatchQueue, rejecter reject: @escaping (Resolution) -> Void, block: @escaping () throws -> Void) { + contain_zalgo(q) { + do { try block() } catch { reject(Resolution(error)) } + } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/after.m b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/after.m new file mode 100644 index 0000000000..25f9966fc5 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/after.m @@ -0,0 +1,14 @@ +#import "AnyPromise.h" +@import Dispatch; +@import Foundation.NSDate; +@import Foundation.NSValue; + +/// @return A promise that fulfills after the specified duration. +AnyPromise *PMKAfter(NSTimeInterval duration) { + return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { + dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)); + dispatch_after(time, dispatch_get_global_queue(0, 0), ^{ + resolve(@(duration)); + }); + }]; +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/after.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/after.swift new file mode 100644 index 0000000000..049ea74fb5 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/after.swift @@ -0,0 +1,12 @@ +import struct Foundation.TimeInterval +import Dispatch + +/** + - Returns: A new promise that fulfills after the specified duration. +*/ +public func after(interval: TimeInterval) -> Promise { + return Promise { fulfill, _ in + let when = DispatchTime.now() + interval + DispatchQueue.global().asyncAfter(deadline: when, execute: fulfill) + } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/dispatch_promise.m b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/dispatch_promise.m new file mode 100644 index 0000000000..ecb89f7111 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/dispatch_promise.m @@ -0,0 +1,10 @@ +#import "AnyPromise.h" +@import Dispatch; + +AnyPromise *dispatch_promise_on(dispatch_queue_t queue, id block) { + return [AnyPromise promiseWithValue:nil].thenOn(queue, block); +} + +AnyPromise *dispatch_promise(id block) { + return dispatch_promise_on(dispatch_get_global_queue(0, 0), block); +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/fwd.h b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/fwd.h new file mode 100644 index 0000000000..78b93f7a4e --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/fwd.h @@ -0,0 +1,240 @@ +#import +#import + +@class AnyPromise; +extern NSString * __nonnull const PMKErrorDomain; + +#define PMKFailingPromiseIndexKey @"PMKFailingPromiseIndexKey" +#define PMKJoinPromisesKey @"PMKJoinPromisesKey" + +#define PMKUnexpectedError 1l +#define PMKInvalidUsageError 3l +#define PMKAccessDeniedError 4l +#define PMKOperationCancelled 5l +#define PMKOperationFailed 8l +#define PMKTaskError 9l +#define PMKJoinError 10l + + +#if __cplusplus +extern "C" { +#endif + +/** + @return A new promise that resolves after the specified duration. + + @parameter duration The duration in seconds to wait before this promise is resolve. + + For example: + + PMKAfter(1).then(^{ + //… + }); +*/ +extern AnyPromise * __nonnull PMKAfter(NSTimeInterval duration) NS_REFINED_FOR_SWIFT; + + + +/** + `when` is a mechanism for waiting more than one asynchronous task and responding when they are all complete. + + `PMKWhen` accepts varied input. If an array is passed then when those promises fulfill, when’s promise fulfills with an array of fulfillment values. If a dictionary is passed then the same occurs, but when’s promise fulfills with a dictionary of fulfillments keyed as per the input. + + Interestingly, if a single promise is passed then when waits on that single promise, and if a single non-promise object is passed then when fulfills immediately with that object. If the array or dictionary that is passed contains objects that are not promises, then these objects are considered fulfilled promises. The reason we do this is to allow a pattern know as "abstracting away asynchronicity". + + If *any* of the provided promises reject, the returned promise is immediately rejected with that promise’s rejection. The error’s `userInfo` object is supplemented with `PMKFailingPromiseIndexKey`. + + For example: + + PMKWhen(@[promise1, promise2]).then(^(NSArray *results){ + //… + }); + + @warning *Important* In the event of rejection the other promises will continue to resolve and as per any other promise will either fulfill or reject. This is the right pattern for `getter` style asynchronous tasks, but often for `setter` tasks (eg. storing data on a server), you most likely will need to wait on all tasks and then act based on which have succeeded and which have failed. In such situations use `PMKJoin`. + + @param input The input upon which to wait before resolving this promise. + + @return A promise that is resolved with either: + + 1. An array of values from the provided array of promises. + 2. The value from the provided promise. + 3. The provided non-promise object. + + @see PMKJoin + +*/ +extern AnyPromise * __nonnull PMKWhen(id __nonnull input) NS_REFINED_FOR_SWIFT; + + + +/** + Creates a new promise that resolves only when all provided promises have resolved. + + Typically, you should use `PMKWhen`. + + For example: + + PMKJoin(@[promise1, promise2]).then(^(NSArray *resultingValues){ + //… + }).catch(^(NSError *error){ + assert(error.domain == PMKErrorDomain); + assert(error.code == PMKJoinError); + + NSArray *promises = error.userInfo[PMKJoinPromisesKey]; + for (AnyPromise *promise in promises) { + if (promise.rejected) { + //… + } + } + }); + + @param promises An array of promises. + + @return A promise that thens three parameters: + + 1) An array of mixed values and errors from the resolved input. + 2) An array of values from the promises that fulfilled. + 3) An array of errors from the promises that rejected or nil if all promises fulfilled. + + @see when +*/ +AnyPromise *__nonnull PMKJoin(NSArray * __nonnull promises) NS_REFINED_FOR_SWIFT; + + + +/** + Literally hangs this thread until the promise has resolved. + + Do not use hang… unless you are testing, playing or debugging. + + If you use it in production code I will literally and honestly cry like a child. + + @return The resolved value of the promise. + + @warning T SAFE. IT IS NOT SAFE. IT IS NOT SAFE. IT IS NOT SAFE. IT IS NO +*/ +extern id __nullable PMKHang(AnyPromise * __nonnull promise); + + + +/** + Sets the unhandled exception handler. + + If an exception is thrown inside an AnyPromise handler it is caught and + this handler is executed to determine if the promise is rejected. + + The default handler rejects the promise if an NSError or an NSString is + thrown. + + The default handler in PromiseKit 1.x would reject whatever object was + thrown (including nil). + + @warning *Important* This handler is provided to allow you to customize + which exceptions cause rejection and which abort. You should either + return a fully-formed NSError object or nil. Returning nil causes the + exception to be re-thrown. + + @warning *Important* The handler is executed on an undefined queue. + + @warning *Important* This function is thread-safe, but to facilitate this + it can only be called once per application lifetime and it must be called + before any promise in the app throws an exception. Subsequent calls will + silently fail. +*/ +extern void PMKSetUnhandledExceptionHandler(NSError * __nullable (^__nonnull handler)(id __nullable)); + +/** + If an error cascades through a promise chain and is not handled by any + `catch`, the unhandled error handler is called. The default logs all + non-cancelled errors. + + This handler can only be set once, and must be set before any promises + are rejected in your application. + + PMKSetUnhandledErrorHandler({ error in + mylogf("Unhandled error: \(error)") + }) + + - Warning: *Important* The handler is executed on an undefined queue. + - Warning: *Important* Don’t use promises in your handler, or you risk an infinite error loop. +*/ +extern void PMKSetUnhandledErrorHandler(void (^__nonnull handler)(NSError * __nonnull)); + +extern void PMKUnhandledErrorHandler(NSError * __nonnull error); + +/** + Executes the provided block on a background queue. + + dispatch_promise is a convenient way to start a promise chain where the + first step needs to run synchronously on a background queue. + + dispatch_promise(^{ + return md5(input); + }).then(^(NSString *md5){ + NSLog(@"md5: %@", md5); + }); + + @param block The block to be executed in the background. Returning an `NSError` will reject the promise, everything else (including void) fulfills the promise. + + @return A promise resolved with the return value of the provided block. + + @see dispatch_async +*/ +extern AnyPromise * __nonnull dispatch_promise(id __nonnull block) NS_SWIFT_UNAVAILABLE("Use our `DispatchQueue.async` override instead"); + + + +/** + Executes the provided block on the specified background queue. + + dispatch_promise_on(myDispatchQueue, ^{ + return md5(input); + }).then(^(NSString *md5){ + NSLog(@"md5: %@", md5); + }); + + @param block The block to be executed in the background. Returning an `NSError` will reject the promise, everything else (including void) fulfills the promise. + + @return A promise resolved with the return value of the provided block. + + @see dispatch_promise +*/ +extern AnyPromise * __nonnull dispatch_promise_on(dispatch_queue_t __nonnull queue, id __nonnull block) NS_SWIFT_UNAVAILABLE("Use our `DispatchQueue.async` override instead"); + + +#define PMKJSONDeserializationOptions ((NSJSONReadingOptions)(NSJSONReadingAllowFragments | NSJSONReadingMutableContainers)) + +/** + Really we shouldn’t assume JSON for (application|text)/(x-)javascript, + really we should return a String of Javascript. However in practice + for the apps we write it *will be* JSON. Thus if you actually want + a Javascript String, use the promise variant of our category functions. +*/ +#define PMKHTTPURLResponseIsJSON(rsp) [@[@"application/json", @"text/json", @"text/javascript", @"application/x-javascript", @"application/javascript"] containsObject:[rsp MIMEType]] +#define PMKHTTPURLResponseIsImage(rsp) [@[@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap"] containsObject:[rsp MIMEType]] +#define PMKHTTPURLResponseIsText(rsp) [[rsp MIMEType] hasPrefix:@"text/"] + +/** + The default queue for all calls to `then`, `catch` etc. is the main queue. + + By default this returns dispatch_get_main_queue() + */ +extern __nonnull dispatch_queue_t PMKDefaultDispatchQueue() NS_REFINED_FOR_SWIFT; + +/** + You may alter the default dispatch queue, but you may only alter it once, and you must alter it before any `then`, etc. calls are made in your app. + + The primary motivation for this function is so that your tests can operate off the main thread preventing dead-locking, or with `zalgo` to speed them up. +*/ +extern void PMKSetDefaultDispatchQueue(__nonnull dispatch_queue_t) NS_REFINED_FOR_SWIFT; + +#if __cplusplus +} // Extern C +#endif + + +typedef NS_OPTIONS(NSInteger, PMKAnimationOptions) { + PMKAnimationOptionsNone = 1 << 0, + PMKAnimationOptionsAppear = 1 << 1, + PMKAnimationOptionsDisappear = 1 << 2, +}; diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/hang.m b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/hang.m new file mode 100644 index 0000000000..1065d91f2f --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/hang.m @@ -0,0 +1,29 @@ +#import "AnyPromise.h" +#import "AnyPromise+Private.h" +@import CoreFoundation.CFRunLoop; + +/** + Suspends the active thread waiting on the provided promise. + + @return The value of the provided promise once resolved. + */ +id PMKHang(AnyPromise *promise) { + if (promise.pending) { + static CFRunLoopSourceContext context; + + CFRunLoopRef runLoop = CFRunLoopGetCurrent(); + CFRunLoopSourceRef runLoopSource = CFRunLoopSourceCreate(NULL, 0, &context); + CFRunLoopAddSource(runLoop, runLoopSource, kCFRunLoopDefaultMode); + + promise.always(^{ + CFRunLoopStop(runLoop); + }); + while (promise.pending) { + CFRunLoopRun(); + } + CFRunLoopRemoveSource(runLoop, runLoopSource, kCFRunLoopDefaultMode); + CFRelease(runLoopSource); + } + + return promise.value; +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/join.m b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/join.m new file mode 100644 index 0000000000..979f092df0 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/join.m @@ -0,0 +1,54 @@ +@import Foundation.NSDictionary; +#import "AnyPromise+Private.h" +#import +@import Foundation.NSError; +@import Foundation.NSNull; +#import "PromiseKit.h" +#import + +/** + Waits on all provided promises. + + `PMKWhen` rejects as soon as one of the provided promises rejects. `PMKJoin` waits on all provided promises, then rejects if any of those promises rejects, otherwise it fulfills with values from the provided promises. + + - Returns: A new promise that resolves once all the provided promises resolve. +*/ +AnyPromise *PMKJoin(NSArray *promises) { + if (promises == nil) + return [AnyPromise promiseWithValue:[NSError errorWithDomain:PMKErrorDomain code:PMKInvalidUsageError userInfo:@{NSLocalizedDescriptionKey: @"PMKJoin(nil)"}]]; + + if (promises.count == 0) + return [AnyPromise promiseWithValue:promises]; + + return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { + NSPointerArray *results = NSPointerArrayMake(promises.count); + __block atomic_int countdown = promises.count; + __block BOOL rejected = NO; + + [promises enumerateObjectsUsingBlock:^(AnyPromise *promise, NSUInteger ii, BOOL *stop) { + [promise __pipe:^(id value) { + + if (IsError(value)) { + rejected = YES; + } + + //FIXME surely this isn't thread safe on multiple cores? + [results replacePointerAtIndex:ii withPointer:(__bridge void *)(value ?: [NSNull null])]; + + atomic_fetch_sub_explicit(&countdown, 1, memory_order_relaxed); + + if (countdown == 0) { + if (!rejected) { + resolve(results.allObjects); + } else { + id userInfo = @{PMKJoinPromisesKey: promises}; + id err = [NSError errorWithDomain:PMKErrorDomain code:PMKJoinError userInfo:userInfo]; + resolve(err); + } + } + }]; + + (void) stop; + }]; + }]; +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/join.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/join.swift new file mode 100644 index 0000000000..8ff69b2c2c --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/join.swift @@ -0,0 +1,60 @@ +import Dispatch + +/** + Waits on all provided promises. + + `when` rejects as soon as one of the provided promises rejects. `join` waits on all provided promises, then rejects if any of those promises rejected, otherwise it fulfills with values from the provided promises. + + join(promise1, promise2, promise3).then { results in + //… + }.catch { error in + switch error { + case Error.Join(let promises): + //… + } + } + + - Returns: A new promise that resolves once all the provided promises resolve. + - SeeAlso: `PromiseKit.Error.join` +*/ +@available(*, deprecated: 4.0, message: "Use when(resolved:)") +public func join(_ promises: Promise...) -> Promise<[T]> { + return join(promises) +} + +/// Waits on all provided promises. +@available(*, deprecated: 4.0, message: "Use when(resolved:)") +public func join(_ promises: [Promise]) -> Promise { + return join(promises).then(on: zalgo) { (_: [Void]) in return Promise(value: ()) } +} + +/// Waits on all provided promises. +@available(*, deprecated: 4.0, message: "Use when(resolved:)") +public func join(_ promises: [Promise]) -> Promise<[T]> { + guard !promises.isEmpty else { return Promise(value: []) } + + var countdown = promises.count + let barrier = DispatchQueue(label: "org.promisekit.barrier.join", attributes: .concurrent) + var rejected = false + + return Promise { fulfill, reject in + for promise in promises { + promise.state.pipe { resolution in + barrier.sync(flags: .barrier) { + if case .rejected(_, let token) = resolution { + token.consumed = true // the parent Error.Join consumes all + rejected = true + } + countdown -= 1 + if countdown == 0 { + if rejected { + reject(PMKError.join(promises)) + } else { + fulfill(promises.map{ $0.value! }) + } + } + } + } + } + } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/race.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/race.swift new file mode 100644 index 0000000000..9ff17005c9 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/race.swift @@ -0,0 +1,40 @@ +/** + Resolves with the first resolving promise from a set of promises. + + race(promise1, promise2, promise3).then { winner in + //… + } + + - Returns: A new promise that resolves when the first promise in the provided promises resolves. + - Warning: If any of the provided promises reject, the returned promise is rejected. + - Warning: aborts if the array is empty. +*/ +public func race(promises: [Promise]) -> Promise { + guard promises.count > 0 else { + fatalError("Cannot race with an empty array of promises") + } + return _race(promises: promises) +} + +/** + Resolves with the first resolving promise from a set of promises. + + race(promise1, promise2, promise3).then { winner in + //… + } + + - Returns: A new promise that resolves when the first promise in the provided promises resolves. + - Warning: If any of the provided promises reject, the returned promise is rejected. + - Warning: aborts if the array is empty. +*/ +public func race(_ promises: Promise...) -> Promise { + return _race(promises: promises) +} + +private func _race(promises: [Promise]) -> Promise { + return Promise(sealant: { resolve in + for promise in promises { + promise.state.pipe(resolve) + } + }) +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/when.m b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/when.m new file mode 100644 index 0000000000..cafb54720c --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/when.m @@ -0,0 +1,100 @@ +@import Foundation.NSDictionary; +#import "AnyPromise+Private.h" +@import Foundation.NSProgress; +#import +@import Foundation.NSError; +@import Foundation.NSNull; +#import "PromiseKit.h" + +// NSProgress resources: +// * https://robots.thoughtbot.com/asynchronous-nsprogress +// * http://oleb.net/blog/2014/03/nsprogress/ +// NSProgress! Beware! +// * https://github.com/AFNetworking/AFNetworking/issues/2261 + +/** + Wait for all promises in a set to resolve. + + @note If *any* of the provided promises reject, the returned promise is immediately rejected with that error. + @warning In the event of rejection the other promises will continue to resolve and, as per any other promise, will either fulfill or reject. This is the right pattern for `getter` style asynchronous tasks, but often for `setter` tasks (eg. storing data on a server), you most likely will need to wait on all tasks and then act based on which have succeeded and which have failed, in such situations use `when(resolved:)`. + @param promises The promises upon which to wait before the returned promise resolves. + @note PMKWhen provides NSProgress. + @return A new promise that resolves when all the provided promises fulfill or one of the provided promises rejects. +*/ +AnyPromise *PMKWhen(id promises) { + if (promises == nil) + return [AnyPromise promiseWithValue:[NSError errorWithDomain:PMKErrorDomain code:PMKInvalidUsageError userInfo:@{NSLocalizedDescriptionKey: @"PMKWhen(nil)"}]]; + + if ([promises isKindOfClass:[NSArray class]] || [promises isKindOfClass:[NSDictionary class]]) { + if ([promises count] == 0) + return [AnyPromise promiseWithValue:promises]; + } else if ([promises isKindOfClass:[AnyPromise class]]) { + promises = @[promises]; + } else { + return [AnyPromise promiseWithValue:promises]; + } + +#ifndef PMKDisableProgress + NSProgress *progress = [NSProgress progressWithTotalUnitCount:(int64_t)[promises count]]; + progress.pausable = NO; + progress.cancellable = NO; +#else + struct PMKProgress { + int completedUnitCount; + int totalUnitCount; + double fractionCompleted; + }; + __block struct PMKProgress progress; +#endif + + __block int32_t countdown = (int32_t)[promises count]; + BOOL const isdict = [promises isKindOfClass:[NSDictionary class]]; + + return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { + NSInteger index = 0; + + for (__strong id key in promises) { + AnyPromise *promise = isdict ? promises[key] : key; + if (!isdict) key = @(index); + + if (![promise isKindOfClass:[AnyPromise class]]) + promise = [AnyPromise promiseWithValue:promise]; + + [promise __pipe:^(id value){ + if (progress.fractionCompleted >= 1) + return; + + if (IsError(value)) { + progress.completedUnitCount = progress.totalUnitCount; + + NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:[value userInfo] ?: @{}]; + userInfo[PMKFailingPromiseIndexKey] = key; + [userInfo setObject:value forKey:NSUnderlyingErrorKey]; + id err = [[NSError alloc] initWithDomain:[value domain] code:[value code] userInfo:userInfo]; + resolve(err); + } + else if (OSAtomicDecrement32(&countdown) == 0) { + progress.completedUnitCount = progress.totalUnitCount; + + id results; + if (isdict) { + results = [NSMutableDictionary new]; + for (id key in promises) { + id promise = promises[key]; + results[key] = IsPromise(promise) ? ((AnyPromise *)promise).value : promise; + } + } else { + results = [NSMutableArray new]; + for (AnyPromise *promise in promises) { + id value = IsPromise(promise) ? (promise.value ?: [NSNull null]) : promise; + [results addObject:value]; + } + } + resolve(results); + } else { + progress.completedUnitCount++; + } + }]; + } + }]; +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/when.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/when.swift new file mode 100644 index 0000000000..638dfa8e06 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/when.swift @@ -0,0 +1,249 @@ +import Foundation +import Dispatch + +private func _when(_ promises: [Promise]) -> Promise { + let root = Promise.pending() + var countdown = promises.count + guard countdown > 0 else { + root.fulfill() + return root.promise + } + +#if PMKDisableProgress || os(Linux) + var progress: (completedUnitCount: Int, totalUnitCount: Int) = (0, 0) +#else + let progress = Progress(totalUnitCount: Int64(promises.count)) + progress.isCancellable = false + progress.isPausable = false +#endif + + let barrier = DispatchQueue(label: "org.promisekit.barrier.when", attributes: .concurrent) + + for promise in promises { + promise.state.pipe { resolution in + barrier.sync(flags: .barrier) { + switch resolution { + case .rejected(let error, let token): + token.consumed = true + if root.promise.isPending { + progress.completedUnitCount = progress.totalUnitCount + root.reject(error) + } + case .fulfilled: + guard root.promise.isPending else { return } + progress.completedUnitCount += 1 + countdown -= 1 + if countdown == 0 { + root.fulfill() + } + } + } + } + } + + return root.promise +} + +/** + Wait for all promises in a set to fulfill. + + For example: + + when(fulfilled: promise1, promise2).then { results in + //… + }.catch { error in + switch error { + case URLError.notConnectedToInternet: + //… + case CLError.denied: + //… + } + } + + - Note: If *any* of the provided promises reject, the returned promise is immediately rejected with that error. + - Warning: In the event of rejection the other promises will continue to resolve and, as per any other promise, will either fulfill or reject. This is the right pattern for `getter` style asynchronous tasks, but often for `setter` tasks (eg. storing data on a server), you most likely will need to wait on all tasks and then act based on which have succeeded and which have failed, in such situations use `when(resolved:)`. + - Parameter promises: The promises upon which to wait before the returned promise resolves. + - Returns: A new promise that resolves when all the provided promises fulfill or one of the provided promises rejects. + - Note: `when` provides `NSProgress`. + - SeeAlso: `when(resolved:)` +*/ +public func when(fulfilled promises: [Promise]) -> Promise<[T]> { + return _when(promises).then(on: zalgo) { promises.map{ $0.value! } } +} + +/// Wait for all promises in a set to fulfill. +public func when(fulfilled promises: Promise...) -> Promise { + return _when(promises) +} + +/// Wait for all promises in a set to fulfill. +public func when(fulfilled promises: [Promise]) -> Promise { + return _when(promises) +} + +/// Wait for all promises in a set to fulfill. +public func when(fulfilled pu: Promise, _ pv: Promise) -> Promise<(U, V)> { + return _when([pu.asVoid(), pv.asVoid()]).then(on: zalgo) { (pu.value!, pv.value!) } +} + +/// Wait for all promises in a set to fulfill. +public func when(fulfilled pu: Promise, _ pv: Promise, _ pw: Promise) -> Promise<(U, V, W)> { + return _when([pu.asVoid(), pv.asVoid(), pw.asVoid()]).then(on: zalgo) { (pu.value!, pv.value!, pw.value!) } +} + +/// Wait for all promises in a set to fulfill. +public func when(fulfilled pu: Promise, _ pv: Promise, _ pw: Promise, _ px: Promise) -> Promise<(U, V, W, X)> { + return _when([pu.asVoid(), pv.asVoid(), pw.asVoid(), px.asVoid()]).then(on: zalgo) { (pu.value!, pv.value!, pw.value!, px.value!) } +} + +/// Wait for all promises in a set to fulfill. +public func when(fulfilled pu: Promise, _ pv: Promise, _ pw: Promise, _ px: Promise, _ py: Promise) -> Promise<(U, V, W, X, Y)> { + return _when([pu.asVoid(), pv.asVoid(), pw.asVoid(), px.asVoid(), py.asVoid()]).then(on: zalgo) { (pu.value!, pv.value!, pw.value!, px.value!, py.value!) } +} + +/** + Generate promises at a limited rate and wait for all to fulfill. + + For example: + + func downloadFile(url: URL) -> Promise { + // ... + } + + let urls: [URL] = /*…*/ + let urlGenerator = urls.makeIterator() + + let generator = AnyIterator> { + guard url = urlGenerator.next() else { + return nil + } + + return downloadFile(url) + } + + when(generator, concurrently: 3).then { datum: [Data] -> Void in + // ... + } + + - Warning: Refer to the warnings on `when(fulfilled:)` + - Parameter promiseGenerator: Generator of promises. + - Returns: A new promise that resolves when all the provided promises fulfill or one of the provided promises rejects. + - SeeAlso: `when(resolved:)` + */ + +public func when(fulfilled promiseIterator: PromiseIterator, concurrently: Int) -> Promise<[T]> where PromiseIterator.Element == Promise { + + guard concurrently > 0 else { + return Promise(error: PMKError.whenConcurrentlyZero) + } + + var generator = promiseIterator + var root = Promise<[T]>.pending() + var pendingPromises = 0 + var promises: [Promise] = [] + + let barrier = DispatchQueue(label: "org.promisekit.barrier.when", attributes: [.concurrent]) + + func dequeue() { + guard root.promise.isPending else { return } // don’t continue dequeueing if root has been rejected + + var shouldDequeue = false + barrier.sync { + shouldDequeue = pendingPromises < concurrently + } + guard shouldDequeue else { return } + + var index: Int! + var promise: Promise! + + barrier.sync(flags: .barrier) { + guard let next = generator.next() else { return } + + promise = next + index = promises.count + + pendingPromises += 1 + promises.append(next) + } + + func testDone() { + barrier.sync { + if pendingPromises == 0 { + root.fulfill(promises.flatMap{ $0.value }) + } + } + } + + guard promise != nil else { + return testDone() + } + + promise.state.pipe { resolution in + barrier.sync(flags: .barrier) { + pendingPromises -= 1 + } + + switch resolution { + case .fulfilled: + dequeue() + testDone() + case .rejected(let error, let token): + token.consumed = true + root.reject(error) + } + } + + dequeue() + } + + dequeue() + + return root.promise +} + +/** + Waits on all provided promises. + + `when(fulfilled:)` rejects as soon as one of the provided promises rejects. `when(resolved:)` waits on all provided promises and **never** rejects. + + when(resolved: promise1, promise2, promise3).then { results in + for result in results where case .fulfilled(let value) { + //… + } + }.catch { error in + // invalid! Never rejects + } + + - Returns: A new promise that resolves once all the provided promises resolve. + - Warning: The returned promise can *not* be rejected. + - Note: Any promises that error are implicitly consumed, your UnhandledErrorHandler will not be called. +*/ +public func when(resolved promises: Promise...) -> Promise<[Result]> { + return when(resolved: promises) +} + +/// Waits on all provided promises. +public func when(resolved promises: [Promise]) -> Promise<[Result]> { + guard !promises.isEmpty else { return Promise(value: []) } + + var countdown = promises.count + let barrier = DispatchQueue(label: "org.promisekit.barrier.join", attributes: .concurrent) + + return Promise { fulfill, reject in + for promise in promises { + promise.state.pipe { resolution in + if case .rejected(_, let token) = resolution { + token.consumed = true // all errors are implicitly consumed + } + var done = false + barrier.sync(flags: .barrier) { + countdown -= 1 + done = countdown == 0 + } + if done { + fulfill(promises.map { Result($0.state.get()!) }) + } + } + } + } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/wrap.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/wrap.swift new file mode 100644 index 0000000000..3b715f1e06 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/wrap.swift @@ -0,0 +1,75 @@ +/** + Create a new pending promise by wrapping another asynchronous system. + + This initializer is convenient when wrapping asynchronous systems that + use common patterns. For example: + + func fetchKitten() -> Promise { + return PromiseKit.wrap { resolve in + KittenFetcher.fetchWithCompletionBlock(resolve) + } + } + + - SeeAlso: Promise.init(resolvers:) +*/ +public func wrap(_ body: (@escaping (T?, Error?) -> Void) throws -> Void) -> Promise { + return Promise { fulfill, reject in + try body { obj, err in + if let err = err { + reject(err) + } else if let obj = obj { + fulfill(obj) + } else { + reject(PMKError.invalidCallingConvention) + } + } + } +} + +/// For completion-handlers that eg. provide an enum or an error. +public func wrap(_ body: (@escaping (T, Error?) -> Void) throws -> Void) -> Promise { + return Promise { fulfill, reject in + try body { obj, err in + if let err = err { + reject(err) + } else { + fulfill(obj) + } + } + } +} + +/// Some APIs unwisely invert the Cocoa standard for completion-handlers. +public func wrap(_ body: (@escaping (Error?, T?) -> Void) throws -> Void) -> Promise { + return Promise { fulfill, reject in + try body { err, obj in + if let err = err { + reject(err) + } else if let obj = obj { + fulfill(obj) + } else { + reject(PMKError.invalidCallingConvention) + } + } + } +} + +/// For completion-handlers with just an optional Error +public func wrap(_ body: (@escaping (Error?) -> Void) throws -> Void) -> Promise { + return Promise { fulfill, reject in + try body { error in + if let error = error { + reject(error) + } else { + fulfill() + } + } + } +} + +/// For completions that cannot error. +public func wrap(_ body: (@escaping (T) -> Void) throws -> Void) -> Promise { + return Promise { fulfill, _ in + try body(fulfill) + } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-dummy.m b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-dummy.m new file mode 100644 index 0000000000..a6c4594242 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Alamofire : NSObject +@end +@implementation PodsDummy_Alamofire +@end diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch new file mode 100644 index 0000000000..aa992a4adb --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch @@ -0,0 +1,4 @@ +#ifdef __OBJC__ +#import +#endif + diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h new file mode 100644 index 0000000000..02327b85e8 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h @@ -0,0 +1,8 @@ +#ifdef __OBJC__ +#import +#endif + + +FOUNDATION_EXPORT double AlamofireVersionNumber; +FOUNDATION_EXPORT const unsigned char AlamofireVersionString[]; + diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.modulemap b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.modulemap new file mode 100644 index 0000000000..d1f125fab6 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.modulemap @@ -0,0 +1,6 @@ +framework module Alamofire { + umbrella header "Alamofire-umbrella.h" + + export * + module * { export * } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.xcconfig b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.xcconfig new file mode 100644 index 0000000000..772ef0b2bc --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.xcconfig @@ -0,0 +1,9 @@ +CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/Alamofire +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist new file mode 100644 index 0000000000..c1c4a98b9a --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 4.5.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/Info.plist b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/Info.plist new file mode 100644 index 0000000000..cba258550b --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 0.0.1 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-dummy.m b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-dummy.m new file mode 100644 index 0000000000..749b412f85 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_PetstoreClient : NSObject +@end +@implementation PodsDummy_PetstoreClient +@end diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-prefix.pch b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-prefix.pch new file mode 100644 index 0000000000..aa992a4adb --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-prefix.pch @@ -0,0 +1,4 @@ +#ifdef __OBJC__ +#import +#endif + diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-umbrella.h b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-umbrella.h new file mode 100644 index 0000000000..435b682a10 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-umbrella.h @@ -0,0 +1,8 @@ +#ifdef __OBJC__ +#import +#endif + + +FOUNDATION_EXPORT double PetstoreClientVersionNumber; +FOUNDATION_EXPORT const unsigned char PetstoreClientVersionString[]; + diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.modulemap b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.modulemap new file mode 100644 index 0000000000..7fdfc46cf7 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.modulemap @@ -0,0 +1,6 @@ +framework module PetstoreClient { + umbrella header "PetstoreClient-umbrella.h" + + export * + module * { export * } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.xcconfig b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.xcconfig new file mode 100644 index 0000000000..59a957e4d4 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.xcconfig @@ -0,0 +1,10 @@ +CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/PetstoreClient +FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/PromiseKit" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Info.plist b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Info.plist new file mode 100644 index 0000000000..2243fe6e27 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.markdown b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.markdown new file mode 100644 index 0000000000..aefa208fd0 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.markdown @@ -0,0 +1,50 @@ +# Acknowledgements +This application makes use of the following third party libraries: + +## Alamofire + +Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +## PromiseKit + +Copyright 2016, Max Howell; mxcl@me.com + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Generated by CocoaPods - https://cocoapods.org diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.plist b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.plist new file mode 100644 index 0000000000..987225cd1b --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.plist @@ -0,0 +1,88 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + 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. + + License + MIT + Title + Alamofire + Type + PSGroupSpecifier + + + FooterText + Copyright 2016, Max Howell; mxcl@me.com + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + License + MIT + Title + PromiseKit + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-dummy.m b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-dummy.m new file mode 100644 index 0000000000..6236440163 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_SwaggerClient : NSObject +@end +@implementation PodsDummy_Pods_SwaggerClient +@end diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh new file mode 100755 index 0000000000..bbccf28833 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh @@ -0,0 +1,95 @@ +#!/bin/sh +set -e + +echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" +mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + +SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" + +install_framework() +{ + if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then + local source="${BUILT_PRODUCTS_DIR}/$1" + elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then + local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" + elif [ -r "$1" ]; then + local source="$1" + fi + + local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + + if [ -L "${source}" ]; then + echo "Symlinked..." + source="$(readlink "${source}")" + fi + + # use filter instead of exclude so missing patterns dont' throw errors + echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" + rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" + + local basename + basename="$(basename -s .framework "$1")" + binary="${destination}/${basename}.framework/${basename}" + if ! [ -r "$binary" ]; then + binary="${destination}/${basename}" + fi + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then + strip_invalid_archs "$binary" + fi + + # Resign the code if required by the build settings to avoid unstable apps + code_sign_if_enabled "${destination}/$(basename "$1")" + + # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. + if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then + local swift_runtime_libs + swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) + for lib in $swift_runtime_libs; do + echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" + rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" + code_sign_if_enabled "${destination}/${lib}" + done + fi +} + +# Signs a framework with the provided identity +code_sign_if_enabled() { + if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then + # Use the current code_sign_identitiy + echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" + echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements \"$1\"" + /usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements "$1" + fi +} + +# Strip invalid architectures +strip_invalid_archs() { + binary="$1" + # Get architectures for current file + archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)" + stripped="" + for arch in $archs; do + if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then + # Strip non-valid architectures in-place + lipo -remove "$arch" -output "$binary" "$binary" || exit 1 + stripped="$stripped $arch" + fi + done + if [[ "$stripped" ]]; then + echo "Stripped $binary of architectures:$stripped" + fi +} + + +if [[ "$CONFIGURATION" == "Debug" ]]; then + install_framework "$BUILT_PRODUCTS_DIR/Alamofire/Alamofire.framework" + install_framework "$BUILT_PRODUCTS_DIR/PetstoreClient/PetstoreClient.framework" + install_framework "$BUILT_PRODUCTS_DIR/PromiseKit/PromiseKit.framework" +fi +if [[ "$CONFIGURATION" == "Release" ]]; then + install_framework "$BUILT_PRODUCTS_DIR/Alamofire/Alamofire.framework" + install_framework "$BUILT_PRODUCTS_DIR/PetstoreClient/PetstoreClient.framework" + install_framework "$BUILT_PRODUCTS_DIR/PromiseKit/PromiseKit.framework" +fi diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh new file mode 100755 index 0000000000..25e9d37757 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh @@ -0,0 +1,96 @@ +#!/bin/sh +set -e + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + +RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt +> "$RESOURCES_TO_COPY" + +XCASSET_FILES=() + +case "${TARGETED_DEVICE_FAMILY}" in + 1,2) + TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone" + ;; + 1) + TARGET_DEVICE_ARGS="--target-device iphone" + ;; + 2) + TARGET_DEVICE_ARGS="--target-device ipad" + ;; + *) + TARGET_DEVICE_ARGS="--target-device mac" + ;; +esac + +install_resource() +{ + if [[ "$1" = /* ]] ; then + RESOURCE_PATH="$1" + else + RESOURCE_PATH="${PODS_ROOT}/$1" + fi + if [[ ! -e "$RESOURCE_PATH" ]] ; then + cat << EOM +error: Resource "$RESOURCE_PATH" not found. Run 'pod install' to update the copy resources script. +EOM + exit 1 + fi + case $RESOURCE_PATH in + *.storyboard) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.xib) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.framework) + echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + echo "rsync -av $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + rsync -av "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + ;; + *.xcdatamodel) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH"`.mom\"" + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodel`.mom" + ;; + *.xcdatamodeld) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd\"" + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd" + ;; + *.xcmappingmodel) + echo "xcrun mapc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm\"" + xcrun mapc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm" + ;; + *.xcassets) + ABSOLUTE_XCASSET_FILE="$RESOURCE_PATH" + XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE") + ;; + *) + echo "$RESOURCE_PATH" + echo "$RESOURCE_PATH" >> "$RESOURCES_TO_COPY" + ;; + esac +} + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +if [[ "${ACTION}" == "install" ]] && [[ "${SKIP_INSTALL}" == "NO" ]]; then + mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi +rm -f "$RESOURCES_TO_COPY" + +if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "$XCASSET_FILES" ] +then + # Find all other xcassets (this unfortunately includes those of path pods and other targets). + OTHER_XCASSETS=$(find "$PWD" -iname "*.xcassets" -type d) + while read line; do + if [[ $line != "${PODS_ROOT}*" ]]; then + XCASSET_FILES+=("$line") + fi + done <<<"$OTHER_XCASSETS" + + printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-umbrella.h b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-umbrella.h new file mode 100644 index 0000000000..2bdb03cd93 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-umbrella.h @@ -0,0 +1,8 @@ +#ifdef __OBJC__ +#import +#endif + + +FOUNDATION_EXPORT double Pods_SwaggerClientVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_SwaggerClientVersionString[]; + diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig new file mode 100644 index 0000000000..609a649dd1 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig @@ -0,0 +1,11 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +EMBEDDED_CONTENT_CONTAINS_SWIFT = YES +FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient" "$PODS_CONFIGURATION_BUILD_DIR/PromiseKit" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient/PetstoreClient.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PromiseKit/PromiseKit.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "PetstoreClient" -framework "PromiseKit" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT}/Pods diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap new file mode 100644 index 0000000000..ef919b6c0d --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap @@ -0,0 +1,6 @@ +framework module Pods_SwaggerClient { + umbrella header "Pods-SwaggerClient-umbrella.h" + + export * + module * { export * } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig new file mode 100644 index 0000000000..609a649dd1 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig @@ -0,0 +1,11 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +EMBEDDED_CONTENT_CONTAINS_SWIFT = YES +FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient" "$PODS_CONFIGURATION_BUILD_DIR/PromiseKit" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient/PetstoreClient.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PromiseKit/PromiseKit.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "PetstoreClient" -framework "PromiseKit" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT}/Pods diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Info.plist b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Info.plist new file mode 100644 index 0000000000..2243fe6e27 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-acknowledgements.markdown b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-acknowledgements.markdown new file mode 100644 index 0000000000..102af75385 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-acknowledgements.markdown @@ -0,0 +1,3 @@ +# Acknowledgements +This application makes use of the following third party libraries: +Generated by CocoaPods - https://cocoapods.org diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-acknowledgements.plist b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-acknowledgements.plist new file mode 100644 index 0000000000..7acbad1eab --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-acknowledgements.plist @@ -0,0 +1,29 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-dummy.m b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-dummy.m new file mode 100644 index 0000000000..bb17fa2b80 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_SwaggerClientTests : NSObject +@end +@implementation PodsDummy_Pods_SwaggerClientTests +@end diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh new file mode 100755 index 0000000000..893c16a631 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh @@ -0,0 +1,84 @@ +#!/bin/sh +set -e + +echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" +mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + +SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" + +install_framework() +{ + if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then + local source="${BUILT_PRODUCTS_DIR}/$1" + elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then + local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" + elif [ -r "$1" ]; then + local source="$1" + fi + + local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + + if [ -L "${source}" ]; then + echo "Symlinked..." + source="$(readlink "${source}")" + fi + + # use filter instead of exclude so missing patterns dont' throw errors + echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" + rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" + + local basename + basename="$(basename -s .framework "$1")" + binary="${destination}/${basename}.framework/${basename}" + if ! [ -r "$binary" ]; then + binary="${destination}/${basename}" + fi + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then + strip_invalid_archs "$binary" + fi + + # Resign the code if required by the build settings to avoid unstable apps + code_sign_if_enabled "${destination}/$(basename "$1")" + + # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. + if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then + local swift_runtime_libs + swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) + for lib in $swift_runtime_libs; do + echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" + rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" + code_sign_if_enabled "${destination}/${lib}" + done + fi +} + +# Signs a framework with the provided identity +code_sign_if_enabled() { + if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then + # Use the current code_sign_identitiy + echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" + echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements \"$1\"" + /usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements "$1" + fi +} + +# Strip invalid architectures +strip_invalid_archs() { + binary="$1" + # Get architectures for current file + archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)" + stripped="" + for arch in $archs; do + if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then + # Strip non-valid architectures in-place + lipo -remove "$arch" -output "$binary" "$binary" || exit 1 + stripped="$stripped $arch" + fi + done + if [[ "$stripped" ]]; then + echo "Stripped $binary of architectures:$stripped" + fi +} + diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh new file mode 100755 index 0000000000..25e9d37757 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh @@ -0,0 +1,96 @@ +#!/bin/sh +set -e + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + +RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt +> "$RESOURCES_TO_COPY" + +XCASSET_FILES=() + +case "${TARGETED_DEVICE_FAMILY}" in + 1,2) + TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone" + ;; + 1) + TARGET_DEVICE_ARGS="--target-device iphone" + ;; + 2) + TARGET_DEVICE_ARGS="--target-device ipad" + ;; + *) + TARGET_DEVICE_ARGS="--target-device mac" + ;; +esac + +install_resource() +{ + if [[ "$1" = /* ]] ; then + RESOURCE_PATH="$1" + else + RESOURCE_PATH="${PODS_ROOT}/$1" + fi + if [[ ! -e "$RESOURCE_PATH" ]] ; then + cat << EOM +error: Resource "$RESOURCE_PATH" not found. Run 'pod install' to update the copy resources script. +EOM + exit 1 + fi + case $RESOURCE_PATH in + *.storyboard) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.xib) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.framework) + echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + echo "rsync -av $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + rsync -av "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + ;; + *.xcdatamodel) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH"`.mom\"" + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodel`.mom" + ;; + *.xcdatamodeld) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd\"" + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd" + ;; + *.xcmappingmodel) + echo "xcrun mapc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm\"" + xcrun mapc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm" + ;; + *.xcassets) + ABSOLUTE_XCASSET_FILE="$RESOURCE_PATH" + XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE") + ;; + *) + echo "$RESOURCE_PATH" + echo "$RESOURCE_PATH" >> "$RESOURCES_TO_COPY" + ;; + esac +} + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +if [[ "${ACTION}" == "install" ]] && [[ "${SKIP_INSTALL}" == "NO" ]]; then + mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi +rm -f "$RESOURCES_TO_COPY" + +if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "$XCASSET_FILES" ] +then + # Find all other xcassets (this unfortunately includes those of path pods and other targets). + OTHER_XCASSETS=$(find "$PWD" -iname "*.xcassets" -type d) + while read line; do + if [[ $line != "${PODS_ROOT}*" ]]; then + XCASSET_FILES+=("$line") + fi + done <<<"$OTHER_XCASSETS" + + printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-umbrella.h b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-umbrella.h new file mode 100644 index 0000000000..950bb19ca7 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-umbrella.h @@ -0,0 +1,8 @@ +#ifdef __OBJC__ +#import +#endif + + +FOUNDATION_EXPORT double Pods_SwaggerClientTestsVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_SwaggerClientTestsVersionString[]; + diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig new file mode 100644 index 0000000000..a855711775 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig @@ -0,0 +1,8 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient" "$PODS_CONFIGURATION_BUILD_DIR/PromiseKit" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient/PetstoreClient.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PromiseKit/PromiseKit.framework/Headers" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT}/Pods diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap new file mode 100644 index 0000000000..a848da7ffb --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap @@ -0,0 +1,6 @@ +framework module Pods_SwaggerClientTests { + umbrella header "Pods-SwaggerClientTests-umbrella.h" + + export * + module * { export * } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig new file mode 100644 index 0000000000..a855711775 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig @@ -0,0 +1,8 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient" "$PODS_CONFIGURATION_BUILD_DIR/PromiseKit" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PetstoreClient/PetstoreClient.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/PromiseKit/PromiseKit.framework/Headers" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT}/Pods diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/Info.plist b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/Info.plist new file mode 100644 index 0000000000..b04e694ee5 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 4.2.2 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit-dummy.m b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit-dummy.m new file mode 100644 index 0000000000..ce92451305 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_PromiseKit : NSObject +@end +@implementation PodsDummy_PromiseKit +@end diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit-prefix.pch b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit-prefix.pch new file mode 100644 index 0000000000..aa992a4adb --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit-prefix.pch @@ -0,0 +1,4 @@ +#ifdef __OBJC__ +#import +#endif + diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit-umbrella.h b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit-umbrella.h new file mode 100644 index 0000000000..3a06b7bd32 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit-umbrella.h @@ -0,0 +1,20 @@ +#ifdef __OBJC__ +#import +#endif + +#import "AnyPromise.h" +#import "fwd.h" +#import "PromiseKit.h" +#import "NSNotificationCenter+AnyPromise.h" +#import "NSTask+AnyPromise.h" +#import "NSURLSession+AnyPromise.h" +#import "PMKFoundation.h" +#import "CALayer+AnyPromise.h" +#import "PMKQuartzCore.h" +#import "PMKUIKit.h" +#import "UIView+AnyPromise.h" +#import "UIViewController+AnyPromise.h" + +FOUNDATION_EXPORT double PromiseKitVersionNumber; +FOUNDATION_EXPORT const unsigned char PromiseKitVersionString[]; + diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit.modulemap b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit.modulemap new file mode 100644 index 0000000000..2b26033e4a --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit.modulemap @@ -0,0 +1,6 @@ +framework module PromiseKit { + umbrella header "PromiseKit-umbrella.h" + + export * + module * { export * } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit.xcconfig b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit.xcconfig new file mode 100644 index 0000000000..dcb583d56a --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/PromiseKit.xcconfig @@ -0,0 +1,10 @@ +CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/PromiseKit +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" +OTHER_LDFLAGS = -framework "Foundation" -framework "QuartzCore" -framework "UIKit" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj new file mode 100644 index 0000000000..67337de03e --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -0,0 +1,563 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 54DA06C1D70D78EC0EC72B61 /* Pods_SwaggerClientTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F65B6638217EDDC99D103B16 /* Pods_SwaggerClientTests.framework */; }; + 6D4EFB951C692C6300B96B06 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */; }; + 6D4EFB971C692C6300B96B06 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFB961C692C6300B96B06 /* ViewController.swift */; }; + 6D4EFB9A1C692C6300B96B06 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 6D4EFB981C692C6300B96B06 /* Main.storyboard */; }; + 6D4EFB9C1C692C6300B96B06 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 6D4EFB9B1C692C6300B96B06 /* Assets.xcassets */; }; + 6D4EFB9F1C692C6300B96B06 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 6D4EFB9D1C692C6300B96B06 /* LaunchScreen.storyboard */; }; + 6D4EFBB51C693BE200B96B06 /* PetAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */; }; + 6D4EFBB71C693BED00B96B06 /* StoreAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */; }; + 6D4EFBB91C693BFC00B96B06 /* UserAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */; }; + 751C65B82F596107A3DC8ED9 /* Pods_SwaggerClient.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8F60AECFF321A25553B6A5B0 /* Pods_SwaggerClient.framework */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 6D4EFBA61C692C6300B96B06 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 6D4EFB891C692C6300B96B06 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 6D4EFB901C692C6300B96B06; + remoteInfo = SwaggerClient; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 289E8A9E9C0BB66AD190C7C6 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; + 6D4EFB911C692C6300B96B06 /* SwaggerClient.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SwaggerClient.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 6D4EFB961C692C6300B96B06 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; + 6D4EFB991C692C6300B96B06 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 6D4EFB9B1C692C6300B96B06 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 6D4EFB9E1C692C6300B96B06 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 6D4EFBA01C692C6300B96B06 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 6D4EFBA51C692C6300B96B06 /* SwaggerClientTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = SwaggerClientTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 6D4EFBAB1C692C6300B96B06 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PetAPITests.swift; sourceTree = ""; }; + 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StoreAPITests.swift; sourceTree = ""; }; + 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UserAPITests.swift; sourceTree = ""; }; + 8F60AECFF321A25553B6A5B0 /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + A638467ACFB30852DEA51F7A /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; + B4B2BEC2ECA535C616F2F3FE /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; + C07EC0A94AA0F86D60668B32 /* Pods.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + F65B6638217EDDC99D103B16 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + FC60BDC7328C2AA916F25840 /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 6D4EFB8E1C692C6300B96B06 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 751C65B82F596107A3DC8ED9 /* Pods_SwaggerClient.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6D4EFBA21C692C6300B96B06 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 54DA06C1D70D78EC0EC72B61 /* Pods_SwaggerClientTests.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 0CAA98BEFA303B94D3664C7D /* Pods */ = { + isa = PBXGroup; + children = ( + A638467ACFB30852DEA51F7A /* Pods-SwaggerClient.debug.xcconfig */, + FC60BDC7328C2AA916F25840 /* Pods-SwaggerClient.release.xcconfig */, + 289E8A9E9C0BB66AD190C7C6 /* Pods-SwaggerClientTests.debug.xcconfig */, + B4B2BEC2ECA535C616F2F3FE /* Pods-SwaggerClientTests.release.xcconfig */, + ); + name = Pods; + sourceTree = ""; + }; + 3FABC56EC0BA84CBF4F99564 /* Frameworks */ = { + isa = PBXGroup; + children = ( + C07EC0A94AA0F86D60668B32 /* Pods.framework */, + 8F60AECFF321A25553B6A5B0 /* Pods_SwaggerClient.framework */, + F65B6638217EDDC99D103B16 /* Pods_SwaggerClientTests.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + 6D4EFB881C692C6300B96B06 = { + isa = PBXGroup; + children = ( + 6D4EFB931C692C6300B96B06 /* SwaggerClient */, + 6D4EFBA81C692C6300B96B06 /* SwaggerClientTests */, + 6D4EFB921C692C6300B96B06 /* Products */, + 3FABC56EC0BA84CBF4F99564 /* Frameworks */, + 0CAA98BEFA303B94D3664C7D /* Pods */, + ); + sourceTree = ""; + }; + 6D4EFB921C692C6300B96B06 /* Products */ = { + isa = PBXGroup; + children = ( + 6D4EFB911C692C6300B96B06 /* SwaggerClient.app */, + 6D4EFBA51C692C6300B96B06 /* SwaggerClientTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 6D4EFB931C692C6300B96B06 /* SwaggerClient */ = { + isa = PBXGroup; + children = ( + 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */, + 6D4EFB961C692C6300B96B06 /* ViewController.swift */, + 6D4EFB981C692C6300B96B06 /* Main.storyboard */, + 6D4EFB9B1C692C6300B96B06 /* Assets.xcassets */, + 6D4EFB9D1C692C6300B96B06 /* LaunchScreen.storyboard */, + 6D4EFBA01C692C6300B96B06 /* Info.plist */, + ); + path = SwaggerClient; + sourceTree = ""; + }; + 6D4EFBA81C692C6300B96B06 /* SwaggerClientTests */ = { + isa = PBXGroup; + children = ( + 6D4EFBAB1C692C6300B96B06 /* Info.plist */, + 6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */, + 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */, + 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */, + ); + path = SwaggerClientTests; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 6D4EFB901C692C6300B96B06 /* SwaggerClient */ = { + isa = PBXNativeTarget; + buildConfigurationList = 6D4EFBAE1C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClient" */; + buildPhases = ( + 1F03F780DC2D9727E5E64BA9 /* [CP] Check Pods Manifest.lock */, + 6D4EFB8D1C692C6300B96B06 /* Sources */, + 6D4EFB8E1C692C6300B96B06 /* Frameworks */, + 6D4EFB8F1C692C6300B96B06 /* Resources */, + 4485A75250058E2D5BBDF63F /* [CP] Embed Pods Frameworks */, + 808CE4A0CE801CAC5ABF5B08 /* [CP] Copy Pods Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = SwaggerClient; + productName = SwaggerClient; + productReference = 6D4EFB911C692C6300B96B06 /* SwaggerClient.app */; + productType = "com.apple.product-type.application"; + }; + 6D4EFBA41C692C6300B96B06 /* SwaggerClientTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 6D4EFBB11C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */; + buildPhases = ( + 79FE27B09B2DD354C831BD49 /* [CP] Check Pods Manifest.lock */, + 6D4EFBA11C692C6300B96B06 /* Sources */, + 6D4EFBA21C692C6300B96B06 /* Frameworks */, + 6D4EFBA31C692C6300B96B06 /* Resources */, + 796EAD48F1BCCDAA291CD963 /* [CP] Embed Pods Frameworks */, + 1652CB1A246A4689869E442D /* [CP] Copy Pods Resources */, + ); + buildRules = ( + ); + dependencies = ( + 6D4EFBA71C692C6300B96B06 /* PBXTargetDependency */, + ); + name = SwaggerClientTests; + productName = SwaggerClientTests; + productReference = 6D4EFBA51C692C6300B96B06 /* SwaggerClientTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 6D4EFB891C692C6300B96B06 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0720; + LastUpgradeCheck = 0800; + ORGANIZATIONNAME = Swagger; + TargetAttributes = { + 6D4EFB901C692C6300B96B06 = { + CreatedOnToolsVersion = 7.2.1; + LastSwiftMigration = 0800; + }; + 6D4EFBA41C692C6300B96B06 = { + CreatedOnToolsVersion = 7.2.1; + LastSwiftMigration = 0800; + TestTargetID = 6D4EFB901C692C6300B96B06; + }; + }; + }; + buildConfigurationList = 6D4EFB8C1C692C6300B96B06 /* Build configuration list for PBXProject "SwaggerClient" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 6D4EFB881C692C6300B96B06; + productRefGroup = 6D4EFB921C692C6300B96B06 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 6D4EFB901C692C6300B96B06 /* SwaggerClient */, + 6D4EFBA41C692C6300B96B06 /* SwaggerClientTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 6D4EFB8F1C692C6300B96B06 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 6D4EFB9F1C692C6300B96B06 /* LaunchScreen.storyboard in Resources */, + 6D4EFB9C1C692C6300B96B06 /* Assets.xcassets in Resources */, + 6D4EFB9A1C692C6300B96B06 /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6D4EFBA31C692C6300B96B06 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 1652CB1A246A4689869E442D /* [CP] Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Copy Pods Resources"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; + 1F03F780DC2D9727E5E64BA9 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Check Pods Manifest.lock"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n"; + showEnvVarsInLog = 0; + }; + 4485A75250058E2D5BBDF63F /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Embed Pods Frameworks"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 796EAD48F1BCCDAA291CD963 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Embed Pods Frameworks"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 79FE27B09B2DD354C831BD49 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Check Pods Manifest.lock"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n"; + showEnvVarsInLog = 0; + }; + 808CE4A0CE801CAC5ABF5B08 /* [CP] Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Copy Pods Resources"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 6D4EFB8D1C692C6300B96B06 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 6D4EFB971C692C6300B96B06 /* ViewController.swift in Sources */, + 6D4EFB951C692C6300B96B06 /* AppDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6D4EFBA11C692C6300B96B06 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 6D4EFBB71C693BED00B96B06 /* StoreAPITests.swift in Sources */, + 6D4EFBB91C693BFC00B96B06 /* UserAPITests.swift in Sources */, + 6D4EFBB51C693BE200B96B06 /* PetAPITests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 6D4EFBA71C692C6300B96B06 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 6D4EFB901C692C6300B96B06 /* SwaggerClient */; + targetProxy = 6D4EFBA61C692C6300B96B06 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 6D4EFB981C692C6300B96B06 /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 6D4EFB991C692C6300B96B06 /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 6D4EFB9D1C692C6300B96B06 /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 6D4EFB9E1C692C6300B96B06 /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 6D4EFBAC1C692C6300B96B06 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.2; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 6D4EFBAD1C692C6300B96B06 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.2; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 6D4EFBAF1C692C6300B96B06 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = A638467ACFB30852DEA51F7A /* Pods-SwaggerClient.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + INFOPLIST_FILE = SwaggerClient/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; + }; + name = Debug; + }; + 6D4EFBB01C692C6300B96B06 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = FC60BDC7328C2AA916F25840 /* Pods-SwaggerClient.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + INFOPLIST_FILE = SwaggerClient/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; + }; + name = Release; + }; + 6D4EFBB21C692C6300B96B06 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 289E8A9E9C0BB66AD190C7C6 /* Pods-SwaggerClientTests.debug.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + INFOPLIST_FILE = SwaggerClientTests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/SwaggerClient.app/SwaggerClient"; + }; + name = Debug; + }; + 6D4EFBB31C692C6300B96B06 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = B4B2BEC2ECA535C616F2F3FE /* Pods-SwaggerClientTests.release.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + INFOPLIST_FILE = SwaggerClientTests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/SwaggerClient.app/SwaggerClient"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 6D4EFB8C1C692C6300B96B06 /* Build configuration list for PBXProject "SwaggerClient" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 6D4EFBAC1C692C6300B96B06 /* Debug */, + 6D4EFBAD1C692C6300B96B06 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 6D4EFBAE1C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClient" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 6D4EFBAF1C692C6300B96B06 /* Debug */, + 6D4EFBB01C692C6300B96B06 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 6D4EFBB11C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 6D4EFBB21C692C6300B96B06 /* Debug */, + 6D4EFBB31C692C6300B96B06 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 6D4EFB891C692C6300B96B06 /* Project object */; +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/SwaggerClient.xcscheme b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/SwaggerClient.xcscheme new file mode 100644 index 0000000000..4d00ed5f92 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/SwaggerClient.xcscheme @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000000..9b3fa18954 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClient/AppDelegate.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClient/AppDelegate.swift new file mode 100644 index 0000000000..7fd6929617 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClient/AppDelegate.swift @@ -0,0 +1,46 @@ +// +// AppDelegate.swift +// SwaggerClient +// +// Created by Joseph Zuromski on 2/8/16. +// Copyright © 2016 Swagger. All rights reserved. +// + +import UIKit + +@UIApplicationMain +class AppDelegate: UIResponder, UIApplicationDelegate { + + var window: UIWindow? + + + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { + // Override point for customization after application launch. + return true + } + + func applicationWillResignActive(_ application: UIApplication) { + // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. + // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. + } + + func applicationDidEnterBackground(_ application: UIApplication) { + // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. + // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. + } + + func applicationWillEnterForeground(_ application: UIApplication) { + // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. + } + + func applicationDidBecomeActive(_ application: UIApplication) { + // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. + } + + func applicationWillTerminate(_ application: UIApplication) { + // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. + } + + +} + diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClient/Assets.xcassets/AppIcon.appiconset/Contents.json b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClient/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000000..1d060ed288 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClient/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,93 @@ +{ + "images" : [ + { + "idiom" : "iphone", + "size" : "20x20", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "20x20", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "29x29", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "29x29", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "40x40", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "40x40", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "60x60", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "60x60", + "scale" : "3x" + }, + { + "idiom" : "ipad", + "size" : "20x20", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "20x20", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "29x29", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "29x29", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "40x40", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "40x40", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "76x76", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "76x76", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "83.5x83.5", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClient/Base.lproj/LaunchScreen.storyboard b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClient/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000000..2e721e1833 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClient/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClient/Base.lproj/Main.storyboard b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClient/Base.lproj/Main.storyboard new file mode 100644 index 0000000000..3a2a49bad8 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClient/Base.lproj/Main.storyboard @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClient/Info.plist b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClient/Info.plist new file mode 100644 index 0000000000..bb71d00fa8 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClient/Info.plist @@ -0,0 +1,59 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + NSAppTransportSecurity + + NSExceptionDomains + + petstore.swagger.io + + + NSTemporaryExceptionAllowsInsecureHTTPLoads + + + + + + diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClient/ViewController.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClient/ViewController.swift new file mode 100644 index 0000000000..cd7e9a1676 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClient/ViewController.swift @@ -0,0 +1,25 @@ +// +// ViewController.swift +// SwaggerClient +// +// Created by Joseph Zuromski on 2/8/16. +// Copyright © 2016 Swagger. All rights reserved. +// + +import UIKit + +class ViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + // Do any additional setup after loading the view, typically from a nib. + } + + override func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + // Dispose of any resources that can be recreated. + } + + +} + diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClientTests/Info.plist b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClientTests/Info.plist new file mode 100644 index 0000000000..802f84f540 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClientTests/Info.plist @@ -0,0 +1,36 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + BNDL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + NSAppTransportSecurity + + NSExceptionDomains + + petstore.swagger.io + + + NSTemporaryExceptionAllowsInsecureHTTPLoads + + + + + + diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift new file mode 100644 index 0000000000..7151720bf4 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift @@ -0,0 +1,69 @@ +// +// PetAPITests.swift +// SwaggerClient +// +// Created by Joseph Zuromski on 2/8/16. +// Copyright © 2016 Swagger. All rights reserved. +// + +import PetstoreClient +import PromiseKit +import XCTest +@testable import SwaggerClient + +class PetAPITests: XCTestCase { + + let testTimeout = 10.0 + + override func setUp() { + super.setUp() + // Put setup code here. This method is called before the invocation of each test method in the class. + } + + override func tearDown() { + // Put teardown code here. This method is called after the invocation of each test method in the class. + super.tearDown() + } + + func test1CreatePet() { + let expectation = self.expectation(description: "testCreatePet") + let newPet = Pet() + let category = PetstoreClient.Category() + category.id = 1234 + category.name = "eyeColor" + newPet.category = category + newPet.id = 1000 + newPet.name = "Fluffy" + newPet.status = .available + PetAPI.addPet(body: newPet).then { + expectation.fulfill() + }.always { + // Noop for now + }.catch { errorType in + XCTFail("error creating pet") + } + self.waitForExpectations(timeout: testTimeout, handler: nil) + } + + func test2GetPet() { + let expectation = self.expectation(description: "testGetPet") + PetAPI.getPetById(petId: 1000).then { pet -> Void in + XCTAssert(pet.id == 1000, "invalid id") + XCTAssert(pet.name == "Fluffy", "invalid name") + expectation.fulfill() + }.always { + // Noop for now + }.catch { errorType in + XCTFail("error creating pet") + } + self.waitForExpectations(timeout: testTimeout, handler: nil) + } + + func test3DeletePet() { + let expectation = self.expectation(description: "testDeletePet") + PetAPI.deletePet(petId: 1000).then { + expectation.fulfill() + } + self.waitForExpectations(timeout: testTimeout, handler: nil) + } +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift new file mode 100644 index 0000000000..b8f58649cb --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift @@ -0,0 +1,88 @@ +// +// StoreAPITests.swift +// SwaggerClient +// +// Created by Joseph Zuromski on 2/8/16. +// Copyright © 2016 Swagger. All rights reserved. +// + +import PetstoreClient +import PromiseKit +import XCTest +@testable import SwaggerClient + +class StoreAPITests: XCTestCase { + + let isoDateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" + + let testTimeout = 10.0 + + func test1PlaceOrder() { + let order = Order() + let shipDate = Date() + order.id = 1000 + order.petId = 1000 + order.complete = false + order.quantity = 10 + order.shipDate = shipDate + // use explicit naming to reference the enum so that we test we don't regress on enum naming + order.status = Order.Status.placed + let expectation = self.expectation(description: "testPlaceOrder") + StoreAPI.placeOrder(body: order).then { order -> Void in + XCTAssert(order.id == 1000, "invalid id") + XCTAssert(order.quantity == 10, "invalid quantity") + XCTAssert(order.status == .placed, "invalid status") + XCTAssert(order.shipDate!.isEqual(shipDate, format: self.isoDateFormat), + "Date should be idempotent") + + expectation.fulfill() + }.always { + // Noop for now + }.catch { errorType in + XCTFail("error placing order") + } + self.waitForExpectations(timeout: testTimeout, handler: nil) + } + + func test2GetOrder() { + let expectation = self.expectation(description: "testGetOrder") + StoreAPI.getOrderById(orderId: 1000).then { order -> Void in + XCTAssert(order.id == 1000, "invalid id") + XCTAssert(order.quantity == 10, "invalid quantity") + XCTAssert(order.status == .placed, "invalid status") + expectation.fulfill() + }.always { + // Noop for now + }.catch { errorType in + XCTFail("error placing order") + } + self.waitForExpectations(timeout: testTimeout, handler: nil) + } + + func test3DeleteOrder() { + let expectation = self.expectation(description: "testDeleteOrder") + StoreAPI.deleteOrder(orderId: "1000").then { + expectation.fulfill() + } + self.waitForExpectations(timeout: testTimeout, handler: nil) + } + +} + +private extension Date { + + /** + Returns true if the dates are equal given the format string. + + - parameter date: The date to compare to. + - parameter format: The format string to use to compare. + + - returns: true if the dates are equal, given the format string. + */ + func isEqual(_ date: Date, format: String) -> Bool { + let fmt = DateFormatter() + fmt.dateFormat = format + return fmt.string(from: self).isEqual(fmt.string(from: date)) + } + +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift new file mode 100644 index 0000000000..3042129608 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift @@ -0,0 +1,77 @@ +// +// UserAPITests.swift +// SwaggerClient +// +// Created by Joseph Zuromski on 2/8/16. +// Copyright © 2016 Swagger. All rights reserved. +// + +import PetstoreClient +import PromiseKit +import XCTest +@testable import SwaggerClient + +class UserAPITests: XCTestCase { + + let testTimeout = 10.0 + + func testLogin() { + let expectation = self.expectation(description: "testLogin") + UserAPI.loginUser(username: "swiftTester", password: "swift").then { _ -> Void in + expectation.fulfill() + } + self.waitForExpectations(timeout: testTimeout, handler: nil) + } + + func testLogout() { + let expectation = self.expectation(description: "testLogout") + UserAPI.logoutUser().then { + expectation.fulfill() + } + self.waitForExpectations(timeout: testTimeout, handler: nil) + } + + func test1CreateUser() { + let expectation = self.expectation(description: "testCreateUser") + let newUser = User() + newUser.email = "test@test.com" + newUser.firstName = "Test" + newUser.lastName = "Tester" + newUser.id = 1000 + newUser.password = "test!" + newUser.phone = "867-5309" + newUser.username = "test@test.com" + newUser.userStatus = 0 + UserAPI.createUser(body: newUser).then { + expectation.fulfill() + } + self.waitForExpectations(timeout: testTimeout, handler: nil) + } + + func test2GetUser() { + let expectation = self.expectation(description: "testGetUser") + UserAPI.getUserByName(username: "test@test.com").then {user -> Void in + XCTAssert(user.userStatus == 0, "invalid userStatus") + XCTAssert(user.email == "test@test.com", "invalid email") + XCTAssert(user.firstName == "Test", "invalid firstName") + XCTAssert(user.lastName == "Tester", "invalid lastName") + XCTAssert(user.password == "test!", "invalid password") + XCTAssert(user.phone == "867-5309", "invalid phone") + expectation.fulfill() + }.always { + // Noop for now + }.catch { errorType in + XCTFail("error getting user") + } + self.waitForExpectations(timeout: testTimeout, handler: nil) + } + + func test3DeleteUser() { + let expectation = self.expectation(description: "testDeleteUser") + UserAPI.deleteUser(username: "test@test.com").then { + expectation.fulfill() + } + self.waitForExpectations(timeout: testTimeout, handler: nil) + } + +} diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/pom.xml b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/pom.xml new file mode 100644 index 0000000000..16941c9528 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/pom.xml @@ -0,0 +1,43 @@ + + 4.0.0 + io.swagger + Swift3PromiseKitPetstoreClientTests + pom + 1.0-SNAPSHOT + Swift3 PromiseKit Swagger Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + xcodebuild-test + integration-test + + exec + + + ./run_xcodebuild.sh + + + + + + + diff --git a/samples/client/petstore/swift4/promisekit/SwaggerClientTests/run_xcodebuild.sh b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/run_xcodebuild.sh new file mode 100755 index 0000000000..f1d4960866 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/SwaggerClientTests/run_xcodebuild.sh @@ -0,0 +1,3 @@ +#!/bin/sh + +xcodebuild -workspace "SwaggerClient.xcworkspace" -scheme "SwaggerClient" test -destination "platform=iOS Simulator,name=iPhone 6,OS=9.3" | xcpretty && exit ${PIPESTATUS[0]} diff --git a/samples/client/petstore/swift4/promisekit/git_push.sh b/samples/client/petstore/swift4/promisekit/git_push.sh new file mode 100644 index 0000000000..ed374619b1 --- /dev/null +++ b/samples/client/petstore/swift4/promisekit/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore/swift4/rxswift/.gitignore b/samples/client/petstore/swift4/rxswift/.gitignore new file mode 100644 index 0000000000..5e5d5cebcf --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/.gitignore @@ -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 diff --git a/samples/client/petstore/swift4/rxswift/.swagger-codegen-ignore b/samples/client/petstore/swift4/rxswift/.swagger-codegen-ignore new file mode 100644 index 0000000000..c5fa491b4c --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/.swagger-codegen-ignore @@ -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 diff --git a/samples/client/petstore/swift4/rxswift/.swagger-codegen/VERSION b/samples/client/petstore/swift4/rxswift/.swagger-codegen/VERSION new file mode 100644 index 0000000000..7fea99011a --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.2.3-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift4/rxswift/Cartfile b/samples/client/petstore/swift4/rxswift/Cartfile new file mode 100644 index 0000000000..d862ef91d0 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/Cartfile @@ -0,0 +1,2 @@ +github "Alamofire/Alamofire" >= 3.1.0 +github "ReactiveX/RxSwift" ~> 2.0 diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient.podspec b/samples/client/petstore/swift4/rxswift/PetstoreClient.podspec new file mode 100644 index 0000000000..2594d6256c --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient.podspec @@ -0,0 +1,14 @@ +Pod::Spec.new do |s| + s.name = 'PetstoreClient' + s.ios.deployment_target = '9.0' + s.osx.deployment_target = '10.11' + s.version = '0.0.1' + s.source = { :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' } + s.authors = '' + s.license = 'Proprietary' + s.homepage = 'https://github.com/swagger-api/swagger-codegen' + s.summary = 'PetstoreClient' + s.source_files = 'PetstoreClient/Classes/Swaggers/**/*.swift' + s.dependency 'RxSwift', '~> 3.4.1' + s.dependency 'Alamofire', '~> 4.5' +end diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIHelper.swift new file mode 100644 index 0000000000..b612ff9092 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIHelper.swift @@ -0,0 +1,65 @@ +// APIHelper.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +class APIHelper { + static func rejectNil(_ source: [String:Any?]) -> [String:Any]? { + var destination = [String:Any]() + for (key, nillableValue) in source { + if let value: Any = nillableValue { + destination[key] = value + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] { + var destination = [String:String]() + for (key, nillableValue) in source { + if let value: Any = nillableValue { + destination[key] = "\(value)" + } + } + return destination + } + + static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? { + guard let source = source else { + return nil + } + var destination = [String:Any]() + let theTrue = NSNumber(value: true as Bool) + let theFalse = NSNumber(value: false as Bool) + for (key, value) in source { + switch value { + case let x where x as? NSNumber === theTrue || x as? NSNumber === theFalse: + destination[key] = "\(value as! Bool)" as Any? + default: + destination[key] = value + } + } + return destination + } + + + static func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem]? { + let returnValues = values + .filter { $0.1 != nil } + .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in + URLQueryItem(name: item._key, value:"\(item._value!)") + } + if returnValues.count == 0 { + return nil + } + return returnValues + } + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs.swift new file mode 100644 index 0000000000..745d640ec1 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs.swift @@ -0,0 +1,61 @@ +// APIs.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +open class PetstoreClientAPI { + open static var basePath = "http://petstore.swagger.io:80/v2" + open static var credential: URLCredential? + open static var customHeaders: [String:String] = [:] + open static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() +} + +open class RequestBuilder { + var credential: URLCredential? + var headers: [String:String] + let parameters: [String:Any]? + 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: ((Progress) -> ())? + + required public init(method: String, URLString: String, parameters: [String:Any]?, isBody: Bool, headers: [String:String] = [:]) { + self.method = method + self.URLString = URLString + self.parameters = parameters + self.isBody = isBody + self.headers = headers + + addHeaders(PetstoreClientAPI.customHeaders) + } + + open func addHeaders(_ aHeaders:[String:String]) { + for (header, value) in aHeaders { + headers[header] = value + } + } + + open func execute(_ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { } + + public func addHeader(name: String, value: String) -> Self { + if !value.isEmpty { + headers[name] = value + } + return self + } + + open func addCredential() -> Self { + self.credential = PetstoreClientAPI.credential + return self + } +} + +public protocol RequestBuilderFactory { + func getNonDecodableBuilder() -> RequestBuilder.Type + func getBuilder() -> RequestBuilder.Type +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift new file mode 100644 index 0000000000..708d90b914 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift @@ -0,0 +1,557 @@ +// +// FakeAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire +import RxSwift + + + +open class FakeAPI { + /** + + - parameter body: (body) Input boolean as post body (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + open class func fakeOuterBooleanSerialize(body: OuterBoolean? = nil, completion: @escaping ((_ data: OuterBoolean?,_ error: Error?) -> Void)) { + fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + /** + + - parameter body: (body) Input boolean as post body (optional) + - returns: Observable + */ + open class func fakeOuterBooleanSerialize(body: OuterBoolean? = nil) -> Observable { + return Observable.create { observer -> Disposable in + fakeOuterBooleanSerialize(body: body) { data, error in + if let error = error { + observer.on(.error(error as Error)) + } else { + observer.on(.next(data!)) + } + observer.on(.completed) + } + return Disposables.create() + } + } + + /** + - POST /fake/outer/boolean + - Test serialization of outer boolean types + - examples: [{contentType=application/json, example={ }}] + + - parameter body: (body) Input boolean as post body (optional) + + - returns: RequestBuilder + */ + open class func fakeOuterBooleanSerializeWithRequestBuilder(body: OuterBoolean? = nil) -> RequestBuilder { + let path = "/fake/outer/boolean" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + + - parameter body: (body) Input composite as post body (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, completion: @escaping ((_ data: OuterComposite?,_ error: Error?) -> Void)) { + fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + /** + + - parameter body: (body) Input composite as post body (optional) + - returns: Observable + */ + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil) -> Observable { + return Observable.create { observer -> Disposable in + fakeOuterCompositeSerialize(body: body) { data, error in + if let error = error { + observer.on(.error(error as Error)) + } else { + observer.on(.next(data!)) + } + observer.on(.completed) + } + return Disposables.create() + } + } + + /** + - POST /fake/outer/composite + - Test serialization of object with outer number type + - examples: [{contentType=application/json, example={ + "my_string" : { }, + "my_number" : { }, + "my_boolean" : { } +}}] + + - parameter body: (body) Input composite as post body (optional) + + - returns: RequestBuilder + */ + open class func fakeOuterCompositeSerializeWithRequestBuilder(body: OuterComposite? = nil) -> RequestBuilder { + let path = "/fake/outer/composite" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + + - parameter body: (body) Input number as post body (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + open class func fakeOuterNumberSerialize(body: OuterNumber? = nil, completion: @escaping ((_ data: OuterNumber?,_ error: Error?) -> Void)) { + fakeOuterNumberSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + /** + + - parameter body: (body) Input number as post body (optional) + - returns: Observable + */ + open class func fakeOuterNumberSerialize(body: OuterNumber? = nil) -> Observable { + return Observable.create { observer -> Disposable in + fakeOuterNumberSerialize(body: body) { data, error in + if let error = error { + observer.on(.error(error as Error)) + } else { + observer.on(.next(data!)) + } + observer.on(.completed) + } + return Disposables.create() + } + } + + /** + - POST /fake/outer/number + - Test serialization of outer number types + - examples: [{contentType=application/json, example={ }}] + + - parameter body: (body) Input number as post body (optional) + + - returns: RequestBuilder + */ + open class func fakeOuterNumberSerializeWithRequestBuilder(body: OuterNumber? = nil) -> RequestBuilder { + let path = "/fake/outer/number" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + + - parameter body: (body) Input string as post body (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + open class func fakeOuterStringSerialize(body: OuterString? = nil, completion: @escaping ((_ data: OuterString?,_ error: Error?) -> Void)) { + fakeOuterStringSerializeWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + /** + + - parameter body: (body) Input string as post body (optional) + - returns: Observable + */ + open class func fakeOuterStringSerialize(body: OuterString? = nil) -> Observable { + return Observable.create { observer -> Disposable in + fakeOuterStringSerialize(body: body) { data, error in + if let error = error { + observer.on(.error(error as Error)) + } else { + observer.on(.next(data!)) + } + observer.on(.completed) + } + return Disposables.create() + } + } + + /** + - POST /fake/outer/string + - Test serialization of outer string types + - examples: [{contentType=application/json, example={ }}] + + - parameter body: (body) Input string as post body (optional) + + - returns: RequestBuilder + */ + open class func fakeOuterStringSerializeWithRequestBuilder(body: OuterString? = nil) -> RequestBuilder { + let path = "/fake/outer/string" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + To test \"client\" model + + - parameter body: (body) client model + - parameter completion: completion handler to receive the data and the error objects + */ + open class func testClientModel(body: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) { + testClientModelWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + /** + To test \"client\" model + + - parameter body: (body) client model + - returns: Observable + */ + open class func testClientModel(body: Client) -> Observable { + return Observable.create { observer -> Disposable in + testClientModel(body: body) { data, error in + if let error = error { + observer.on(.error(error as Error)) + } else { + observer.on(.next(data!)) + } + observer.on(.completed) + } + return Disposables.create() + } + } + + /** + To test \"client\" model + - PATCH /fake + - To test \"client\" model + - examples: [{contentType=application/json, example={ + "client" : "aeiou" +}}] + + - parameter body: (body) client model + + - returns: RequestBuilder + */ + open class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder { + let path = "/fake" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + + - parameter number: (form) None + - parameter double: (form) None + - parameter patternWithoutDelimiter: (form) None + - parameter byte: (form) None + - parameter integer: (form) None (optional) + - parameter int32: (form) None (optional) + - parameter int64: (form) None (optional) + - parameter float: (form) None (optional) + - parameter string: (form) None (optional) + - parameter binary: (form) None (optional) + - parameter date: (form) None (optional) + - parameter dateTime: (form) None (optional) + - parameter password: (form) None (optional) + - parameter callback: (form) None (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int32? = nil, int32: Int32? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: Data? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute { (response, error) -> Void in + completion(error); + } + } + + /** + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + + - parameter number: (form) None + - parameter double: (form) None + - parameter patternWithoutDelimiter: (form) None + - parameter byte: (form) None + - parameter integer: (form) None (optional) + - parameter int32: (form) None (optional) + - parameter int64: (form) None (optional) + - parameter float: (form) None (optional) + - parameter string: (form) None (optional) + - parameter binary: (form) None (optional) + - parameter date: (form) None (optional) + - parameter dateTime: (form) None (optional) + - parameter password: (form) None (optional) + - parameter callback: (form) None (optional) + - returns: Observable + */ + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int32? = nil, int32: Int32? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: Data? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> Observable { + return Observable.create { observer -> Disposable in + testEndpointParameters(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback) { error in + if let error = error { + observer.on(.error(error as Error)) + } else { + observer.on(.next()) + } + observer.on(.completed) + } + return Disposables.create() + } + } + + /** + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + - POST /fake + - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + - BASIC: + - type: basic + - name: http_basic_test + + - parameter number: (form) None + - parameter double: (form) None + - parameter patternWithoutDelimiter: (form) None + - parameter byte: (form) None + - parameter integer: (form) None (optional) + - parameter int32: (form) None (optional) + - parameter int64: (form) None (optional) + - parameter float: (form) None (optional) + - parameter string: (form) None (optional) + - parameter binary: (form) None (optional) + - parameter date: (form) None (optional) + - parameter dateTime: (form) None (optional) + - parameter password: (form) None (optional) + - parameter callback: (form) None (optional) + + - returns: RequestBuilder + */ + open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int32? = nil, int32: Int32? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: Data? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { + let path = "/fake" + let URLString = PetstoreClientAPI.basePath + path + let formParams: [String:Any?] = [ + "integer": integer?.encodeToJSON(), + "int32": int32?.encodeToJSON(), + "int64": int64?.encodeToJSON(), + "number": number, + "float": float, + "double": double, + "string": string, + "pattern_without_delimiter": patternWithoutDelimiter, + "byte": byte, + "binary": binary, + "date": date?.encodeToJSON(), + "dateTime": dateTime?.encodeToJSON(), + "password": password, + "callback": callback + ] + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + * enum for parameter enumFormStringArray + */ + public enum EnumFormStringArray_testEnumParameters: String { + case greaterThan = ">" + case dollar = "$" + } + + /** + * enum for parameter enumFormString + */ + public enum EnumFormString_testEnumParameters: String { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + } + + /** + * enum for parameter enumHeaderStringArray + */ + public enum EnumHeaderStringArray_testEnumParameters: String { + case greaterThan = ">" + case dollar = "$" + } + + /** + * enum for parameter enumHeaderString + */ + public enum EnumHeaderString_testEnumParameters: String { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + } + + /** + * enum for parameter enumQueryStringArray + */ + public enum EnumQueryStringArray_testEnumParameters: String { + case greaterThan = ">" + case dollar = "$" + } + + /** + * enum for parameter enumQueryString + */ + public enum EnumQueryString_testEnumParameters: String { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + } + + /** + * enum for parameter enumQueryInteger + */ + public enum EnumQueryInteger_testEnumParameters: Int32 { + case _1 = 1 + case numberminus2 = -2 + } + + /** + * enum for parameter enumQueryDouble + */ + public enum EnumQueryDouble_testEnumParameters: Double { + case _11 = 1.1 + case numberminus12 = -1.2 + } + + /** + To test enum parameters + + - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional) + - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to -efg) + - parameter enumHeaderStringArray: (header) Header parameter enum test (string array) (optional) + - parameter enumHeaderString: (header) Header parameter enum test (string) (optional, default to -efg) + - parameter enumQueryStringArray: (query) Query parameter enum test (string array) (optional) + - parameter enumQueryString: (query) Query parameter enum test (string) (optional, default to -efg) + - parameter enumQueryInteger: (query) Query parameter enum test (double) (optional) + - parameter enumQueryDouble: (form) Query parameter enum test (double) (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + testEnumParametersWithRequestBuilder(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble).execute { (response, error) -> Void in + completion(error); + } + } + + /** + To test enum parameters + + - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional) + - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to -efg) + - parameter enumHeaderStringArray: (header) Header parameter enum test (string array) (optional) + - parameter enumHeaderString: (header) Header parameter enum test (string) (optional, default to -efg) + - parameter enumQueryStringArray: (query) Query parameter enum test (string array) (optional) + - parameter enumQueryString: (query) Query parameter enum test (string) (optional, default to -efg) + - parameter enumQueryInteger: (query) Query parameter enum test (double) (optional) + - parameter enumQueryDouble: (form) Query parameter enum test (double) (optional) + - returns: Observable + */ + open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil) -> Observable { + return Observable.create { observer -> Disposable in + testEnumParameters(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble) { error in + if let error = error { + observer.on(.error(error as Error)) + } else { + observer.on(.next()) + } + observer.on(.completed) + } + return Disposables.create() + } + } + + /** + To test enum parameters + - GET /fake + - To test enum parameters + + - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional) + - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to -efg) + - parameter enumHeaderStringArray: (header) Header parameter enum test (string array) (optional) + - parameter enumHeaderString: (header) Header parameter enum test (string) (optional, default to -efg) + - parameter enumQueryStringArray: (query) Query parameter enum test (string array) (optional) + - parameter enumQueryString: (query) Query parameter enum test (string) (optional, default to -efg) + - parameter enumQueryInteger: (query) Query parameter enum test (double) (optional) + - parameter enumQueryDouble: (form) Query parameter enum test (double) (optional) + + - returns: RequestBuilder + */ + open class func testEnumParametersWithRequestBuilder(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil) -> RequestBuilder { + let path = "/fake" + let URLString = PetstoreClientAPI.basePath + path + let formParams: [String:Any?] = [ + "enum_form_string_array": enumFormStringArray, + "enum_form_string": enumFormString?.rawValue, + "enum_query_double": enumQueryDouble?.rawValue + ] + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + "enum_query_string_array": enumQueryStringArray, + "enum_query_string": enumQueryString?.rawValue, + "enum_query_integer": enumQueryInteger?.rawValue + ]) + + let nillableHeaders: [String: Any?] = [ + "enum_header_string_array": enumHeaderStringArray, + "enum_header_string": enumHeaderString?.rawValue + ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + } + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift new file mode 100644 index 0000000000..51192f5799 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -0,0 +1,664 @@ +// +// PetAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire +import RxSwift + + + +open class PetAPI { + /** + Add a new pet to the store + + - parameter body: (body) Pet object that needs to be added to the store + - parameter completion: completion handler to receive the data and the error objects + */ + open class func addPet(body: Pet, completion: @escaping ((_ error: Error?) -> Void)) { + addPetWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error); + } + } + + /** + Add a new pet to the store + + - parameter body: (body) Pet object that needs to be added to the store + - returns: Observable + */ + open class func addPet(body: Pet) -> Observable { + return Observable.create { observer -> Disposable in + addPet(body: body) { error in + if let error = error { + observer.on(.error(error as Error)) + } else { + observer.on(.next()) + } + observer.on(.completed) + } + return Disposables.create() + } + } + + /** + 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 + + - returns: RequestBuilder + */ + open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder { + let path = "/pet" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + Deletes a pet + + - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + open class func deletePet(petId: Int64, apiKey: String? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (response, error) -> Void in + completion(error); + } + } + + /** + Deletes a pet + + - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) + - returns: Observable + */ + open class func deletePet(petId: Int64, apiKey: String? = nil) -> Observable { + return Observable.create { observer -> Disposable in + deletePet(petId: petId, apiKey: apiKey) { error in + if let error = error { + observer.on(.error(error as Error)) + } else { + observer.on(.next()) + } + observer.on(.completed) + } + return Disposables.create() + } + } + + /** + Deletes a pet + - DELETE /pet/{petId} + - + - OAuth: + - type: oauth2 + - name: petstore_auth + + - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) + + - returns: RequestBuilder + */ + open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder { + var path = "/pet/{petId}" + path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + "api_key": apiKey + ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) + } + + /** + * enum for parameter status + */ + public enum Status_findPetsByStatus: String { + case available = "available" + case pending = "pending" + case sold = "sold" + } + + /** + Finds Pets by status + + - parameter status: (query) Status values that need to be considered for filter + - parameter completion: completion handler to receive the data and the error objects + */ + open class func findPetsByStatus(status: [String], completion: @escaping ((_ data: [Pet]?,_ error: Error?) -> Void)) { + findPetsByStatusWithRequestBuilder(status: status).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + /** + Finds Pets by status + + - parameter status: (query) Status values that need to be considered for filter + - returns: Observable<[Pet]> + */ + open class func findPetsByStatus(status: [String]) -> Observable<[Pet]> { + return Observable.create { observer -> Disposable in + findPetsByStatus(status: status) { data, error in + if let error = error { + observer.on(.error(error as Error)) + } else { + observer.on(.next(data!)) + } + observer.on(.completed) + } + return Disposables.create() + } + } + + /** + Finds Pets by status + - GET /pet/findByStatus + - Multiple status values can be provided with comma separated strings + - OAuth: + - type: oauth2 + - name: petstore_auth + - examples: [{contentType=application/xml, example= + 123456789 + doggie + + aeiou + + + + aeiou +}, {contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "aeiou", + "id" : 6 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 1 + } ], + "status" : "available" +} ]}] + - examples: [{contentType=application/xml, example= + 123456789 + doggie + + aeiou + + + + aeiou +}, {contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "aeiou", + "id" : 6 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 1 + } ], + "status" : "available" +} ]}] + + - parameter status: (query) Status values that need to be considered for filter + + - returns: RequestBuilder<[Pet]> + */ + open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + let path = "/pet/findByStatus" + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + "status": status + ]) + + + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Finds Pets by tags + + - parameter tags: (query) Tags to filter by + - parameter completion: completion handler to receive the data and the error objects + */ + open class func findPetsByTags(tags: [String], completion: @escaping ((_ data: [Pet]?,_ error: Error?) -> Void)) { + findPetsByTagsWithRequestBuilder(tags: tags).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + /** + Finds Pets by tags + + - parameter tags: (query) Tags to filter by + - returns: Observable<[Pet]> + */ + open class func findPetsByTags(tags: [String]) -> Observable<[Pet]> { + return Observable.create { observer -> Disposable in + findPetsByTags(tags: tags) { data, error in + if let error = error { + observer.on(.error(error as Error)) + } else { + observer.on(.next(data!)) + } + observer.on(.completed) + } + return Disposables.create() + } + } + + /** + Finds Pets by tags + - GET /pet/findByTags + - Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + - OAuth: + - type: oauth2 + - name: petstore_auth + - examples: [{contentType=application/xml, example= + 123456789 + doggie + + aeiou + + + + aeiou +}, {contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "aeiou", + "id" : 6 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 1 + } ], + "status" : "available" +} ]}] + - examples: [{contentType=application/xml, example= + 123456789 + doggie + + aeiou + + + + aeiou +}, {contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "aeiou", + "id" : 6 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 1 + } ], + "status" : "available" +} ]}] + + - parameter tags: (query) Tags to filter by + + - returns: RequestBuilder<[Pet]> + */ + open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { + let path = "/pet/findByTags" + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + "tags": tags + ]) + + + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Find pet by ID + + - parameter petId: (path) ID of pet to return + - parameter completion: completion handler to receive the data and the error objects + */ + open class func getPetById(petId: Int64, completion: @escaping ((_ data: Pet?,_ error: Error?) -> Void)) { + getPetByIdWithRequestBuilder(petId: petId).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + /** + Find pet by ID + + - parameter petId: (path) ID of pet to return + - returns: Observable + */ + open class func getPetById(petId: Int64) -> Observable { + return Observable.create { observer -> Disposable in + getPetById(petId: petId) { data, error in + if let error = error { + observer.on(.error(error as Error)) + } else { + observer.on(.next(data!)) + } + observer.on(.completed) + } + return Disposables.create() + } + } + + /** + Find pet by ID + - GET /pet/{petId} + - Returns a single pet + - API Key: + - type: apiKey api_key + - name: api_key + - examples: [{contentType=application/xml, example= + 123456789 + doggie + + aeiou + + + + aeiou +}, {contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "aeiou", + "id" : 6 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 1 + } ], + "status" : "available" +}}] + - examples: [{contentType=application/xml, example= + 123456789 + doggie + + aeiou + + + + aeiou +}, {contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "aeiou", + "id" : 6 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 1 + } ], + "status" : "available" +}}] + + - parameter petId: (path) ID of pet to return + + - returns: RequestBuilder + */ + open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder { + var path = "/pet/{petId}" + path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Update an existing pet + + - parameter body: (body) Pet object that needs to be added to the store + - parameter completion: completion handler to receive the data and the error objects + */ + open class func updatePet(body: Pet, completion: @escaping ((_ error: Error?) -> Void)) { + updatePetWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error); + } + } + + /** + Update an existing pet + + - parameter body: (body) Pet object that needs to be added to the store + - returns: Observable + */ + open class func updatePet(body: Pet) -> Observable { + return Observable.create { observer -> Disposable in + updatePet(body: body) { error in + if let error = error { + observer.on(.error(error as Error)) + } else { + observer.on(.next()) + } + observer.on(.completed) + } + return Disposables.create() + } + } + + /** + 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 + + - returns: RequestBuilder + */ + open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder { + let path = "/pet" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, 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 + */ + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (response, error) -> Void in + completion(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 + */ + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil) -> Observable { + return Observable.create { observer -> Disposable in + updatePetWithForm(petId: petId, name: name, status: status) { error in + if let error = error { + observer.on(.error(error as Error)) + } else { + observer.on(.next()) + } + observer.on(.completed) + } + return Disposables.create() + } + } + + /** + 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 + */ + open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder { + var path = "/pet/{petId}" + path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let formParams: [String:Any?] = [ + "name": name, + "status": status + ] + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, 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 + */ + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, completion: @escaping ((_ data: ApiResponse?,_ error: Error?) -> Void)) { + uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute { (response, error) -> Void in + completion(response?.body, 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 + */ + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> Observable { + return Observable.create { observer -> Disposable in + uploadFile(petId: petId, additionalMetadata: additionalMetadata, file: file) { data, error in + if let error = error { + observer.on(.error(error as Error)) + } else { + observer.on(.next(data!)) + } + observer.on(.completed) + } + return Disposables.create() + } + } + + /** + uploads an image + - POST /pet/{petId}/uploadImage + - + - OAuth: + - type: oauth2 + - name: petstore_auth + - examples: [{contentType=application/json, example={ + "code" : 0, + "type" : "aeiou", + "message" : "aeiou" +}}] + + - 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 + */ + open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder { + var path = "/pet/{petId}/uploadImage" + path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let formParams: [String:Any?] = [ + "additionalMetadata": additionalMetadata, + "file": file + ] + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift new file mode 100644 index 0000000000..9483e10aba --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -0,0 +1,295 @@ +// +// StoreAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire +import RxSwift + + + +open class StoreAPI { + /** + 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 + */ + open class func deleteOrder(orderId: String, completion: @escaping ((_ error: Error?) -> Void)) { + deleteOrderWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in + completion(error); + } + } + + /** + Delete purchase order by ID + + - parameter orderId: (path) ID of the order that needs to be deleted + - returns: Observable + */ + open class func deleteOrder(orderId: String) -> Observable { + return Observable.create { observer -> Disposable in + deleteOrder(orderId: orderId) { error in + if let error = error { + observer.on(.error(error as Error)) + } else { + observer.on(.next()) + } + observer.on(.completed) + } + return Disposables.create() + } + } + + /** + Delete purchase order by ID + - DELETE /store/order/{order_id} + - 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 + */ + open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder { + var path = "/store/order/{order_id}" + path = path.replacingOccurrences(of: "{order_id}", with: "\(orderId)", options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Returns pet inventories by status + + - parameter completion: completion handler to receive the data and the error objects + */ + open class func getInventory(completion: @escaping ((_ data: [String:Int32]?,_ error: Error?) -> Void)) { + getInventoryWithRequestBuilder().execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + /** + Returns pet inventories by status + + - returns: Observable<[String:Int32]> + */ + open 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 Error)) + } else { + observer.on(.next(data!)) + } + observer.on(.completed) + } + return Disposables.create() + } + } + + /** + Returns pet inventories by status + - GET /store/inventory + - Returns a map of status codes to quantities + - API Key: + - type: apiKey api_key + - name: api_key + - examples: [{contentType=application/json, example={ + "key" : 0 +}}] + + - returns: RequestBuilder<[String:Int32]> + */ + open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String:Int32]> { + let path = "/store/inventory" + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder<[String:Int32]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + 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 + */ + open class func getOrderById(orderId: Int64, completion: @escaping ((_ data: Order?,_ error: Error?) -> Void)) { + getOrderByIdWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + /** + Find purchase order by ID + + - parameter orderId: (path) ID of pet that needs to be fetched + - returns: Observable + */ + open class func getOrderById(orderId: Int64) -> Observable { + return Observable.create { observer -> Disposable in + getOrderById(orderId: orderId) { data, error in + if let error = error { + observer.on(.error(error as Error)) + } else { + observer.on(.next(data!)) + } + observer.on(.completed) + } + return Disposables.create() + } + } + + /** + Find purchase order by ID + - GET /store/order/{order_id} + - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + - examples: [{contentType=application/xml, example= + 123456789 + 123456789 + 123 + 2000-01-23T04:56:07.000Z + aeiou + true +}, {contentType=application/json, example={ + "petId" : 6, + "quantity" : 1, + "id" : 0, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : false, + "status" : "placed" +}}] + - examples: [{contentType=application/xml, example= + 123456789 + 123456789 + 123 + 2000-01-23T04:56:07.000Z + aeiou + true +}, {contentType=application/json, example={ + "petId" : 6, + "quantity" : 1, + "id" : 0, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : false, + "status" : "placed" +}}] + + - parameter orderId: (path) ID of pet that needs to be fetched + + - returns: RequestBuilder + */ + open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder { + var path = "/store/order/{order_id}" + path = path.replacingOccurrences(of: "{order_id}", with: "\(orderId)", options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Place an order for a pet + + - parameter body: (body) order placed for purchasing the pet + - parameter completion: completion handler to receive the data and the error objects + */ + open class func placeOrder(body: Order, completion: @escaping ((_ data: Order?,_ error: Error?) -> Void)) { + placeOrderWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + /** + Place an order for a pet + + - parameter body: (body) order placed for purchasing the pet + - returns: Observable + */ + open class func placeOrder(body: Order) -> Observable { + return Observable.create { observer -> Disposable in + placeOrder(body: body) { data, error in + if let error = error { + observer.on(.error(error as Error)) + } else { + observer.on(.next(data!)) + } + observer.on(.completed) + } + return Disposables.create() + } + } + + /** + Place an order for a pet + - POST /store/order + - + - examples: [{contentType=application/xml, example= + 123456789 + 123456789 + 123 + 2000-01-23T04:56:07.000Z + aeiou + true +}, {contentType=application/json, example={ + "petId" : 6, + "quantity" : 1, + "id" : 0, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : false, + "status" : "placed" +}}] + - examples: [{contentType=application/xml, example= + 123456789 + 123456789 + 123 + 2000-01-23T04:56:07.000Z + aeiou + true +}, {contentType=application/json, example={ + "petId" : 6, + "quantity" : 1, + "id" : 0, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : false, + "status" : "placed" +}}] + + - parameter body: (body) order placed for purchasing the pet + + - returns: RequestBuilder + */ + open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder { + let path = "/store/order" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift new file mode 100644 index 0000000000..2c8371f406 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -0,0 +1,498 @@ +// +// UserAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire +import RxSwift + + + +open class UserAPI { + /** + Create user + + - parameter body: (body) Created user object + - parameter completion: completion handler to receive the data and the error objects + */ + open class func createUser(body: User, completion: @escaping ((_ error: Error?) -> Void)) { + createUserWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error); + } + } + + /** + Create user + + - parameter body: (body) Created user object + - returns: Observable + */ + open class func createUser(body: User) -> Observable { + return Observable.create { observer -> Disposable in + createUser(body: body) { error in + if let error = error { + observer.on(.error(error as Error)) + } else { + observer.on(.next()) + } + observer.on(.completed) + } + return Disposables.create() + } + } + + /** + Create user + - POST /user + - This can only be done by the logged in user. + + - parameter body: (body) Created user object + + - returns: RequestBuilder + */ + open class func createUserWithRequestBuilder(body: User) -> RequestBuilder { + let path = "/user" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + Creates list of users with given input array + + - parameter body: (body) List of user object + - parameter completion: completion handler to receive the data and the error objects + */ + open class func createUsersWithArrayInput(body: [User], completion: @escaping ((_ error: Error?) -> Void)) { + createUsersWithArrayInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error); + } + } + + /** + Creates list of users with given input array + + - parameter body: (body) List of user object + - returns: Observable + */ + open class func createUsersWithArrayInput(body: [User]) -> Observable { + return Observable.create { observer -> Disposable in + createUsersWithArrayInput(body: body) { error in + if let error = error { + observer.on(.error(error as Error)) + } else { + observer.on(.next()) + } + observer.on(.completed) + } + return Disposables.create() + } + } + + /** + Creates list of users with given input array + - POST /user/createWithArray + - + + - parameter body: (body) List of user object + + - returns: RequestBuilder + */ + open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder { + let path = "/user/createWithArray" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + + /** + Creates list of users with given input array + + - parameter body: (body) List of user object + - parameter completion: completion handler to receive the data and the error objects + */ + open class func createUsersWithListInput(body: [User], completion: @escaping ((_ error: Error?) -> Void)) { + createUsersWithListInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error); + } + } + + /** + Creates list of users with given input array + + - parameter body: (body) List of user object + - returns: Observable + */ + open class func createUsersWithListInput(body: [User]) -> Observable { + return Observable.create { observer -> Disposable in + createUsersWithListInput(body: body) { error in + if let error = error { + observer.on(.error(error as Error)) + } else { + observer.on(.next()) + } + observer.on(.completed) + } + return Disposables.create() + } + } + + /** + Creates list of users with given input array + - POST /user/createWithList + - + + - parameter body: (body) List of user object + + - returns: RequestBuilder + */ + open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder { + let path = "/user/createWithList" + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, 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 + */ + open class func deleteUser(username: String, completion: @escaping ((_ error: Error?) -> Void)) { + deleteUserWithRequestBuilder(username: username).execute { (response, error) -> Void in + completion(error); + } + } + + /** + Delete user + + - parameter username: (path) The name that needs to be deleted + - returns: Observable + */ + open class func deleteUser(username: String) -> Observable { + return Observable.create { observer -> Disposable in + deleteUser(username: username) { error in + if let error = error { + observer.on(.error(error as Error)) + } else { + observer.on(.next()) + } + observer.on(.completed) + } + return Disposables.create() + } + } + + /** + 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 + */ + open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder { + var path = "/user/{username}" + path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + 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 + */ + open class func getUserByName(username: String, completion: @escaping ((_ data: User?,_ error: Error?) -> Void)) { + getUserByNameWithRequestBuilder(username: username).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + /** + Get user by user name + + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + - returns: Observable + */ + open class func getUserByName(username: String) -> Observable { + return Observable.create { observer -> Disposable in + getUserByName(username: username) { data, error in + if let error = error { + observer.on(.error(error as Error)) + } else { + observer.on(.next(data!)) + } + observer.on(.completed) + } + return Disposables.create() + } + } + + /** + Get user by user name + - GET /user/{username} + - + - examples: [{contentType=application/xml, example= + 123456789 + aeiou + aeiou + aeiou + aeiou + aeiou + aeiou + 123 +}, {contentType=application/json, example={ + "firstName" : "aeiou", + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 6, + "phone" : "aeiou", + "id" : 0, + "email" : "aeiou", + "username" : "aeiou" +}}] + - examples: [{contentType=application/xml, example= + 123456789 + aeiou + aeiou + aeiou + aeiou + aeiou + aeiou + 123 +}, {contentType=application/json, example={ + "firstName" : "aeiou", + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 6, + "phone" : "aeiou", + "id" : 0, + "email" : "aeiou", + "username" : "aeiou" +}}] + + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + + - returns: RequestBuilder + */ + open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder { + var path = "/user/{username}" + path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Logs user into the system + + - parameter username: (query) The user name for login + - parameter password: (query) The password for login in clear text + - parameter completion: completion handler to receive the data and the error objects + */ + open class func loginUser(username: String, password: String, completion: @escaping ((_ data: String?,_ error: Error?) -> Void)) { + loginUserWithRequestBuilder(username: username, password: password).execute { (response, error) -> Void in + completion(response?.body, error); + } + } + + /** + Logs user into the system + + - parameter username: (query) The user name for login + - parameter password: (query) The password for login in clear text + - returns: Observable + */ + open class func loginUser(username: String, password: String) -> Observable { + return Observable.create { observer -> Disposable in + loginUser(username: username, password: password) { data, error in + if let error = error { + observer.on(.error(error as Error)) + } else { + observer.on(.next(data!)) + } + observer.on(.completed) + } + return Disposables.create() + } + } + + /** + Logs user into the system + - GET /user/login + - + - responseHeaders: [X-Rate-Limit(Int32), X-Expires-After(Date)] + - responseHeaders: [X-Rate-Limit(Int32), X-Expires-After(Date)] + - examples: [{contentType=application/xml, example=aeiou}, {contentType=application/json, example="aeiou"}] + - examples: [{contentType=application/xml, example=aeiou}, {contentType=application/json, example="aeiou"}] + + - parameter username: (query) The user name for login + - parameter password: (query) The password for login in clear text + + - returns: RequestBuilder + */ + open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { + let path = "/user/login" + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + "username": username, + "password": password + ]) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Logs out current logged in user session + + - parameter completion: completion handler to receive the data and the error objects + */ + open class func logoutUser(completion: @escaping ((_ error: Error?) -> Void)) { + logoutUserWithRequestBuilder().execute { (response, error) -> Void in + completion(error); + } + } + + /** + Logs out current logged in user session + + - returns: Observable + */ + open class func logoutUser() -> Observable { + return Observable.create { observer -> Disposable in + logoutUser() { error in + if let error = error { + observer.on(.error(error as Error)) + } else { + observer.on(.next()) + } + observer.on(.completed) + } + return Disposables.create() + } + } + + /** + Logs out current logged in user session + - GET /user/logout + - + + - returns: RequestBuilder + */ + open class func logoutUserWithRequestBuilder() -> RequestBuilder { + let path = "/user/logout" + let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) + } + + /** + Updated user + + - parameter username: (path) name that need to be deleted + - parameter body: (body) Updated user object + - parameter completion: completion handler to receive the data and the error objects + */ + open class func updateUser(username: String, body: User, completion: @escaping ((_ error: Error?) -> Void)) { + updateUserWithRequestBuilder(username: username, body: body).execute { (response, error) -> Void in + completion(error); + } + } + + /** + Updated user + + - parameter username: (path) name that need to be deleted + - parameter body: (body) Updated user object + - returns: Observable + */ + open class func updateUser(username: String, body: User) -> Observable { + return Observable.create { observer -> Disposable in + updateUser(username: username, body: body) { error in + if let error = error { + observer.on(.error(error as Error)) + } else { + observer.on(.next()) + } + observer.on(.completed) + } + return Disposables.create() + } + } + + /** + 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 + + - returns: RequestBuilder + */ + open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder { + var path = "/user/{username}" + path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let url = NSURLComponents(string: URLString) + + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) + } + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift new file mode 100644 index 0000000000..b9d2a2727d --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -0,0 +1,307 @@ +// AlamofireImplementations.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire + +class AlamofireRequestBuilderFactory: RequestBuilderFactory { + func getNonDecodableBuilder() -> RequestBuilder.Type { + return AlamofireRequestBuilder.self + } + + func getBuilder() -> RequestBuilder.Type { + return AlamofireDecodableRequestBuilder.self + } +} + +// Store manager to retain its reference +private var managerStore: [String: Alamofire.SessionManager] = [:] + +open class AlamofireRequestBuilder: RequestBuilder { + required public init(method: String, URLString: String, parameters: [String : Any]?, isBody: Bool, headers: [String : String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody, headers: headers) + } + + /** + May be overridden by a subclass if you want to control the session + configuration. + */ + open func createSessionManager() -> Alamofire.SessionManager { + let configuration = URLSessionConfiguration.default + configuration.httpAdditionalHeaders = buildHeaders() + return Alamofire.SessionManager(configuration: configuration) + } + + /** + May be overridden by a subclass if you want to control the Content-Type + that is given to an uploaded form part. + + Return nil to use the default behavior (inferring the Content-Type from + the file extension). Return the desired Content-Type otherwise. + */ + open func contentTypeForFormPart(fileURL: URL) -> String? { + return nil + } + + /** + May be overridden by a subclass if you want to control the request + configuration (e.g. to override the cache policy). + */ + open func makeRequest(manager: SessionManager, method: HTTPMethod, encoding: ParameterEncoding, headers: [String:String]) -> DataRequest { + return manager.request(URLString, method: method, parameters: parameters, encoding: encoding, headers: headers) + } + + override open func execute(_ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { + let managerId:String = UUID().uuidString + // Create a new manager for each request to customize its request header + let manager = createSessionManager() + managerStore[managerId] = manager + + let encoding:ParameterEncoding = isBody ? JSONDataEncoding() : URLEncoding() + + let xMethod = Alamofire.HTTPMethod(rawValue: method) + let fileKeys = parameters == nil ? [] : parameters!.filter { $1 is NSURL } + .map { $0.0 } + + if fileKeys.count > 0 { + manager.upload(multipartFormData: { mpForm in + for (k, v) in self.parameters! { + switch v { + case let fileURL as URL: + if let mimeType = self.contentTypeForFormPart(fileURL: fileURL) { + mpForm.append(fileURL, withName: k, fileName: fileURL.lastPathComponent, mimeType: mimeType) + } + else { + mpForm.append(fileURL, withName: k) + } + break + case let string as String: + mpForm.append(string.data(using: String.Encoding.utf8)!, withName: k) + break + case let number as NSNumber: + mpForm.append(number.stringValue.data(using: String.Encoding.utf8)!, withName: k) + break + default: + fatalError("Unprocessable value \(v) with key \(k)") + break + } + } + }, to: URLString, method: xMethod!, headers: nil, encodingCompletion: { encodingResult in + switch encodingResult { + case .success(let upload, _, _): + if let onProgressReady = self.onProgressReady { + onProgressReady(upload.uploadProgress) + } + self.processRequest(request: upload, managerId, completion) + case .failure(let encodingError): + completion(nil, ErrorResponse.Error(415, nil, encodingError)) + } + }) + } else { + let request = makeRequest(manager: manager, method: xMethod!, encoding: encoding, headers: headers) + if let onProgressReady = self.onProgressReady { + onProgressReady(request.progress) + } + processRequest(request: request, managerId, completion) + } + + } + + fileprivate func processRequest(request: DataRequest, _ managerId: String, _ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { + if let credential = self.credential { + request.authenticate(usingCredential: credential) + } + + let cleanupRequest = { + _ = managerStore.removeValue(forKey: managerId) + } + + let validatedRequest = request.validate() + + switch T.self { + case is String.Type: + validatedRequest.responseString(completionHandler: { (stringResponse) in + cleanupRequest() + + if stringResponse.result.isFailure { + completion( + nil, + ErrorResponse.Error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.result.error as Error!) + ) + return + } + + completion( + Response( + response: stringResponse.response!, + body: ((stringResponse.result.value ?? "") as! T) + ), + nil + ) + }) + case is Void.Type: + validatedRequest.responseData(completionHandler: { (voidResponse) in + cleanupRequest() + + if voidResponse.result.isFailure { + completion( + nil, + ErrorResponse.Error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.result.error!) + ) + return + } + + completion( + Response( + response: voidResponse.response!, + body: nil), + nil + ) + }) + default: + validatedRequest.responseData(completionHandler: { (dataResponse) in + cleanupRequest() + + if (dataResponse.result.isFailure) { + completion( + nil, + ErrorResponse.Error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!) + ) + return + } + + completion( + Response( + response: dataResponse.response!, + body: (dataResponse.data as! T) + ), + nil + ) + }) + } + } + + open func buildHeaders() -> [String: String] { + var httpHeaders = SessionManager.defaultHTTPHeaders + for (key, value) in self.headers { + httpHeaders[key] = value + } + return httpHeaders + } +} + +public enum AlamofireDecodableRequestBuilderError: Error { + case emptyDataResponse + case nilHTTPResponse + case jsonDecoding(DecodingError) + case generalError(Error) +} + +open class AlamofireDecodableRequestBuilder: AlamofireRequestBuilder { + + override fileprivate func processRequest(request: DataRequest, _ managerId: String, _ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { + if let credential = self.credential { + request.authenticate(usingCredential: credential) + } + + let cleanupRequest = { + _ = managerStore.removeValue(forKey: managerId) + } + + let validatedRequest = request.validate() + + switch T.self { + case is String.Type: + validatedRequest.responseString(completionHandler: { (stringResponse) in + cleanupRequest() + + if stringResponse.result.isFailure { + completion( + nil, + ErrorResponse.Error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.result.error as Error!) + ) + return + } + + completion( + Response( + response: stringResponse.response!, + body: ((stringResponse.result.value ?? "") as! T) + ), + nil + ) + }) + case is Void.Type: + validatedRequest.responseData(completionHandler: { (voidResponse) in + cleanupRequest() + + if voidResponse.result.isFailure { + completion( + nil, + ErrorResponse.Error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.result.error!) + ) + return + } + + completion( + Response( + response: voidResponse.response!, + body: nil), + nil + ) + }) + case is Data.Type: + validatedRequest.responseData(completionHandler: { (dataResponse) in + cleanupRequest() + + if (dataResponse.result.isFailure) { + completion( + nil, + ErrorResponse.Error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!) + ) + return + } + + completion( + Response( + response: dataResponse.response!, + body: (dataResponse.data as! T) + ), + nil + ) + }) + default: + validatedRequest.responseData(completionHandler: { (dataResponse: DataResponse) in + cleanupRequest() + + guard dataResponse.result.isSuccess else { + completion(nil, ErrorResponse.Error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!)) + return + } + + guard let data = dataResponse.data, !data.isEmpty else { + completion(nil, ErrorResponse.Error(-1, nil, AlamofireDecodableRequestBuilderError.emptyDataResponse)) + return + } + + guard let httpResponse = dataResponse.response else { + completion(nil, ErrorResponse.Error(-2, nil, AlamofireDecodableRequestBuilderError.nilHTTPResponse)) + return + } + + var responseObj: Response? = nil + + let decodeResult: (decodableObj: T?, error: Error?) = CodableHelper.decode(T.self, from: data) + if decodeResult.error == nil { + responseObj = Response(response: httpResponse, body: decodeResult.decodableObj) + } + + completion(responseObj, decodeResult.error) + }) + } + } + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/CodableHelper.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/CodableHelper.swift new file mode 100644 index 0000000000..7603003824 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/CodableHelper.swift @@ -0,0 +1,53 @@ +// +// CodableHelper.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +public typealias EncodeResult = (data: Data?, error: Error?) + +open class CodableHelper { + + open class func decode(_ type: T.Type, from data: Data) -> (decodableObj: T?, error: Error?) where T : Decodable { + var returnedDecodable: T? = nil + var returnedError: Error? = nil + + let decoder = JSONDecoder() + decoder.dataDecodingStrategy = .base64Decode + if #available(iOS 10.0, *) { + decoder.dateDecodingStrategy = .iso8601 + } + + do { + returnedDecodable = try decoder.decode(type, from: data) + } catch { + returnedError = error + } + + return (returnedDecodable, returnedError) + } + + open class func encode(_ value: T, prettyPrint: Bool = false) -> EncodeResult where T : Encodable { + var returnedData: Data? + var returnedError: Error? = nil + + let encoder = JSONEncoder() + encoder.outputFormatting = (prettyPrint ? .prettyPrinted : .compact) + encoder.dataEncodingStrategy = .base64Encode + if #available(iOS 10.0, *) { + encoder.dateEncodingStrategy = .iso8601 + } + + do { + returnedData = try encoder.encode(value) + } catch { + returnedError = error + } + + return (returnedData, returnedError) + } + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Configuration.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Configuration.swift new file mode 100644 index 0000000000..c03a10b930 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Configuration.swift @@ -0,0 +1,15 @@ +// Configuration.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +open class Configuration { + + // This value is used to configure the date formatter that is used to serialize dates into JSON format. + // You must set it prior to encoding any dates, and it will only be read once. + open static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + +} \ No newline at end of file diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Extensions.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Extensions.swift new file mode 100644 index 0000000000..202b47449d --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Extensions.swift @@ -0,0 +1,87 @@ +// Extensions.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire + +extension Bool: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension Float: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension Int: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension Int32: JSONEncodable { + func encodeToJSON() -> Any { return NSNumber(value: self as Int32) } +} + +extension Int64: JSONEncodable { + func encodeToJSON() -> Any { return NSNumber(value: self as Int64) } +} + +extension Double: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension String: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +private func encodeIfPossible(_ object: T) -> Any { + if let encodableObject = object as? JSONEncodable { + return encodableObject.encodeToJSON() + } else { + return object as Any + } +} + +extension Array: JSONEncodable { + func encodeToJSON() -> Any { + return self.map(encodeIfPossible) + } +} + +extension Dictionary: JSONEncodable { + func encodeToJSON() -> Any { + var dictionary = [AnyHashable: Any]() + for (key, value) in self { + dictionary[key as! NSObject] = encodeIfPossible(value) + } + return dictionary as Any + } +} + +extension Data: JSONEncodable { + func encodeToJSON() -> Any { + return self.base64EncodedString(options: Data.Base64EncodingOptions()) + } +} + +private let dateFormatter: DateFormatter = { + let fmt = DateFormatter() + fmt.dateFormat = Configuration.dateFormat + fmt.locale = Locale(identifier: "en_US_POSIX") + return fmt +}() + +extension Date: JSONEncodable { + func encodeToJSON() -> Any { + return dateFormatter.string(from: self) as Any + } +} + +extension UUID: JSONEncodable { + func encodeToJSON() -> Any { + return self.uuidString + } +} + + diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/JSONEncodableEncoding.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/JSONEncodableEncoding.swift new file mode 100644 index 0000000000..472e955ee8 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/JSONEncodableEncoding.swift @@ -0,0 +1,54 @@ +// +// JSONDataEncoding.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire + +public struct JSONDataEncoding: ParameterEncoding { + + // MARK: Properties + + private static let jsonDataKey = "jsonData" + + // MARK: Encoding + + /// 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. This should have a single key/value + /// pair with "jsonData" as the key and a Data object as the value. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let jsonData = parameters?[JSONDataEncoding.jsonDataKey] as? Data, !jsonData.isEmpty else { + return urlRequest + } + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = jsonData + + return urlRequest + } + + public static func encodingParameters(jsonData: Data?) -> Parameters? { + var returnedParams: Parameters? = nil + if let jsonData = jsonData, !jsonData.isEmpty { + var params = Parameters() + params[jsonDataKey] = jsonData + returnedParams = params + } + return returnedParams + } + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/JSONEncodingHelper.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/JSONEncodingHelper.swift new file mode 100644 index 0000000000..4cf4ac206a --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/JSONEncodingHelper.swift @@ -0,0 +1,27 @@ +// +// JSONEncodingHelper.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import Alamofire + +open class JSONEncodingHelper { + + open class func encodingParameters(forEncodableObject encodableObj: T?) -> Parameters? { + var params: Parameters? = nil + + // Encode the Encodable object + if let encodableObj = encodableObj { + let encodeResult = CodableHelper.encode(encodableObj, prettyPrint: true) + if encodeResult.error == nil { + params = JSONDataEncoding.encodingParameters(jsonData: encodeResult.data) + } + } + + return params + } + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models.swift new file mode 100644 index 0000000000..2c19b32158 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models.swift @@ -0,0 +1,36 @@ +// Models.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +protocol JSONEncodable { + func encodeToJSON() -> Any +} + +public enum ErrorResponse : Error { + case Error(Int, Data?, Error) +} + +open class Response { + open let statusCode: Int + open let header: [String: String] + open 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: HTTPURLResponse, 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) + } +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift new file mode 100644 index 0000000000..8d3e08500d --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift @@ -0,0 +1,18 @@ +// +// AdditionalPropertiesClass.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class AdditionalPropertiesClass: Codable { + + public var mapProperty: [String:String]? + public var mapOfMapProperty: [String:[String:String]]? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Animal.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Animal.swift new file mode 100644 index 0000000000..b2079ff79c --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Animal.swift @@ -0,0 +1,18 @@ +// +// Animal.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Animal: Codable { + + public var className: String? + public var color: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/AnimalFarm.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/AnimalFarm.swift new file mode 100644 index 0000000000..6830836489 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/AnimalFarm.swift @@ -0,0 +1,11 @@ +// +// AnimalFarm.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift new file mode 100644 index 0000000000..b9af1103e2 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift @@ -0,0 +1,19 @@ +// +// ApiResponse.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class ApiResponse: Codable { + + public var code: Int32? + public var type: String? + public var message: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift new file mode 100644 index 0000000000..7eb6b23bd2 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift @@ -0,0 +1,17 @@ +// +// ArrayOfArrayOfNumberOnly.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class ArrayOfArrayOfNumberOnly: Codable { + + public var arrayArrayNumber: [[Double]]? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift new file mode 100644 index 0000000000..ab6493cb3c --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift @@ -0,0 +1,17 @@ +// +// ArrayOfNumberOnly.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class ArrayOfNumberOnly: Codable { + + public var arrayNumber: [Double]? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift new file mode 100644 index 0000000000..bf28bb3cc9 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift @@ -0,0 +1,19 @@ +// +// ArrayTest.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class ArrayTest: Codable { + + public var arrayOfString: [String]? + public var arrayArrayOfInteger: [[Int64]]? + public var arrayArrayOfModel: [[ReadOnlyFirst]]? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift new file mode 100644 index 0000000000..e9569b9fb0 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift @@ -0,0 +1,23 @@ +// +// Capitalization.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Capitalization: Codable { + + public var smallCamel: String? + public var capitalCamel: String? + public var smallSnake: String? + public var capitalSnake: String? + public var sCAETHFlowPoints: String? + /** Name of the pet */ + public var ATT_NAME: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Cat.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Cat.swift new file mode 100644 index 0000000000..5ea6f4ea94 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Cat.swift @@ -0,0 +1,17 @@ +// +// Cat.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Cat: Animal { + + public var declawed: Bool? + + + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Category.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Category.swift new file mode 100644 index 0000000000..e21a4c54dd --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Category.swift @@ -0,0 +1,18 @@ +// +// Category.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Category: Codable { + + public var id: Int64? + public var name: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift new file mode 100644 index 0000000000..8fe4a89e76 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift @@ -0,0 +1,18 @@ +// +// ClassModel.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +/** Model for testing model with \"_class\" property */ +open class ClassModel: Codable { + + public var _class: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Client.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Client.swift new file mode 100644 index 0000000000..874bdd7cee --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Client.swift @@ -0,0 +1,17 @@ +// +// Client.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Client: Codable { + + public var client: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Dog.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Dog.swift new file mode 100644 index 0000000000..2b4c3f8a3e --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Dog.swift @@ -0,0 +1,17 @@ +// +// Dog.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Dog: Animal { + + public var breed: String? + + + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift new file mode 100644 index 0000000000..d3da696d1c --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift @@ -0,0 +1,26 @@ +// +// EnumArrays.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class EnumArrays: Codable { + + public enum JustSymbol: String, Codable { + case greaterThanOrEqualTo = ">=" + case dollar = "$" + } + public enum ArrayEnum: String, Codable { + case fish = "fish" + case crab = "crab" + } + public var justSymbol: JustSymbol? + public var arrayEnum: [ArrayEnum]? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/EnumClass.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/EnumClass.swift new file mode 100644 index 0000000000..d0889a3520 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/EnumClass.swift @@ -0,0 +1,16 @@ +// +// EnumClass.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public enum EnumClass: String, Codable { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift new file mode 100644 index 0000000000..7e0266de3f --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift @@ -0,0 +1,33 @@ +// +// EnumTest.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class EnumTest: Codable { + + public enum EnumString: String, Codable { + case upper = "UPPER" + case lower = "lower" + case empty = "" + } + public enum EnumInteger: Int32, Codable { + case _1 = 1 + case numberminus1 = -1 + } + public enum EnumNumber: Double, Codable { + case _11 = 1.1 + case numberminus12 = -1.2 + } + public var enumString: EnumString? + public var enumInteger: EnumInteger? + public var enumNumber: EnumNumber? + public var outerEnum: OuterEnum? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift new file mode 100644 index 0000000000..3c6ef7d3e3 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift @@ -0,0 +1,29 @@ +// +// FormatTest.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class FormatTest: Codable { + + public var integer: Int32? + public var int32: Int32? + public var int64: Int64? + public var number: Double? + public var float: Float? + public var double: Double? + public var string: String? + public var byte: Data? + public var binary: Data? + public var date: Date? + public var dateTime: Date? + public var uuid: UUID? + public var password: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift new file mode 100644 index 0000000000..fef361d308 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift @@ -0,0 +1,18 @@ +// +// HasOnlyReadOnly.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class HasOnlyReadOnly: Codable { + + public var bar: String? + public var foo: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/List.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/List.swift new file mode 100644 index 0000000000..5fab950e8e --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/List.swift @@ -0,0 +1,17 @@ +// +// List.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class List: Codable { + + public var _123List: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/MapTest.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/MapTest.swift new file mode 100644 index 0000000000..584b181f02 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/MapTest.swift @@ -0,0 +1,22 @@ +// +// MapTest.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class MapTest: Codable { + + public enum MapOfEnumString: String, Codable { + case upper = "UPPER" + case lower = "lower" + } + public var mapMapOfString: [String:[String:String]]? + public var mapOfEnumString: [String:String]? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift new file mode 100644 index 0000000000..7fd6c6cf10 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -0,0 +1,19 @@ +// +// MixedPropertiesAndAdditionalPropertiesClass.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class MixedPropertiesAndAdditionalPropertiesClass: Codable { + + public var uuid: UUID? + public var dateTime: Date? + public var map: [String:Animal]? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift new file mode 100644 index 0000000000..ac1ec94073 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift @@ -0,0 +1,19 @@ +// +// Model200Response.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +/** Model for testing model name starting with number */ +open class Model200Response: Codable { + + public var name: Int32? + public var _class: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Name.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Name.swift new file mode 100644 index 0000000000..de6751e52d --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Name.swift @@ -0,0 +1,21 @@ +// +// Name.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +/** Model for testing model name same as property name */ +open class Name: Codable { + + public var name: Int32? + public var snakeCase: Int32? + public var property: String? + public var _123Number: Int32? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift new file mode 100644 index 0000000000..e4f4dc0f7c --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift @@ -0,0 +1,17 @@ +// +// NumberOnly.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class NumberOnly: Codable { + + public var justNumber: Double? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Order.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Order.swift new file mode 100644 index 0000000000..f5fab2487e --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Order.swift @@ -0,0 +1,28 @@ +// +// Order.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Order: Codable { + + public enum Status: String, Codable { + case placed = "placed" + case approved = "approved" + case delivered = "delivered" + } + public var id: Int64? + public var petId: Int64? + public var quantity: Int32? + public var shipDate: Date? + /** Order Status */ + public var status: Status? + public var complete: Bool? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/OuterBoolean.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/OuterBoolean.swift new file mode 100644 index 0000000000..3c49ad2940 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/OuterBoolean.swift @@ -0,0 +1,11 @@ +// +// OuterBoolean.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public typealias OuterBoolean = Bool diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/OuterComposite.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/OuterComposite.swift new file mode 100644 index 0000000000..6d3b435cd1 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/OuterComposite.swift @@ -0,0 +1,19 @@ +// +// OuterComposite.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class OuterComposite: Codable { + + public var myNumber: OuterNumber? + public var myString: OuterString? + public var myBoolean: OuterBoolean? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/OuterEnum.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/OuterEnum.swift new file mode 100644 index 0000000000..d6222d2b1c --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/OuterEnum.swift @@ -0,0 +1,16 @@ +// +// OuterEnum.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public enum OuterEnum: String, Codable { + case placed = "placed" + case approved = "approved" + case delivered = "delivered" + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/OuterNumber.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/OuterNumber.swift new file mode 100644 index 0000000000..f285f4e5e2 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/OuterNumber.swift @@ -0,0 +1,11 @@ +// +// OuterNumber.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public typealias OuterNumber = Double diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/OuterString.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/OuterString.swift new file mode 100644 index 0000000000..9da794627d --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/OuterString.swift @@ -0,0 +1,11 @@ +// +// OuterString.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public typealias OuterString = String diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Pet.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Pet.swift new file mode 100644 index 0000000000..08128cc529 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Pet.swift @@ -0,0 +1,28 @@ +// +// Pet.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Pet: Codable { + + public enum Status: String, Codable { + 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() {} + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift new file mode 100644 index 0000000000..0a779fdd48 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift @@ -0,0 +1,18 @@ +// +// ReadOnlyFirst.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class ReadOnlyFirst: Codable { + + public var bar: String? + public var baz: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Return.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Return.swift new file mode 100644 index 0000000000..629ec1fba6 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Return.swift @@ -0,0 +1,18 @@ +// +// Return.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +/** Model for testing reserved words */ +open class Return: Codable { + + public var _return: Int32? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift new file mode 100644 index 0000000000..e012be66e3 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift @@ -0,0 +1,17 @@ +// +// SpecialModelName.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class SpecialModelName: Codable { + + public var specialPropertyName: Int64? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Tag.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Tag.swift new file mode 100644 index 0000000000..219dd5bade --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/Tag.swift @@ -0,0 +1,18 @@ +// +// Tag.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Tag: Codable { + + public var id: Int64? + public var name: String? + + public init() {} + +} diff --git a/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/User.swift b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/User.swift new file mode 100644 index 0000000000..2e80b7d20f --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/PetstoreClient/Classes/Swaggers/Models/User.swift @@ -0,0 +1,25 @@ +// +// User.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class User: Codable { + + 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() {} + +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Podfile b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Podfile new file mode 100644 index 0000000000..77b1f16f2f --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Podfile @@ -0,0 +1,18 @@ +use_frameworks! +source 'https://github.com/CocoaPods/Specs.git' + +target 'SwaggerClient' do + pod "PetstoreClient", :path => "../" + + target 'SwaggerClientTests' do + inherit! :search_paths + end +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + target.build_configurations.each do |configuration| + configuration.build_settings['SWIFT_VERSION'] = "3.0" + end + end +end diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Podfile.lock b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Podfile.lock new file mode 100644 index 0000000000..2e01f2467a --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Podfile.lock @@ -0,0 +1,22 @@ +PODS: + - Alamofire (4.5.0) + - PetstoreClient (0.0.1): + - Alamofire (~> 4.5) + - RxSwift (~> 3.4.1) + - RxSwift (3.4.1) + +DEPENDENCIES: + - PetstoreClient (from `../`) + +EXTERNAL SOURCES: + PetstoreClient: + :path: ../ + +SPEC CHECKSUMS: + Alamofire: f28cdffd29de33a7bfa022cbd63ae95a27fae140 + PetstoreClient: 23a1f7941fd65b9ebc1806a1646b3ff415371e34 + RxSwift: 656f8fbeca5bc372121a72d9ebdd3cd3bc0ffade + +PODFILE CHECKSUM: 417049e9ed0e4680602b34d838294778389bd418 + +COCOAPODS: 1.1.1 diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/LICENSE b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/LICENSE new file mode 100644 index 0000000000..4cfbf72a4d --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/LICENSE @@ -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. diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/README.md b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/README.md new file mode 100644 index 0000000000..e1966fdca0 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/README.md @@ -0,0 +1,1857 @@ +![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/assets/alamofire.png) + +[![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg?branch=master)](https://travis-ci.org/Alamofire/Alamofire) +[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg) +[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) +[![Platform](https://img.shields.io/cocoapods/p/Alamofire.svg?style=flat)](http://cocoadocs.org/docsets/Alamofire) +[![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat)](http://twitter.com/AlamofireSF) +[![Gitter](https://badges.gitter.im/Alamofire/Alamofire.svg)](https://gitter.im/Alamofire/Alamofire?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) + +Alamofire is an HTTP networking library written in Swift. + +- [Features](#features) +- [Component Libraries](#component-libraries) +- [Requirements](#requirements) +- [Migration Guides](#migration-guides) +- [Communication](#communication) +- [Installation](#installation) +- [Usage](#usage) + - **Intro -** [Making a Request](#making-a-request), [Response Handling](#response-handling), [Response Validation](#response-validation), [Response Caching](#response-caching) + - **HTTP -** [HTTP Methods](#http-methods), [Parameter Encoding](#parameter-encoding), [HTTP Headers](#http-headers), [Authentication](#authentication) + - **Large Data -** [Downloading Data to a File](#downloading-data-to-a-file), [Uploading Data to a Server](#uploading-data-to-a-server) + - **Tools -** [Statistical Metrics](#statistical-metrics), [cURL Command Output](#curl-command-output) +- [Advanced Usage](#advanced-usage) + - **URL Session -** [Session Manager](#session-manager), [Session Delegate](#session-delegate), [Request](#request) + - **Routing -** [Routing Requests](#routing-requests), [Adapting and Retrying Requests](#adapting-and-retrying-requests) + - **Model Objects -** [Custom Response Serialization](#custom-response-serialization) + - **Connection -** [Security](#security), [Network Reachability](#network-reachability) +- [Open Radars](#open-radars) +- [FAQ](#faq) +- [Credits](#credits) +- [Donations](#donations) +- [License](#license) + +## Features + +- [x] Chainable Request / Response Methods +- [x] URL / JSON / plist Parameter Encoding +- [x] Upload File / Data / Stream / MultipartFormData +- [x] Download File using Request or Resume Data +- [x] Authentication with URLCredential +- [x] HTTP Response Validation +- [x] Upload and Download Progress Closures with Progress +- [x] cURL Command Output +- [x] Dynamically Adapt and Retry Requests +- [x] TLS Certificate and Public Key Pinning +- [x] Network Reachability +- [x] Comprehensive Unit and Integration Test Coverage +- [x] [Complete Documentation](http://cocoadocs.org/docsets/Alamofire) + +## Component Libraries + +In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem. + +- [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system. +- [AlamofireNetworkActivityIndicator](https://github.com/Alamofire/AlamofireNetworkActivityIndicator) - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support `URLSession` instances not managed by Alamofire. + +## Requirements + +- iOS 8.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ +- Xcode 8.1, 8.2, 8.3, and 9.0 +- Swift 3.0, 3.1, 3.2, and 4.0 + +## Migration Guides + +- [Alamofire 4.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md) +- [Alamofire 3.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md) +- [Alamofire 2.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%202.0%20Migration%20Guide.md) + +## Communication + +- If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/alamofire). (Tag 'alamofire') +- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/alamofire). +- If you **found a bug**, open an issue. +- If you **have a feature request**, open an issue. +- If you **want to contribute**, submit a pull request. + +## Installation + +### CocoaPods + +[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command: + +```bash +$ gem install cocoapods +``` + +> CocoaPods 1.1.0+ is required to build Alamofire 4.0.0+. + +To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`: + +```ruby +source 'https://github.com/CocoaPods/Specs.git' +platform :ios, '10.0' +use_frameworks! + +target '' do + pod 'Alamofire', '~> 4.4' +end +``` + +Then, run the following command: + +```bash +$ pod install +``` + +### Carthage + +[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. + +You can install Carthage with [Homebrew](http://brew.sh/) using the following command: + +```bash +$ brew update +$ brew install carthage +``` + +To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: + +```ogdl +github "Alamofire/Alamofire" ~> 4.4 +``` + +Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project. + +### Swift Package Manager + +The [Swift Package Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the `swift` compiler. It is in early development, but Alamofire does support its use on supported platforms. + +Once you have your Swift package set up, adding Alamofire as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`. + +```swift +dependencies: [ + .Package(url: "https://github.com/Alamofire/Alamofire.git", majorVersion: 4) +] +``` + +### Manually + +If you prefer not to use any of the aforementioned dependency managers, you can integrate Alamofire into your project manually. + +#### Embedded Framework + +- Open up Terminal, `cd` into your top-level project directory, and run the following command "if" your project is not initialized as a git repository: + + ```bash + $ git init + ``` + +- Add Alamofire as a git [submodule](http://git-scm.com/docs/git-submodule) by running the following command: + + ```bash + $ git submodule add https://github.com/Alamofire/Alamofire.git + ``` + +- Open the new `Alamofire` folder, and drag the `Alamofire.xcodeproj` into the Project Navigator of your application's Xcode project. + + > It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter. + +- Select the `Alamofire.xcodeproj` in the Project Navigator and verify the deployment target matches that of your application target. +- Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar. +- In the tab bar at the top of that window, open the "General" panel. +- Click on the `+` button under the "Embedded Binaries" section. +- You will see two different `Alamofire.xcodeproj` folders each with two different versions of the `Alamofire.framework` nested inside a `Products` folder. + + > It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`. + +- Select the top `Alamofire.framework` for iOS and the bottom one for OS X. + + > You can verify which one you selected by inspecting the build log for your project. The build target for `Alamofire` will be listed as either `Alamofire iOS`, `Alamofire macOS`, `Alamofire tvOS` or `Alamofire watchOS`. + +- And that's it! + + > The `Alamofire.framework` is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device. + +--- + +## Usage + +### Making a Request + +```swift +import Alamofire + +Alamofire.request("https://httpbin.org/get") +``` + +### Response Handling + +Handling the `Response` of a `Request` made in Alamofire involves chaining a response handler onto the `Request`. + +```swift +Alamofire.request("https://httpbin.org/get").responseJSON { response in + print("Request: \(String(describing: response.request))") // original url request + print("Response: \(String(describing: response.response))") // http url response + print("Result: \(response.result)") // response serialization result + + if let json = response.result.value { + print("JSON: \(json)") // serialized json response + } + + if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) { + print("Data: \(utf8Text)") // original server data as UTF8 string + } +} +``` + +In the above example, the `responseJSON` handler is appended to the `Request` to be executed once the `Request` is complete. Rather than blocking execution to wait for a response from the server, a [callback](http://en.wikipedia.org/wiki/Callback_%28computer_programming%29) in the form of a closure is specified to handle the response once it's received. The result of a request is only available inside the scope of a response closure. Any execution contingent on the response or data received from the server must be done within a response closure. + +> Networking in Alamofire is done _asynchronously_. Asynchronous programming may be a source of frustration to programmers unfamiliar with the concept, but there are [very good reasons](https://developer.apple.com/library/ios/qa/qa1693/_index.html) for doing it this way. + +Alamofire contains five different response handlers by default including: + +```swift +// Response Handler - Unserialized Response +func response( + queue: DispatchQueue?, + completionHandler: @escaping (DefaultDataResponse) -> Void) + -> Self + +// Response Data Handler - Serialized into Data +func responseData( + queue: DispatchQueue?, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + +// Response String Handler - Serialized into String +func responseString( + queue: DispatchQueue?, + encoding: String.Encoding?, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + +// Response JSON Handler - Serialized into Any +func responseJSON( + queue: DispatchQueue?, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + +// Response PropertyList (plist) Handler - Serialized into Any +func responsePropertyList( + queue: DispatchQueue?, + completionHandler: @escaping (DataResponse) -> Void)) + -> Self +``` + +None of the response handlers perform any validation of the `HTTPURLResponse` it gets back from the server. + +> For example, response status codes in the `400..<500` and `500..<600` ranges do NOT automatically trigger an `Error`. Alamofire uses [Response Validation](#response-validation) method chaining to achieve this. + +#### Response Handler + +The `response` handler does NOT evaluate any of the response data. It merely forwards on all information directly from the URL session delegate. It is the Alamofire equivalent of using `cURL` to execute a `Request`. + +```swift +Alamofire.request("https://httpbin.org/get").response { response in + print("Request: \(response.request)") + print("Response: \(response.response)") + print("Error: \(response.error)") + + if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) { + print("Data: \(utf8Text)") + } +} +``` + +> We strongly encourage you to leverage the other response serializers taking advantage of `Response` and `Result` types. + +#### Response Data Handler + +The `responseData` handler uses the `responseDataSerializer` (the object that serializes the server data into some other type) to extract the `Data` returned by the server. If no errors occur and `Data` is returned, the response `Result` will be a `.success` and the `value` will be of type `Data`. + +```swift +Alamofire.request("https://httpbin.org/get").responseData { response in + debugPrint("All Response Info: \(response)") + + if let data = response.result.value, let utf8Text = String(data: data, encoding: .utf8) { + print("Data: \(utf8Text)") + } +} +``` + +#### Response String Handler + +The `responseString` handler uses the `responseStringSerializer` to convert the `Data` returned by the server into a `String` with the specified encoding. If no errors occur and the server data is successfully serialized into a `String`, the response `Result` will be a `.success` and the `value` will be of type `String`. + +```swift +Alamofire.request("https://httpbin.org/get").responseString { response in + print("Success: \(response.result.isSuccess)") + print("Response String: \(response.result.value)") +} +``` + +> If no encoding is specified, Alamofire will use the text encoding specified in the `HTTPURLResponse` from the server. If the text encoding cannot be determined by the server response, it defaults to `.isoLatin1`. + +#### Response JSON Handler + +The `responseJSON` handler uses the `responseJSONSerializer` to convert the `Data` returned by the server into an `Any` type using the specified `JSONSerialization.ReadingOptions`. If no errors occur and the server data is successfully serialized into a JSON object, the response `Result` will be a `.success` and the `value` will be of type `Any`. + +```swift +Alamofire.request("https://httpbin.org/get").responseJSON { response in + debugPrint(response) + + if let json = response.result.value { + print("JSON: \(json)") + } +} +``` + +> All JSON serialization is handled by the `JSONSerialization` API in the `Foundation` framework. + +#### Chained Response Handlers + +Response handlers can even be chained: + +```swift +Alamofire.request("https://httpbin.org/get") + .responseString { response in + print("Response String: \(response.result.value)") + } + .responseJSON { response in + print("Response JSON: \(response.result.value)") + } +``` + +> It is important to note that using multiple response handlers on the same `Request` requires the server data to be serialized multiple times. Once for each response handler. + +#### Response Handler Queue + +Response handlers by default are executed on the main dispatch queue. However, a custom dispatch queue can be provided instead. + +```swift +let utilityQueue = DispatchQueue.global(qos: .utility) + +Alamofire.request("https://httpbin.org/get").responseJSON(queue: utilityQueue) { response in + print("Executing response handler on utility queue") +} +``` + +### Response Validation + +By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling `validate` before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type. + +#### Manual Validation + +```swift +Alamofire.request("https://httpbin.org/get") + .validate(statusCode: 200..<300) + .validate(contentType: ["application/json"]) + .responseData { response in + switch response.result { + case .success: + print("Validation Successful") + case .failure(let error): + print(error) + } + } +``` + +#### Automatic Validation + +Automatically validates status code within `200..<300` range, and that the `Content-Type` header of the response matches the `Accept` header of the request, if one is provided. + +```swift +Alamofire.request("https://httpbin.org/get").validate().responseJSON { response in + switch response.result { + case .success: + print("Validation Successful") + case .failure(let error): + print(error) + } +} +``` + +### Response Caching + +Response Caching is handled on the system framework level by [`URLCache`](https://developer.apple.com/reference/foundation/urlcache). It provides a composite in-memory and on-disk cache and lets you manipulate the sizes of both the in-memory and on-disk portions. + +> By default, Alamofire leverages the shared `URLCache`. In order to customize it, see the [Session Manager Configurations](#session-manager) section. + +### HTTP Methods + +The `HTTPMethod` enumeration lists the HTTP methods defined in [RFC 7231 §4.3](http://tools.ietf.org/html/rfc7231#section-4.3): + +```swift +public enum HTTPMethod: String { + case options = "OPTIONS" + case get = "GET" + case head = "HEAD" + case post = "POST" + case put = "PUT" + case patch = "PATCH" + case delete = "DELETE" + case trace = "TRACE" + case connect = "CONNECT" +} +``` + +These values can be passed as the `method` argument to the `Alamofire.request` API: + +```swift +Alamofire.request("https://httpbin.org/get") // method defaults to `.get` + +Alamofire.request("https://httpbin.org/post", method: .post) +Alamofire.request("https://httpbin.org/put", method: .put) +Alamofire.request("https://httpbin.org/delete", method: .delete) +``` + +> The `Alamofire.request` method parameter defaults to `.get`. + +### Parameter Encoding + +Alamofire supports three types of parameter encoding including: `URL`, `JSON` and `PropertyList`. It can also support any custom encoding that conforms to the `ParameterEncoding` protocol. + +#### URL Encoding + +The `URLEncoding` type creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP body of the URL request. Whether the query string is set or appended to any existing URL query string or set as the HTTP body depends on the `Destination` of the encoding. The `Destination` enumeration has three cases: + +- `.methodDependent` - Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` requests and sets as the HTTP body for requests with any other HTTP method. +- `.queryString` - Sets or appends encoded query string result to existing query string. +- `.httpBody` - Sets encoded query string result as the HTTP body of the URL request. + +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`). + +##### GET Request With URL-Encoded Parameters + +```swift +let parameters: Parameters = ["foo": "bar"] + +// All three of these calls are equivalent +Alamofire.request("https://httpbin.org/get", parameters: parameters) // encoding defaults to `URLEncoding.default` +Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding.default) +Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding(destination: .methodDependent)) + +// https://httpbin.org/get?foo=bar +``` + +##### POST Request With URL-Encoded Parameters + +```swift +let parameters: Parameters = [ + "foo": "bar", + "baz": ["a", 1], + "qux": [ + "x": 1, + "y": 2, + "z": 3 + ] +] + +// All three of these calls are equivalent +Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters) +Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.default) +Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.httpBody) + +// HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3 +``` + +#### JSON Encoding + +The `JSONEncoding` type creates a JSON representation of the parameters object, which is set as the HTTP body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. + +##### POST Request with JSON-Encoded Parameters + +```swift +let parameters: Parameters = [ + "foo": [1,2,3], + "bar": [ + "baz": "qux" + ] +] + +// Both calls are equivalent +Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding.default) +Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding(options: [])) + +// HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}} +``` + +#### Property List Encoding + +The `PropertyListEncoding` uses `PropertyListSerialization` 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 Encoding + +In the event that the provided `ParameterEncoding` types do not meet your needs, you can create your own custom encoding. Here's a quick example of how you could build a custom `JSONStringArrayEncoding` type to encode a JSON string array onto a `Request`. + +```swift +struct JSONStringArrayEncoding: ParameterEncoding { + private let array: [String] + + init(array: [String]) { + self.array = array + } + + func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + let data = try JSONSerialization.data(withJSONObject: array, options: []) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = data + + return urlRequest + } +} +``` + +#### Manual Parameter Encoding of a URLRequest + +The `ParameterEncoding` APIs can be used outside of making network requests. + +```swift +let url = URL(string: "https://httpbin.org/get")! +var urlRequest = URLRequest(url: url) + +let parameters: Parameters = ["foo": "bar"] +let encodedURLRequest = try URLEncoding.queryString.encode(urlRequest, with: parameters) +``` + +### HTTP Headers + +Adding a custom HTTP header to a `Request` is supported directly in the global `request` method. This makes it easy to attach HTTP headers to a `Request` that can be constantly changing. + +```swift +let headers: HTTPHeaders = [ + "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", + "Accept": "application/json" +] + +Alamofire.request("https://httpbin.org/headers", headers: headers).responseJSON { response in + debugPrint(response) +} +``` + +> For HTTP headers that do not change, it is recommended to set them on the `URLSessionConfiguration` so they are automatically applied to any `URLSessionTask` created by the underlying `URLSession`. For more information, see the [Session Manager Configurations](#session-manager) section. + +The default Alamofire `SessionManager` provides a default set of headers for every `Request`. These include: + +- `Accept-Encoding`, which defaults to `gzip;q=1.0, compress;q=0.5`, per [RFC 7230 §4.2.3](https://tools.ietf.org/html/rfc7230#section-4.2.3). +- `Accept-Language`, which defaults to up to the top 6 preferred languages on the system, formatted like `en;q=1.0`, per [RFC 7231 §5.3.5](https://tools.ietf.org/html/rfc7231#section-5.3.5). +- `User-Agent`, which contains versioning information about the current app. For example: `iOS Example/1.0 (com.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0`, per [RFC 7231 §5.5.3](https://tools.ietf.org/html/rfc7231#section-5.5.3). + +If you need to customize these headers, a custom `URLSessionConfiguration` should be created, the `defaultHTTPHeaders` property updated and the configuration applied to a new `SessionManager` instance. + +### Authentication + +Authentication is handled on the system framework level by [`URLCredential`](https://developer.apple.com/reference/foundation/nsurlcredential) and [`URLAuthenticationChallenge`](https://developer.apple.com/reference/foundation/urlauthenticationchallenge). + +**Supported Authentication Schemes** + +- [HTTP Basic](http://en.wikipedia.org/wiki/Basic_access_authentication) +- [HTTP Digest](http://en.wikipedia.org/wiki/Digest_access_authentication) +- [Kerberos](http://en.wikipedia.org/wiki/Kerberos_%28protocol%29) +- [NTLM](http://en.wikipedia.org/wiki/NT_LAN_Manager) + +#### HTTP Basic Authentication + +The `authenticate` method on a `Request` will automatically provide a `URLCredential` to a `URLAuthenticationChallenge` when appropriate: + +```swift +let user = "user" +let password = "password" + +Alamofire.request("https://httpbin.org/basic-auth/\(user)/\(password)") + .authenticate(user: user, password: password) + .responseJSON { response in + debugPrint(response) + } +``` + +Depending upon your server implementation, an `Authorization` header may also be appropriate: + +```swift +let user = "user" +let password = "password" + +var headers: HTTPHeaders = [:] + +if let authorizationHeader = Request.authorizationHeader(user: user, password: password) { + headers[authorizationHeader.key] = authorizationHeader.value +} + +Alamofire.request("https://httpbin.org/basic-auth/user/password", headers: headers) + .responseJSON { response in + debugPrint(response) + } +``` + +#### Authentication with URLCredential + +```swift +let user = "user" +let password = "password" + +let credential = URLCredential(user: user, password: password, persistence: .forSession) + +Alamofire.request("https://httpbin.org/basic-auth/\(user)/\(password)") + .authenticate(usingCredential: credential) + .responseJSON { response in + debugPrint(response) + } +``` + +> It is important to note that when using a `URLCredential` for authentication, the underlying `URLSession` will actually end up making two requests if a challenge is issued by the server. The first request will not include the credential which "may" trigger a challenge from the server. The challenge is then received by Alamofire, the credential is appended and the request is retried by the underlying `URLSession`. + +### Downloading Data to a File + +Requests made in Alamofire that fetch data from a server can download the data in-memory or on-disk. The `Alamofire.request` APIs used in all the examples so far always downloads the server data in-memory. This is great for smaller payloads because it's more efficient, but really bad for larger payloads because the download could run your entire application out-of-memory. Because of this, you can also use the `Alamofire.download` APIs to download the server data to a temporary file on-disk. + +> This will only work on `macOS` as is. Other platforms don't allow access to the filesystem outside of your app's sandbox. To download files on other platforms, see the [Download File Destination](#download-file-destination) section. + +```swift +Alamofire.download("https://httpbin.org/image/png").responseData { response in + if let data = response.result.value { + let image = UIImage(data: data) + } +} +``` + +> The `Alamofire.download` APIs should also be used if you need to download data while your app is in the background. For more information, please see the [Session Manager Configurations](#session-manager) section. + +#### Download File Destination + +You can also provide a `DownloadFileDestination` closure to move the file from the temporary directory to a final destination. Before the temporary file is actually moved to the `destinationURL`, the `DownloadOptions` specified in the closure will be executed. The two currently supported `DownloadOptions` are: + +- `.createIntermediateDirectories` - Creates intermediate directories for the destination URL if specified. +- `.removePreviousFile` - Removes a previous file from the destination URL if specified. + +```swift +let destination: DownloadRequest.DownloadFileDestination = { _, _ in + let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] + let fileURL = documentsURL.appendingPathComponent("pig.png") + + return (fileURL, [.removePreviousFile, .createIntermediateDirectories]) +} + +Alamofire.download(urlString, to: destination).response { response in + print(response) + + if response.error == nil, let imagePath = response.destinationURL?.path { + let image = UIImage(contentsOfFile: imagePath) + } +} +``` + +You can also use the suggested download destination API. + +```swift +let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory) +Alamofire.download("https://httpbin.org/image/png", to: destination) +``` + +#### Download Progress + +Many times it can be helpful to report download progress to the user. Any `DownloadRequest` can report download progress using the `downloadProgress` API. + +```swift +Alamofire.download("https://httpbin.org/image/png") + .downloadProgress { progress in + print("Download Progress: \(progress.fractionCompleted)") + } + .responseData { response in + if let data = response.result.value { + let image = UIImage(data: data) + } + } +``` + +The `downloadProgress` API also takes a `queue` parameter which defines which `DispatchQueue` the download progress closure should be called on. + +```swift +let utilityQueue = DispatchQueue.global(qos: .utility) + +Alamofire.download("https://httpbin.org/image/png") + .downloadProgress(queue: utilityQueue) { progress in + print("Download Progress: \(progress.fractionCompleted)") + } + .responseData { response in + if let data = response.result.value { + let image = UIImage(data: data) + } + } +``` + +#### Resuming a Download + +If a `DownloadRequest` is cancelled or interrupted, the underlying URL session may generate resume data for the active `DownloadRequest`. If this happens, the resume data can be re-used to restart the `DownloadRequest` where it left off. The resume data can be accessed through the download response, then reused when trying to restart the request. + +> **IMPORTANT:** On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the data is written incorrectly and will always fail to resume the download. For more information about the bug and possible workarounds, please see this Stack Overflow [post](http://stackoverflow.com/a/39347461/1342462). + +```swift +class ImageRequestor { + private var resumeData: Data? + private var image: UIImage? + + func fetchImage(completion: (UIImage?) -> Void) { + guard image == nil else { completion(image) ; return } + + let destination: DownloadRequest.DownloadFileDestination = { _, _ in + let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] + let fileURL = documentsURL.appendingPathComponent("pig.png") + + return (fileURL, [.removePreviousFile, .createIntermediateDirectories]) + } + + let request: DownloadRequest + + if let resumeData = resumeData { + request = Alamofire.download(resumingWith: resumeData) + } else { + request = Alamofire.download("https://httpbin.org/image/png") + } + + request.responseData { response in + switch response.result { + case .success(let data): + self.image = UIImage(data: data) + case .failure: + self.resumeData = response.resumeData + } + } + } +} +``` + +### Uploading Data to a Server + +When sending relatively small amounts of data to a server using JSON or URL encoded parameters, the `Alamofire.request` APIs are usually sufficient. If you need to send much larger amounts of data from a file URL or an `InputStream`, then the `Alamofire.upload` APIs are what you want to use. + +> The `Alamofire.upload` APIs should also be used if you need to upload data while your app is in the background. For more information, please see the [Session Manager Configurations](#session-manager) section. + +#### Uploading Data + +```swift +let imageData = UIPNGRepresentation(image)! + +Alamofire.upload(imageData, to: "https://httpbin.org/post").responseJSON { response in + debugPrint(response) +} +``` + +#### Uploading a File + +```swift +let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov") + +Alamofire.upload(fileURL, to: "https://httpbin.org/post").responseJSON { response in + debugPrint(response) +} +``` + +#### Uploading Multipart Form Data + +```swift +Alamofire.upload( + multipartFormData: { multipartFormData in + multipartFormData.append(unicornImageURL, withName: "unicorn") + multipartFormData.append(rainbowImageURL, withName: "rainbow") + }, + to: "https://httpbin.org/post", + encodingCompletion: { encodingResult in + switch encodingResult { + case .success(let upload, _, _): + upload.responseJSON { response in + debugPrint(response) + } + case .failure(let encodingError): + print(encodingError) + } + } +) +``` + +#### Upload Progress + +While your user is waiting for their upload to complete, sometimes it can be handy to show the progress of the upload to the user. Any `UploadRequest` can report both upload progress and download progress of the response data using the `uploadProgress` and `downloadProgress` APIs. + +```swift +let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov") + +Alamofire.upload(fileURL, to: "https://httpbin.org/post") + .uploadProgress { progress in // main queue by default + print("Upload Progress: \(progress.fractionCompleted)") + } + .downloadProgress { progress in // main queue by default + print("Download Progress: \(progress.fractionCompleted)") + } + .responseJSON { response in + debugPrint(response) + } +``` + +### Statistical Metrics + +#### Timeline + +Alamofire collects timings throughout the lifecycle of a `Request` and creates a `Timeline` object exposed as a property on all response types. + +```swift +Alamofire.request("https://httpbin.org/get").responseJSON { response in + print(response.timeline) +} +``` + +The above reports the following `Timeline` info: + +- `Latency`: 0.428 seconds +- `Request Duration`: 0.428 seconds +- `Serialization Duration`: 0.001 seconds +- `Total Duration`: 0.429 seconds + +#### URL Session Task Metrics + +In iOS and tvOS 10 and macOS 10.12, Apple introduced the new [URLSessionTaskMetrics](https://developer.apple.com/reference/foundation/urlsessiontaskmetrics) APIs. The task metrics encapsulate some fantastic statistical information about the request and response execution. The API is very similar to the `Timeline`, but provides many more statistics that Alamofire doesn't have access to compute. The metrics can be accessed through any response type. + +```swift +Alamofire.request("https://httpbin.org/get").responseJSON { response in + print(response.metrics) +} +``` + +It's important to note that these APIs are only available on iOS and tvOS 10 and macOS 10.12. Therefore, depending on your deployment target, you may need to use these inside availability checks: + +```swift +Alamofire.request("https://httpbin.org/get").responseJSON { response in + if #available(iOS 10.0, *) { + print(response.metrics) + } +} +``` + +### cURL Command Output + +Debugging platform issues can be frustrating. Thankfully, Alamofire `Request` objects conform to both the `CustomStringConvertible` and `CustomDebugStringConvertible` protocols to provide some VERY helpful debugging tools. + +#### CustomStringConvertible + +```swift +let request = Alamofire.request("https://httpbin.org/ip") + +print(request) +// GET https://httpbin.org/ip (200) +``` + +#### CustomDebugStringConvertible + +```swift +let request = Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"]) +debugPrint(request) +``` + +Outputs: + +```bash +$ curl -i \ + -H "User-Agent: Alamofire/4.0.0" \ + -H "Accept-Encoding: gzip;q=1.0, compress;q=0.5" \ + -H "Accept-Language: en;q=1.0,fr;q=0.9,de;q=0.8,zh-Hans;q=0.7,zh-Hant;q=0.6,ja;q=0.5" \ + "https://httpbin.org/get?foo=bar" +``` + +--- + +## Advanced Usage + +Alamofire is built on `URLSession` and the Foundation URL Loading System. To make the most of this framework, it is recommended that you be familiar with the concepts and capabilities of the underlying networking stack. + +**Recommended Reading** + +- [URL Loading System Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html) +- [URLSession Class Reference](https://developer.apple.com/reference/foundation/nsurlsession) +- [URLCache Class Reference](https://developer.apple.com/reference/foundation/urlcache) +- [URLAuthenticationChallenge Class Reference](https://developer.apple.com/reference/foundation/urlauthenticationchallenge) + +### Session Manager + +Top-level convenience methods like `Alamofire.request` use a default instance of `Alamofire.SessionManager`, which is configured with the default `URLSessionConfiguration`. + +As such, the following two statements are equivalent: + +```swift +Alamofire.request("https://httpbin.org/get") +``` + +```swift +let sessionManager = Alamofire.SessionManager.default +sessionManager.request("https://httpbin.org/get") +``` + +Applications can create session managers for background and ephemeral sessions, as well as new managers that customize the default session configuration, such as for default headers (`httpAdditionalHeaders`) or timeout interval (`timeoutIntervalForRequest`). + +#### Creating a Session Manager with Default Configuration + +```swift +let configuration = URLSessionConfiguration.default +let sessionManager = Alamofire.SessionManager(configuration: configuration) +``` + +#### Creating a Session Manager with Background Configuration + +```swift +let configuration = URLSessionConfiguration.background(withIdentifier: "com.example.app.background") +let sessionManager = Alamofire.SessionManager(configuration: configuration) +``` + +#### Creating a Session Manager with Ephemeral Configuration + +```swift +let configuration = URLSessionConfiguration.ephemeral +let sessionManager = Alamofire.SessionManager(configuration: configuration) +``` + +#### Modifying the Session Configuration + +```swift +var defaultHeaders = Alamofire.SessionManager.defaultHTTPHeaders +defaultHeaders["DNT"] = "1 (Do Not Track Enabled)" + +let configuration = URLSessionConfiguration.default +configuration.httpAdditionalHeaders = defaultHeaders + +let sessionManager = Alamofire.SessionManager(configuration: configuration) +``` + +> This is **not** recommended for `Authorization` or `Content-Type` headers. Instead, use the `headers` parameter in the top-level `Alamofire.request` APIs, `URLRequestConvertible` and `ParameterEncoding`, respectively. + +### Session Delegate + +By default, an Alamofire `SessionManager` instance creates a `SessionDelegate` object to handle all the various types of delegate callbacks that are generated by the underlying `URLSession`. The implementations of each delegate method handle the most common use cases for these types of calls abstracting the complexity away from the top-level APIs. However, advanced users may find the need to override the default functionality for various reasons. + +#### Override Closures + +The first way to customize the `SessionDelegate` behavior is through the use of the override closures. Each closure gives you the ability to override the implementation of the matching `SessionDelegate` API, yet still use the default implementation for all other APIs. This makes it easy to customize subsets of the delegate functionality. Here are a few examples of some of the override closures available: + +```swift +/// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`. +open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + +/// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`. +open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)? + +/// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`. +open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? + +/// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`. +open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? +``` + +The following is a short example of how to use the `taskWillPerformHTTPRedirection` to avoid following redirects to any `apple.com` domains. + +```swift +let sessionManager = Alamofire.SessionManager(configuration: URLSessionConfiguration.default) +let delegate: Alamofire.SessionDelegate = sessionManager.delegate + +delegate.taskWillPerformHTTPRedirection = { session, task, response, request in + var finalRequest = request + + if + let originalRequest = task.originalRequest, + let urlString = originalRequest.url?.urlString, + urlString.contains("apple.com") + { + finalRequest = originalRequest + } + + return finalRequest +} +``` + +#### Subclassing + +Another way to override the default implementation of the `SessionDelegate` is to subclass it. Subclassing allows you completely customize the behavior of the API or to create a proxy for the API and still use the default implementation. Creating a proxy allows you to log events, emit notifications, provide pre and post hook implementations, etc. Here's a quick example of subclassing the `SessionDelegate` and logging a message when a redirect occurs. + +```swift +class LoggingSessionDelegate: SessionDelegate { + override func urlSession( + _ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) + { + print("URLSession will perform HTTP redirection to request: \(request)") + + super.urlSession( + session, + task: task, + willPerformHTTPRedirection: response, + newRequest: request, + completionHandler: completionHandler + ) + } +} +``` + +Generally speaking, either the default implementation or the override closures should provide the necessary functionality required. Subclassing should only be used as a last resort. + +> It is important to keep in mind that the `subdelegates` are initialized and destroyed in the default implementation. Be careful when subclassing to not introduce memory leaks. + +### Request + +The result of a `request`, `download`, `upload` or `stream` methods are a `DataRequest`, `DownloadRequest`, `UploadRequest` and `StreamRequest` which all inherit from `Request`. All `Request` instances are always created by an owning session manager, and never initialized directly. + +Each subclass has specialized methods such as `authenticate`, `validate`, `responseJSON` and `uploadProgress` that each return the caller instance in order to facilitate method chaining. + +Requests can be suspended, resumed and cancelled: + +- `suspend()`: Suspends the underlying task and dispatch queue. +- `resume()`: Resumes the underlying task and dispatch queue. If the owning manager does not have `startRequestsImmediately` set to `true`, the request must call `resume()` in order to start. +- `cancel()`: Cancels the underlying task, producing an error that is passed to any registered response handlers. + +### Routing Requests + +As apps grow in size, it's important to adopt common patterns as you build out your network stack. An important part of that design is how to route your requests. The Alamofire `URLConvertible` and `URLRequestConvertible` protocols along with the `Router` design pattern are here to help. + +#### URLConvertible + +Types adopting the `URLConvertible` protocol can be used to construct URLs, which are then used to construct URL requests internally. `String`, `URL`, and `URLComponents` conform to `URLConvertible` by default, allowing any of them to be passed as `url` parameters to the `request`, `upload`, and `download` methods: + +```swift +let urlString = "https://httpbin.org/post" +Alamofire.request(urlString, method: .post) + +let url = URL(string: urlString)! +Alamofire.request(url, method: .post) + +let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true)! +Alamofire.request(urlComponents, method: .post) +``` + +Applications interacting with web applications in a significant manner are encouraged to have custom types conform to `URLConvertible` as a convenient way to map domain-specific models to server resources. + +##### Type-Safe Routing + +```swift +extension User: URLConvertible { + static let baseURLString = "https://example.com" + + func asURL() throws -> URL { + let urlString = User.baseURLString + "/users/\(username)/" + return try urlString.asURL() + } +} +``` + +```swift +let user = User(username: "mattt") +Alamofire.request(user) // https://example.com/users/mattt +``` + +#### URLRequestConvertible + +Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. `URLRequest` conforms to `URLRequestConvertible` by default, allowing it to be passed into `request`, `upload`, and `download` methods directly (this is the recommended way to specify custom HTTP body for individual requests): + +```swift +let url = URL(string: "https://httpbin.org/post")! +var urlRequest = URLRequest(url: url) +urlRequest.httpMethod = "POST" + +let parameters = ["foo": "bar"] + +do { + urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: []) +} catch { + // No-op +} + +urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + +Alamofire.request(urlRequest) +``` + +Applications interacting with web applications in a significant manner are encouraged to have custom types conform to `URLRequestConvertible` as a way to ensure consistency of requested endpoints. Such an approach can be used to abstract away server-side inconsistencies and provide type-safe routing, as well as manage authentication credentials and other state. + +##### API Parameter Abstraction + +```swift +enum Router: URLRequestConvertible { + case search(query: String, page: Int) + + static let baseURLString = "https://example.com" + static let perPage = 50 + + // MARK: URLRequestConvertible + + func asURLRequest() throws -> URLRequest { + let result: (path: String, parameters: Parameters) = { + switch self { + case let .search(query, page) where page > 0: + return ("/search", ["q": query, "offset": Router.perPage * page]) + case let .search(query, _): + return ("/search", ["q": query]) + } + }() + + let url = try Router.baseURLString.asURL() + let urlRequest = URLRequest(url: url.appendingPathComponent(result.path)) + + return try URLEncoding.default.encode(urlRequest, with: result.parameters) + } +} +``` + +```swift +Alamofire.request(Router.search(query: "foo bar", page: 1)) // https://example.com/search?q=foo%20bar&offset=50 +``` + +##### CRUD & Authorization + +```swift +import Alamofire + +enum Router: URLRequestConvertible { + case createUser(parameters: Parameters) + case readUser(username: String) + case updateUser(username: String, parameters: Parameters) + case destroyUser(username: String) + + static let baseURLString = "https://example.com" + + var method: HTTPMethod { + switch self { + case .createUser: + return .post + case .readUser: + return .get + case .updateUser: + return .put + case .destroyUser: + return .delete + } + } + + var path: String { + switch self { + case .createUser: + return "/users" + case .readUser(let username): + return "/users/\(username)" + case .updateUser(let username, _): + return "/users/\(username)" + case .destroyUser(let username): + return "/users/\(username)" + } + } + + // MARK: URLRequestConvertible + + func asURLRequest() throws -> URLRequest { + let url = try Router.baseURLString.asURL() + + var urlRequest = URLRequest(url: url.appendingPathComponent(path)) + urlRequest.httpMethod = method.rawValue + + switch self { + case .createUser(let parameters): + urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters) + case .updateUser(_, let parameters): + urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters) + default: + break + } + + return urlRequest + } +} +``` + +```swift +Alamofire.request(Router.readUser("mattt")) // GET https://example.com/users/mattt +``` + +### Adapting and Retrying Requests + +Most web services these days are behind some sort of authentication system. One of the more common ones today is OAuth. This generally involves generating an access token authorizing your application or user to call the various supported web services. While creating these initial access tokens can be laborsome, it can be even more complicated when your access token expires and you need to fetch a new one. There are many thread-safety issues that need to be considered. + +The `RequestAdapter` and `RequestRetrier` protocols were created to make it much easier to create a thread-safe authentication system for a specific set of web services. + +#### RequestAdapter + +The `RequestAdapter` protocol allows each `Request` made on a `SessionManager` to be inspected and adapted before being created. One very specific way to use an adapter is to append an `Authorization` header to requests behind a certain type of authentication. + +```swift +class AccessTokenAdapter: RequestAdapter { + private let accessToken: String + + init(accessToken: String) { + self.accessToken = accessToken + } + + func adapt(_ urlRequest: URLRequest) throws -> URLRequest { + var urlRequest = urlRequest + + if let urlString = urlRequest.url?.absoluteString, urlString.hasPrefix("https://httpbin.org") { + urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization") + } + + return urlRequest + } +} +``` + +```swift +let sessionManager = SessionManager() +sessionManager.adapter = AccessTokenAdapter(accessToken: "1234") + +sessionManager.request("https://httpbin.org/get") +``` + +#### RequestRetrier + +The `RequestRetrier` protocol allows a `Request` that encountered an `Error` while being executed to be retried. When using both the `RequestAdapter` and `RequestRetrier` protocols together, you can create credential refresh systems for OAuth1, OAuth2, Basic Auth and even exponential backoff retry policies. The possibilities are endless. Here's an example of how you could implement a refresh flow for OAuth2 access tokens. + +> **DISCLAIMER:** This is **NOT** a global `OAuth2` solution. It is merely an example demonstrating how one could use the `RequestAdapter` in conjunction with the `RequestRetrier` to create a thread-safe refresh system. + +> To reiterate, **do NOT copy** this sample code and drop it into a production application. This is merely an example. Each authentication system must be tailored to a particular platform and authentication type. + +```swift +class OAuth2Handler: RequestAdapter, RequestRetrier { + private typealias RefreshCompletion = (_ succeeded: Bool, _ accessToken: String?, _ refreshToken: String?) -> Void + + private let sessionManager: SessionManager = { + let configuration = URLSessionConfiguration.default + configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders + + return SessionManager(configuration: configuration) + }() + + private let lock = NSLock() + + private var clientID: String + private var baseURLString: String + private var accessToken: String + private var refreshToken: String + + private var isRefreshing = false + private var requestsToRetry: [RequestRetryCompletion] = [] + + // MARK: - Initialization + + public init(clientID: String, baseURLString: String, accessToken: String, refreshToken: String) { + self.clientID = clientID + self.baseURLString = baseURLString + self.accessToken = accessToken + self.refreshToken = refreshToken + } + + // MARK: - RequestAdapter + + func adapt(_ urlRequest: URLRequest) throws -> URLRequest { + if let urlString = urlRequest.url?.absoluteString, urlString.hasPrefix(baseURLString) { + var urlRequest = urlRequest + urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization") + return urlRequest + } + + return urlRequest + } + + // MARK: - RequestRetrier + + func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) { + lock.lock() ; defer { lock.unlock() } + + if let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401 { + requestsToRetry.append(completion) + + if !isRefreshing { + refreshTokens { [weak self] succeeded, accessToken, refreshToken in + guard let strongSelf = self else { return } + + strongSelf.lock.lock() ; defer { strongSelf.lock.unlock() } + + if let accessToken = accessToken, let refreshToken = refreshToken { + strongSelf.accessToken = accessToken + strongSelf.refreshToken = refreshToken + } + + strongSelf.requestsToRetry.forEach { $0(succeeded, 0.0) } + strongSelf.requestsToRetry.removeAll() + } + } + } else { + completion(false, 0.0) + } + } + + // MARK: - Private - Refresh Tokens + + private func refreshTokens(completion: @escaping RefreshCompletion) { + guard !isRefreshing else { return } + + isRefreshing = true + + let urlString = "\(baseURLString)/oauth2/token" + + let parameters: [String: Any] = [ + "access_token": accessToken, + "refresh_token": refreshToken, + "client_id": clientID, + "grant_type": "refresh_token" + ] + + sessionManager.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default) + .responseJSON { [weak self] response in + guard let strongSelf = self else { return } + + if + let json = response.result.value as? [String: Any], + let accessToken = json["access_token"] as? String, + let refreshToken = json["refresh_token"] as? String + { + completion(true, accessToken, refreshToken) + } else { + completion(false, nil, nil) + } + + strongSelf.isRefreshing = false + } + } +} +``` + +```swift +let baseURLString = "https://some.domain-behind-oauth2.com" + +let oauthHandler = OAuth2Handler( + clientID: "12345678", + baseURLString: baseURLString, + accessToken: "abcd1234", + refreshToken: "ef56789a" +) + +let sessionManager = SessionManager() +sessionManager.adapter = oauthHandler +sessionManager.retrier = oauthHandler + +let urlString = "\(baseURLString)/some/endpoint" + +sessionManager.request(urlString).validate().responseJSON { response in + debugPrint(response) +} +``` + +Once the `OAuth2Handler` is applied as both the `adapter` and `retrier` for the `SessionManager`, it will handle an invalid access token error by automatically refreshing the access token and retrying all failed requests in the same order they failed. + +> If you needed them to execute in the same order they were created, you could sort them by their task identifiers. + +The example above only checks for a `401` response code which is not nearly robust enough, but does demonstrate how one could check for an invalid access token error. In a production application, one would want to check the `realm` and most likely the `www-authenticate` header response although it depends on the OAuth2 implementation. + +Another important note is that this authentication system could be shared between multiple session managers. For example, you may need to use both a `default` and `ephemeral` session configuration for the same set of web services. The example above allows the same `oauthHandler` instance to be shared across multiple session managers to manage the single refresh flow. + +### Custom Response Serialization + +Alamofire provides built-in response serialization for data, strings, JSON, and property lists: + +```swift +Alamofire.request(...).responseData { (resp: DataResponse) in ... } +Alamofire.request(...).responseString { (resp: DataResponse) in ... } +Alamofire.request(...).responseJSON { (resp: DataResponse) in ... } +Alamofire.request(...).responsePropertyList { resp: DataResponse) in ... } +``` + +Those responses wrap deserialized *values* (Data, String, Any) or *errors* (network, validation errors), as well as *meta-data* (URL request, HTTP headers, status code, [metrics](#statistical-metrics), ...). + +You have several ways to customize all of those response elements: + +- [Response Mapping](#response-mapping) +- [Handling Errors](#handling-errors) +- [Creating a Custom Response Serializer](#creating-a-custom-response-serializer) +- [Generic Response Object Serialization](#generic-response-object-serialization) + +#### Response Mapping + +Response mapping is the simplest way to produce customized responses. It transforms the value of a response, while preserving eventual errors and meta-data. For example, you can turn a json response `DataResponse` into a response that holds an application model, such as `DataResponse`. You perform response mapping with the `DataResponse.map` method: + +```swift +Alamofire.request("https://example.com/users/mattt").responseJSON { (response: DataResponse) in + let userResponse = response.map { json in + // We assume an existing User(json: Any) initializer + return User(json: json) + } + + // Process userResponse, of type DataResponse: + if let user = userResponse.value { + print("User: { username: \(user.username), name: \(user.name) }") + } +} +``` + +When the transformation may throw an error, use `flatMap` instead: + +```swift +Alamofire.request("https://example.com/users/mattt").responseJSON { response in + let userResponse = response.flatMap { json in + try User(json: json) + } +} +``` + +Response mapping is a good fit for your custom completion handlers: + +```swift +@discardableResult +func loadUser(completionHandler: @escaping (DataResponse) -> Void) -> Alamofire.DataRequest { + return Alamofire.request("https://example.com/users/mattt").responseJSON { response in + let userResponse = response.flatMap { json in + try User(json: json) + } + + completionHandler(userResponse) + } +} + +loadUser { response in + if let user = response.value { + print("User: { username: \(user.username), name: \(user.name) }") + } +} +``` + +When the map/flatMap closure may process a big amount of data, make sure you execute it outside of the main thread: + +```swift +@discardableResult +func loadUser(completionHandler: @escaping (DataResponse) -> Void) -> Alamofire.DataRequest { + let utilityQueue = DispatchQueue.global(qos: .utility) + + return Alamofire.request("https://example.com/users/mattt").responseJSON(queue: utilityQueue) { response in + let userResponse = response.flatMap { json in + try User(json: json) + } + + DispatchQueue.main.async { + completionHandler(userResponse) + } + } +} +``` + +`map` and `flatMap` are also available for [download responses](#downloading-data-to-a-file). + +#### Handling Errors + +Before implementing custom response serializers or object serialization methods, it's important to consider how to handle any errors that may occur. There are two basic options: passing existing errors along unmodified, to be dealt with at response time; or, wrapping all errors in an `Error` type specific to your app. + +For example, here's a simple `BackendError` enum which will be used in later examples: + +```swift +enum BackendError: Error { + case network(error: Error) // Capture any underlying Error from the URLSession API + case dataSerialization(error: Error) + case jsonSerialization(error: Error) + case xmlSerialization(error: Error) + case objectSerialization(reason: String) +} +``` + +#### Creating a Custom Response Serializer + +Alamofire provides built-in response serialization for strings, JSON, and property lists, but others can be added in extensions on `Alamofire.DataRequest` and / or `Alamofire.DownloadRequest`. + +For example, here's how a response handler using [Ono](https://github.com/mattt/Ono) might be implemented: + +```swift +extension DataRequest { + static func xmlResponseSerializer() -> DataResponseSerializer { + return DataResponseSerializer { request, response, data, error in + // Pass through any underlying URLSession error to the .network case. + guard error == nil else { return .failure(BackendError.network(error: error!)) } + + // Use Alamofire's existing data serializer to extract the data, passing the error as nil, as it has + // already been handled. + let result = Request.serializeResponseData(response: response, data: data, error: nil) + + guard case let .success(validData) = result else { + return .failure(BackendError.dataSerialization(error: result.error! as! AFError)) + } + + do { + let xml = try ONOXMLDocument(data: validData) + return .success(xml) + } catch { + return .failure(BackendError.xmlSerialization(error: error)) + } + } + } + + @discardableResult + func responseXMLDocument( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.xmlResponseSerializer(), + completionHandler: completionHandler + ) + } +} +``` + +#### Generic Response Object Serialization + +Generics can be used to provide automatic, type-safe response object serialization. + +```swift +protocol ResponseObjectSerializable { + init?(response: HTTPURLResponse, representation: Any) +} + +extension DataRequest { + func responseObject( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + let responseSerializer = DataResponseSerializer { request, response, data, error in + guard error == nil else { return .failure(BackendError.network(error: error!)) } + + let jsonResponseSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments) + let result = jsonResponseSerializer.serializeResponse(request, response, data, nil) + + guard case let .success(jsonObject) = result else { + return .failure(BackendError.jsonSerialization(error: result.error!)) + } + + guard let response = response, let responseObject = T(response: response, representation: jsonObject) else { + return .failure(BackendError.objectSerialization(reason: "JSON could not be serialized: \(jsonObject)")) + } + + return .success(responseObject) + } + + return response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) + } +} +``` + +```swift +struct User: ResponseObjectSerializable, CustomStringConvertible { + let username: String + let name: String + + var description: String { + return "User: { username: \(username), name: \(name) }" + } + + init?(response: HTTPURLResponse, representation: Any) { + guard + let username = response.url?.lastPathComponent, + let representation = representation as? [String: Any], + let name = representation["name"] as? String + else { return nil } + + self.username = username + self.name = name + } +} +``` + +```swift +Alamofire.request("https://example.com/users/mattt").responseObject { (response: DataResponse) in + debugPrint(response) + + if let user = response.result.value { + print("User: { username: \(user.username), name: \(user.name) }") + } +} +``` + +The same approach can also be used to handle endpoints that return a representation of a collection of objects: + +```swift +protocol ResponseCollectionSerializable { + static func collection(from response: HTTPURLResponse, withRepresentation representation: Any) -> [Self] +} + +extension ResponseCollectionSerializable where Self: ResponseObjectSerializable { + static func collection(from response: HTTPURLResponse, withRepresentation representation: Any) -> [Self] { + var collection: [Self] = [] + + if let representation = representation as? [[String: Any]] { + for itemRepresentation in representation { + if let item = Self(response: response, representation: itemRepresentation) { + collection.append(item) + } + } + } + + return collection + } +} +``` + +```swift +extension DataRequest { + @discardableResult + func responseCollection( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DataResponse<[T]>) -> Void) -> Self + { + let responseSerializer = DataResponseSerializer<[T]> { request, response, data, error in + guard error == nil else { return .failure(BackendError.network(error: error!)) } + + let jsonSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments) + let result = jsonSerializer.serializeResponse(request, response, data, nil) + + guard case let .success(jsonObject) = result else { + return .failure(BackendError.jsonSerialization(error: result.error!)) + } + + guard let response = response else { + let reason = "Response collection could not be serialized due to nil response." + return .failure(BackendError.objectSerialization(reason: reason)) + } + + return .success(T.collection(from: response, withRepresentation: jsonObject)) + } + + return response(responseSerializer: responseSerializer, completionHandler: completionHandler) + } +} +``` + +```swift +struct User: ResponseObjectSerializable, ResponseCollectionSerializable, CustomStringConvertible { + let username: String + let name: String + + var description: String { + return "User: { username: \(username), name: \(name) }" + } + + init?(response: HTTPURLResponse, representation: Any) { + guard + let username = response.url?.lastPathComponent, + let representation = representation as? [String: Any], + let name = representation["name"] as? String + else { return nil } + + self.username = username + self.name = name + } +} +``` + +```swift +Alamofire.request("https://example.com/users").responseCollection { (response: DataResponse<[User]>) in + debugPrint(response) + + if let users = response.result.value { + users.forEach { print("- \($0)") } + } +} +``` + +### Security + +Using a secure HTTPS connection when communicating with servers and web services is an important step in securing sensitive data. By default, Alamofire will evaluate the certificate chain provided by the server using Apple's built in validation provided by the Security framework. While this guarantees the certificate chain is valid, it does not prevent man-in-the-middle (MITM) attacks or other potential vulnerabilities. In order to mitigate MITM attacks, applications dealing with sensitive customer data or financial information should use certificate or public key pinning provided by the `ServerTrustPolicy`. + +#### ServerTrustPolicy + +The `ServerTrustPolicy` enumeration evaluates the server trust generally provided by an `URLAuthenticationChallenge` when connecting to a server over a secure HTTPS connection. + +```swift +let serverTrustPolicy = ServerTrustPolicy.pinCertificates( + certificates: ServerTrustPolicy.certificates(), + validateCertificateChain: true, + validateHost: true +) +``` + +There are many different cases of server trust evaluation giving you complete control over the validation process: + +* `performDefaultEvaluation`: Uses the default server trust evaluation while allowing you to control whether to validate the host provided by the challenge. +* `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. +* `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. +* `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 thus giving you complete control over the validation process. Use with caution. + +#### Server Trust Policy Manager + +The `ServerTrustPolicyManager` is responsible for storing an internal mapping of server trust policies to a particular host. This allows Alamofire to evaluate each host against a different server trust policy. + +```swift +let serverTrustPolicies: [String: ServerTrustPolicy] = [ + "test.example.com": .pinCertificates( + certificates: ServerTrustPolicy.certificates(), + validateCertificateChain: true, + validateHost: true + ), + "insecure.expired-apis.com": .disableEvaluation +] + +let sessionManager = SessionManager( + serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies) +) +``` + +> Make sure to keep a reference to the new `SessionManager` instance, otherwise your requests will all get cancelled when your `sessionManager` is deallocated. + +These server trust policies will result in the following behavior: + +- `test.example.com` will always use certificate pinning with certificate chain and host validation enabled thus requiring the following criteria to be met to allow the TLS handshake to succeed: + - Certificate chain MUST be valid. + - Certificate chain MUST include one of the pinned certificates. + - Challenge host MUST match the host in the certificate chain's leaf certificate. +- `insecure.expired-apis.com` will never evaluate the certificate chain and will always allow the TLS handshake to succeed. +- All other hosts will use the default evaluation provided by Apple. + +##### Subclassing Server Trust Policy Manager + +If you find yourself needing more flexible server trust policy matching behavior (i.e. wildcarded domains), then subclass the `ServerTrustPolicyManager` and override the `serverTrustPolicyForHost` method with your own custom implementation. + +```swift +class CustomServerTrustPolicyManager: ServerTrustPolicyManager { + override func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? { + var policy: ServerTrustPolicy? + + // Implement your custom domain matching behavior... + + return policy + } +} +``` + +#### Validating the Host + +The `.performDefaultEvaluation`, `.pinCertificates` and `.pinPublicKeys` server trust policies all take a `validateHost` parameter. Setting the value to `true` will cause the server trust evaluation to verify that hostname in the certificate matches the hostname of the challenge. If they do not match, evaluation will fail. A `validateHost` value of `false` will still evaluate the full certificate chain, but will not validate the hostname of the leaf certificate. + +> It is recommended that `validateHost` always be set to `true` in production environments. + +#### Validating the Certificate Chain + +Pinning certificates and public keys both have the option of validating the certificate chain using the `validateCertificateChain` parameter. By setting this value to `true`, the full certificate chain will be evaluated in addition to performing a byte equality check against the pinned certificates or public keys. A value of `false` will skip the certificate chain validation, but will still perform the byte equality check. + +There are several cases where it may make sense to disable certificate chain validation. The most common use cases for disabling validation are self-signed and expired certificates. The evaluation would always fail in both of these cases, but the byte equality check will still ensure you are receiving the certificate you expect from the server. + +> It is recommended that `validateCertificateChain` always be set to `true` in production environments. + +#### App Transport Security + +With the addition of App Transport Security (ATS) in iOS 9, it is possible that using a custom `ServerTrustPolicyManager` with several `ServerTrustPolicy` objects will have no effect. If you continuously see `CFNetwork SSLHandshake failed (-9806)` errors, you have probably run into this problem. Apple's ATS system overrides the entire challenge system unless you configure the ATS settings in your app's plist to disable enough of it to allow your app to evaluate the server trust. + +If you run into this problem (high probability with self-signed certificates), you can work around this issue by adding the following to your `Info.plist`. + +```xml + + NSAppTransportSecurity + + NSExceptionDomains + + example.com + + NSExceptionAllowsInsecureHTTPLoads + + NSExceptionRequiresForwardSecrecy + + NSIncludesSubdomains + + + NSTemporaryExceptionMinimumTLSVersion + TLSv1.2 + + + + +``` + +Whether you need to set the `NSExceptionRequiresForwardSecrecy` to `NO` depends on whether your TLS connection is using an allowed cipher suite. In certain cases, it will need to be set to `NO`. The `NSExceptionAllowsInsecureHTTPLoads` MUST be set to `YES` in order to allow the `SessionDelegate` to receive challenge callbacks. Once the challenge callbacks are being called, the `ServerTrustPolicyManager` will take over the server trust evaluation. You may also need to specify the `NSTemporaryExceptionMinimumTLSVersion` if you're trying to connect to a host that only supports TLS versions less than `1.2`. + +> It is recommended to always use valid certificates in production environments. + +### Network Reachability + +The `NetworkReachabilityManager` listens for reachability changes of hosts and addresses for both WWAN and WiFi network interfaces. + +```swift +let manager = NetworkReachabilityManager(host: "www.apple.com") + +manager?.listener = { status in + print("Network Status Changed: \(status)") +} + +manager?.startListening() +``` + +> Make sure to remember to retain the `manager` in the above example, or no status changes will be reported. +> Also, do not include the scheme in the `host` string or reachability won't function correctly. + +There are some important things to remember when using network reachability to determine what to do next. + +- **Do NOT** use Reachability to determine if a network request should be sent. + - You should **ALWAYS** send it. +- When Reachability is restored, use the event to retry failed network requests. + - Even though the network requests may still fail, this is a good moment to retry them. +- The network reachability status can be useful for determining why a network request may have failed. + - If a network request fails, it is more useful to tell the user that the network request failed due to being offline rather than a more technical error, such as "request timed out." + +> It is recommended to check out [WWDC 2012 Session 706, "Networking Best Practices"](https://developer.apple.com/videos/play/wwdc2012-706/) for more info. + +--- + +## Open Radars + +The following radars have some effect on the current implementation of Alamofire. + +- [`rdar://21349340`](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case +- [`rdar://26761490`](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage +- `rdar://26870455` - Background URL Session Configurations do not work in the simulator +- `rdar://26849668` - Some URLProtocol APIs do not properly handle `URLRequest` + +## FAQ + +### What's the origin of the name Alamofire? + +Alamofire is named after the [Alamo Fire flower](https://aggie-horticulture.tamu.edu/wildseed/alamofire.html), a hybrid variant of the Bluebonnet, the official state flower of Texas. + +### What logic belongs in a Router vs. a Request Adapter? + +Simple, static data such as paths, parameters and common headers belong in the `Router`. Dynamic data such as an `Authorization` header whose value can changed based on an authentication system belongs in a `RequestAdapter`. + +The reason the dynamic data MUST be placed into the `RequestAdapter` is to support retry operations. When a `Request` is retried, the original request is not rebuilt meaning the `Router` will not be called again. The `RequestAdapter` is called again allowing the dynamic data to be updated on the original request before retrying the `Request`. + +--- + +## Credits + +Alamofire is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). You can follow them on Twitter at [@AlamofireSF](https://twitter.com/AlamofireSF) for project updates and releases. + +### Security Disclosure + +If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. + +## Donations + +The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise money to officially register as a federal non-profit organization. Registering will allow us members to gain some legal protections and also allow us to put donations to use, tax free. Donating to the ASF will enable us to: + +- Pay our legal fees to register as a federal non-profit organization +- Pay our yearly legal fees to keep the non-profit in good status +- Pay for our mail servers to help us stay on top of all questions and security issues +- Potentially fund test servers to make it easier for us to test the edge cases +- Potentially fund developers to work on one of our projects full-time + +The community adoption of the ASF libraries has been amazing. We are greatly humbled by your enthusiasm around the projects, and want to continue to do everything we can to move the needle forward. With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. If you use any of our libraries for work, see if your employers would be interested in donating. Our initial goal is to raise $1000 to get all our legal ducks in a row and kickstart this campaign. Any amount you can donate today to help us reach our goal would be greatly appreciated. + +Click here to lend your support to: Alamofire Software Foundation and make a donation at pledgie.com ! + +## License + +Alamofire is released under the MIT license. [See LICENSE](https://github.com/Alamofire/Alamofire/blob/master/LICENSE) for details. diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/AFError.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/AFError.swift new file mode 100644 index 0000000000..f047695b6d --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/AFError.swift @@ -0,0 +1,460 @@ +// +// AFError.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 + +/// `AFError` is the error type returned by Alamofire. It encompasses a few different types of errors, each with +/// their own associated reasons. +/// +/// - invalidURL: Returned when a `URLConvertible` type fails to create a valid `URL`. +/// - parameterEncodingFailed: Returned when a parameter encoding object throws an error during the encoding process. +/// - multipartEncodingFailed: Returned when some step in the multipart encoding process fails. +/// - responseValidationFailed: Returned when a `validate()` call fails. +/// - responseSerializationFailed: Returned when a response serializer encounters an error in the serialization process. +public enum AFError: Error { + /// The underlying reason the parameter encoding error occurred. + /// + /// - missingURL: The URL request did not have a URL to encode. + /// - jsonEncodingFailed: JSON serialization failed with an underlying system error during the + /// encoding process. + /// - propertyListEncodingFailed: Property list serialization failed with an underlying system error during + /// encoding process. + public enum ParameterEncodingFailureReason { + case missingURL + case jsonEncodingFailed(error: Error) + case propertyListEncodingFailed(error: Error) + } + + /// The underlying reason the multipart encoding error occurred. + /// + /// - bodyPartURLInvalid: The `fileURL` provided for reading an encodable body part isn't a + /// file URL. + /// - bodyPartFilenameInvalid: The filename of the `fileURL` provided has either an empty + /// `lastPathComponent` or `pathExtension. + /// - bodyPartFileNotReachable: The file at the `fileURL` provided was not reachable. + /// - bodyPartFileNotReachableWithError: Attempting to check the reachability of the `fileURL` provided threw + /// an error. + /// - bodyPartFileIsDirectory: The file at the `fileURL` provided is actually a directory. + /// - bodyPartFileSizeNotAvailable: The size of the file at the `fileURL` provided was not returned by + /// the system. + /// - bodyPartFileSizeQueryFailedWithError: The attempt to find the size of the file at the `fileURL` provided + /// threw an error. + /// - bodyPartInputStreamCreationFailed: An `InputStream` could not be created for the provided `fileURL`. + /// - outputStreamCreationFailed: An `OutputStream` could not be created when attempting to write the + /// encoded data to disk. + /// - outputStreamFileAlreadyExists: The encoded body data could not be writtent disk because a file + /// already exists at the provided `fileURL`. + /// - outputStreamURLInvalid: The `fileURL` provided for writing the encoded body data to disk is + /// not a file URL. + /// - outputStreamWriteFailed: The attempt to write the encoded body data to disk failed with an + /// underlying error. + /// - inputStreamReadFailed: The attempt to read an encoded body part `InputStream` failed with + /// underlying system error. + public enum MultipartEncodingFailureReason { + case bodyPartURLInvalid(url: URL) + case bodyPartFilenameInvalid(in: URL) + case bodyPartFileNotReachable(at: URL) + case bodyPartFileNotReachableWithError(atURL: URL, error: Error) + case bodyPartFileIsDirectory(at: URL) + case bodyPartFileSizeNotAvailable(at: URL) + case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error) + case bodyPartInputStreamCreationFailed(for: URL) + + case outputStreamCreationFailed(for: URL) + case outputStreamFileAlreadyExists(at: URL) + case outputStreamURLInvalid(url: URL) + case outputStreamWriteFailed(error: Error) + + case inputStreamReadFailed(error: Error) + } + + /// The underlying reason the response validation error occurred. + /// + /// - dataFileNil: The data file containing the server response did not exist. + /// - dataFileReadFailed: The data file containing the server response could not be read. + /// - missingContentType: The response did not contain a `Content-Type` and the `acceptableContentTypes` + /// provided did not contain wildcard type. + /// - unacceptableContentType: The response `Content-Type` did not match any type in the provided + /// `acceptableContentTypes`. + /// - unacceptableStatusCode: The response status code was not acceptable. + public enum ResponseValidationFailureReason { + case dataFileNil + case dataFileReadFailed(at: URL) + case missingContentType(acceptableContentTypes: [String]) + case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String) + case unacceptableStatusCode(code: Int) + } + + /// The underlying reason the response serialization error occurred. + /// + /// - inputDataNil: The server response contained no data. + /// - inputDataNilOrZeroLength: The server response contained no data or the data was zero length. + /// - inputFileNil: The file containing the server response did not exist. + /// - inputFileReadFailed: The file containing the server response could not be read. + /// - stringSerializationFailed: String serialization failed using the provided `String.Encoding`. + /// - jsonSerializationFailed: JSON serialization failed with an underlying system error. + /// - propertyListSerializationFailed: Property list serialization failed with an underlying system error. + public enum ResponseSerializationFailureReason { + case inputDataNil + case inputDataNilOrZeroLength + case inputFileNil + case inputFileReadFailed(at: URL) + case stringSerializationFailed(encoding: String.Encoding) + case jsonSerializationFailed(error: Error) + case propertyListSerializationFailed(error: Error) + } + + case invalidURL(url: URLConvertible) + case parameterEncodingFailed(reason: ParameterEncodingFailureReason) + case multipartEncodingFailed(reason: MultipartEncodingFailureReason) + case responseValidationFailed(reason: ResponseValidationFailureReason) + case responseSerializationFailed(reason: ResponseSerializationFailureReason) +} + +// MARK: - Adapt Error + +struct AdaptError: Error { + let error: Error +} + +extension Error { + var underlyingAdaptError: Error? { return (self as? AdaptError)?.error } +} + +// MARK: - Error Booleans + +extension AFError { + /// Returns whether the AFError is an invalid URL error. + public var isInvalidURLError: Bool { + if case .invalidURL = self { return true } + return false + } + + /// Returns whether the AFError is a parameter encoding error. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isParameterEncodingError: Bool { + if case .parameterEncodingFailed = self { return true } + return false + } + + /// Returns whether the AFError is a multipart encoding error. When `true`, the `url` and `underlyingError` properties + /// will contain the associated values. + public var isMultipartEncodingError: Bool { + if case .multipartEncodingFailed = self { return true } + return false + } + + /// Returns whether the `AFError` is a response validation error. When `true`, the `acceptableContentTypes`, + /// `responseContentType`, and `responseCode` properties will contain the associated values. + public var isResponseValidationError: Bool { + if case .responseValidationFailed = self { return true } + return false + } + + /// Returns whether the `AFError` is a response serialization error. When `true`, the `failedStringEncoding` and + /// `underlyingError` properties will contain the associated values. + public var isResponseSerializationError: Bool { + if case .responseSerializationFailed = self { return true } + return false + } +} + +// MARK: - Convenience Properties + +extension AFError { + /// The `URLConvertible` associated with the error. + public var urlConvertible: URLConvertible? { + switch self { + case .invalidURL(let url): + return url + default: + return nil + } + } + + /// The `URL` associated with the error. + public var url: URL? { + switch self { + case .multipartEncodingFailed(let reason): + return reason.url + default: + return nil + } + } + + /// The `Error` returned by a system framework associated with a `.parameterEncodingFailed`, + /// `.multipartEncodingFailed` or `.responseSerializationFailed` error. + public var underlyingError: Error? { + switch self { + case .parameterEncodingFailed(let reason): + return reason.underlyingError + case .multipartEncodingFailed(let reason): + return reason.underlyingError + case .responseSerializationFailed(let reason): + return reason.underlyingError + default: + return nil + } + } + + /// The acceptable `Content-Type`s of a `.responseValidationFailed` error. + public var acceptableContentTypes: [String]? { + switch self { + case .responseValidationFailed(let reason): + return reason.acceptableContentTypes + default: + return nil + } + } + + /// The response `Content-Type` of a `.responseValidationFailed` error. + public var responseContentType: String? { + switch self { + case .responseValidationFailed(let reason): + return reason.responseContentType + default: + return nil + } + } + + /// The response code of a `.responseValidationFailed` error. + public var responseCode: Int? { + switch self { + case .responseValidationFailed(let reason): + return reason.responseCode + default: + return nil + } + } + + /// The `String.Encoding` associated with a failed `.stringResponse()` call. + public var failedStringEncoding: String.Encoding? { + switch self { + case .responseSerializationFailed(let reason): + return reason.failedStringEncoding + default: + return nil + } + } +} + +extension AFError.ParameterEncodingFailureReason { + var underlyingError: Error? { + switch self { + case .jsonEncodingFailed(let error), .propertyListEncodingFailed(let error): + return error + default: + return nil + } + } +} + +extension AFError.MultipartEncodingFailureReason { + var url: URL? { + switch self { + case .bodyPartURLInvalid(let url), .bodyPartFilenameInvalid(let url), .bodyPartFileNotReachable(let url), + .bodyPartFileIsDirectory(let url), .bodyPartFileSizeNotAvailable(let url), + .bodyPartInputStreamCreationFailed(let url), .outputStreamCreationFailed(let url), + .outputStreamFileAlreadyExists(let url), .outputStreamURLInvalid(let url), + .bodyPartFileNotReachableWithError(let url, _), .bodyPartFileSizeQueryFailedWithError(let url, _): + return url + default: + return nil + } + } + + var underlyingError: Error? { + switch self { + case .bodyPartFileNotReachableWithError(_, let error), .bodyPartFileSizeQueryFailedWithError(_, let error), + .outputStreamWriteFailed(let error), .inputStreamReadFailed(let error): + return error + default: + return nil + } + } +} + +extension AFError.ResponseValidationFailureReason { + var acceptableContentTypes: [String]? { + switch self { + case .missingContentType(let types), .unacceptableContentType(let types, _): + return types + default: + return nil + } + } + + var responseContentType: String? { + switch self { + case .unacceptableContentType(_, let responseType): + return responseType + default: + return nil + } + } + + var responseCode: Int? { + switch self { + case .unacceptableStatusCode(let code): + return code + default: + return nil + } + } +} + +extension AFError.ResponseSerializationFailureReason { + var failedStringEncoding: String.Encoding? { + switch self { + case .stringSerializationFailed(let encoding): + return encoding + default: + return nil + } + } + + var underlyingError: Error? { + switch self { + case .jsonSerializationFailed(let error), .propertyListSerializationFailed(let error): + return error + default: + return nil + } + } +} + +// MARK: - Error Descriptions + +extension AFError: LocalizedError { + public var errorDescription: String? { + switch self { + case .invalidURL(let url): + return "URL is not valid: \(url)" + case .parameterEncodingFailed(let reason): + return reason.localizedDescription + case .multipartEncodingFailed(let reason): + return reason.localizedDescription + case .responseValidationFailed(let reason): + return reason.localizedDescription + case .responseSerializationFailed(let reason): + return reason.localizedDescription + } + } +} + +extension AFError.ParameterEncodingFailureReason { + var localizedDescription: String { + switch self { + case .missingURL: + return "URL request to encode was missing a URL" + case .jsonEncodingFailed(let error): + return "JSON could not be encoded because of error:\n\(error.localizedDescription)" + case .propertyListEncodingFailed(let error): + return "PropertyList could not be encoded because of error:\n\(error.localizedDescription)" + } + } +} + +extension AFError.MultipartEncodingFailureReason { + var localizedDescription: String { + switch self { + case .bodyPartURLInvalid(let url): + return "The URL provided is not a file URL: \(url)" + case .bodyPartFilenameInvalid(let url): + return "The URL provided does not have a valid filename: \(url)" + case .bodyPartFileNotReachable(let url): + return "The URL provided is not reachable: \(url)" + case .bodyPartFileNotReachableWithError(let url, let error): + return ( + "The system returned an error while checking the provided URL for " + + "reachability.\nURL: \(url)\nError: \(error)" + ) + case .bodyPartFileIsDirectory(let url): + return "The URL provided is a directory: \(url)" + case .bodyPartFileSizeNotAvailable(let url): + return "Could not fetch the file size from the provided URL: \(url)" + case .bodyPartFileSizeQueryFailedWithError(let url, let error): + return ( + "The system returned an error while attempting to fetch the file size from the " + + "provided URL.\nURL: \(url)\nError: \(error)" + ) + case .bodyPartInputStreamCreationFailed(let url): + return "Failed to create an InputStream for the provided URL: \(url)" + case .outputStreamCreationFailed(let url): + return "Failed to create an OutputStream for URL: \(url)" + case .outputStreamFileAlreadyExists(let url): + return "A file already exists at the provided URL: \(url)" + case .outputStreamURLInvalid(let url): + return "The provided OutputStream URL is invalid: \(url)" + case .outputStreamWriteFailed(let error): + return "OutputStream write failed with error: \(error)" + case .inputStreamReadFailed(let error): + return "InputStream read failed with error: \(error)" + } + } +} + +extension AFError.ResponseSerializationFailureReason { + var localizedDescription: String { + switch self { + case .inputDataNil: + return "Response could not be serialized, input data was nil." + case .inputDataNilOrZeroLength: + return "Response could not be serialized, input data was nil or zero length." + case .inputFileNil: + return "Response could not be serialized, input file was nil." + case .inputFileReadFailed(let url): + return "Response could not be serialized, input file could not be read: \(url)." + case .stringSerializationFailed(let encoding): + return "String could not be serialized with encoding: \(encoding)." + case .jsonSerializationFailed(let error): + return "JSON could not be serialized because of error:\n\(error.localizedDescription)" + case .propertyListSerializationFailed(let error): + return "PropertyList could not be serialized because of error:\n\(error.localizedDescription)" + } + } +} + +extension AFError.ResponseValidationFailureReason { + var localizedDescription: String { + switch self { + case .dataFileNil: + return "Response could not be validated, data file was nil." + case .dataFileReadFailed(let url): + return "Response could not be validated, data file could not be read: \(url)." + case .missingContentType(let types): + return ( + "Response Content-Type was missing and acceptable content types " + + "(\(types.joined(separator: ","))) do not match \"*/*\"." + ) + case .unacceptableContentType(let acceptableTypes, let responseType): + return ( + "Response Content-Type \"\(responseType)\" does not match any acceptable types: " + + "\(acceptableTypes.joined(separator: ","))." + ) + case .unacceptableStatusCode(let code): + return "Response status code was unacceptable: \(code)." + } + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift new file mode 100644 index 0000000000..edcf717ca9 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift @@ -0,0 +1,465 @@ +// +// 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 + +/// Types adopting the `URLConvertible` protocol can be used to construct URLs, which are then used to construct +/// URL requests. +public protocol URLConvertible { + /// Returns a URL that conforms to RFC 2396 or throws an `Error`. + /// + /// - throws: An `Error` if the type cannot be converted to a `URL`. + /// + /// - returns: A URL or throws an `Error`. + func asURL() throws -> URL +} + +extension String: URLConvertible { + /// Returns a URL if `self` represents a valid URL string that conforms to RFC 2396 or throws an `AFError`. + /// + /// - throws: An `AFError.invalidURL` if `self` is not a valid URL string. + /// + /// - returns: A URL or throws an `AFError`. + public func asURL() throws -> URL { + guard let url = URL(string: self) else { throw AFError.invalidURL(url: self) } + return url + } +} + +extension URL: URLConvertible { + /// Returns self. + public func asURL() throws -> URL { return self } +} + +extension URLComponents: URLConvertible { + /// Returns a URL if `url` is not nil, otherwise throws an `Error`. + /// + /// - throws: An `AFError.invalidURL` if `url` is `nil`. + /// + /// - returns: A URL or throws an `AFError`. + public func asURL() throws -> URL { + guard let url = url else { throw AFError.invalidURL(url: self) } + return url + } +} + +// MARK: - + +/// Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. +public protocol URLRequestConvertible { + /// Returns a URL request or throws if an `Error` was encountered. + /// + /// - throws: An `Error` if the underlying `URLRequest` is `nil`. + /// + /// - returns: A URL request. + func asURLRequest() throws -> URLRequest +} + +extension URLRequestConvertible { + /// The URL request. + public var urlRequest: URLRequest? { return try? asURLRequest() } +} + +extension URLRequest: URLRequestConvertible { + /// Returns a URL request or throws if an `Error` was encountered. + public func asURLRequest() throws -> URLRequest { return self } +} + +// MARK: - + +extension URLRequest { + /// Creates an instance with the specified `method`, `urlString` and `headers`. + /// + /// - parameter url: The URL. + /// - parameter method: The HTTP method. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The new `URLRequest` instance. + public init(url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws { + let url = try url.asURL() + + self.init(url: url) + + httpMethod = method.rawValue + + if let headers = headers { + for (headerField, headerValue) in headers { + setValue(headerValue, forHTTPHeaderField: headerField) + } + } + } + + func adapt(using adapter: RequestAdapter?) throws -> URLRequest { + guard let adapter = adapter else { return self } + return try adapter.adapt(self) + } +} + +// MARK: - Data Request + +/// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, +/// `method`, `parameters`, `encoding` and `headers`. +/// +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.get` by default. +/// - parameter parameters: The parameters. `nil` by default. +/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `DataRequest`. +@discardableResult +public func request( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil) + -> DataRequest +{ + return SessionManager.default.request( + url, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers + ) +} + +/// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of a URL based on the +/// specified `urlRequest`. +/// +/// - parameter urlRequest: The URL request +/// +/// - returns: The created `DataRequest`. +@discardableResult +public func request(_ urlRequest: URLRequestConvertible) -> DataRequest { + return SessionManager.default.request(urlRequest) +} + +// MARK: - Download Request + +// MARK: URL Request + +/// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, +/// `method`, `parameters`, `encoding`, `headers` and save them to the `destination`. +/// +/// If `destination` is not specified, the contents will remain in the temporary location determined by the +/// underlying URL session. +/// +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.get` by default. +/// - parameter parameters: The parameters. `nil` by default. +/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. +/// +/// - returns: The created `DownloadRequest`. +@discardableResult +public func download( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest +{ + return SessionManager.default.download( + url, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers, + to: destination + ) +} + +/// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of a URL based on the +/// specified `urlRequest` and save them to the `destination`. +/// +/// If `destination` is not specified, the contents will remain in the temporary location determined by the +/// underlying URL session. +/// +/// - parameter urlRequest: The URL request. +/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. +/// +/// - returns: The created `DownloadRequest`. +@discardableResult +public func download( + _ urlRequest: URLRequestConvertible, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest +{ + return SessionManager.default.download(urlRequest, to: destination) +} + +// MARK: Resume Data + +/// Creates a `DownloadRequest` using the default `SessionManager` from the `resumeData` produced from a +/// previous request cancellation to retrieve the contents of the original request and save them to the `destination`. +/// +/// If `destination` is not specified, the contents will remain in the temporary location determined by the +/// underlying URL session. +/// +/// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken +/// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the +/// data is written incorrectly and will always fail to resume the download. For more information about the bug and +/// possible workarounds, please refer to the following Stack Overflow post: +/// +/// - http://stackoverflow.com/a/39347461/1342462 +/// +/// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` +/// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for additional +/// information. +/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. +/// +/// - returns: The created `DownloadRequest`. +@discardableResult +public func download( + resumingWith resumeData: Data, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest +{ + return SessionManager.default.download(resumingWith: resumeData, to: destination) +} + +// MARK: - Upload Request + +// MARK: File + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` +/// for uploading the `file`. +/// +/// - parameter file: The file to upload. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload( + _ fileURL: URL, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest +{ + return SessionManager.default.upload(fileURL, to: url, method: method, headers: headers) +} + +/// Creates a `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for +/// uploading the `file`. +/// +/// - parameter file: The file to upload. +/// - parameter urlRequest: The URL request. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { + return SessionManager.default.upload(fileURL, with: urlRequest) +} + +// MARK: Data + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` +/// for uploading the `data`. +/// +/// - parameter data: The data to upload. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload( + _ data: Data, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest +{ + return SessionManager.default.upload(data, to: url, method: method, headers: headers) +} + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for +/// uploading the `data`. +/// +/// - parameter data: The data to upload. +/// - parameter urlRequest: The URL request. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { + return SessionManager.default.upload(data, with: urlRequest) +} + +// MARK: InputStream + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` +/// for uploading the `stream`. +/// +/// - parameter stream: The stream to upload. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload( + _ stream: InputStream, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest +{ + return SessionManager.default.upload(stream, to: url, method: method, headers: headers) +} + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for +/// uploading the `stream`. +/// +/// - parameter urlRequest: The URL request. +/// - parameter stream: The stream to upload. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { + return SessionManager.default.upload(stream, with: urlRequest) +} + +// MARK: MultipartFormData + +/// Encodes `multipartFormData` using `encodingMemoryThreshold` with the default `SessionManager` and calls +/// `encodingCompletion` with new `UploadRequest` using the `url`, `method` and `headers`. +/// +/// 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. +/// +/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. +/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. +/// `multipartFormDataEncodingMemoryThreshold` by default. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. +public func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) +{ + return SessionManager.default.upload( + multipartFormData: multipartFormData, + usingThreshold: encodingMemoryThreshold, + to: url, + method: method, + headers: headers, + encodingCompletion: encodingCompletion + ) +} + +/// Encodes `multipartFormData` using `encodingMemoryThreshold` and the default `SessionManager` and +/// calls `encodingCompletion` with new `UploadRequest` using the `urlRequest`. +/// +/// 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. +/// +/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. +/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. +/// `multipartFormDataEncodingMemoryThreshold` by default. +/// - parameter urlRequest: The URL request. +/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. +public func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + with urlRequest: URLRequestConvertible, + encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) +{ + return SessionManager.default.upload( + multipartFormData: multipartFormData, + usingThreshold: encodingMemoryThreshold, + with: urlRequest, + encodingCompletion: encodingCompletion + ) +} + +#if !os(watchOS) + +// MARK: - Stream Request + +// MARK: Hostname and Port + +/// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `hostname` +/// and `port`. +/// +/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. +/// +/// - parameter hostName: The hostname of the server to connect to. +/// - parameter port: The port of the server to connect to. +/// +/// - returns: The created `StreamRequest`. +@discardableResult +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +public func stream(withHostName hostName: String, port: Int) -> StreamRequest { + return SessionManager.default.stream(withHostName: hostName, port: port) +} + +// MARK: NetService + +/// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `netService`. +/// +/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. +/// +/// - parameter netService: The net service used to identify the endpoint. +/// +/// - returns: The created `StreamRequest`. +@discardableResult +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +public func stream(with netService: NetService) -> StreamRequest { + return SessionManager.default.stream(with: netService) +} + +#endif diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift new file mode 100644 index 0000000000..78e214ea17 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift @@ -0,0 +1,37 @@ +// +// DispatchQueue+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 Dispatch +import Foundation + +extension DispatchQueue { + static var userInteractive: DispatchQueue { return DispatchQueue.global(qos: .userInteractive) } + static var userInitiated: DispatchQueue { return DispatchQueue.global(qos: .userInitiated) } + static var utility: DispatchQueue { return DispatchQueue.global(qos: .utility) } + static var background: DispatchQueue { return DispatchQueue.global(qos: .background) } + + func after(_ delay: TimeInterval, execute closure: @escaping () -> Void) { + asyncAfter(deadline: .now() + delay, execute: closure) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift new file mode 100644 index 0000000000..c5093f9f85 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift @@ -0,0 +1,580 @@ +// +// 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(macOS) +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 +open 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(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data { + 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.data(using: String.Encoding.utf8, allowLossyConversion: false)! + } + } + + class BodyPart { + let headers: HTTPHeaders + let bodyStream: InputStream + let bodyContentLength: UInt64 + var hasInitialBoundary = false + var hasFinalBoundary = false + + init(headers: HTTPHeaders, bodyStream: InputStream, 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`. + open lazy var contentType: String = "multipart/form-data; boundary=\(self.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: AFError? + 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 append(_ data: Data, withName name: String) { + let headers = contentHeaders(withName: name) + let stream = InputStream(data: data) + let length = UInt64(data.count) + + append(stream, withLength: 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 append(_ data: Data, withName name: String, mimeType: String) { + let headers = contentHeaders(withName: name, mimeType: mimeType) + let stream = InputStream(data: data) + let length = UInt64(data.count) + + append(stream, withLength: 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 append(_ data: Data, withName name: String, fileName: String, mimeType: String) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + let stream = InputStream(data: data) + let length = UInt64(data.count) + + append(stream, withLength: 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 append(_ fileURL: URL, withName name: String) { + let fileName = fileURL.lastPathComponent + let pathExtension = fileURL.pathExtension + + if !fileName.isEmpty && !pathExtension.isEmpty { + let mime = mimeType(forPathExtension: pathExtension) + append(fileURL, withName: name, fileName: fileName, mimeType: mime) + } else { + setBodyPartError(withReason: .bodyPartFilenameInvalid(in: fileURL)) + } + } + + /// 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 append(_ fileURL: URL, withName name: String, fileName: String, mimeType: String) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + + //============================================================ + // Check 1 - is file URL? + //============================================================ + + guard fileURL.isFileURL else { + setBodyPartError(withReason: .bodyPartURLInvalid(url: fileURL)) + return + } + + //============================================================ + // Check 2 - is file URL reachable? + //============================================================ + + do { + let isReachable = try fileURL.checkPromisedItemIsReachable() + guard isReachable else { + setBodyPartError(withReason: .bodyPartFileNotReachable(at: fileURL)) + return + } + } catch { + setBodyPartError(withReason: .bodyPartFileNotReachableWithError(atURL: fileURL, error: error)) + return + } + + //============================================================ + // Check 3 - is file URL a directory? + //============================================================ + + var isDirectory: ObjCBool = false + let path = fileURL.path + + guard FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) && !isDirectory.boolValue else { + setBodyPartError(withReason: .bodyPartFileIsDirectory(at: fileURL)) + return + } + + //============================================================ + // Check 4 - can the file size be extracted? + //============================================================ + + let bodyContentLength: UInt64 + + do { + guard let fileSize = try FileManager.default.attributesOfItem(atPath: path)[.size] as? NSNumber else { + setBodyPartError(withReason: .bodyPartFileSizeNotAvailable(at: fileURL)) + return + } + + bodyContentLength = fileSize.uint64Value + } + catch { + setBodyPartError(withReason: .bodyPartFileSizeQueryFailedWithError(forURL: fileURL, error: error)) + return + } + + //============================================================ + // Check 5 - can a stream be created from file URL? + //============================================================ + + guard let stream = InputStream(url: fileURL) else { + setBodyPartError(withReason: .bodyPartInputStreamCreationFailed(for: fileURL)) + return + } + + append(stream, withLength: bodyContentLength, 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 append( + _ stream: InputStream, + withLength length: UInt64, + name: String, + fileName: String, + mimeType: String) + { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + append(stream, withLength: 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 append(_ stream: InputStream, withLength length: UInt64, headers: HTTPHeaders) { + let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length) + bodyParts.append(bodyPart) + } + + // MARK: - Data Encoding + + /// Encodes all the appended body parts into a single `Data` value. + /// + /// 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 `AFError` if encoding encounters an error. + /// + /// - returns: The encoded `Data` if encoding is successful. + public func encode() throws -> Data { + if let bodyPartError = bodyPartError { + throw bodyPartError + } + + var encoded = Data() + + bodyParts.first?.hasInitialBoundary = true + bodyParts.last?.hasFinalBoundary = true + + for bodyPart in bodyParts { + let encodedData = try encode(bodyPart) + encoded.append(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 `AFError` if encoding encounters an error. + public func writeEncodedData(to fileURL: URL) throws { + if let bodyPartError = bodyPartError { + throw bodyPartError + } + + if FileManager.default.fileExists(atPath: fileURL.path) { + throw AFError.multipartEncodingFailed(reason: .outputStreamFileAlreadyExists(at: fileURL)) + } else if !fileURL.isFileURL { + throw AFError.multipartEncodingFailed(reason: .outputStreamURLInvalid(url: fileURL)) + } + + guard let outputStream = OutputStream(url: fileURL, append: false) else { + throw AFError.multipartEncodingFailed(reason: .outputStreamCreationFailed(for: fileURL)) + } + + outputStream.open() + defer { outputStream.close() } + + self.bodyParts.first?.hasInitialBoundary = true + self.bodyParts.last?.hasFinalBoundary = true + + for bodyPart in self.bodyParts { + try write(bodyPart, to: outputStream) + } + } + + // MARK: - Private - Body Part Encoding + + private func encode(_ bodyPart: BodyPart) throws -> Data { + var encoded = Data() + + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + encoded.append(initialData) + + let headerData = encodeHeaders(for: bodyPart) + encoded.append(headerData) + + let bodyStreamData = try encodeBodyStream(for: bodyPart) + encoded.append(bodyStreamData) + + if bodyPart.hasFinalBoundary { + encoded.append(finalBoundaryData()) + } + + return encoded + } + + private func encodeHeaders(for bodyPart: BodyPart) -> Data { + var headerText = "" + + for (key, value) in bodyPart.headers { + headerText += "\(key): \(value)\(EncodingCharacters.crlf)" + } + headerText += EncodingCharacters.crlf + + return headerText.data(using: String.Encoding.utf8, allowLossyConversion: false)! + } + + private func encodeBodyStream(for bodyPart: BodyPart) throws -> Data { + let inputStream = bodyPart.bodyStream + inputStream.open() + defer { inputStream.close() } + + var encoded = Data() + + while inputStream.hasBytesAvailable { + var buffer = [UInt8](repeating: 0, count: streamBufferSize) + let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) + + if let error = inputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error)) + } + + if bytesRead > 0 { + encoded.append(buffer, count: bytesRead) + } else { + break + } + } + + return encoded + } + + // MARK: - Private - Writing Body Part to Output Stream + + private func write(_ bodyPart: BodyPart, to outputStream: OutputStream) throws { + try writeInitialBoundaryData(for: bodyPart, to: outputStream) + try writeHeaderData(for: bodyPart, to: outputStream) + try writeBodyStream(for: bodyPart, to: outputStream) + try writeFinalBoundaryData(for: bodyPart, to: outputStream) + } + + private func writeInitialBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + return try write(initialData, to: outputStream) + } + + private func writeHeaderData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let headerData = encodeHeaders(for: bodyPart) + return try write(headerData, to: outputStream) + } + + private func writeBodyStream(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let inputStream = bodyPart.bodyStream + + inputStream.open() + defer { inputStream.close() } + + while inputStream.hasBytesAvailable { + var buffer = [UInt8](repeating: 0, count: streamBufferSize) + let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) + + if let streamError = inputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: streamError)) + } + + if bytesRead > 0 { + if buffer.count != bytesRead { + buffer = Array(buffer[0.. 0, outputStream.hasSpaceAvailable { + let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite) + + if let error = outputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .outputStreamWriteFailed(error: error)) + } + + bytesToWrite -= bytesWritten + + if bytesToWrite > 0 { + buffer = Array(buffer[bytesWritten.. String { + if + let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), + let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() + { + return contentType as String + } + + return "application/octet-stream" + } + + // MARK: - Private - Content Headers + + private func contentHeaders(withName name: String, fileName: String? = nil, mimeType: String? = nil) -> [String: String] { + var disposition = "form-data; name=\"\(name)\"" + if let fileName = fileName { disposition += "; filename=\"\(fileName)\"" } + + var headers = ["Content-Disposition": disposition] + if let mimeType = mimeType { headers["Content-Type"] = mimeType } + + return headers + } + + // MARK: - Private - Boundary Encoding + + private func initialBoundaryData() -> Data { + return BoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary) + } + + private func encapsulatedBoundaryData() -> Data { + return BoundaryGenerator.boundaryData(forBoundaryType: .encapsulated, boundary: boundary) + } + + private func finalBoundaryData() -> Data { + return BoundaryGenerator.boundaryData(forBoundaryType: .final, boundary: boundary) + } + + // MARK: - Private - Errors + + private func setBodyPartError(withReason reason: AFError.MultipartEncodingFailureReason) { + guard bodyPartError == nil else { return } + bodyPartError = AFError.multipartEncodingFailed(reason: reason) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/NetworkReachabilityManager.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/NetworkReachabilityManager.swift new file mode 100644 index 0000000000..30443b99b2 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/NetworkReachabilityManager.swift @@ -0,0 +1,233 @@ +// +// NetworkReachabilityManager.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#if !os(watchOS) + +import Foundation +import SystemConfiguration + +/// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and +/// WiFi network interfaces. +/// +/// Reachability can be used to determine background information about why a network operation failed, or to retry +/// network requests when a connection is established. It should not be used to prevent a user from initiating a network +/// request, as it's possible that an initial request may be required to establish reachability. +public class NetworkReachabilityManager { + /// Defines the various states of network reachability. + /// + /// - unknown: It is unknown whether the network is reachable. + /// - notReachable: The network is not reachable. + /// - reachable: The network is reachable. + public enum NetworkReachabilityStatus { + case unknown + case notReachable + case reachable(ConnectionType) + } + + /// Defines the various connection types detected by reachability flags. + /// + /// - ethernetOrWiFi: The connection type is either over Ethernet or WiFi. + /// - wwan: The connection type is a WWAN connection. + public enum ConnectionType { + case ethernetOrWiFi + case wwan + } + + /// A closure executed when the network reachability status changes. The closure takes a single argument: the + /// network reachability status. + public typealias Listener = (NetworkReachabilityStatus) -> Void + + // MARK: - Properties + + /// Whether the network is currently reachable. + public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi } + + /// Whether the network is currently reachable over the WWAN interface. + public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .reachable(.wwan) } + + /// Whether the network is currently reachable over Ethernet or WiFi interface. + public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .reachable(.ethernetOrWiFi) } + + /// The current network reachability status. + public var networkReachabilityStatus: NetworkReachabilityStatus { + guard let flags = self.flags else { return .unknown } + return networkReachabilityStatusForFlags(flags) + } + + /// The dispatch queue to execute the `listener` closure on. + public var listenerQueue: DispatchQueue = DispatchQueue.main + + /// A closure executed when the network reachability status changes. + public var listener: Listener? + + private var flags: SCNetworkReachabilityFlags? { + var flags = SCNetworkReachabilityFlags() + + if SCNetworkReachabilityGetFlags(reachability, &flags) { + return flags + } + + return nil + } + + private let reachability: SCNetworkReachability + private var previousFlags: SCNetworkReachabilityFlags + + // MARK: - Initialization + + /// Creates a `NetworkReachabilityManager` instance with the specified host. + /// + /// - parameter host: The host used to evaluate network reachability. + /// + /// - returns: The new `NetworkReachabilityManager` instance. + public convenience init?(host: String) { + guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } + self.init(reachability: reachability) + } + + /// Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0. + /// + /// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing + /// status of the device, both IPv4 and IPv6. + /// + /// - returns: The new `NetworkReachabilityManager` instance. + public convenience init?() { + var address = sockaddr_in() + address.sin_len = UInt8(MemoryLayout.size) + address.sin_family = sa_family_t(AF_INET) + + guard let reachability = withUnsafePointer(to: &address, { pointer in + return pointer.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout.size) { + return SCNetworkReachabilityCreateWithAddress(nil, $0) + } + }) else { return nil } + + self.init(reachability: reachability) + } + + private init(reachability: SCNetworkReachability) { + self.reachability = reachability + self.previousFlags = SCNetworkReachabilityFlags() + } + + deinit { + stopListening() + } + + // MARK: - Listening + + /// Starts listening for changes in network reachability status. + /// + /// - returns: `true` if listening was started successfully, `false` otherwise. + @discardableResult + public func startListening() -> Bool { + var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) + context.info = Unmanaged.passUnretained(self).toOpaque() + + let callbackEnabled = SCNetworkReachabilitySetCallback( + reachability, + { (_, flags, info) in + let reachability = Unmanaged.fromOpaque(info!).takeUnretainedValue() + reachability.notifyListener(flags) + }, + &context + ) + + let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue) + + listenerQueue.async { + self.previousFlags = SCNetworkReachabilityFlags() + self.notifyListener(self.flags ?? SCNetworkReachabilityFlags()) + } + + return callbackEnabled && queueEnabled + } + + /// Stops listening for changes in network reachability status. + public func stopListening() { + SCNetworkReachabilitySetCallback(reachability, nil, nil) + SCNetworkReachabilitySetDispatchQueue(reachability, nil) + } + + // MARK: - Internal - Listener Notification + + func notifyListener(_ flags: SCNetworkReachabilityFlags) { + guard previousFlags != flags else { return } + previousFlags = flags + + listener?(networkReachabilityStatusForFlags(flags)) + } + + // MARK: - Internal - Network Reachability Status + + func networkReachabilityStatusForFlags(_ flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus { + guard isNetworkReachable(with: flags) else { return .notReachable } + + var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi) + + #if os(iOS) + if flags.contains(.isWWAN) { networkStatus = .reachable(.wwan) } + #endif + + return networkStatus + } + + func isNetworkReachable(with flags: SCNetworkReachabilityFlags) -> Bool { + let isReachable = flags.contains(.reachable) + let needsConnection = flags.contains(.connectionRequired) + let canConnectAutomatically = flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic) + let canConnectWithoutUserInteraction = canConnectAutomatically && !flags.contains(.interventionRequired) + + return isReachable && (!needsConnection || canConnectWithoutUserInteraction) + } +} + +// MARK: - + +extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} + +/// Returns whether the two network reachability status values are equal. +/// +/// - parameter lhs: The left-hand side value to compare. +/// - parameter rhs: The right-hand side value to compare. +/// +/// - returns: `true` if the two values are equal, `false` otherwise. +public func ==( + lhs: NetworkReachabilityManager.NetworkReachabilityStatus, + rhs: NetworkReachabilityManager.NetworkReachabilityStatus) + -> Bool +{ + switch (lhs, rhs) { + case (.unknown, .unknown): + return true + case (.notReachable, .notReachable): + return true + case let (.reachable(lhsConnectionType), .reachable(rhsConnectionType)): + return lhsConnectionType == rhsConnectionType + default: + return false + } +} + +#endif diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Notifications.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Notifications.swift new file mode 100644 index 0000000000..81f6e378c8 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Notifications.swift @@ -0,0 +1,52 @@ +// +// Notifications.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension Notification.Name { + /// Used as a namespace for all `URLSessionTask` related notifications. + public struct Task { + /// Posted when a `URLSessionTask` is resumed. The notification `object` contains the resumed `URLSessionTask`. + public static let DidResume = Notification.Name(rawValue: "org.alamofire.notification.name.task.didResume") + + /// Posted when a `URLSessionTask` is suspended. The notification `object` contains the suspended `URLSessionTask`. + public static let DidSuspend = Notification.Name(rawValue: "org.alamofire.notification.name.task.didSuspend") + + /// Posted when a `URLSessionTask` is cancelled. The notification `object` contains the cancelled `URLSessionTask`. + public static let DidCancel = Notification.Name(rawValue: "org.alamofire.notification.name.task.didCancel") + + /// Posted when a `URLSessionTask` is completed. The notification `object` contains the completed `URLSessionTask`. + public static let DidComplete = Notification.Name(rawValue: "org.alamofire.notification.name.task.didComplete") + } +} + +// MARK: - + +extension Notification { + /// Used as a namespace for all `Notification` user info dictionary keys. + public struct Key { + /// User info dictionary key representing the `URLSessionTask` associated with the notification. + public static let Task = "org.alamofire.notification.key.task" + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift new file mode 100644 index 0000000000..959af6f936 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift @@ -0,0 +1,436 @@ +// +// 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 HTTPMethod: String { + case options = "OPTIONS" + case get = "GET" + case head = "HEAD" + case post = "POST" + case put = "PUT" + case patch = "PATCH" + case delete = "DELETE" + case trace = "TRACE" + case connect = "CONNECT" +} + +// MARK: - + +/// A dictionary of parameters to apply to a `URLRequest`. +public typealias Parameters = [String: Any] + +/// A type used to define how a set of parameters are applied to a `URLRequest`. +public protocol ParameterEncoding { + /// 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. + /// + /// - throws: An `AFError.parameterEncodingFailed` error if encoding fails. + /// + /// - returns: The encoded request. + func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest +} + +// MARK: - + +/// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP +/// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as +/// the HTTP body depends on the destination of the encoding. +/// +/// 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`). +public struct URLEncoding: ParameterEncoding { + + // MARK: Helper Types + + /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the + /// resulting URL request. + /// + /// - methodDependent: Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` + /// requests and sets as the HTTP body for requests with any other HTTP method. + /// - queryString: Sets or appends encoded query string result to existing query string. + /// - httpBody: Sets encoded query string result as the HTTP body of the URL request. + public enum Destination { + case methodDependent, queryString, httpBody + } + + // MARK: Properties + + /// Returns a default `URLEncoding` instance. + public static var `default`: URLEncoding { return URLEncoding() } + + /// Returns a `URLEncoding` instance with a `.methodDependent` destination. + public static var methodDependent: URLEncoding { return URLEncoding() } + + /// Returns a `URLEncoding` instance with a `.queryString` destination. + public static var queryString: URLEncoding { return URLEncoding(destination: .queryString) } + + /// Returns a `URLEncoding` instance with an `.httpBody` destination. + public static var httpBody: URLEncoding { return URLEncoding(destination: .httpBody) } + + /// The destination defining where the encoded query string is to be applied to the URL request. + public let destination: Destination + + // MARK: Initialization + + /// Creates a `URLEncoding` instance using the specified destination. + /// + /// - parameter destination: The destination defining where the encoded query string is to be applied. + /// + /// - returns: The new `URLEncoding` instance. + public init(destination: Destination = .methodDependent) { + self.destination = destination + } + + // MARK: Encoding + + /// 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. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters = parameters else { return urlRequest } + + if let method = HTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: method) { + guard let url = urlRequest.url else { + throw AFError.parameterEncodingFailed(reason: .missingURL) + } + + if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { + let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) + urlComponents.percentEncodedQuery = percentEncodedQuery + urlRequest.url = urlComponents.url + } + } else { + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false) + } + + return urlRequest + } + + /// 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(fromKey key: String, value: Any) -> [(String, String)] { + var components: [(String, String)] = [] + + if let dictionary = value as? [String: Any] { + for (nestedKey, value) in dictionary { + components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value) + } + } else if let array = value as? [Any] { + for value in array { + components += queryComponents(fromKey: "\(key)[]", value: value) + } + } else if let value = value as? NSNumber { + if value.isBool { + components.append((escape(key), escape((value.boolValue ? "1" : "0")))) + } else { + components.append((escape(key), escape("\(value)"))) + } + } else if let bool = value as? Bool { + components.append((escape(key), escape((bool ? "1" : "0")))) + } 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 = "!$&'()*+,;=" + + var allowedCharacterSet = CharacterSet.urlQueryAllowed + allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") + + var escaped = "" + + //========================================================================================================== + // + // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few + // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no + // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more + // info, please refer to: + // + // - https://github.com/Alamofire/Alamofire/issues/206 + // + //========================================================================================================== + + if #available(iOS 8.3, *) { + escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string + } else { + let batchSize = 50 + var index = string.startIndex + + while index != string.endIndex { + let startIndex = index + let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex + let range = startIndex.. String { + var components: [(String, String)] = [] + + for key in parameters.keys.sorted(by: <) { + let value = parameters[key]! + components += queryComponents(fromKey: key, value: value) + } + #if swift(>=4.0) + return components.map { "\($0.0)=\($0.1)" }.joined(separator: "&") + #else + return components.map { "\($0)=\($1)" }.joined(separator: "&") + #endif + } + + private func encodesParametersInURL(with method: HTTPMethod) -> Bool { + switch destination { + case .queryString: + return true + case .httpBody: + return false + default: + break + } + + switch method { + case .get, .head, .delete: + return true + default: + return false + } + } +} + +// MARK: - + +/// Uses `JSONSerialization` 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`. +public struct JSONEncoding: ParameterEncoding { + + // MARK: Properties + + /// Returns a `JSONEncoding` instance with default writing options. + public static var `default`: JSONEncoding { return JSONEncoding() } + + /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options. + public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) } + + /// The options for writing the parameters as JSON data. + public let options: JSONSerialization.WritingOptions + + // MARK: Initialization + + /// Creates a `JSONEncoding` instance using the specified options. + /// + /// - parameter options: The options for writing the parameters as JSON data. + /// + /// - returns: The new `JSONEncoding` instance. + public init(options: JSONSerialization.WritingOptions = []) { + self.options = options + } + + // MARK: Encoding + + /// 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. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters = parameters else { return urlRequest } + + do { + let data = try JSONSerialization.data(withJSONObject: parameters, options: options) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return urlRequest + } + + /// Creates a URL request by encoding the JSON object and setting the resulting data on the HTTP body. + /// + /// - parameter urlRequest: The request to apply the JSON object to. + /// - parameter jsonObject: The JSON object to apply to the request. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let jsonObject = jsonObject else { return urlRequest } + + do { + let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return urlRequest + } +} + +// MARK: - + +/// Uses `PropertyListSerialization` 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`. +public struct PropertyListEncoding: ParameterEncoding { + + // MARK: Properties + + /// Returns a default `PropertyListEncoding` instance. + public static var `default`: PropertyListEncoding { return PropertyListEncoding() } + + /// Returns a `PropertyListEncoding` instance with xml formatting and default writing options. + public static var xml: PropertyListEncoding { return PropertyListEncoding(format: .xml) } + + /// Returns a `PropertyListEncoding` instance with binary formatting and default writing options. + public static var binary: PropertyListEncoding { return PropertyListEncoding(format: .binary) } + + /// The property list serialization format. + public let format: PropertyListSerialization.PropertyListFormat + + /// The options for writing the parameters as plist data. + public let options: PropertyListSerialization.WriteOptions + + // MARK: Initialization + + /// Creates a `PropertyListEncoding` instance using the specified format and options. + /// + /// - parameter format: The property list serialization format. + /// - parameter options: The options for writing the parameters as plist data. + /// + /// - returns: The new `PropertyListEncoding` instance. + public init( + format: PropertyListSerialization.PropertyListFormat = .xml, + options: PropertyListSerialization.WriteOptions = 0) + { + self.format = format + self.options = options + } + + // MARK: Encoding + + /// 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. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters = parameters else { return urlRequest } + + do { + let data = try PropertyListSerialization.data( + fromPropertyList: parameters, + format: format, + options: options + ) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .propertyListEncodingFailed(error: error)) + } + + return urlRequest + } +} + +// MARK: - + +extension NSNumber { + fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Request.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Request.swift new file mode 100644 index 0000000000..4f6350c5bf --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Request.swift @@ -0,0 +1,647 @@ +// +// 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 + +/// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary. +public protocol RequestAdapter { + /// Inspects and adapts the specified `URLRequest` in some manner if necessary and returns the result. + /// + /// - parameter urlRequest: The URL request to adapt. + /// + /// - throws: An `Error` if the adaptation encounters an error. + /// + /// - returns: The adapted `URLRequest`. + func adapt(_ urlRequest: URLRequest) throws -> URLRequest +} + +// MARK: - + +/// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not. +public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void + +/// A type that determines whether a request should be retried after being executed by the specified session manager +/// and encountering an error. +public protocol RequestRetrier { + /// Determines whether the `Request` should be retried by calling the `completion` closure. + /// + /// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs + /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly + /// cleaned up after. + /// + /// - parameter manager: The session manager the request was executed on. + /// - parameter request: The request that failed due to the encountered error. + /// - parameter error: The error encountered when executing the request. + /// - parameter completion: The completion closure to be executed when retry decision has been determined. + func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) +} + +// MARK: - + +protocol TaskConvertible { + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask +} + +/// A dictionary of headers to apply to a `URLRequest`. +public typealias HTTPHeaders = [String: String] + +// MARK: - + +/// Responsible for sending a request and receiving the response and associated data from the server, as well as +/// managing its underlying `URLSessionTask`. +open class Request { + + // MARK: Helper Types + + /// A closure executed when monitoring upload or download progress of a request. + public typealias ProgressHandler = (Progress) -> Void + + enum RequestTask { + case data(TaskConvertible?, URLSessionTask?) + case download(TaskConvertible?, URLSessionTask?) + case upload(TaskConvertible?, URLSessionTask?) + case stream(TaskConvertible?, URLSessionTask?) + } + + // MARK: Properties + + /// The delegate for the underlying task. + open internal(set) var delegate: TaskDelegate { + get { + taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } + return taskDelegate + } + set { + taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } + taskDelegate = newValue + } + } + + /// The underlying task. + open var task: URLSessionTask? { return delegate.task } + + /// The session belonging to the underlying task. + open let session: URLSession + + /// The request sent or to be sent to the server. + open var request: URLRequest? { return task?.originalRequest } + + /// The response received from the server, if any. + open var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse } + + /// The number of times the request has been retried. + open internal(set) var retryCount: UInt = 0 + + let originalTask: TaskConvertible? + + var startTime: CFAbsoluteTime? + var endTime: CFAbsoluteTime? + + var validations: [() -> Void] = [] + + private var taskDelegate: TaskDelegate + private var taskDelegateLock = NSLock() + + // MARK: Lifecycle + + init(session: URLSession, requestTask: RequestTask, error: Error? = nil) { + self.session = session + + switch requestTask { + case .data(let originalTask, let task): + taskDelegate = DataTaskDelegate(task: task) + self.originalTask = originalTask + case .download(let originalTask, let task): + taskDelegate = DownloadTaskDelegate(task: task) + self.originalTask = originalTask + case .upload(let originalTask, let task): + taskDelegate = UploadTaskDelegate(task: task) + self.originalTask = originalTask + case .stream(let originalTask, let task): + taskDelegate = TaskDelegate(task: task) + self.originalTask = originalTask + } + + delegate.error = error + delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() } + } + + // MARK: Authentication + + /// Associates an HTTP Basic credential with the request. + /// + /// - parameter user: The user. + /// - parameter password: The password. + /// - parameter persistence: The URL credential persistence. `.ForSession` by default. + /// + /// - returns: The request. + @discardableResult + open func authenticate( + user: String, + password: String, + persistence: URLCredential.Persistence = .forSession) + -> Self + { + let credential = URLCredential(user: user, password: password, persistence: persistence) + return authenticate(usingCredential: credential) + } + + /// Associates a specified credential with the request. + /// + /// - parameter credential: The credential. + /// + /// - returns: The request. + @discardableResult + open func authenticate(usingCredential credential: URLCredential) -> Self { + delegate.credential = credential + return self + } + + /// Returns a base64 encoded basic authentication credential as an authorization header tuple. + /// + /// - parameter user: The user. + /// - parameter password: The password. + /// + /// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise. + open static func authorizationHeader(user: String, password: String) -> (key: String, value: String)? { + guard let data = "\(user):\(password)".data(using: .utf8) else { return nil } + + let credential = data.base64EncodedString(options: []) + + return (key: "Authorization", value: "Basic \(credential)") + } + + // MARK: State + + /// Resumes the request. + open func resume() { + guard let task = task else { delegate.queue.isSuspended = false ; return } + + if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } + + task.resume() + + NotificationCenter.default.post( + name: Notification.Name.Task.DidResume, + object: self, + userInfo: [Notification.Key.Task: task] + ) + } + + /// Suspends the request. + open func suspend() { + guard let task = task else { return } + + task.suspend() + + NotificationCenter.default.post( + name: Notification.Name.Task.DidSuspend, + object: self, + userInfo: [Notification.Key.Task: task] + ) + } + + /// Cancels the request. + open func cancel() { + guard let task = task else { return } + + task.cancel() + + NotificationCenter.default.post( + name: Notification.Name.Task.DidCancel, + object: self, + userInfo: [Notification.Key.Task: task] + ) + } +} + +// 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. + open 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.joined(separator: " ") + } +} + +// MARK: - CustomDebugStringConvertible + +extension Request: CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, in the form of a cURL command. + open var debugDescription: String { + return cURLRepresentation() + } + + func cURLRepresentation() -> String { + var components = ["$ curl -v"] + + guard let request = self.request, + let url = request.url, + let host = url.host + else { + return "$ curl command could not be created" + } + + if let httpMethod = request.httpMethod, httpMethod != "GET" { + components.append("-X \(httpMethod)") + } + + if let credentialStorage = self.session.configuration.urlCredentialStorage { + let protectionSpace = URLProtectionSpace( + host: host, + port: url.port ?? 0, + protocol: url.scheme, + realm: host, + authenticationMethod: NSURLAuthenticationMethodHTTPBasic + ) + + if let credentials = credentialStorage.credentials(for: 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, + let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty + { + let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" } + components.append("-b \"\(string.substring(to: string.characters.index(before: string.endIndex)))\"") + } + } + + var headers: [AnyHashable: Any] = [:] + + if let additionalHeaders = session.configuration.httpAdditionalHeaders { + for (field, value) in additionalHeaders where field != AnyHashable("Cookie") { + headers[field] = value + } + } + + if let headerFields = request.allHTTPHeaderFields { + for (field, value) in headerFields where field != "Cookie" { + headers[field] = value + } + } + + for (field, value) in headers { + components.append("-H \"\(field): \(value)\"") + } + + if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) { + var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"") + escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"") + + components.append("-d \"\(escapedBody)\"") + } + + components.append("\"\(url.absoluteString)\"") + + return components.joined(separator: " \\\n\t") + } +} + +// MARK: - + +/// Specific type of `Request` that manages an underlying `URLSessionDataTask`. +open class DataRequest: Request { + + // MARK: Helper Types + + struct Requestable: TaskConvertible { + let urlRequest: URLRequest + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + do { + let urlRequest = try self.urlRequest.adapt(using: adapter) + return queue.sync { session.dataTask(with: urlRequest) } + } catch { + throw AdaptError(error: error) + } + } + } + + // MARK: Properties + + /// The request sent or to be sent to the server. + open override var request: URLRequest? { + if let request = super.request { return request } + if let requestable = originalTask as? Requestable { return requestable.urlRequest } + + return nil + } + + /// The progress of fetching the response data from the server for the request. + open var progress: Progress { return dataDelegate.progress } + + var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate } + + // MARK: Stream + + /// 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 server data in any `Response` object will be `nil`. + /// + /// - parameter closure: The code to be executed periodically during the lifecycle of the request. + /// + /// - returns: The request. + @discardableResult + open func stream(closure: ((Data) -> Void)? = nil) -> Self { + dataDelegate.dataStream = closure + return self + } + + // MARK: Progress + + /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. + /// + /// - parameter queue: The dispatch queue to execute the closure on. + /// - parameter closure: The code to be executed periodically as data is read from the server. + /// + /// - returns: The request. + @discardableResult + open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { + dataDelegate.progressHandler = (closure, queue) + return self + } +} + +// MARK: - + +/// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`. +open class DownloadRequest: Request { + + // MARK: Helper Types + + /// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the + /// destination URL. + public struct DownloadOptions: OptionSet { + /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol. + public let rawValue: UInt + + /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified. + public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0) + + /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified. + public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1) + + /// Creates a `DownloadFileDestinationOptions` instance with the specified raw value. + /// + /// - parameter rawValue: The raw bitmask value for the option. + /// + /// - returns: A new log level instance. + public init(rawValue: UInt) { + self.rawValue = rawValue + } + } + + /// A closure executed once a download 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 two arguments: the file URL where the temporary file should be moved and + /// the options defining how the file should be moved. + public typealias DownloadFileDestination = ( + _ temporaryURL: URL, + _ response: HTTPURLResponse) + -> (destinationURL: URL, options: DownloadOptions) + + enum Downloadable: TaskConvertible { + case request(URLRequest) + case resumeData(Data) + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + do { + let task: URLSessionTask + + switch self { + case let .request(urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.downloadTask(with: urlRequest) } + case let .resumeData(resumeData): + task = queue.sync { session.downloadTask(withResumeData: resumeData) } + } + + return task + } catch { + throw AdaptError(error: error) + } + } + } + + // MARK: Properties + + /// The request sent or to be sent to the server. + open override var request: URLRequest? { + if let request = super.request { return request } + + if let downloadable = originalTask as? Downloadable, case let .request(urlRequest) = downloadable { + return urlRequest + } + + return nil + } + + /// The resume data of the underlying download task if available after a failure. + open var resumeData: Data? { return downloadDelegate.resumeData } + + /// The progress of downloading the response data from the server for the request. + open var progress: Progress { return downloadDelegate.progress } + + var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate } + + // MARK: State + + /// Cancels the request. + open override func cancel() { + downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 } + + NotificationCenter.default.post( + name: Notification.Name.Task.DidCancel, + object: self, + userInfo: [Notification.Key.Task: task as Any] + ) + } + + // MARK: Progress + + /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. + /// + /// - parameter queue: The dispatch queue to execute the closure on. + /// - parameter closure: The code to be executed periodically as data is read from the server. + /// + /// - returns: The request. + @discardableResult + open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { + downloadDelegate.progressHandler = (closure, queue) + return self + } + + // MARK: Destination + + /// 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. + open class func suggestedDownloadDestination( + for directory: FileManager.SearchPathDirectory = .documentDirectory, + in domain: FileManager.SearchPathDomainMask = .userDomainMask) + -> DownloadFileDestination + { + return { temporaryURL, response in + let directoryURLs = FileManager.default.urls(for: directory, in: domain) + + if !directoryURLs.isEmpty { + return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), []) + } + + return (temporaryURL, []) + } + } +} + +// MARK: - + +/// Specific type of `Request` that manages an underlying `URLSessionUploadTask`. +open class UploadRequest: DataRequest { + + // MARK: Helper Types + + enum Uploadable: TaskConvertible { + case data(Data, URLRequest) + case file(URL, URLRequest) + case stream(InputStream, URLRequest) + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + do { + let task: URLSessionTask + + switch self { + case let .data(data, urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.uploadTask(with: urlRequest, from: data) } + case let .file(url, urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.uploadTask(with: urlRequest, fromFile: url) } + case let .stream(_, urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.uploadTask(withStreamedRequest: urlRequest) } + } + + return task + } catch { + throw AdaptError(error: error) + } + } + } + + // MARK: Properties + + /// The request sent or to be sent to the server. + open override var request: URLRequest? { + if let request = super.request { return request } + + guard let uploadable = originalTask as? Uploadable else { return nil } + + switch uploadable { + case .data(_, let urlRequest), .file(_, let urlRequest), .stream(_, let urlRequest): + return urlRequest + } + } + + /// The progress of uploading the payload to the server for the upload request. + open var uploadProgress: Progress { return uploadDelegate.uploadProgress } + + var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate } + + // MARK: Upload Progress + + /// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to + /// the server. + /// + /// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress + /// of data being read from the server. + /// + /// - parameter queue: The dispatch queue to execute the closure on. + /// - parameter closure: The code to be executed periodically as data is sent to the server. + /// + /// - returns: The request. + @discardableResult + open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { + uploadDelegate.uploadProgressHandler = (closure, queue) + return self + } +} + +// MARK: - + +#if !os(watchOS) + +/// Specific type of `Request` that manages an underlying `URLSessionStreamTask`. +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +open class StreamRequest: Request { + enum Streamable: TaskConvertible { + case stream(hostName: String, port: Int) + case netService(NetService) + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + let task: URLSessionTask + + switch self { + case let .stream(hostName, port): + task = queue.sync { session.streamTask(withHostName: hostName, port: port) } + case let .netService(netService): + task = queue.sync { session.streamTask(with: netService) } + } + + return task + } + } +} + +#endif diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Response.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Response.swift new file mode 100644 index 0000000000..5d3b6d2542 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Response.swift @@ -0,0 +1,465 @@ +// +// 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 data associated with an non-serialized response of a data or upload request. +public struct DefaultDataResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The data returned by the server. + public let data: Data? + + /// The error encountered while executing or validating the request. + public let error: Error? + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + var _metrics: AnyObject? + + /// Creates a `DefaultDataResponse` instance from the specified parameters. + /// + /// - Parameters: + /// - request: The URL request sent to the server. + /// - response: The server's response to the URL request. + /// - data: The data returned by the server. + /// - error: The error encountered while executing or validating the request. + /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. + /// - metrics: The task metrics containing the request / response statistics. `nil` by default. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + data: Data?, + error: Error?, + timeline: Timeline = Timeline(), + metrics: AnyObject? = nil) + { + self.request = request + self.response = response + self.data = data + self.error = error + self.timeline = timeline + } +} + +// MARK: - + +/// Used to store all data associated with a serialized response of a data or upload request. +public struct DataResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The data returned by the server. + public let data: Data? + + /// The result of response serialization. + public let result: Result + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + /// Returns the associated value of the result if it is a success, `nil` otherwise. + public var value: Value? { return result.value } + + /// Returns the associated error value if the result if it is a failure, `nil` otherwise. + public var error: Error? { return result.error } + + var _metrics: AnyObject? + + /// Creates a `DataResponse` instance with the specified parameters derived from response serialization. + /// + /// - parameter request: The URL request sent to the server. + /// - parameter response: The server's response to the URL request. + /// - parameter data: The data returned by the server. + /// - parameter result: The result of response serialization. + /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. + /// + /// - returns: The new `DataResponse` instance. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + data: Data?, + result: Result, + timeline: Timeline = Timeline()) + { + self.request = request + self.response = response + self.data = data + self.result = result + self.timeline = timeline + } +} + +// MARK: - + +extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible { + /// 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 + } + + /// The debug textual representation used when written to an output stream, which includes the URL request, the URL + /// response, the server data, the response serialization result and the timeline. + public var debugDescription: String { + var output: [String] = [] + + output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") + output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") + output.append("[Data]: \(data?.count ?? 0) bytes") + output.append("[Result]: \(result.debugDescription)") + output.append("[Timeline]: \(timeline.debugDescription)") + + return output.joined(separator: "\n") + } +} + +// MARK: - + +extension DataResponse { + /// Evaluates the specified closure when the result of this `DataResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `map` method with a closure that does not throw. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleInt = possibleData.map { $0.count } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A `DataResponse` whose result wraps the value returned by the given closure. If this instance's + /// result is a failure, returns a response wrapping the same failure. + public func map(_ transform: (Value) -> T) -> DataResponse { + var response = DataResponse( + request: request, + response: self.response, + data: data, + result: result.map(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result + /// value as a parameter. + /// + /// Use the `flatMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleObject = possibleData.flatMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A success or failure `DataResponse` depending on the result of the given closure. If this instance's + /// result is a failure, returns the same failure. + public func flatMap(_ transform: (Value) throws -> T) -> DataResponse { + var response = DataResponse( + request: request, + response: self.response, + data: data, + result: result.flatMap(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } +} + +// MARK: - + +/// Used to store all data associated with an non-serialized response of a download request. +public struct DefaultDownloadResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The temporary destination URL of the data returned from the server. + public let temporaryURL: URL? + + /// The final destination URL of the data returned from the server if it was moved. + public let destinationURL: URL? + + /// The resume data generated if the request was cancelled. + public let resumeData: Data? + + /// The error encountered while executing or validating the request. + public let error: Error? + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + var _metrics: AnyObject? + + /// Creates a `DefaultDownloadResponse` instance from the specified parameters. + /// + /// - Parameters: + /// - request: The URL request sent to the server. + /// - response: The server's response to the URL request. + /// - temporaryURL: The temporary destination URL of the data returned from the server. + /// - destinationURL: The final destination URL of the data returned from the server if it was moved. + /// - resumeData: The resume data generated if the request was cancelled. + /// - error: The error encountered while executing or validating the request. + /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. + /// - metrics: The task metrics containing the request / response statistics. `nil` by default. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + temporaryURL: URL?, + destinationURL: URL?, + resumeData: Data?, + error: Error?, + timeline: Timeline = Timeline(), + metrics: AnyObject? = nil) + { + self.request = request + self.response = response + self.temporaryURL = temporaryURL + self.destinationURL = destinationURL + self.resumeData = resumeData + self.error = error + self.timeline = timeline + } +} + +// MARK: - + +/// Used to store all data associated with a serialized response of a download request. +public struct DownloadResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The temporary destination URL of the data returned from the server. + public let temporaryURL: URL? + + /// The final destination URL of the data returned from the server if it was moved. + public let destinationURL: URL? + + /// The resume data generated if the request was cancelled. + public let resumeData: Data? + + /// The result of response serialization. + public let result: Result + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + /// Returns the associated value of the result if it is a success, `nil` otherwise. + public var value: Value? { return result.value } + + /// Returns the associated error value if the result if it is a failure, `nil` otherwise. + public var error: Error? { return result.error } + + var _metrics: AnyObject? + + /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization. + /// + /// - parameter request: The URL request sent to the server. + /// - parameter response: The server's response to the URL request. + /// - parameter temporaryURL: The temporary destination URL of the data returned from the server. + /// - parameter destinationURL: The final destination URL of the data returned from the server if it was moved. + /// - parameter resumeData: The resume data generated if the request was cancelled. + /// - parameter result: The result of response serialization. + /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. + /// + /// - returns: The new `DownloadResponse` instance. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + temporaryURL: URL?, + destinationURL: URL?, + resumeData: Data?, + result: Result, + timeline: Timeline = Timeline()) + { + self.request = request + self.response = response + self.temporaryURL = temporaryURL + self.destinationURL = destinationURL + self.resumeData = resumeData + self.result = result + self.timeline = timeline + } +} + +// MARK: - + +extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible { + /// 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 + } + + /// The debug textual representation used when written to an output stream, which includes the URL request, the URL + /// response, the temporary and destination URLs, the resume data, the response serialization result and the + /// timeline. + public var debugDescription: String { + var output: [String] = [] + + output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") + output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") + output.append("[TemporaryURL]: \(temporaryURL?.path ?? "nil")") + output.append("[DestinationURL]: \(destinationURL?.path ?? "nil")") + output.append("[ResumeData]: \(resumeData?.count ?? 0) bytes") + output.append("[Result]: \(result.debugDescription)") + output.append("[Timeline]: \(timeline.debugDescription)") + + return output.joined(separator: "\n") + } +} + +// MARK: - + +extension DownloadResponse { + /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `map` method with a closure that does not throw. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleInt = possibleData.map { $0.count } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's + /// result is a failure, returns a response wrapping the same failure. + public func map(_ transform: (Value) -> T) -> DownloadResponse { + var response = DownloadResponse( + request: request, + response: self.response, + temporaryURL: temporaryURL, + destinationURL: destinationURL, + resumeData: resumeData, + result: result.map(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `flatMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleObject = possibleData.flatMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this + /// instance's result is a failure, returns the same failure. + public func flatMap(_ transform: (Value) throws -> T) -> DownloadResponse { + var response = DownloadResponse( + request: request, + response: self.response, + temporaryURL: temporaryURL, + destinationURL: destinationURL, + resumeData: resumeData, + result: result.flatMap(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } +} + +// MARK: - + +protocol Response { + /// The task metrics containing the request / response statistics. + var _metrics: AnyObject? { get set } + mutating func add(_ metrics: AnyObject?) +} + +extension Response { + mutating func add(_ metrics: AnyObject?) { + #if !os(watchOS) + guard #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) else { return } + guard let metrics = metrics as? URLSessionTaskMetrics else { return } + + _metrics = metrics + #endif + } +} + +// MARK: - + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DefaultDataResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DataResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DefaultDownloadResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DownloadResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift new file mode 100644 index 0000000000..1a59da550a --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift @@ -0,0 +1,715 @@ +// +// 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 + +/// The type in which all data response serializers must conform to in order to serialize a response. +public protocol DataResponseSerializerProtocol { + /// The type of serialized object to be created by this `DataResponseSerializerType`. + associatedtype SerializedObject + + /// A closure used by response handlers that takes a request, response, data and error and returns a result. + var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result { get } +} + +// MARK: - + +/// A generic `DataResponseSerializerType` used to serialize a request, response, and data into a serialized object. +public struct DataResponseSerializer: DataResponseSerializerProtocol { + /// The type of serialized object to be created by this `DataResponseSerializer`. + public typealias SerializedObject = Value + + /// A closure used by response handlers that takes a request, response, data and error and returns a result. + public var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result + + /// 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: @escaping (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result) { + self.serializeResponse = serializeResponse + } +} + +// MARK: - + +/// The type in which all download response serializers must conform to in order to serialize a response. +public protocol DownloadResponseSerializerProtocol { + /// The type of serialized object to be created by this `DownloadResponseSerializerType`. + associatedtype SerializedObject + + /// A closure used by response handlers that takes a request, response, url and error and returns a result. + var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result { get } +} + +// MARK: - + +/// A generic `DownloadResponseSerializerType` used to serialize a request, response, and data into a serialized object. +public struct DownloadResponseSerializer: DownloadResponseSerializerProtocol { + /// The type of serialized object to be created by this `DownloadResponseSerializer`. + public typealias SerializedObject = Value + + /// A closure used by response handlers that takes a request, response, url and error and returns a result. + public var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result + + /// 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: @escaping (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result) { + self.serializeResponse = serializeResponse + } +} + +// MARK: - Timeline + +extension Request { + var timeline: Timeline { + let requestStartTime = self.startTime ?? CFAbsoluteTimeGetCurrent() + let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent() + let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime + + return Timeline( + requestStartTime: requestStartTime, + initialResponseTime: initialResponseTime, + requestCompletedTime: requestCompletedTime, + serializationCompletedTime: CFAbsoluteTimeGetCurrent() + ) + } +} + +// MARK: - Default + +extension DataRequest { + /// 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. + @discardableResult + public func response(queue: DispatchQueue? = nil, completionHandler: @escaping (DefaultDataResponse) -> Void) -> Self { + delegate.queue.addOperation { + (queue ?? DispatchQueue.main).async { + var dataResponse = DefaultDataResponse( + request: self.request, + response: self.response, + data: self.delegate.data, + error: self.delegate.error, + timeline: self.timeline + ) + + dataResponse.add(self.delegate.metrics) + + completionHandler(dataResponse) + } + } + + 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. + @discardableResult + public func response( + queue: DispatchQueue? = nil, + responseSerializer: T, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + delegate.queue.addOperation { + let result = responseSerializer.serializeResponse( + self.request, + self.response, + self.delegate.data, + self.delegate.error + ) + + var dataResponse = DataResponse( + request: self.request, + response: self.response, + data: self.delegate.data, + result: result, + timeline: self.timeline + ) + + dataResponse.add(self.delegate.metrics) + + (queue ?? DispatchQueue.main).async { completionHandler(dataResponse) } + } + + return self + } +} + +extension DownloadRequest { + /// 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. + @discardableResult + public func response( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DefaultDownloadResponse) -> Void) + -> Self + { + delegate.queue.addOperation { + (queue ?? DispatchQueue.main).async { + var downloadResponse = DefaultDownloadResponse( + request: self.request, + response: self.response, + temporaryURL: self.downloadDelegate.temporaryURL, + destinationURL: self.downloadDelegate.destinationURL, + resumeData: self.downloadDelegate.resumeData, + error: self.downloadDelegate.error, + timeline: self.timeline + ) + + downloadResponse.add(self.delegate.metrics) + + completionHandler(downloadResponse) + } + } + + 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 contained in the destination url. + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func response( + queue: DispatchQueue? = nil, + responseSerializer: T, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + delegate.queue.addOperation { + let result = responseSerializer.serializeResponse( + self.request, + self.response, + self.downloadDelegate.fileURL, + self.downloadDelegate.error + ) + + var downloadResponse = DownloadResponse( + request: self.request, + response: self.response, + temporaryURL: self.downloadDelegate.temporaryURL, + destinationURL: self.downloadDelegate.destinationURL, + resumeData: self.downloadDelegate.resumeData, + result: result, + timeline: self.timeline + ) + + downloadResponse.add(self.delegate.metrics) + + (queue ?? DispatchQueue.main).async { completionHandler(downloadResponse) } + } + + return self + } +} + +// MARK: - Data + +extension Request { + /// Returns a result data type that contains the response data as-is. + /// + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponseData(response: HTTPURLResponse?, data: Data?, error: Error?) -> Result { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(Data()) } + + guard let validData = data else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) + } + + return .success(validData) + } +} + +extension DataRequest { + /// Creates a response serializer that returns the associated data as-is. + /// + /// - returns: A data response serializer. + public static func dataResponseSerializer() -> DataResponseSerializer { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponseData(response: response, data: data, error: error) + } + } + + /// 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. + @discardableResult + public func responseData( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.dataResponseSerializer(), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns the associated data as-is. + /// + /// - returns: A data response serializer. + public static func dataResponseSerializer() -> DownloadResponseSerializer { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponseData(response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// 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. + @discardableResult + public func responseData( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.dataResponseSerializer(), + completionHandler: completionHandler + ) + } +} + +// MARK: - String + +extension Request { + /// Returns a result string type 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. + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponseString( + encoding: String.Encoding?, + response: HTTPURLResponse?, + data: Data?, + error: Error?) + -> Result + { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success("") } + + guard let validData = data else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) + } + + var convertedEncoding = encoding + + if let encodingName = response?.textEncodingName as CFString!, convertedEncoding == nil { + convertedEncoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding( + CFStringConvertIANACharSetNameToEncoding(encodingName)) + ) + } + + let actualEncoding = convertedEncoding ?? String.Encoding.isoLatin1 + + if let string = String(data: validData, encoding: actualEncoding) { + return .success(string) + } else { + return .failure(AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding))) + } + } +} + +extension DataRequest { + /// Creates a response serializer that returns a result string type initialized from the response data with + /// the specified string encoding. + /// + /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server + /// response, falling back to the default HTTP default character set, ISO-8859-1. + /// + /// - returns: A string response serializer. + public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DataResponseSerializer { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: 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. + @discardableResult + public func responseString( + queue: DispatchQueue? = nil, + encoding: String.Encoding? = nil, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.stringResponseSerializer(encoding: encoding), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns a result string type initialized from the response data with + /// the specified string encoding. + /// + /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server + /// response, falling back to the default HTTP default character set, ISO-8859-1. + /// + /// - returns: A string response serializer. + public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DownloadResponseSerializer { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// 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. + @discardableResult + public func responseString( + queue: DispatchQueue? = nil, + encoding: String.Encoding? = nil, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.stringResponseSerializer(encoding: encoding), + completionHandler: completionHandler + ) + } +} + +// MARK: - JSON + +extension Request { + /// Returns a JSON object contained in a result type constructed from the response data using `JSONSerialization` + /// with the specified reading options. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponseJSON( + options: JSONSerialization.ReadingOptions, + response: HTTPURLResponse?, + data: Data?, + error: Error?) + -> Result + { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } + + guard let validData = data, validData.count > 0 else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) + } + + do { + let json = try JSONSerialization.jsonObject(with: validData, options: options) + return .success(json) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error))) + } + } +} + +extension DataRequest { + /// Creates a response serializer that returns a JSON object result type constructed from the response data using + /// `JSONSerialization` with the specified reading options. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// + /// - returns: A JSON object response serializer. + public static func jsonResponseSerializer( + options: JSONSerialization.ReadingOptions = .allowFragments) + -> DataResponseSerializer + { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseJSON( + queue: DispatchQueue? = nil, + options: JSONSerialization.ReadingOptions = .allowFragments, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.jsonResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns a JSON object result type constructed from the response data using + /// `JSONSerialization` with the specified reading options. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// + /// - returns: A JSON object response serializer. + public static func jsonResponseSerializer( + options: JSONSerialization.ReadingOptions = .allowFragments) + -> DownloadResponseSerializer + { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseJSON( + queue: DispatchQueue? = nil, + options: JSONSerialization.ReadingOptions = .allowFragments, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.jsonResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +// MARK: - Property List + +extension Request { + /// Returns a plist object contained in a result type constructed from the response data using + /// `PropertyListSerialization` with the specified reading options. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponsePropertyList( + options: PropertyListSerialization.ReadOptions, + response: HTTPURLResponse?, + data: Data?, + error: Error?) + -> Result + { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } + + guard let validData = data, validData.count > 0 else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) + } + + do { + let plist = try PropertyListSerialization.propertyList(from: validData, options: options, format: nil) + return .success(plist) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .propertyListSerializationFailed(error: error))) + } + } +} + +extension DataRequest { + /// Creates a response serializer that returns an object constructed from the response data using + /// `PropertyListSerialization` with the specified reading options. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// + /// - returns: A property list object response serializer. + public static func propertyListResponseSerializer( + options: PropertyListSerialization.ReadOptions = []) + -> DataResponseSerializer + { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responsePropertyList( + queue: DispatchQueue? = nil, + options: PropertyListSerialization.ReadOptions = [], + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.propertyListResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns an object constructed from the response data using + /// `PropertyListSerialization` with the specified reading options. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// + /// - returns: A property list object response serializer. + public static func propertyListResponseSerializer( + options: PropertyListSerialization.ReadOptions = []) + -> DownloadResponseSerializer + { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responsePropertyList( + queue: DispatchQueue? = nil, + options: PropertyListSerialization.ReadOptions = [], + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.propertyListResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +/// A set of HTTP response status code that do not contain response data. +private let emptyDataStatusCodes: Set = [204, 205] diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Result.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Result.swift new file mode 100644 index 0000000000..bf7e70255b --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Result.swift @@ -0,0 +1,300 @@ +// +// 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 { + 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)" + } + } +} + +// MARK: - Functional APIs + +extension Result { + /// Creates a `Result` instance from the result of a closure. + /// + /// A failure result is created when the closure throws, and a success result is created when the closure + /// succeeds without throwing an error. + /// + /// func someString() throws -> String { ... } + /// + /// let result = Result(value: { + /// return try someString() + /// }) + /// + /// // The type of result is Result + /// + /// The trailing closure syntax is also supported: + /// + /// let result = Result { try someString() } + /// + /// - parameter value: The closure to execute and create the result for. + public init(value: () throws -> Value) { + do { + self = try .success(value()) + } catch { + self = .failure(error) + } + } + + /// Returns the success value, or throws the failure error. + /// + /// let possibleString: Result = .success("success") + /// try print(possibleString.unwrap()) + /// // Prints "success" + /// + /// let noString: Result = .failure(error) + /// try print(noString.unwrap()) + /// // Throws error + public func unwrap() throws -> Value { + switch self { + case .success(let value): + return value + case .failure(let error): + throw error + } + } + + /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. + /// + /// Use the `map` method with a closure that does not throw. For example: + /// + /// let possibleData: Result = .success(Data()) + /// let possibleInt = possibleData.map { $0.count } + /// try print(possibleInt.unwrap()) + /// // Prints "0" + /// + /// let noData: Result = .failure(error) + /// let noInt = noData.map { $0.count } + /// try print(noInt.unwrap()) + /// // Throws error + /// + /// - parameter transform: A closure that takes the success value of the `Result` instance. + /// + /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the + /// same failure. + public func map(_ transform: (Value) -> T) -> Result { + switch self { + case .success(let value): + return .success(transform(value)) + case .failure(let error): + return .failure(error) + } + } + + /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. + /// + /// Use the `flatMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: Result = .success(Data(...)) + /// let possibleObject = possibleData.flatMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance. + /// + /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the + /// same failure. + public func flatMap(_ transform: (Value) throws -> T) -> Result { + switch self { + case .success(let value): + do { + return try .success(transform(value)) + } catch { + return .failure(error) + } + case .failure(let error): + return .failure(error) + } + } + + /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `mapError` function with a closure that does not throw. For example: + /// + /// let possibleData: Result = .failure(someError) + /// let withMyError: Result = possibleData.mapError { MyError.error($0) } + /// + /// - Parameter transform: A closure that takes the error of the instance. + /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns + /// the same instance. + public func mapError(_ transform: (Error) -> T) -> Result { + switch self { + case .failure(let error): + return .failure(transform(error)) + case .success: + return self + } + } + + /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `flatMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: Result = .success(Data(...)) + /// let possibleObject = possibleData.flatMapError { + /// try someFailableFunction(taking: $0) + /// } + /// + /// - Parameter transform: A throwing closure that takes the error of the instance. + /// + /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns + /// the same instance. + public func flatMapError(_ transform: (Error) throws -> T) -> Result { + switch self { + case .failure(let error): + do { + return try .failure(transform(error)) + } catch { + return .failure(error) + } + case .success: + return self + } + } + + /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. + /// + /// Use the `withValue` function to evaluate the passed closure without modifying the `Result` instance. + /// + /// - Parameter closure: A closure that takes the success value of this instance. + /// - Returns: This `Result` instance, unmodified. + @discardableResult + public func withValue(_ closure: (Value) -> Void) -> Result { + if case let .success(value) = self { closure(value) } + + return self + } + + /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `withError` function to evaluate the passed closure without modifying the `Result` instance. + /// + /// - Parameter closure: A closure that takes the success value of this instance. + /// - Returns: This `Result` instance, unmodified. + @discardableResult + public func withError(_ closure: (Error) -> Void) -> Result { + if case let .failure(error) = self { closure(error) } + + return self + } + + /// Evaluates the specified closure when the `Result` is a success. + /// + /// Use the `ifSuccess` function to evaluate the passed closure without modifying the `Result` instance. + /// + /// - Parameter closure: A `Void` closure. + /// - Returns: This `Result` instance, unmodified. + @discardableResult + public func ifSuccess(_ closure: () -> Void) -> Result { + if isSuccess { closure() } + + return self + } + + /// Evaluates the specified closure when the `Result` is a failure. + /// + /// Use the `ifFailure` function to evaluate the passed closure without modifying the `Result` instance. + /// + /// - Parameter closure: A `Void` closure. + /// - Returns: This `Result` instance, unmodified. + @discardableResult + public func ifFailure(_ closure: () -> Void) -> Result { + if isFailure { closure() } + + return self + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift new file mode 100644 index 0000000000..9c0e7c8d50 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift @@ -0,0 +1,307 @@ +// +// 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. +open class ServerTrustPolicyManager { + /// The dictionary of policies mapped to a particular host. + open 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. + open func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? { + return policies[host] + } +} + +// MARK: - + +extension URLSession { + private struct AssociatedKeys { + static var managerKey = "URLSession.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. +/// +/// - performRevokedEvaluation: Uses the default and revoked server trust evaluations allowing you to control whether to +/// validate the host provided by the challenge as well as specify the revocation flags for +/// testing for revoked certificates. Apple platforms did not start testing for revoked +/// certificates automatically until iOS 10.1, macOS 10.12 and tvOS 10.1 which is +/// demonstrated in our TLS tests. 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 performRevokedEvaluation(validateHost: Bool, revocationFlags: CFOptionFlags) + 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 certificates(in bundle: Bundle = Bundle.main) -> [SecCertificate] { + var certificates: [SecCertificate] = [] + + let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in + bundle.paths(forResourcesOfType: fileExtension, inDirectory: nil) + }.joined()) + + for path in paths { + if + let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData, + let 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 publicKeys(in bundle: Bundle = Bundle.main) -> [SecKey] { + var publicKeys: [SecKey] = [] + + for certificate in certificates(in: bundle) { + if let publicKey = publicKey(for: 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 evaluate(_ serverTrust: SecTrust, forHost 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 .performRevokedEvaluation(validateHost, revocationFlags): + let defaultPolicy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + let revokedPolicy = SecPolicyCreateRevocation(revocationFlags) + SecTrustSetPolicies(serverTrust, [defaultPolicy, revokedPolicy] as CFTypeRef) + + 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 as CFArray) + SecTrustSetAnchorCertificatesOnly(serverTrust, true) + + serverTrustIsValid = trustIsValid(serverTrust) + } else { + let serverCertificatesDataArray = certificateData(for: serverTrust) + let pinnedCertificatesDataArray = certificateData(for: pinnedCertificates) + + outerLoop: for serverCertificateData in serverCertificatesDataArray { + for pinnedCertificateData in pinnedCertificatesDataArray { + if serverCertificateData == 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.publicKeys(for: 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, host) + } + + return serverTrustIsValid + } + + // MARK: - Private - Trust Validation + + private func trustIsValid(_ trust: SecTrust) -> Bool { + var isValid = false + + var result = SecTrustResultType.invalid + let status = SecTrustEvaluate(trust, &result) + + if status == errSecSuccess { + let unspecified = SecTrustResultType.unspecified + let proceed = SecTrustResultType.proceed + + + isValid = result == unspecified || result == proceed + } + + return isValid + } + + // MARK: - Private - Certificate Data + + private func certificateData(for trust: SecTrust) -> [Data] { + var certificates: [SecCertificate] = [] + + for index in 0.. [Data] { + return certificates.map { SecCertificateCopyData($0) as Data } + } + + // MARK: - Private - Public Key Extraction + + private static func publicKeys(for trust: SecTrust) -> [SecKey] { + var publicKeys: [SecKey] = [] + + for index in 0.. SecKey? { + var publicKey: SecKey? + + let policy = SecPolicyCreateBasicX509() + var trust: SecTrust? + let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust) + + if let trust = trust, trustCreationStatus == errSecSuccess { + publicKey = SecTrustCopyPublicKey(trust) + } + + return publicKey + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/SessionDelegate.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/SessionDelegate.swift new file mode 100644 index 0000000000..8edb492b69 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/SessionDelegate.swift @@ -0,0 +1,719 @@ +// +// SessionDelegate.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 handling all delegate callbacks for the underlying session. +open class SessionDelegate: NSObject { + + // MARK: URLSessionDelegate Overrides + + /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didBecomeInvalidWithError:)`. + open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)? + + /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`. + open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + + /// Overrides all behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)` and requires the caller to call the `completionHandler`. + open var sessionDidReceiveChallengeWithCompletion: ((URLSession, URLAuthenticationChallenge, @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`. + open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)? + + // MARK: URLSessionTaskDelegate Overrides + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`. + open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? + + /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` and + /// requires the caller to call the `completionHandler`. + open var taskWillPerformHTTPRedirectionWithCompletion: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest, @escaping (URLRequest?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)`. + open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + + /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)` and + /// requires the caller to call the `completionHandler`. + open var taskDidReceiveChallengeWithCompletion: ((URLSession, URLSessionTask, URLAuthenticationChallenge, @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)`. + open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? + + /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)` and + /// requires the caller to call the `completionHandler`. + open var taskNeedNewBodyStreamWithCompletion: ((URLSession, URLSessionTask, @escaping (InputStream?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)`. + open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didCompleteWithError:)`. + open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)? + + // MARK: URLSessionDataDelegate Overrides + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)`. + open var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? + + /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)` and + /// requires caller to call the `completionHandler`. + open var dataTaskDidReceiveResponseWithCompletion: ((URLSession, URLSessionDataTask, URLResponse, @escaping (URLSession.ResponseDisposition) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didBecome:)`. + open var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:)`. + open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`. + open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? + + /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)` and + /// requires caller to call the `completionHandler`. + open var dataTaskWillCacheResponseWithCompletion: ((URLSession, URLSessionDataTask, CachedURLResponse, @escaping (CachedURLResponse?) -> Void) -> Void)? + + // MARK: URLSessionDownloadDelegate Overrides + + /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didFinishDownloadingTo:)`. + open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)? + + /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)`. + open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + + /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)`. + open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? + + // MARK: URLSessionStreamDelegate Overrides + +#if !os(watchOS) + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:readClosedFor:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskReadClosed: ((URLSession, URLSessionStreamTask) -> Void)? { + get { + return _streamTaskReadClosed as? (URLSession, URLSessionStreamTask) -> Void + } + set { + _streamTaskReadClosed = newValue + } + } + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:writeClosedFor:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskWriteClosed: ((URLSession, URLSessionStreamTask) -> Void)? { + get { + return _streamTaskWriteClosed as? (URLSession, URLSessionStreamTask) -> Void + } + set { + _streamTaskWriteClosed = newValue + } + } + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:betterRouteDiscoveredFor:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskBetterRouteDiscovered: ((URLSession, URLSessionStreamTask) -> Void)? { + get { + return _streamTaskBetterRouteDiscovered as? (URLSession, URLSessionStreamTask) -> Void + } + set { + _streamTaskBetterRouteDiscovered = newValue + } + } + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:streamTask:didBecome:outputStream:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskDidBecomeInputAndOutputStreams: ((URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void)? { + get { + return _streamTaskDidBecomeInputStream as? (URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void + } + set { + _streamTaskDidBecomeInputStream = newValue + } + } + + var _streamTaskReadClosed: Any? + var _streamTaskWriteClosed: Any? + var _streamTaskBetterRouteDiscovered: Any? + var _streamTaskDidBecomeInputStream: Any? + +#endif + + // MARK: Properties + + var retrier: RequestRetrier? + weak var sessionManager: SessionManager? + + private var requests: [Int: Request] = [:] + private let lock = NSLock() + + /// Access the task delegate for the specified task in a thread-safe manner. + open subscript(task: URLSessionTask) -> Request? { + get { + lock.lock() ; defer { lock.unlock() } + return requests[task.taskIdentifier] + } + set { + lock.lock() ; defer { lock.unlock() } + requests[task.taskIdentifier] = newValue + } + } + + // MARK: Lifecycle + + /// Initializes the `SessionDelegate` instance. + /// + /// - returns: The new `SessionDelegate` instance. + public override init() { + super.init() + } + + // MARK: NSObject Overrides + + /// Returns a `Bool` indicating whether the `SessionDelegate` implements or inherits a method that can respond + /// to a specified message. + /// + /// - parameter selector: A selector that identifies a message. + /// + /// - returns: `true` if the receiver implements or inherits a method that can respond to selector, otherwise `false`. + open override func responds(to selector: Selector) -> Bool { + #if !os(macOS) + if selector == #selector(URLSessionDelegate.urlSessionDidFinishEvents(forBackgroundURLSession:)) { + return sessionDidFinishEventsForBackgroundURLSession != nil + } + #endif + + #if !os(watchOS) + if #available(iOS 9.0, macOS 10.11, tvOS 9.0, *) { + switch selector { + case #selector(URLSessionStreamDelegate.urlSession(_:readClosedFor:)): + return streamTaskReadClosed != nil + case #selector(URLSessionStreamDelegate.urlSession(_:writeClosedFor:)): + return streamTaskWriteClosed != nil + case #selector(URLSessionStreamDelegate.urlSession(_:betterRouteDiscoveredFor:)): + return streamTaskBetterRouteDiscovered != nil + case #selector(URLSessionStreamDelegate.urlSession(_:streamTask:didBecome:outputStream:)): + return streamTaskDidBecomeInputAndOutputStreams != nil + default: + break + } + } + #endif + + switch selector { + case #selector(URLSessionDelegate.urlSession(_:didBecomeInvalidWithError:)): + return sessionDidBecomeInvalidWithError != nil + case #selector(URLSessionDelegate.urlSession(_:didReceive:completionHandler:)): + return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil) + case #selector(URLSessionTaskDelegate.urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)): + return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil) + case #selector(URLSessionDataDelegate.urlSession(_:dataTask:didReceive:completionHandler:)): + return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil) + default: + return type(of: self).instancesRespond(to: selector) + } + } +} + +// MARK: - URLSessionDelegate + +extension SessionDelegate: URLSessionDelegate { + /// 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. + open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { + 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. + open func urlSession( + _ session: URLSession, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + guard sessionDidReceiveChallengeWithCompletion == nil else { + sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler) + return + } + + var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling + var credential: URLCredential? + + 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?.serverTrustPolicy(forHost: host), + let serverTrust = challenge.protectionSpace.serverTrust + { + if serverTrustPolicy.evaluate(serverTrust, forHost: host) { + disposition = .useCredential + credential = URLCredential(trust: serverTrust) + } else { + disposition = .cancelAuthenticationChallenge + } + } + } + + completionHandler(disposition, credential) + } + +#if !os(macOS) + + /// Tells the delegate that all messages enqueued for a session have been delivered. + /// + /// - parameter session: The session that no longer has any outstanding requests. + open func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { + sessionDidFinishEventsForBackgroundURLSession?(session) + } + +#endif +} + +// MARK: - URLSessionTaskDelegate + +extension SessionDelegate: URLSessionTaskDelegate { + /// 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. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) + { + guard taskWillPerformHTTPRedirectionWithCompletion == nil else { + taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler) + return + } + + var redirectRequest: URLRequest? = 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. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + guard taskDidReceiveChallengeWithCompletion == nil else { + taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler) + return + } + + if let taskDidReceiveChallenge = taskDidReceiveChallenge { + let result = taskDidReceiveChallenge(session, task, challenge) + completionHandler(result.0, result.1) + } else if let delegate = self[task]?.delegate { + delegate.urlSession( + session, + task: task, + didReceive: challenge, + completionHandler: completionHandler + ) + } else { + urlSession(session, didReceive: 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. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) + { + guard taskNeedNewBodyStreamWithCompletion == nil else { + taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler) + return + } + + if let taskNeedNewBodyStream = taskNeedNewBodyStream { + completionHandler(taskNeedNewBodyStream(session, task)) + } else if let delegate = self[task]?.delegate { + 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. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) + { + if let taskDidSendBodyData = taskDidSendBodyData { + taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) + } else if let delegate = self[task]?.delegate as? UploadTaskDelegate { + delegate.URLSession( + session, + task: task, + didSendBodyData: bytesSent, + totalBytesSent: totalBytesSent, + totalBytesExpectedToSend: totalBytesExpectedToSend + ) + } + } + +#if !os(watchOS) + + /// Tells the delegate that the session finished collecting metrics for the task. + /// + /// - parameter session: The session collecting the metrics. + /// - parameter task: The task whose metrics have been collected. + /// - parameter metrics: The collected metrics. + @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) + @objc(URLSession:task:didFinishCollectingMetrics:) + open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { + self[task]?.delegate.metrics = metrics + } + +#endif + + /// 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. + open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + /// Executed after it is determined that the request is not going to be retried + let completeTask: (URLSession, URLSessionTask, Error?) -> Void = { [weak self] session, task, error in + guard let strongSelf = self else { return } + + strongSelf.taskDidComplete?(session, task, error) + + strongSelf[task]?.delegate.urlSession(session, task: task, didCompleteWithError: error) + + NotificationCenter.default.post( + name: Notification.Name.Task.DidComplete, + object: strongSelf, + userInfo: [Notification.Key.Task: task] + ) + + strongSelf[task] = nil + } + + guard let request = self[task], let sessionManager = sessionManager else { + completeTask(session, task, error) + return + } + + // Run all validations on the request before checking if an error occurred + request.validations.forEach { $0() } + + // Determine whether an error has occurred + var error: Error? = error + + if request.delegate.error != nil { + error = request.delegate.error + } + + /// If an error occurred and the retrier is set, asynchronously ask the retrier if the request + /// should be retried. Otherwise, complete the task by notifying the task delegate. + if let retrier = retrier, let error = error { + retrier.should(sessionManager, retry: request, with: error) { [weak self] shouldRetry, timeDelay in + guard shouldRetry else { completeTask(session, task, error) ; return } + + DispatchQueue.utility.after(timeDelay) { [weak self] in + guard let strongSelf = self else { return } + + let retrySucceeded = strongSelf.sessionManager?.retry(request) ?? false + + if retrySucceeded, let task = request.task { + strongSelf[task] = request + return + } else { + completeTask(session, task, error) + } + } + } + } else { + completeTask(session, task, error) + } + } +} + +// MARK: - URLSessionDataDelegate + +extension SessionDelegate: URLSessionDataDelegate { + /// 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. + open func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didReceive response: URLResponse, + completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) + { + guard dataTaskDidReceiveResponseWithCompletion == nil else { + dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler) + return + } + + var disposition: URLSession.ResponseDisposition = .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. + open func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didBecome downloadTask: URLSessionDownloadTask) + { + if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask { + dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask) + } else { + self[downloadTask]?.delegate = DownloadTaskDelegate(task: downloadTask) + } + } + + /// 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. + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + if let dataTaskDidReceiveData = dataTaskDidReceiveData { + dataTaskDidReceiveData(session, dataTask, data) + } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { + delegate.urlSession(session, dataTask: dataTask, didReceive: 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. + open func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse, + completionHandler: @escaping (CachedURLResponse?) -> Void) + { + guard dataTaskWillCacheResponseWithCompletion == nil else { + dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler) + return + } + + if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { + completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) + } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { + delegate.urlSession( + session, + dataTask: dataTask, + willCacheResponse: proposedResponse, + completionHandler: completionHandler + ) + } else { + completionHandler(proposedResponse) + } + } +} + +// MARK: - URLSessionDownloadDelegate + +extension SessionDelegate: URLSessionDownloadDelegate { + /// 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. + open func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didFinishDownloadingTo location: URL) + { + if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { + downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) + } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { + delegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: 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`. + open func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) + { + if let downloadTaskDidWriteData = downloadTaskDidWriteData { + downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) + } else if let delegate = self[downloadTask]?.delegate as? 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. + open func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) + { + if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { + downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) + } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { + delegate.urlSession( + session, + downloadTask: downloadTask, + didResumeAtOffset: fileOffset, + expectedTotalBytes: expectedTotalBytes + ) + } + } +} + +// MARK: - URLSessionStreamDelegate + +#if !os(watchOS) + +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +extension SessionDelegate: URLSessionStreamDelegate { + /// Tells the delegate that the read side of the connection has been closed. + /// + /// - parameter session: The session. + /// - parameter streamTask: The stream task. + open func urlSession(_ session: URLSession, readClosedFor streamTask: URLSessionStreamTask) { + 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. + open func urlSession(_ session: URLSession, writeClosedFor streamTask: URLSessionStreamTask) { + 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. + open func urlSession(_ session: URLSession, betterRouteDiscoveredFor streamTask: URLSessionStreamTask) { + 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. + open func urlSession( + _ session: URLSession, + streamTask: URLSessionStreamTask, + didBecome inputStream: InputStream, + outputStream: OutputStream) + { + streamTaskDidBecomeInputAndOutputStreams?(session, streamTask, inputStream, outputStream) + } +} + +#endif diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/SessionManager.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/SessionManager.swift new file mode 100644 index 0000000000..493ce29cb4 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/SessionManager.swift @@ -0,0 +1,899 @@ +// +// SessionManager.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`. +open class SessionManager { + + // MARK: - Helper Types + + /// 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 `UploadRequest` 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: UploadRequest, streamingFromDisk: Bool, streamFileURL: URL?) + case failure(Error) + } + + // MARK: - Properties + + /// A default instance of `SessionManager`, used by top-level Alamofire request methods, and suitable for use + /// directly for any ad hoc requests. + open static let `default`: SessionManager = { + let configuration = URLSessionConfiguration.default + configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders + + return SessionManager(configuration: configuration) + }() + + /// Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. + open static let defaultHTTPHeaders: HTTPHeaders = { + // 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 + #if swift(>=4.0) + let acceptLanguage = Locale.preferredLanguages.prefix(6).enumerated().map { enumeratedLanguage in + let (index, languageCode) = enumeratedLanguage + let quality = 1.0 - (Double(index) * 0.1) + return "\(languageCode);q=\(quality)" + }.joined(separator: ", ") + #else + let acceptLanguage = Locale.preferredLanguages.prefix(6).enumerated().map { index, languageCode in + let quality = 1.0 - (Double(index) * 0.1) + return "\(languageCode);q=\(quality)" + }.joined(separator: ", ") + #endif + + // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 + // Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0` + let userAgent: String = { + if let info = Bundle.main.infoDictionary { + let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" + let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" + let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown" + let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown" + + let osNameVersion: String = { + let version = ProcessInfo.processInfo.operatingSystemVersion + let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" + + let osName: String = { + #if os(iOS) + return "iOS" + #elseif os(watchOS) + return "watchOS" + #elseif os(tvOS) + return "tvOS" + #elseif os(macOS) + return "OS X" + #elseif os(Linux) + return "Linux" + #else + return "Unknown" + #endif + }() + + return "\(osName) \(versionString)" + }() + + let alamofireVersion: String = { + guard + let afInfo = Bundle(for: SessionManager.self).infoDictionary, + let build = afInfo["CFBundleShortVersionString"] + else { return "Unknown" } + + return "Alamofire/\(build)" + }() + + return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)" + } + + return "Alamofire" + }() + + return [ + "Accept-Encoding": acceptEncoding, + "Accept-Language": acceptLanguage, + "User-Agent": userAgent + ] + }() + + /// Default memory threshold used when encoding `MultipartFormData` in bytes. + open static let multipartFormDataEncodingMemoryThreshold: UInt64 = 10_000_000 + + /// The underlying session. + open let session: URLSession + + /// The session delegate handling all the task and session delegate callbacks. + open let delegate: SessionDelegate + + /// Whether to start requests immediately after being constructed. `true` by default. + open var startRequestsImmediately: Bool = true + + /// The request adapter called each time a new request is created. + open var adapter: RequestAdapter? + + /// The request retrier called each time a request encounters an error to determine whether to retry the request. + open var retrier: RequestRetrier? { + get { return delegate.retrier } + set { delegate.retrier = newValue } + } + + /// 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. + open var backgroundCompletionHandler: (() -> Void)? + + let queue = DispatchQueue(label: "org.alamofire.session-manager." + UUID().uuidString) + + // MARK: - Lifecycle + + /// Creates an instance with the specified `configuration`, `delegate` and `serverTrustPolicyManager`. + /// + /// - parameter configuration: The configuration used to construct the managed session. + /// `URLSessionConfiguration.default` 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 `SessionManager` instance. + public init( + configuration: URLSessionConfiguration = URLSessionConfiguration.default, + delegate: SessionDelegate = SessionDelegate(), + serverTrustPolicyManager: ServerTrustPolicyManager? = nil) + { + self.delegate = delegate + self.session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) + + commonInit(serverTrustPolicyManager: serverTrustPolicyManager) + } + + /// Creates an instance with the specified `session`, `delegate` and `serverTrustPolicyManager`. + /// + /// - 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 `SessionManager` instance if the URL session's delegate matches; `nil` otherwise. + public init?( + session: URLSession, + delegate: SessionDelegate, + serverTrustPolicyManager: ServerTrustPolicyManager? = nil) + { + guard delegate === session.delegate else { return nil } + + self.delegate = delegate + self.session = session + + commonInit(serverTrustPolicyManager: serverTrustPolicyManager) + } + + private func commonInit(serverTrustPolicyManager: ServerTrustPolicyManager?) { + session.serverTrustPolicyManager = serverTrustPolicyManager + + delegate.sessionManager = self + + delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in + guard let strongSelf = self else { return } + DispatchQueue.main.async { strongSelf.backgroundCompletionHandler?() } + } + } + + deinit { + session.invalidateAndCancel() + } + + // MARK: - Data Request + + /// Creates a `DataRequest` to retrieve the contents of the specified `url`, `method`, `parameters`, `encoding` + /// and `headers`. + /// + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.get` by default. + /// - parameter parameters: The parameters. `nil` by default. + /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `DataRequest`. + @discardableResult + open func request( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil) + -> DataRequest + { + var originalRequest: URLRequest? + + do { + originalRequest = try URLRequest(url: url, method: method, headers: headers) + let encodedURLRequest = try encoding.encode(originalRequest!, with: parameters) + return request(encodedURLRequest) + } catch { + return request(originalRequest, failedWith: error) + } + } + + /// Creates a `DataRequest` to retrieve the contents of a URL based on the specified `urlRequest`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `DataRequest`. + open func request(_ urlRequest: URLRequestConvertible) -> DataRequest { + var originalRequest: URLRequest? + + do { + originalRequest = try urlRequest.asURLRequest() + let originalTask = DataRequest.Requestable(urlRequest: originalRequest!) + + let task = try originalTask.task(session: session, adapter: adapter, queue: queue) + let request = DataRequest(session: session, requestTask: .data(originalTask, task)) + + delegate[task] = request + + if startRequestsImmediately { request.resume() } + + return request + } catch { + return request(originalRequest, failedWith: error) + } + } + + // MARK: Private - Request Implementation + + private func request(_ urlRequest: URLRequest?, failedWith error: Error) -> DataRequest { + var requestTask: Request.RequestTask = .data(nil, nil) + + if let urlRequest = urlRequest { + let originalTask = DataRequest.Requestable(urlRequest: urlRequest) + requestTask = .data(originalTask, nil) + } + + let underlyingError = error.underlyingAdaptError ?? error + let request = DataRequest(session: session, requestTask: requestTask, error: underlyingError) + + if let retrier = retrier, error is AdaptError { + allowRetrier(retrier, toRetry: request, with: underlyingError) + } else { + if startRequestsImmediately { request.resume() } + } + + return request + } + + // MARK: - Download Request + + // MARK: URL Request + + /// Creates a `DownloadRequest` to retrieve the contents the specified `url`, `method`, `parameters`, `encoding`, + /// `headers` and save them to the `destination`. + /// + /// If `destination` is not specified, the contents will remain in the temporary location determined by the + /// underlying URL session. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.get` by default. + /// - parameter parameters: The parameters. `nil` by default. + /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. + /// + /// - returns: The created `DownloadRequest`. + @discardableResult + open func download( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + let encodedURLRequest = try encoding.encode(urlRequest, with: parameters) + return download(encodedURLRequest, to: destination) + } catch { + return download(nil, to: destination, failedWith: error) + } + } + + /// Creates a `DownloadRequest` to retrieve the contents of a URL based on the specified `urlRequest` and save + /// them to the `destination`. + /// + /// If `destination` is not specified, the contents will remain in the temporary location determined by the + /// underlying URL session. + /// + /// 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. `nil` by default. + /// + /// - returns: The created `DownloadRequest`. + @discardableResult + open func download( + _ urlRequest: URLRequestConvertible, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest + { + do { + let urlRequest = try urlRequest.asURLRequest() + return download(.request(urlRequest), to: destination) + } catch { + return download(nil, to: destination, failedWith: error) + } + } + + // MARK: Resume Data + + /// Creates a `DownloadRequest` from the `resumeData` produced from a previous request cancellation to retrieve + /// the contents of the original request and save them to the `destination`. + /// + /// If `destination` is not specified, the contents will remain in the temporary location determined by the + /// underlying URL session. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken + /// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the + /// data is written incorrectly and will always fail to resume the download. For more information about the bug and + /// possible workarounds, please refer to the following Stack Overflow post: + /// + /// - http://stackoverflow.com/a/39347461/1342462 + /// + /// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` + /// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for + /// additional information. + /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. + /// + /// - returns: The created `DownloadRequest`. + @discardableResult + open func download( + resumingWith resumeData: Data, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest + { + return download(.resumeData(resumeData), to: destination) + } + + // MARK: Private - Download Implementation + + private func download( + _ downloadable: DownloadRequest.Downloadable, + to destination: DownloadRequest.DownloadFileDestination?) + -> DownloadRequest + { + do { + let task = try downloadable.task(session: session, adapter: adapter, queue: queue) + let download = DownloadRequest(session: session, requestTask: .download(downloadable, task)) + + download.downloadDelegate.destination = destination + + delegate[task] = download + + if startRequestsImmediately { download.resume() } + + return download + } catch { + return download(downloadable, to: destination, failedWith: error) + } + } + + private func download( + _ downloadable: DownloadRequest.Downloadable?, + to destination: DownloadRequest.DownloadFileDestination?, + failedWith error: Error) + -> DownloadRequest + { + var downloadTask: Request.RequestTask = .download(nil, nil) + + if let downloadable = downloadable { + downloadTask = .download(downloadable, nil) + } + + let underlyingError = error.underlyingAdaptError ?? error + + let download = DownloadRequest(session: session, requestTask: downloadTask, error: underlyingError) + download.downloadDelegate.destination = destination + + if let retrier = retrier, error is AdaptError { + allowRetrier(retrier, toRetry: download, with: underlyingError) + } else { + if startRequestsImmediately { download.resume() } + } + + return download + } + + // MARK: - Upload Request + + // MARK: File + + /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `file`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter file: The file to upload. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload( + _ fileURL: URL, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + return upload(fileURL, with: urlRequest) + } catch { + return upload(nil, failedWith: error) + } + } + + /// Creates a `UploadRequest` from the specified `urlRequest` for uploading the `file`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter file: The file to upload. + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { + do { + let urlRequest = try urlRequest.asURLRequest() + return upload(.file(fileURL, urlRequest)) + } catch { + return upload(nil, failedWith: error) + } + } + + // MARK: Data + + /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `data`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter data: The data to upload. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload( + _ data: Data, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + return upload(data, with: urlRequest) + } catch { + return upload(nil, failedWith: error) + } + } + + /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `data`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter data: The data to upload. + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { + do { + let urlRequest = try urlRequest.asURLRequest() + return upload(.data(data, urlRequest)) + } catch { + return upload(nil, failedWith: error) + } + } + + // MARK: InputStream + + /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `stream`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter stream: The stream to upload. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload( + _ stream: InputStream, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + return upload(stream, with: urlRequest) + } catch { + return upload(nil, failedWith: error) + } + } + + /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `stream`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter stream: The stream to upload. + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { + do { + let urlRequest = try urlRequest.asURLRequest() + return upload(.stream(stream, urlRequest)) + } catch { + return upload(nil, failedWith: error) + } + } + + // MARK: MultipartFormData + + /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new + /// `UploadRequest` using the `url`, `method` and `headers`. + /// + /// 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 multipartFormData: The closure used to append body parts to the `MultipartFormData`. + /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + /// `multipartFormDataEncodingMemoryThreshold` by default. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. + open func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + + return upload( + multipartFormData: multipartFormData, + usingThreshold: encodingMemoryThreshold, + with: urlRequest, + encodingCompletion: encodingCompletion + ) + } catch { + DispatchQueue.main.async { encodingCompletion?(.failure(error)) } + } + } + + /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new + /// `UploadRequest` using the `urlRequest`. + /// + /// 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 multipartFormData: The closure used to append body parts to the `MultipartFormData`. + /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + /// `multipartFormDataEncodingMemoryThreshold` by default. + /// - parameter urlRequest: The URL request. + /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. + open func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + with urlRequest: URLRequestConvertible, + encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) + { + DispatchQueue.global(qos: .utility).async { + let formData = MultipartFormData() + multipartFormData(formData) + + var tempFileURL: URL? + + do { + var urlRequestWithContentType = try urlRequest.asURLRequest() + urlRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type") + + let isBackgroundSession = self.session.configuration.identifier != nil + + if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession { + let data = try formData.encode() + + let encodingResult = MultipartFormDataEncodingResult.success( + request: self.upload(data, with: urlRequestWithContentType), + streamingFromDisk: false, + streamFileURL: nil + ) + + DispatchQueue.main.async { encodingCompletion?(encodingResult) } + } else { + let fileManager = FileManager.default + let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory()) + let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data") + let fileName = UUID().uuidString + let fileURL = directoryURL.appendingPathComponent(fileName) + + tempFileURL = fileURL + + var directoryError: Error? + + // Create directory inside serial queue to ensure two threads don't do this in parallel + self.queue.sync { + do { + try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) + } catch { + directoryError = error + } + } + + if let directoryError = directoryError { throw directoryError } + + try formData.writeEncodedData(to: fileURL) + + let upload = self.upload(fileURL, with: urlRequestWithContentType) + + // Cleanup the temp file once the upload is complete + upload.delegate.queue.addOperation { + do { + try FileManager.default.removeItem(at: fileURL) + } catch { + // No-op + } + } + + DispatchQueue.main.async { + let encodingResult = MultipartFormDataEncodingResult.success( + request: upload, + streamingFromDisk: true, + streamFileURL: fileURL + ) + + encodingCompletion?(encodingResult) + } + } + } catch { + // Cleanup the temp file in the event that the multipart form data encoding failed + if let tempFileURL = tempFileURL { + do { + try FileManager.default.removeItem(at: tempFileURL) + } catch { + // No-op + } + } + + DispatchQueue.main.async { encodingCompletion?(.failure(error)) } + } + } + } + + // MARK: Private - Upload Implementation + + private func upload(_ uploadable: UploadRequest.Uploadable) -> UploadRequest { + do { + let task = try uploadable.task(session: session, adapter: adapter, queue: queue) + let upload = UploadRequest(session: session, requestTask: .upload(uploadable, task)) + + if case let .stream(inputStream, _) = uploadable { + upload.delegate.taskNeedNewBodyStream = { _, _ in inputStream } + } + + delegate[task] = upload + + if startRequestsImmediately { upload.resume() } + + return upload + } catch { + return upload(uploadable, failedWith: error) + } + } + + private func upload(_ uploadable: UploadRequest.Uploadable?, failedWith error: Error) -> UploadRequest { + var uploadTask: Request.RequestTask = .upload(nil, nil) + + if let uploadable = uploadable { + uploadTask = .upload(uploadable, nil) + } + + let underlyingError = error.underlyingAdaptError ?? error + let upload = UploadRequest(session: session, requestTask: uploadTask, error: underlyingError) + + if let retrier = retrier, error is AdaptError { + allowRetrier(retrier, toRetry: upload, with: underlyingError) + } else { + if startRequestsImmediately { upload.resume() } + } + + return upload + } + +#if !os(watchOS) + + // MARK: - Stream Request + + // MARK: Hostname and Port + + /// Creates a `StreamRequest` for bidirectional streaming using the `hostname` and `port`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter hostName: The hostname of the server to connect to. + /// - parameter port: The port of the server to connect to. + /// + /// - returns: The created `StreamRequest`. + @discardableResult + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open func stream(withHostName hostName: String, port: Int) -> StreamRequest { + return stream(.stream(hostName: hostName, port: port)) + } + + // MARK: NetService + + /// Creates a `StreamRequest` for bidirectional streaming using the `netService`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter netService: The net service used to identify the endpoint. + /// + /// - returns: The created `StreamRequest`. + @discardableResult + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open func stream(with netService: NetService) -> StreamRequest { + return stream(.netService(netService)) + } + + // MARK: Private - Stream Implementation + + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + private func stream(_ streamable: StreamRequest.Streamable) -> StreamRequest { + do { + let task = try streamable.task(session: session, adapter: adapter, queue: queue) + let request = StreamRequest(session: session, requestTask: .stream(streamable, task)) + + delegate[task] = request + + if startRequestsImmediately { request.resume() } + + return request + } catch { + return stream(failedWith: error) + } + } + + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + private func stream(failedWith error: Error) -> StreamRequest { + let stream = StreamRequest(session: session, requestTask: .stream(nil, nil), error: error) + if startRequestsImmediately { stream.resume() } + return stream + } + +#endif + + // MARK: - Internal - Retry Request + + func retry(_ request: Request) -> Bool { + guard let originalTask = request.originalTask else { return false } + + do { + let task = try originalTask.task(session: session, adapter: adapter, queue: queue) + + request.delegate.task = task // resets all task delegate data + + request.retryCount += 1 + request.startTime = CFAbsoluteTimeGetCurrent() + request.endTime = nil + + task.resume() + + return true + } catch { + request.delegate.error = error.underlyingAdaptError ?? error + return false + } + } + + private func allowRetrier(_ retrier: RequestRetrier, toRetry request: Request, with error: Error) { + DispatchQueue.utility.async { [weak self] in + guard let strongSelf = self else { return } + + retrier.should(strongSelf, retry: request, with: error) { shouldRetry, timeDelay in + guard let strongSelf = self else { return } + + guard shouldRetry else { + if strongSelf.startRequestsImmediately { request.resume() } + return + } + + DispatchQueue.utility.after(timeDelay) { + guard let strongSelf = self else { return } + + let retrySucceeded = strongSelf.retry(request) + + if retrySucceeded, let task = request.task { + strongSelf.delegate[task] = request + } else { + if strongSelf.startRequestsImmediately { request.resume() } + } + } + } + } + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/TaskDelegate.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/TaskDelegate.swift new file mode 100644 index 0000000000..d4fd2163c1 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/TaskDelegate.swift @@ -0,0 +1,453 @@ +// +// TaskDelegate.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 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. +open class TaskDelegate: NSObject { + + // MARK: Properties + + /// The serial operation queue used to execute all operations after the task completes. + open let queue: OperationQueue + + /// The data returned by the server. + public var data: Data? { return nil } + + /// The error generated throughout the lifecyle of the task. + public var error: Error? + + var task: URLSessionTask? { + didSet { reset() } + } + + var initialResponseTime: CFAbsoluteTime? + var credential: URLCredential? + var metrics: AnyObject? // URLSessionTaskMetrics + + // MARK: Lifecycle + + init(task: URLSessionTask?) { + self.task = task + + self.queue = { + let operationQueue = OperationQueue() + + operationQueue.maxConcurrentOperationCount = 1 + operationQueue.isSuspended = true + operationQueue.qualityOfService = .utility + + return operationQueue + }() + } + + func reset() { + error = nil + initialResponseTime = nil + } + + // MARK: URLSessionTaskDelegate + + var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? + var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? + var taskDidCompleteWithError: ((URLSession, URLSessionTask, Error?) -> Void)? + + @objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:) + func urlSession( + _ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) + { + var redirectRequest: URLRequest? = request + + if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { + redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) + } + + completionHandler(redirectRequest) + } + + @objc(URLSession:task:didReceiveChallenge:completionHandler:) + func urlSession( + _ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling + var credential: URLCredential? + + 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?.serverTrustPolicy(forHost: host), + let serverTrust = challenge.protectionSpace.serverTrust + { + if serverTrustPolicy.evaluate(serverTrust, forHost: host) { + disposition = .useCredential + credential = URLCredential(trust: serverTrust) + } else { + disposition = .cancelAuthenticationChallenge + } + } + } else { + if challenge.previousFailureCount > 0 { + disposition = .rejectProtectionSpace + } else { + credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace) + + if credential != nil { + disposition = .useCredential + } + } + } + + completionHandler(disposition, credential) + } + + @objc(URLSession:task:needNewBodyStream:) + func urlSession( + _ session: URLSession, + task: URLSessionTask, + needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) + { + var bodyStream: InputStream? + + if let taskNeedNewBodyStream = taskNeedNewBodyStream { + bodyStream = taskNeedNewBodyStream(session, task) + } + + completionHandler(bodyStream) + } + + @objc(URLSession:task:didCompleteWithError:) + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + if let taskDidCompleteWithError = taskDidCompleteWithError { + taskDidCompleteWithError(session, task, error) + } else { + if let error = error { + if self.error == nil { self.error = error } + + if + let downloadDelegate = self as? DownloadTaskDelegate, + let resumeData = (error as NSError).userInfo[NSURLSessionDownloadTaskResumeData] as? Data + { + downloadDelegate.resumeData = resumeData + } + } + + queue.isSuspended = false + } + } +} + +// MARK: - + +class DataTaskDelegate: TaskDelegate, URLSessionDataDelegate { + + // MARK: Properties + + var dataTask: URLSessionDataTask { return task as! URLSessionDataTask } + + override var data: Data? { + if dataStream != nil { + return nil + } else { + return mutableData + } + } + + var progress: Progress + var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? + + var dataStream: ((_ data: Data) -> Void)? + + private var totalBytesReceived: Int64 = 0 + private var mutableData: Data + + private var expectedContentLength: Int64? + + // MARK: Lifecycle + + override init(task: URLSessionTask?) { + mutableData = Data() + progress = Progress(totalUnitCount: 0) + + super.init(task: task) + } + + override func reset() { + super.reset() + + progress = Progress(totalUnitCount: 0) + totalBytesReceived = 0 + mutableData = Data() + expectedContentLength = nil + } + + // MARK: URLSessionDataDelegate + + var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? + var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? + var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? + var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? + + func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didReceive response: URLResponse, + completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) + { + var disposition: URLSession.ResponseDisposition = .allow + + expectedContentLength = response.expectedContentLength + + if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { + disposition = dataTaskDidReceiveResponse(session, dataTask, response) + } + + completionHandler(disposition) + } + + func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didBecome downloadTask: URLSessionDownloadTask) + { + dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask) + } + + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + + if let dataTaskDidReceiveData = dataTaskDidReceiveData { + dataTaskDidReceiveData(session, dataTask, data) + } else { + if let dataStream = dataStream { + dataStream(data) + } else { + mutableData.append(data) + } + + let bytesReceived = Int64(data.count) + totalBytesReceived += bytesReceived + let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown + + progress.totalUnitCount = totalBytesExpected + progress.completedUnitCount = totalBytesReceived + + if let progressHandler = progressHandler { + progressHandler.queue.async { progressHandler.closure(self.progress) } + } + } + } + + func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse, + completionHandler: @escaping (CachedURLResponse?) -> Void) + { + var cachedResponse: CachedURLResponse? = proposedResponse + + if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { + cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse) + } + + completionHandler(cachedResponse) + } +} + +// MARK: - + +class DownloadTaskDelegate: TaskDelegate, URLSessionDownloadDelegate { + + // MARK: Properties + + var downloadTask: URLSessionDownloadTask { return task as! URLSessionDownloadTask } + + var progress: Progress + var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? + + var resumeData: Data? + override var data: Data? { return resumeData } + + var destination: DownloadRequest.DownloadFileDestination? + + var temporaryURL: URL? + var destinationURL: URL? + + var fileURL: URL? { return destination != nil ? destinationURL : temporaryURL } + + // MARK: Lifecycle + + override init(task: URLSessionTask?) { + progress = Progress(totalUnitCount: 0) + super.init(task: task) + } + + override func reset() { + super.reset() + + progress = Progress(totalUnitCount: 0) + resumeData = nil + } + + // MARK: URLSessionDownloadDelegate + + var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> URL)? + var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? + + func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didFinishDownloadingTo location: URL) + { + temporaryURL = location + + guard + let destination = destination, + let response = downloadTask.response as? HTTPURLResponse + else { return } + + let result = destination(location, response) + let destinationURL = result.destinationURL + let options = result.options + + self.destinationURL = destinationURL + + do { + if options.contains(.removePreviousFile), FileManager.default.fileExists(atPath: destinationURL.path) { + try FileManager.default.removeItem(at: destinationURL) + } + + if options.contains(.createIntermediateDirectories) { + let directory = destinationURL.deletingLastPathComponent() + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + + try FileManager.default.moveItem(at: location, to: destinationURL) + } catch { + self.error = error + } + } + + func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) + { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + + if let downloadTaskDidWriteData = downloadTaskDidWriteData { + downloadTaskDidWriteData( + session, + downloadTask, + bytesWritten, + totalBytesWritten, + totalBytesExpectedToWrite + ) + } else { + progress.totalUnitCount = totalBytesExpectedToWrite + progress.completedUnitCount = totalBytesWritten + + if let progressHandler = progressHandler { + progressHandler.queue.async { progressHandler.closure(self.progress) } + } + } + } + + func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) + { + if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { + downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) + } else { + progress.totalUnitCount = expectedTotalBytes + progress.completedUnitCount = fileOffset + } + } +} + +// MARK: - + +class UploadTaskDelegate: DataTaskDelegate { + + // MARK: Properties + + var uploadTask: URLSessionUploadTask { return task as! URLSessionUploadTask } + + var uploadProgress: Progress + var uploadProgressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? + + // MARK: Lifecycle + + override init(task: URLSessionTask?) { + uploadProgress = Progress(totalUnitCount: 0) + super.init(task: task) + } + + override func reset() { + super.reset() + uploadProgress = Progress(totalUnitCount: 0) + } + + // MARK: URLSessionTaskDelegate + + var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? + + func URLSession( + _ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) + { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + + if let taskDidSendBodyData = taskDidSendBodyData { + taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) + } else { + uploadProgress.totalUnitCount = totalBytesExpectedToSend + uploadProgress.completedUnitCount = totalBytesSent + + if let uploadProgressHandler = uploadProgressHandler { + uploadProgressHandler.queue.async { uploadProgressHandler.closure(self.uploadProgress) } + } + } + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Timeline.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Timeline.swift new file mode 100644 index 0000000000..1440989d5f --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Timeline.swift @@ -0,0 +1,136 @@ +// +// Timeline.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Responsible for computing the timing metrics for the complete lifecycle of a `Request`. +public struct Timeline { + /// The time the request was initialized. + public let requestStartTime: CFAbsoluteTime + + /// The time the first bytes were received from or sent to the server. + public let initialResponseTime: CFAbsoluteTime + + /// The time when the request was completed. + public let requestCompletedTime: CFAbsoluteTime + + /// The time when the response serialization was completed. + public let serializationCompletedTime: CFAbsoluteTime + + /// The time interval in seconds from the time the request started to the initial response from the server. + public let latency: TimeInterval + + /// The time interval in seconds from the time the request started to the time the request completed. + public let requestDuration: TimeInterval + + /// The time interval in seconds from the time the request completed to the time response serialization completed. + public let serializationDuration: TimeInterval + + /// The time interval in seconds from the time the request started to the time response serialization completed. + public let totalDuration: TimeInterval + + /// Creates a new `Timeline` instance with the specified request times. + /// + /// - parameter requestStartTime: The time the request was initialized. Defaults to `0.0`. + /// - parameter initialResponseTime: The time the first bytes were received from or sent to the server. + /// Defaults to `0.0`. + /// - parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`. + /// - parameter serializationCompletedTime: The time when the response serialization was completed. Defaults + /// to `0.0`. + /// + /// - returns: The new `Timeline` instance. + public init( + requestStartTime: CFAbsoluteTime = 0.0, + initialResponseTime: CFAbsoluteTime = 0.0, + requestCompletedTime: CFAbsoluteTime = 0.0, + serializationCompletedTime: CFAbsoluteTime = 0.0) + { + self.requestStartTime = requestStartTime + self.initialResponseTime = initialResponseTime + self.requestCompletedTime = requestCompletedTime + self.serializationCompletedTime = serializationCompletedTime + + self.latency = initialResponseTime - requestStartTime + self.requestDuration = requestCompletedTime - requestStartTime + self.serializationDuration = serializationCompletedTime - requestCompletedTime + self.totalDuration = serializationCompletedTime - requestStartTime + } +} + +// MARK: - CustomStringConvertible + +extension Timeline: CustomStringConvertible { + /// The textual representation used when written to an output stream, which includes the latency, the request + /// duration and the total duration. + public var description: String { + let latency = String(format: "%.3f", self.latency) + let requestDuration = String(format: "%.3f", self.requestDuration) + let serializationDuration = String(format: "%.3f", self.serializationDuration) + let totalDuration = String(format: "%.3f", self.totalDuration) + + // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is + // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. + let timings = [ + "\"Latency\": " + latency + " secs", + "\"Request Duration\": " + requestDuration + " secs", + "\"Serialization Duration\": " + serializationDuration + " secs", + "\"Total Duration\": " + totalDuration + " secs" + ] + + return "Timeline: { " + timings.joined(separator: ", ") + " }" + } +} + +// MARK: - CustomDebugStringConvertible + +extension Timeline: CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes the request start time, the + /// initial response time, the request completed time, the serialization completed time, the latency, the request + /// duration and the total duration. + public var debugDescription: String { + let requestStartTime = String(format: "%.3f", self.requestStartTime) + let initialResponseTime = String(format: "%.3f", self.initialResponseTime) + let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime) + let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime) + let latency = String(format: "%.3f", self.latency) + let requestDuration = String(format: "%.3f", self.requestDuration) + let serializationDuration = String(format: "%.3f", self.serializationDuration) + let totalDuration = String(format: "%.3f", self.totalDuration) + + // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is + // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. + let timings = [ + "\"Request Start Time\": " + requestStartTime, + "\"Initial Response Time\": " + initialResponseTime, + "\"Request Completed Time\": " + requestCompletedTime, + "\"Serialization Completed Time\": " + serializationCompletedTime, + "\"Latency\": " + latency + " secs", + "\"Request Duration\": " + requestDuration + " secs", + "\"Serialization Duration\": " + serializationDuration + " secs", + "\"Total Duration\": " + totalDuration + " secs" + ] + + return "Timeline: { " + timings.joined(separator: ", ") + " }" + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift new file mode 100644 index 0000000000..c405d02af1 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift @@ -0,0 +1,309 @@ +// +// 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 { + + // MARK: Helper Types + + fileprivate typealias ErrorReason = AFError.ResponseValidationFailureReason + + /// 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(Error) + } + + fileprivate struct MIMEType { + let type: String + let subtype: String + + var isWildcard: Bool { return type == "*" && subtype == "*" } + + init?(_ string: String) { + let components: [String] = { + let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines) + let split = stripped.substring(to: stripped.range(of: ";")?.lowerBound ?? stripped.endIndex) + return split.components(separatedBy: "/") + }() + + if let type = components.first, let 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 + } + } + } + + // MARK: Properties + + fileprivate var acceptableStatusCodes: [Int] { return Array(200..<300) } + + fileprivate var acceptableContentTypes: [String] { + if let accept = request?.value(forHTTPHeaderField: "Accept") { + return accept.components(separatedBy: ",") + } + + return ["*/*"] + } + + // MARK: Status Code + + fileprivate func validate( + statusCode acceptableStatusCodes: S, + response: HTTPURLResponse) + -> ValidationResult + where S.Iterator.Element == Int + { + if acceptableStatusCodes.contains(response.statusCode) { + return .success + } else { + let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode) + return .failure(AFError.responseValidationFailed(reason: reason)) + } + } + + // MARK: Content Type + + fileprivate func validate( + contentType acceptableContentTypes: S, + response: HTTPURLResponse, + data: Data?) + -> ValidationResult + where S.Iterator.Element == String + { + guard let data = data, data.count > 0 else { return .success } + + guard + let responseContentType = response.mimeType, + let responseMIMEType = MIMEType(responseContentType) + else { + for contentType in acceptableContentTypes { + if let mimeType = MIMEType(contentType), mimeType.isWildcard { + return .success + } + } + + let error: AFError = { + let reason: ErrorReason = .missingContentType(acceptableContentTypes: Array(acceptableContentTypes)) + return AFError.responseValidationFailed(reason: reason) + }() + + return .failure(error) + } + + for contentType in acceptableContentTypes { + if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) { + return .success + } + } + + let error: AFError = { + let reason: ErrorReason = .unacceptableContentType( + acceptableContentTypes: Array(acceptableContentTypes), + responseContentType: responseContentType + ) + + return AFError.responseValidationFailed(reason: reason) + }() + + return .failure(error) + } +} + +// MARK: - + +extension DataRequest { + /// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the + /// request was valid. + public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> 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. + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validationExecution: () -> Void = { [unowned self] in + if + let response = self.response, + self.delegate.error == nil, + case let .failure(error) = validation(self.request, response, self.delegate.data) + { + self.delegate.error = error + } + } + + validations.append(validationExecution) + + return self + } + + /// Validates that the response has a status code in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter range: The range of acceptable status codes. + /// + /// - returns: The request. + @discardableResult + public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { + return validate { [unowned self] _, response, _ in + return self.validate(statusCode: acceptableStatusCodes, response: response) + } + } + + /// Validates that the response has a content type in the specified sequence. + /// + /// 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. + @discardableResult + public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { + return validate { [unowned self] _, response, data in + return self.validate(contentType: acceptableContentTypes, response: response, data: data) + } + } + + /// 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. + @discardableResult + public func validate() -> Self { + return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes) + } +} + +// MARK: - + +extension DownloadRequest { + /// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a + /// destination URL, and returns whether the request was valid. + public typealias Validation = ( + _ request: URLRequest?, + _ response: HTTPURLResponse, + _ temporaryURL: URL?, + _ destinationURL: URL?) + -> 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. + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validationExecution: () -> Void = { [unowned self] in + let request = self.request + let temporaryURL = self.downloadDelegate.temporaryURL + let destinationURL = self.downloadDelegate.destinationURL + + if + let response = self.response, + self.delegate.error == nil, + case let .failure(error) = validation(request, response, temporaryURL, destinationURL) + { + self.delegate.error = error + } + } + + validations.append(validationExecution) + + return self + } + + /// Validates that the response has a status code in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter range: The range of acceptable status codes. + /// + /// - returns: The request. + @discardableResult + public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { + return validate { [unowned self] _, response, _, _ in + return self.validate(statusCode: acceptableStatusCodes, response: response) + } + } + + /// Validates that the response has a content type in the specified sequence. + /// + /// 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. + @discardableResult + public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { + return validate { [unowned self] _, response, _, _ in + let fileURL = self.downloadDelegate.fileURL + + guard let validFileURL = fileURL else { + return .failure(AFError.responseValidationFailed(reason: .dataFileNil)) + } + + do { + let data = try Data(contentsOf: validFileURL) + return self.validate(contentType: acceptableContentTypes, response: response, data: data) + } catch { + return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL))) + } + } + } + + /// 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. + @discardableResult + public func validate() -> Self { + return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json new file mode 100644 index 0000000000..955f316ec6 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json @@ -0,0 +1,25 @@ +{ + "name": "PetstoreClient", + "platforms": { + "ios": "9.0", + "osx": "10.11" + }, + "version": "0.0.1", + "source": { + "git": "git@github.com:swagger-api/swagger-mustache.git", + "tag": "v1.0.0" + }, + "authors": "", + "license": "Proprietary", + "homepage": "https://github.com/swagger-api/swagger-codegen", + "summary": "PetstoreClient", + "source_files": "PetstoreClient/Classes/Swaggers/**/*.swift", + "dependencies": { + "RxSwift": [ + "~> 3.4.1" + ], + "Alamofire": [ + "~> 4.5" + ] + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Manifest.lock b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Manifest.lock new file mode 100644 index 0000000000..2e01f2467a --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Manifest.lock @@ -0,0 +1,22 @@ +PODS: + - Alamofire (4.5.0) + - PetstoreClient (0.0.1): + - Alamofire (~> 4.5) + - RxSwift (~> 3.4.1) + - RxSwift (3.4.1) + +DEPENDENCIES: + - PetstoreClient (from `../`) + +EXTERNAL SOURCES: + PetstoreClient: + :path: ../ + +SPEC CHECKSUMS: + Alamofire: f28cdffd29de33a7bfa022cbd63ae95a27fae140 + PetstoreClient: 23a1f7941fd65b9ebc1806a1646b3ff415371e34 + RxSwift: 656f8fbeca5bc372121a72d9ebdd3cd3bc0ffade + +PODFILE CHECKSUM: 417049e9ed0e4680602b34d838294778389bd418 + +COCOAPODS: 1.1.1 diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj new file mode 100644 index 0000000000..57dd8236f8 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj @@ -0,0 +1,1956 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 00C95B00E274459CAEA6FBBC3E3DFA3F /* ShareReplay1WhileConnected.swift in Sources */ = {isa = PBXBuildFile; fileRef = 365AE864123C488FD72C61ADC9EC624D /* ShareReplay1WhileConnected.swift */; }; + 0161E77CE771A20E652637576C11288A /* RetryWhen.swift in Sources */ = {isa = PBXBuildFile; fileRef = 62F9DE8CE4FBC650CD1C45E4D55A76AB /* RetryWhen.swift */; }; + 023D1D9D4E093100D847913CFED50A74 /* OuterEnum.swift in Sources */ = {isa = PBXBuildFile; fileRef = 38959EA7078A1CA2DE422B13FE95BB7F /* OuterEnum.swift */; }; + 029FC30CF995C77BD2B077C475C5ABF9 /* HasOnlyReadOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61FA7A1374F8436149AD148E6CBFB4B8 /* HasOnlyReadOnly.swift */; }; + 042CEED27B8AEA495E49959EB3F82053 /* BinaryDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 510BB12F1D8076F5BA1888E67E121E79 /* BinaryDisposable.swift */; }; + 05434308230CE260C67F2AA72F668B42 /* AsSingle.swift in Sources */ = {isa = PBXBuildFile; fileRef = B4644DAD437464D93509A585F99B235E /* AsSingle.swift */; }; + 07B475A196F098B24CD1E19A88DC7014 /* StoreAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = E13906B829CC4C4FB42267C2D107C933 /* StoreAPI.swift */; }; + 08C5AAFAA82B2B16870A85DC53AA9D54 /* DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75DAC3F84E978269F03F6516EE7E9FAE /* DistinctUntilChanged.swift */; }; + 08EB4C1011B17FDF370CF8B8DCFB6C26 /* SerialDispatchQueueScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8317D3F53EA1D6DC62811B7F71E22E8E /* SerialDispatchQueueScheduler.swift */; }; + 092E09A292EACB3789AB861CC905C9B1 /* Skip.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7011CBC583696921D4186C6121A7F67F /* Skip.swift */; }; + 0A1B1515BE0679E0C397005946DBACE6 /* ObserverType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 88515C2D0E31A4BB398381850BBA2A54 /* ObserverType.swift */; }; + 0AAEA1A171BF1E732F383B4BCA84EA57 /* SynchronizedOnType.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9178D3690ADCB4F8C9057F81C073A45 /* SynchronizedOnType.swift */; }; + 0C929D0417407AC779147DB0484DAD54 /* StartWith.swift in Sources */ = {isa = PBXBuildFile; fileRef = B77F93192159DCCC6CEF8FC5A0924F9A /* StartWith.swift */; }; + 0DCBC9CE464A08CED750039A2076E29A /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3107FACD612EFAEA66240443DDC4BAED /* Configuration.swift */; }; + 0E95E2B4EE376617EED90402D22E2064 /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FCDAA2549A70BCA3749CF5FCCF837E9 /* Error.swift */; }; + 0F1EC6F732F2A572C50396C8AC80B09C /* SwitchIfEmpty.swift in Sources */ = {isa = PBXBuildFile; fileRef = B4EEA393253D8586EB38190FC649A3FA /* SwitchIfEmpty.swift */; }; + 0F5E293AFDB33339261060E5346578A9 /* Delay.swift in Sources */ = {isa = PBXBuildFile; fileRef = D14A5F119805F0FCFCC8C1314040D871 /* Delay.swift */; }; + 10EB23E9ECC4B33E16933BB1EA560B6A /* Timeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5F0AE167B06634076A6A2605697CE49 /* Timeline.swift */; }; + 11662A34666A7661D79EF3F66B19C853 /* AsyncLock.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA4F47C5A2E55E47E45F95C0672F0820 /* AsyncLock.swift */; }; + 1178860EDD15DEB3E6A410AF8259253B /* SubscriptionDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 15F7B4D89DB784C462A959824F1E698C /* SubscriptionDisposable.swift */; }; + 1426B771241B8FEF628AC5AF5812CC3E /* Using.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA907F82073836CB66D5D606FB1333D9 /* Using.swift */; }; + 14AF37170805FEEA7FC1663CB1741E56 /* Amb.swift in Sources */ = {isa = PBXBuildFile; fileRef = A6635256007E4FB66691FA58431C5B23 /* Amb.swift */; }; + 173B6F93D4DE52781164BBC0E28FA6C0 /* CompositeDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = D497E96ABC5BEF4E26087D1F8D61D35E /* CompositeDisposable.swift */; }; + 174EBB2A52F1BB6E943D43A9118E5BA7 /* PetAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18E75181C75944E0ADFCDE449B362260 /* PetAPI.swift */; }; + 1B9EDEDC964E6B08F78920B4F4B9DB84 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F42569FD7843064F8467B7215CC7A9A9 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1D6086B9EB58E46FA66BF6BCC4B77CD5 /* VirtualTimeScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = E721CFEFA8C057FD4766D5603B283218 /* VirtualTimeScheduler.swift */; }; + 1DE613D9E922FB6ED5CD5200912B2629 /* Repeat.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAED6E7C8067874A040C7B3863732D73 /* Repeat.swift */; }; + 1F514669DD8305A932C9686E90653160 /* DisposeBag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 77762B0005C750E84813994CE0075E3B /* DisposeBag.swift */; }; + 204293B54491328EBFCC506EF2F2331F /* InvocableType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC0097103243FBF2702AB35BF7C0A4 /* InvocableType.swift */; }; + 2126C1E263B2EF2007442FB3953670CF /* Disposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5A98136CD6F078204F8B95D995205F04 /* Disposable.swift */; }; + 23BC8C28FAA73E066964C6DF829B08C9 /* AdditionalPropertiesClass.swift in Sources */ = {isa = PBXBuildFile; fileRef = EB03103EEECB00DA5C32271413E4E8A3 /* AdditionalPropertiesClass.swift */; }; + 246646DA752E6C3A9DB8FC582BF21DEC /* SchedulerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = B258A9C347C516AA8D8A3FB2CD665D6D /* SchedulerType.swift */; }; + 251956FE94EBA2E766BE0F99847DBB37 /* AnonymousInvocable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83CF28DA7318DA2566376ACECE87D6E3 /* AnonymousInvocable.swift */; }; + 26D4DB444B51A5F8B5B5379F031179E4 /* DisposeBase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 32C44C9A30733440A3D263B43861FBA1 /* DisposeBase.swift */; }; + 277A7BF574628ECBA24B448004302D2A /* Window.swift in Sources */ = {isa = PBXBuildFile; fileRef = DAE679F6024F9BDC9690AFE107798377 /* Window.swift */; }; + 281AFAEA94C9F83ACC6296BBD7A0D2E4 /* Pods-SwaggerClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2822F49595AEE69D96D94D5793B3373E /* RxSwift-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 5E047D08FB3120A3AFA0DF05CCC1712A /* RxSwift-dummy.m */; }; + 2A250E5CD76AED19E973BA51D18FCBA9 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AE307308EA13685E2F9959277D7E355A /* Foundation.framework */; }; + 2A834CD7058DCD3A72B680DB99B76EFC /* NumberOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA0A658092155D1AEAD460DFF753DBEA /* NumberOnly.swift */; }; + 2AB4A4574BC8CB64F49E0B68F8ED61F6 /* ScheduledItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6C32D4D3484C860B70069CD1C629F666 /* ScheduledItem.swift */; }; + 2B07B6C2E7F071930AD113DED4E6340D /* RefCountDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31DC6B167D2D13AFD8EAAF1E63021B52 /* RefCountDisposable.swift */; }; + 2C31FD96F208B18BDC8D7486C3AA4A26 /* AlamofireImplementations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B9186043B7CBCC0AD79F75AFB2A5A23 /* AlamofireImplementations.swift */; }; + 2C9B1C3DCBAB56C8F63E4AD23394747D /* Cancelable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 463ABD4055AB6537A2C5B0EDB617C139 /* Cancelable.swift */; }; + 31717691AB3E9C1758792C3CF652DC2C /* Category.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616489D0E6F317C88360E090E031046 /* Category.swift */; }; + 31F8B86E3672D0B828B6352C875649C4 /* Pods-SwaggerClientTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 33DF7CD52F1810D369E0B6246D9F4026 /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 939E73AB843F47D6C9EA0D065BAF63FC /* Map.swift */; }; + 33FE2620347DD810E56795EC10991E11 /* Cat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4BE1E4D333C9D950F060195C0BBBF502 /* Cat.swift */; }; + 3626B94094672CB1C9DEA32B9F9502E1 /* TaskDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = E181A2141028C3EB376581163644E247 /* TaskDelegate.swift */; }; + 366C0CE0948D4FD875334C2F655BA6A0 /* Models.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3AE0D19F7A56CAD4B0A1454D328AF7F2 /* Models.swift */; }; + 36FDD0A47378AADCA2D2FF11F07FE629 /* Do.swift in Sources */ = {isa = PBXBuildFile; fileRef = CB3FCE54551234A4F3910C33EB48C016 /* Do.swift */; }; + 3728D59522E663AAD6C46F46EFECAECE /* Buffer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 596A0129DA8C10F8A3BEECED9EE16F68 /* Buffer.swift */; }; + 378E8BDB87FEB648A473B1A8C09880BF /* BehaviorSubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4FE676DC3C01D76D82723E22A695A308 /* BehaviorSubject.swift */; }; + 3A70221A6F02D3DB6265483E3FCDAA5D /* Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B5F05AEF12013DFCBEBE433EEBB3C8F /* Rx.swift */; }; + 3AD79904F10FAA988080A99CA3DEA1B0 /* Empty.swift in Sources */ = {isa = PBXBuildFile; fileRef = C860BEC2AFE3C3670391CECBA2707574 /* Empty.swift */; }; + 3B39CFE8304874684649508E1C5B6AF7 /* NopDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7737478C5B309559EBEB826D48D81C26 /* NopDisposable.swift */; }; + 3B6185DBF9E4D927E1EFA16AC5ECC64F /* PriorityQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 880C5FA0EC7B351BE64E748163FA1C31 /* PriorityQueue.swift */; }; + 3BF121D4A9FBEAA1ACCCB784D882FC28 /* SkipUntil.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C897A93D54D11502C0795F3D0F8510F /* SkipUntil.swift */; }; + 3C5C260B32509F399FB6A66A420AFA61 /* SynchronizedSubscribeType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B70F2B6C174F1E6C285A5F774C3C97E /* SynchronizedSubscribeType.swift */; }; + 3D533E2D5A41DE864A2EBEA7E1FC6EAD /* ReplaySubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7269CAD149BFD0BE4D3B1CA43FE6424F /* ReplaySubject.swift */; }; + 3F75EA6E43704FDCB74DE2FBE7B26B98 /* SerialDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = C367D19B8DD4C0F9954A24DD5A2A6AFB /* SerialDisposable.swift */; }; + 41CE2A41E4001649958EE2C8BD18BCBA /* SubjectType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18328C3FA1839793D455774B0473668C /* SubjectType.swift */; }; + 422DCB5DC011F3D4B56E6BDF6076B0B4 /* FakeAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 82B0E05085347AAB90EB2BDF2E0D3F83 /* FakeAPI.swift */; }; + 4360C9F8B14834B74EF2EE4FC112977D /* Throttle.swift in Sources */ = {isa = PBXBuildFile; fileRef = F9F0644CBB2BCA2DB969F16E2B5D92CE /* Throttle.swift */; }; + 437FD4F20E6CCA77205C06A80254013D /* BooleanDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B6D35FB8DCCEAAD8DC223CD5BC95E99 /* BooleanDisposable.swift */; }; + 46408F878C74A244E8A54D1CEF78561F /* Order.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6F36EADEC6543EBFEF7DA50ADACD2981 /* Order.swift */; }; + 46621BFF25A14BE57402CDC543E176C8 /* Dog.swift in Sources */ = {isa = PBXBuildFile; fileRef = C2F1C9683D99C60CBEAB9AE235CE6113 /* Dog.swift */; }; + 478E697551223A40A48A7CA4F732B6D2 /* AnyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = BA58F20D8C1234D395CD1165DC3690F3 /* AnyObserver.swift */; }; + 48BD9FF08780754C12487CB31F66C283 /* AsMaybe.swift in Sources */ = {isa = PBXBuildFile; fileRef = A222C21465FACA23A74CB83AA9A51FF9 /* AsMaybe.swift */; }; + 4A92F049533F11DD39C2CC7EEFFE1C8A /* OuterComposite.swift in Sources */ = {isa = PBXBuildFile; fileRef = F0E53AA6619F07B7C176744B56E96128 /* OuterComposite.swift */; }; + 4E611B02357FA35BC9BE3ABF54204720 /* Catch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4313BF26CA6B25832E158F8FC403D849 /* Catch.swift */; }; + 4E9624834AEB88088D34D7A1C5963E0A /* Pet.swift in Sources */ = {isa = PBXBuildFile; fileRef = BBEB0E03EEF6C09C149D4010E27EBCD6 /* Pet.swift */; }; + 500D3B6DEBB40B757375AC8AFA9337CF /* TakeLast.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4EACF73E072E466AF5911B9BB191E174 /* TakeLast.swift */; }; + 52BFD5DED3C1390E8AF35944507BDA41 /* Timeout.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6CBCC23A46623376CB1616C1C121603D /* Timeout.swift */; }; + 5387216E723A3C68E851CA15573CDD71 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = F57EA9DD77194E4F1E5E5E6CB4CDAE4E /* Request.swift */; }; + 566F127E9A2C44E602ED79003C26FAC4 /* Concat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 287F0ED0B2D6A3F3220B6F4E92A7F350 /* Concat.swift */; }; + 5808F5D7BD8F0F5C53B085E23EDE442E /* Optional.swift in Sources */ = {isa = PBXBuildFile; fileRef = ECB0A2EA86FF43E01E3D3ACE3BD2752B /* Optional.swift */; }; + 59BA6D9D29F93FBDEB624C0B66F54699 /* Bag+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5D641B399A74F0F9D45B05F8D357C806 /* Bag+Rx.swift */; }; + 5A6B1C1CBBD3AAC96E1D301C1041C67B /* List.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A79D7FF65BAE396D6ACAAA55E3F7181 /* List.swift */; }; + 5CF06AC8C33500191521DED85C42E0E7 /* Range.swift in Sources */ = {isa = PBXBuildFile; fileRef = 80C18B1881A0F511B8D6DDA77F355B51 /* Range.swift */; }; + 5CF5991A8288B434E6E6888DBD1CD2A1 /* PetstoreClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */; }; + 5D4C6F66F5E087BE67F2887E5E29EF4B /* ArrayTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 36255652C59CEFD4F66EB0B2D5B29273 /* ArrayTest.swift */; }; + 5F1AE969EB429C504C3D7902AE733270 /* Timer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26CDF11A8572688E0011727ADD962B74 /* Timer.swift */; }; + 5F5FD5BBB0BE079D6225327B54D77856 /* Lock.swift in Sources */ = {isa = PBXBuildFile; fileRef = DACA1956515F0B0CED7487724276C51B /* Lock.swift */; }; + 60B375EE1E1B3D8B358B6F616A3BDBD5 /* JSONEncodableEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 034FC37E78F0BAC8EA70F3597100D018 /* JSONEncodableEncoding.swift */; }; + 61200D01A1855D7920CEF835C8BE00B0 /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6DA0155598FD96A2BBFF3496F7380D93 /* DispatchQueue+Alamofire.swift */; }; + 6232741FBF5E14F1FDCEA83F645E721A /* MixedPropertiesAndAdditionalPropertiesClass.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA9B4E5D66CE4B3D2AB2A934AD6C38CC /* MixedPropertiesAndAdditionalPropertiesClass.swift */; }; + 62909E143F6F7EE50CAFC48DF725EBFB /* ArrayOfNumberOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9673B63A000870E60EE3AACD4B6638F2 /* ArrayOfNumberOnly.swift */; }; + 62F65AD8DC4F0F9610F4B8B4738EC094 /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 64AB42C9C8AA1EFF0761D23E6FEF4776 /* ServerTrustPolicy.swift */; }; + 63CD1B23614A22D49CE538603A922FB8 /* Reactive.swift in Sources */ = {isa = PBXBuildFile; fileRef = D984AFE3BDFDD95C397A0D0F80DFECA6 /* Reactive.swift */; }; + 63D0E36AD412A2FD9CDF7F88E0057B40 /* TakeUntil.swift in Sources */ = {isa = PBXBuildFile; fileRef = 65518CF96489DBA6322987069B264467 /* TakeUntil.swift */; }; + 63FA3285013BD933ACE21B6E63FD8FEA /* Switch.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7677FD01A3CD0014041B75BD92F6D97 /* Switch.swift */; }; + 64C751E7EE440C59D6A0EC77C2E499DE /* OuterString.swift in Sources */ = {isa = PBXBuildFile; fileRef = B5964709E13140A84C6C6822A5E52436 /* OuterString.swift */; }; + 66E79497A285F244010125A8CCCC8DA6 /* Materialize.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1D34B07FCD98BCADAA8A3B68F1ACF1E /* Materialize.swift */; }; + 674961F2E1587E146A678DE0E7F7799E /* LockOwnerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72730856B78AF39AB4D248DDA7771A5B /* LockOwnerType.swift */; }; + 687A75F93305045731FE4788F204FBE7 /* AsyncSubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 80AD53E4312C3B362D3336BDC9D80A80 /* AsyncSubject.swift */; }; + 699728DB0F1DD4724A6194D6E3AFE5F9 /* Merge.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1FCEDB728FD2060B1A8C36A71039328 /* Merge.swift */; }; + 6B2A09D0E78C6A727C1A7F81E6D2A78D /* Platform.Darwin.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB1413438046E9B3E8A94F51358A8205 /* Platform.Darwin.swift */; }; + 6B8F33F8AF88B6B9F7E71D3A51CBBF26 /* ConcurrentMainScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9B782CE63F4EDE0F2FE5908E009D66D3 /* ConcurrentMainScheduler.swift */; }; + 6BB7B2D7A0C1882973D5C79CE11B5FD0 /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AA9C5856BEAE5090A7D1EB450A10C04F /* Alamofire.framework */; }; + 6DF49C373380B586ACF445271F522258 /* CodableHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3F6E2A324F7EF774E148D1D334A98623 /* CodableHelper.swift */; }; + 706A9EED70851EF557850C22EBB4A55E /* EnumArrays.swift in Sources */ = {isa = PBXBuildFile; fileRef = 91F74F344B9A30862A3CE7AA00DF9505 /* EnumArrays.swift */; }; + 7184914B9064EDED86A2BAE7D8FD8E73 /* Name.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8CB7F81ADB00D1823D0166C4402AFCAD /* Name.swift */; }; + 718FD78BC2B5CE5D26FBDF35777FD50B /* Deferred.swift in Sources */ = {isa = PBXBuildFile; fileRef = F119426570E6238D04EAB498E1902F13 /* Deferred.swift */; }; + 71E5BFD91E5C8AF6ED5D7064321B5127 /* ArrayOfArrayOfNumberOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9F3D725DEDE73039BDB7E383A795037 /* ArrayOfArrayOfNumberOnly.swift */; }; + 738FC6F9A5AF6977170AA24621FE9A89 /* Platform.Linux.swift in Sources */ = {isa = PBXBuildFile; fileRef = 48242CA8E564C2C50CFF8E3E77668FB7 /* Platform.Linux.swift */; }; + 752C27C236935788BAE0385B31EB337B /* Debounce.swift in Sources */ = {isa = PBXBuildFile; fileRef = 09CF571E27DC65BF77EFFF62354B5EF0 /* Debounce.swift */; }; + 75C53DB402B577C8F2B84FF52B215273 /* CombineLatest+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0AF6AF4017DB31B86B803FEA577F7A22 /* CombineLatest+arity.swift */; }; + 769CA2CEA89938507051682F58F5B739 /* PublishSubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA436001918C6F92DC029B7E695520E8 /* PublishSubject.swift */; }; + 76D17ABECF45D1B4D734F13084330870 /* Variable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 39A2B57F2DAE55FA57D315FDD6953365 /* Variable.swift */; }; + 78512A64DF32CABEC36D10DF56D86A19 /* ScheduledDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 48E60FBF9296448D4A2FEC7E14FBE6DB /* ScheduledDisposable.swift */; }; + 795CC0B664785EBD5F138549E457FB05 /* UserAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = B6B8342FF1E17FB5EEB366F22D6E81F4 /* UserAPI.swift */; }; + 7A4BBA7F582C8B323D338CF692448AED /* Bag.swift in Sources */ = {isa = PBXBuildFile; fileRef = D5FE55155242FEDEC1B330C78429337F /* Bag.swift */; }; + 7B5FE28C7EA4122B0598738E54DBEBD8 /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7098927F58CDA88AF2F555BD54050500 /* SessionDelegate.swift */; }; + 7CCEA4D230FCC455D4D9C04122F11AEE /* OperationQueueScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24917B863385D1BB04A2303451C9E272 /* OperationQueueScheduler.swift */; }; + 7CE6DC55D9152FB95629A52752FAF5CA /* Animal.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7F67103A7F189F8F3C0CB4A26343EC9 /* Animal.swift */; }; + 7D76060250DB268942EB8DC75DBF6D91 /* SynchronizedUnsubscribeType.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA39A7A8DF958888156A2207EF666EB1 /* SynchronizedUnsubscribeType.swift */; }; + 7D8CC01E8C9EFFF9F4D65406CDE0AB66 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3ECB713449813E363ABB94C83D77F3A9 /* Result.swift */; }; + 7EC367969459A4C9954F68892920C636 /* Queue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5A98B8DAD74FBDB55E3D879266AA14CA /* Queue.swift */; }; + 7F22F2B8DA555C92027C84C14865D117 /* ElementAt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0668A90FD8DFEB8D178EE6721979B788 /* ElementAt.swift */; }; + 7FA7CE127D4B0DAFCACA8258B1AFB1EB /* Multicast.swift in Sources */ = {isa = PBXBuildFile; fileRef = 59E44229281B70ACA538454D8DB49FC0 /* Multicast.swift */; }; + 7FE94EEF4752F45F7D9F66D9524A179C /* SkipWhile.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7E3BEFA00C2C7854A37F845BF40B59F4 /* SkipWhile.swift */; }; + 80EAFB32C911390136DF02D78D43A43A /* ObservableType+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = C30419C2A3E0EC1B15E0D3AF3D91FB15 /* ObservableType+Extensions.swift */; }; + 82CAF4682477DBE59734FF1341227663 /* RecursiveScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = DAE1A43C13EDE68CF0C6AEA7EA3A2521 /* RecursiveScheduler.swift */; }; + 82EC83088D42C7AF036EAC90CA0EC4DD /* ImmediateSchedulerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 883F8BF59AD1E1C16492B6CA9A82FB3D /* ImmediateSchedulerType.swift */; }; + 8445D12322A938A0B580CE83C0EC8112 /* RxSwift.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 19296A8C5E948345E5744A748B1CC720 /* RxSwift.framework */; }; + 858CE0C1137E20D7790A86FA94E3BA93 /* ReadOnlyFirst.swift in Sources */ = {isa = PBXBuildFile; fileRef = 371A937F09567375756221D7F49C2A8F /* ReadOnlyFirst.swift */; }; + 876D748B0125657E576848AFCA30320E /* Take.swift in Sources */ = {isa = PBXBuildFile; fileRef = 16B7B7BE1A379F72CFC27449A45EE5AE /* Take.swift */; }; + 87710B0BE6B1D35BA1089D3D26A3C6B3 /* ConnectableObservableType.swift in Sources */ = {isa = PBXBuildFile; fileRef = AFDFA640848914890DC3B2555740FF84 /* ConnectableObservableType.swift */; }; + 881A524A3B984BD661474E613677A8B1 /* Debug.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4FF46ACE1C78929AB44803AE915B394F /* Debug.swift */; }; + 8947B195C3745586358032D1A4F6C611 /* Dematerialize.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33E7362EED7450FC886B01AB15E22681 /* Dematerialize.swift */; }; + 897985FA042CD12B825C3032898FAB26 /* Pods-SwaggerClientTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */; }; + 8B381A672F67EFD4E28AE41DC6C09E32 /* CombineLatest+Collection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 86B5A2A541FCAB86964565123DAF4719 /* CombineLatest+Collection.swift */; }; + 8B4EEEB1E2148EB4E33F3E4DD168AE6D /* JSONEncodingHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = D5A96975879BDC727B590A6D26389021 /* JSONEncodingHelper.swift */; }; + 8CA70260592E5581330996FFCFE46244 /* SynchronizedDisposeType.swift in Sources */ = {isa = PBXBuildFile; fileRef = B34B9F812BB8C50E3EA28F4FB51A1095 /* SynchronizedDisposeType.swift */; }; + 8CF9E1445350F8173583A6976731DDBD /* SpecialModelName.swift in Sources */ = {isa = PBXBuildFile; fileRef = A613FB311411985DD74A85AA342A119D /* SpecialModelName.swift */; }; + 8DAA4A1278B5BC5F7B4D88964444B27F /* Capitalization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0C997A31F9838A2F145464A1235F5BF4 /* Capitalization.swift */; }; + 8E2709D7B67CFB3F9DD9350B6D10F9E1 /* ClassModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 480529C4E288A9BE50C43685CD9BEC40 /* ClassModel.swift */; }; + 8E5914B860D1B5199F751A3FEB8DB835 /* AddRef.swift in Sources */ = {isa = PBXBuildFile; fileRef = A962E5C6DA31E53BA6DEFCE4F2BC34B8 /* AddRef.swift */; }; + 8F93A485E427E9174C5B226C0745C50C /* ObserverBase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9BE04EA000FD69A9AF7258C56417D785 /* ObserverBase.swift */; }; + 91BCA631F516CB40742B0D2B1A211246 /* Pods-SwaggerClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */; }; + 92B4415759ED63F6179B4145A97DDF9D /* FormatTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 816735E5125EF6F54113D94CBA10808D /* FormatTest.swift */; }; + 9385E37D5298476BEE58892CDB2AB911 /* Producer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6CCE606004614C138E5498F58AA0D8DF /* Producer.swift */; }; + 996C2CA8DEF676FCF156B247CB261E4D /* CurrentThreadScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9BEFD5C825FC7E42B492A86160C4B4D9 /* CurrentThreadScheduler.swift */; }; + 99C8FFABABC2F8EEA3E7DEEA53CFD05F /* WithLatestFrom.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3A07BFAFDAB02F19561FDA4115668F66 /* WithLatestFrom.swift */; }; + 9BE98C6A25F0A3D58447D017E329A74C /* ShareReplay1.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7513ADBA4C19938F615442415D28732 /* ShareReplay1.swift */; }; + 9C0BB2AF97FD62807EDEBE69DEF50782 /* PetstoreClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 9E592E40FE434896241A81819DA417D9 /* InvocableScheduledItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30436E554B573E5078213F681DA0061F /* InvocableScheduledItem.swift */; }; + 9ED2BB2981896E0A39EFA365503F58CE /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7728F2E75E01542A06BFA62D24420ADB /* AFError.swift */; }; + A04BFC558D69E7DBB68023C80A9CFE4E /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AE307308EA13685E2F9959277D7E355A /* Foundation.framework */; }; + A0970A71F45E91480EF6CA6C704ACFA9 /* TakeWhile.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61148633F9614B9AD57C5470C729902C /* TakeWhile.swift */; }; + A27F8BAE0E571A46B89423DE8A14289F /* Sample.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7FE769331C0AFEF35319E2F6260F9DF /* Sample.swift */; }; + A2A6F71B727312BD45CC7A4AAD7B0AB7 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4668C7356C845C883E13EAB41F34154 /* NetworkReachabilityManager.swift */; }; + A33B32B21637691751A537C4D3AC01BB /* EnumTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0480E728A2EC0B202D415F572B00AC0A /* EnumTest.swift */; }; + A6531EC821090A82EED5E99C1A3FAFC8 /* AnonymousObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6472AECA91A4E834A9AF15721BC6D569 /* AnonymousObserver.swift */; }; + A7345084BD26040CDC406F5B8ACEB439 /* Generate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9675783D8A4B72DF63BAA2050C4E5659 /* Generate.swift */; }; + A873E42860058F41BC2A86A30D800A82 /* MainScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4AF8DBA8D803E5226616EC41FA7405ED /* MainScheduler.swift */; }; + A9EEEA7477981DEEBC72432DE9990A4B /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = F9CD1F74BF087D277406BF9164B9D058 /* Alamofire-dummy.m */; }; + AA3D05951A21C1D18FB7CC6CF9B17CD4 /* OuterBoolean.swift in Sources */ = {isa = PBXBuildFile; fileRef = AAA1E6C85A45A787DDD0928D381E3A9A /* OuterBoolean.swift */; }; + ADD1CB76F8658ECE9A0FF6BD51908BF3 /* Observable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6887D641E8100CE8A13FFA165FC59B73 /* Observable.swift */; }; + AE1EF48399533730D0066E04B22CA2D6 /* SessionManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 321FE523C25A0EAF6FF886D6FDE6D24D /* SessionManager.swift */; }; + AE284464AE544C8F6F0DB932E5CDAAE8 /* DefaultIfEmpty.swift in Sources */ = {isa = PBXBuildFile; fileRef = 14E29B89A0BDB135B2088F4F20D14F46 /* DefaultIfEmpty.swift */; }; + AF641042D53C43BF8757FBD3CA8E6B5D /* GroupedObservable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7AC7E0F67AECA3C1CBDBF7BC409CDADC /* GroupedObservable.swift */; }; + AFB1EB0005188DEE754ABF4C4BB5A8C7 /* Errors.swift in Sources */ = {isa = PBXBuildFile; fileRef = 821702C06296B57D769A8DCDD13DE971 /* Errors.swift */; }; + B31F79F9A3C2824A2993493E4B915E0D /* PrimitiveSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9BF77ECD45A0F08FB7892B9597B135 /* PrimitiveSequence.swift */; }; + B34E6708A4AC47051C04F75C58D3BEEC /* APIHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA5DE5258E533171F4B2F41EE6FB6BA8 /* APIHelper.swift */; }; + B65FCF589DA398C3EFE0128064E510EC /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA42FD2B1F921714FC4FEABAFB8D190A /* MultipartFormData.swift */; }; + B6EDAB8C1E6B1AB3BFE4EE7EBC9C49BE /* ScheduledItemType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2AF9D1F5A21CB847E913BF41EC110B1F /* ScheduledItemType.swift */; }; + B74BE992119AE1BAC8380B2A62A85A96 /* HistoricalScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = C071467FD72C9E762BDC54865F1A4193 /* HistoricalScheduler.swift */; }; + B9CA494A4AFDE8C52B3F6D90A4BD1120 /* APIs.swift in Sources */ = {isa = PBXBuildFile; fileRef = 60A9C36627D74537170A05AF2FD4AB9B /* APIs.swift */; }; + B9F0D01FEDAF7011F7A4417A43AA0A10 /* Never.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F94DF516E7B950F928922C1D41C6D4D /* Never.swift */; }; + BA7354944E9F7AAD4E38332F1FF39A6E /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AE307308EA13685E2F9959277D7E355A /* Foundation.framework */; }; + BB0B398A709DABBED7B4B9BAA3601585 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AE307308EA13685E2F9959277D7E355A /* Foundation.framework */; }; + BBEFE2F9CEB73DC7BD97FFA66A0D9D4F /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0528EC401C03A7544A658C38016A893 /* Validation.swift */; }; + BCA27068F62DF3C4AF7F922A5800DAD0 /* SingleAsync.swift in Sources */ = {isa = PBXBuildFile; fileRef = 805F15552659D5E233243B40C0C6F028 /* SingleAsync.swift */; }; + BDA28FE86F9E0530B7C6B93C5BE6A3B0 /* VirtualTimeConverterType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 772DB63372E4253C20C516EBF68DD251 /* VirtualTimeConverterType.swift */; }; + BE5C67A07E289FE1F9BE27335B159997 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F69F88B1008A9EE1DDF85CBC79677A8 /* ParameterEncoding.swift */; }; + C0075D24F6A3B955E7494EF1E489F88C /* DispatchQueueConfiguration.swift in Sources */ = {isa = PBXBuildFile; fileRef = F847CE4C82EA73A82952D85A608F86AB /* DispatchQueueConfiguration.swift */; }; + C05CC775CDC72B19F39193D0A7963FD5 /* SingleAssignmentDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A3D311EA38EC997A02CB05BACC0DD7D /* SingleAssignmentDisposable.swift */; }; + C1231330EA76D9B9229B19C872C75523 /* MapTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = B080D68ACAB64CC43222BB3EB4C891E6 /* MapTest.swift */; }; + C2F1E72D8D37218AEAD0AF8CDF7CDA2A /* Deprecated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 63A236E8B385B46BC8C1268A38CCBDE5 /* Deprecated.swift */; }; + C476C0D3C68492238174642EC1FBB8D0 /* Sink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18254952242D69F129DC1ACD4BDF8AF4 /* Sink.swift */; }; + C6BC225ADD9B69CED61B8BFBD4C2D24D /* InfiniteSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5017E276F3AE00F1F45A62F9A35F51C0 /* InfiniteSequence.swift */; }; + C6EADDBBCB153E895C983C06EF6DD3AC /* DelaySubscription.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9B939DC5892884F0418DD9231B1C333B /* DelaySubscription.swift */; }; + C7DB82C5CF6A8F3191DD1B6CAFFB025D /* ToArray.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37CEC3599B3E7B7EB3DA8FBA9610E255 /* ToArray.swift */; }; + C85636A520F6B62A5705106396CC8555 /* CombineLatest.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA3E73A8C322E8F93F432A4821A988DD /* CombineLatest.swift */; }; + CB6D60925223897FFA2662667DF83E8A /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = DF7CAA870676F2440AC2CCFC5A522F6C /* Response.swift */; }; + CEA2A8A4E36095510E15298612F32C58 /* GroupBy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F067CE8E1D793F3477FF78E26651CDB /* GroupBy.swift */; }; + D07EC53425E587F6C78DC216196706D3 /* SchedulerServices+Emulation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 60544C2EB93D2C784EF3673B4BA12FAD /* SchedulerServices+Emulation.swift */; }; + D0A0CFCF09F7868220437333F425BDCC /* String+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = F104D45199031F05FCEEFA8E947F210E /* String+Rx.swift */; }; + D1EA8B4DFD94E6BB87F5301A73E5E953 /* Model200Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83CC571E11B106EB638320B0CBFAE7EC /* Model200Response.swift */; }; + D32130A2C8AC5B1FF21AF43BCC2B5217 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AE307308EA13685E2F9959277D7E355A /* Foundation.framework */; }; + D556076DDC550682BEECCEB3C37FADF9 /* ObservableConvertibleType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93D2B184ED95D52B41994F4AA9D93A6C /* ObservableConvertibleType.swift */; }; + D76C36F4419B1029715732B8F79B5358 /* Zip.swift in Sources */ = {isa = PBXBuildFile; fileRef = A45D3DB105B4381656B330C1B2B6301E /* Zip.swift */; }; + D9D7157B8E82FD3EA9527FFB55FDFDA3 /* EnumClass.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4151B89B79A8DF7595086BD4A06995F /* EnumClass.swift */; }; + DA66B65753E93CE2577AD8B0F1840E2C /* TailRecursiveSink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 11316F7A1A5EB2E5B756703C0EE77CF6 /* TailRecursiveSink.swift */; }; + DCF2A0BC50F66AC329586306A6D31155 /* SubscribeOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = B80609FF38FDE35E5FE2D38886D2361F /* SubscribeOn.swift */; }; + DD5F8EB279A6341B3CDEC6B36A057001 /* Reduce.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A9E77B670AC48E19FB2C9FE2BD11E32 /* Reduce.swift */; }; + DF2FB5F62117CCC04A595C338B089C69 /* Zip+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = BFBD0B4CB17B692257A69160584B0895 /* Zip+arity.swift */; }; + E07F9E8C01F513BFECB85D28AD83778E /* User.swift in Sources */ = {isa = PBXBuildFile; fileRef = 953C28E03A094CB9F3C4E5BB52A3F216 /* User.swift */; }; + E0E2C585E6FAE78A091C3E9D68E8C51D /* Client.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A49E06FDB29F4420D8D3A423DFF3C20 /* Client.swift */; }; + E198B4DBA859E20C62670BFA81AD4C3F /* Create.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A96069F19C031BE285BF982214ABCB4 /* Create.swift */; }; + E25F732E580028B0199F4066D13C597B /* Disposables.swift in Sources */ = {isa = PBXBuildFile; fileRef = E841A5E38033B35ED3073E4BBB921518 /* Disposables.swift */; }; + E3452A69A219F48484893674A8F8B333 /* ImmediateScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = F777764A45E0A77BE276ADA473AF453A /* ImmediateScheduler.swift */; }; + E585F8E6C1C60A0D07836B3B59B265B1 /* DispatchQueue+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3F1C7AD0D97D1F541A20DEDFD5AC30AF /* DispatchQueue+Extensions.swift */; }; + E5A9844D1E1181CC100901AEBFEF2594 /* ConcurrentDispatchQueueScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3B1C5A8AB9C095DD01A23DB6B7179E5C /* ConcurrentDispatchQueueScheduler.swift */; }; + E77F71BF5E59D5B613A01CE2402B452C /* OuterNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = 168C646B7D9EDB05BD30540CC92FF275 /* OuterNumber.swift */; }; + E956BF8E052B4841F99C3A963BA6C55A /* ApiResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = E0C52E62EB600F7CD3CE9C927980C5FD /* ApiResponse.swift */; }; + E9F1BECE5C764114F317E3B6B9162667 /* Filter.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7A01B1A67EE04FE1D9C036932C4C037 /* Filter.swift */; }; + EA673361DD150A38520EF307EB17AD9E /* Event.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0BED5103BCF9D40F85068CF32B24A63E /* Event.swift */; }; + EB82DDF3CDA1C8F4119D65ADD824E229 /* ConnectableObservable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5AC613DA00AD0B2ACF145E94AED80E86 /* ConnectableObservable.swift */; }; + EF95B008F0A8E62D9B326C0269E06D76 /* Scan.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5FA4778A42883943FE99141A948880BE /* Scan.swift */; }; + EFD264FC408EBF3BA2528E70B08DDD94 /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 64082BE2455C7B840B138508D24C0B0C /* Notifications.swift */; }; + F01BC24737A6EF6A7BE993F32846D421 /* RxSwift-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 36918AB1CF9222600ABF5A21CBEDEAAC /* RxSwift-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F07B9F771FFEDE12F88006F49C22A6E0 /* AnonymousDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = CB186FED84E02D4539A7335A7D657AEB /* AnonymousDisposable.swift */; }; + F1AC8927E1A33C651564627140495148 /* Tag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F03D835E561FE785ADB017EC579801D /* Tag.swift */; }; + F2935C2E2CEEA6C3E8633E0B03EACBD9 /* Return.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0AAD5E7EA7DD4A277DCCEDDF25B5C91E /* Return.swift */; }; + F31D497BACB658228637EB913918F952 /* HistoricalSchedulerTimeConverter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 870EAFD138EAD59EAC7EE2CE19DE25B4 /* HistoricalSchedulerTimeConverter.swift */; }; + F5C0376459DD63893B9F91FDC8BCF807 /* PrimitiveSequence+Zip+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 269E63D0B9C1F5552DF3ABA3F5BF88EB /* PrimitiveSequence+Zip+arity.swift */; }; + F6BECD98B97CBFEBE2C96F0E9E72A6C0 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1FCD92EC4EAB245624BBB2DDECF9B2C /* ResponseSerialization.swift */; }; + F8B3D3092ED0417E8CDF32033F6122F5 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6489C0664BA4C768FBB891CF9DF2CFD1 /* Alamofire.swift */; }; + F8C14BA4A8CF63EF1C1495175402EE0F /* Zip+Collection.swift in Sources */ = {isa = PBXBuildFile; fileRef = B23F66A643FB8A1DEAC31DC3B637ACEB /* Zip+Collection.swift */; }; + F8C505130735B376CBDA87289A56095E /* RxMutableBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 59EA941CFCC415131D36B17780FA7F33 /* RxMutableBox.swift */; }; + FA1D1261DB26D216DD6B78418D024A31 /* ObservableType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B4FF38E4CA2AFB54D788C9F1919BFA8 /* ObservableType.swift */; }; + FAD42007C7BC77A262FDA9F5265C3312 /* Just.swift in Sources */ = {isa = PBXBuildFile; fileRef = C541B03ABB2F0F5E10F027D5E3C9DF4B /* Just.swift */; }; + FB57C81A917036130717B7633D6C61E9 /* Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C5338CFA8BEC6D40B446583ED47E4C2 /* Extensions.swift */; }; + FBADAA44CA33F062B9A0CB84A7558262 /* ObserveOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC5B3446AD01BE42D27E9F1B9673C334 /* ObserveOn.swift */; }; + FC2E633740DE8FBE2A334BC7BDCA06C2 /* Sequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1F0B7854DD41D311F76522F61203F7F /* Sequence.swift */; }; + FCE497B5706C8900534EE96E790F1205 /* RecursiveLock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C7C61BEED15998D9D7B47AD6F3E069D /* RecursiveLock.swift */; }; + FFB5B1F30F30210B83B17FCCF4C0453A /* AnimalFarm.swift in Sources */ = {isa = PBXBuildFile; fileRef = C83E0FDC2BB7298F1CA6A95272EF6798 /* AnimalFarm.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 0B2AA791B256C6F1530511EEF7AB4A24 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 88E9EC28B8B46C3631E6B242B50F4442; + remoteInfo = Alamofire; + }; + 2B4A36E763D78D2BA39A638AF167D81A /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 2837E5FF96967EA63E5F7E861959BFC5; + remoteInfo = PetstoreClient; + }; + 2DCB98A99AD653C10CE969703079F4AA /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = E8DEDAB11E7B037AA8A5C5105BF53D42; + remoteInfo = RxSwift; + }; + A50F0C9B9BA00FA72637B7EE5F05D32C /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = E8DEDAB11E7B037AA8A5C5105BF53D42; + remoteInfo = RxSwift; + }; + F4CD590A32AA7D5C2F5D6400E4547B0C /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 88E9EC28B8B46C3631E6B242B50F4442; + remoteInfo = Alamofire; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 00ACB4396DD1B4E4539E4E81C1D7A14E /* Pods-SwaggerClientTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = "Pods-SwaggerClientTests.modulemap"; sourceTree = ""; }; + 02F28E719AA874BE9213D6CF8CE7E36B /* Pods-SwaggerClientTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClientTests-acknowledgements.plist"; sourceTree = ""; }; + 034FC37E78F0BAC8EA70F3597100D018 /* JSONEncodableEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = JSONEncodableEncoding.swift; sourceTree = ""; }; + 0480E728A2EC0B202D415F572B00AC0A /* EnumTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = EnumTest.swift; sourceTree = ""; }; + 057FC3E5DE19EA8F4DD600557D771032 /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_SwaggerClient.framework; path = "Pods-SwaggerClient.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + 0668A90FD8DFEB8D178EE6721979B788 /* ElementAt.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ElementAt.swift; path = RxSwift/Observables/ElementAt.swift; sourceTree = ""; }; + 09CF571E27DC65BF77EFFF62354B5EF0 /* Debounce.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Debounce.swift; path = RxSwift/Observables/Debounce.swift; sourceTree = ""; }; + 0AAD5E7EA7DD4A277DCCEDDF25B5C91E /* Return.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Return.swift; sourceTree = ""; }; + 0AF6AF4017DB31B86B803FEA577F7A22 /* CombineLatest+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "CombineLatest+arity.swift"; path = "RxSwift/Observables/CombineLatest+arity.swift"; sourceTree = ""; }; + 0B6D35FB8DCCEAAD8DC223CD5BC95E99 /* BooleanDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BooleanDisposable.swift; path = RxSwift/Disposables/BooleanDisposable.swift; sourceTree = ""; }; + 0BED5103BCF9D40F85068CF32B24A63E /* Event.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Event.swift; path = RxSwift/Event.swift; sourceTree = ""; }; + 0C997A31F9838A2F145464A1235F5BF4 /* Capitalization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Capitalization.swift; sourceTree = ""; }; + 11316F7A1A5EB2E5B756703C0EE77CF6 /* TailRecursiveSink.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TailRecursiveSink.swift; path = RxSwift/Observers/TailRecursiveSink.swift; sourceTree = ""; }; + 14E29B89A0BDB135B2088F4F20D14F46 /* DefaultIfEmpty.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DefaultIfEmpty.swift; path = RxSwift/Observables/DefaultIfEmpty.swift; sourceTree = ""; }; + 15F7B4D89DB784C462A959824F1E698C /* SubscriptionDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SubscriptionDisposable.swift; path = RxSwift/Disposables/SubscriptionDisposable.swift; sourceTree = ""; }; + 168C646B7D9EDB05BD30540CC92FF275 /* OuterNumber.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterNumber.swift; sourceTree = ""; }; + 16B7B7BE1A379F72CFC27449A45EE5AE /* Take.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Take.swift; path = RxSwift/Observables/Take.swift; sourceTree = ""; }; + 18254952242D69F129DC1ACD4BDF8AF4 /* Sink.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Sink.swift; path = RxSwift/Observables/Sink.swift; sourceTree = ""; }; + 18328C3FA1839793D455774B0473668C /* SubjectType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SubjectType.swift; path = RxSwift/Subjects/SubjectType.swift; sourceTree = ""; }; + 18E75181C75944E0ADFCDE449B362260 /* PetAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PetAPI.swift; sourceTree = ""; }; + 19296A8C5E948345E5744A748B1CC720 /* RxSwift.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = RxSwift.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 1A3D311EA38EC997A02CB05BACC0DD7D /* SingleAssignmentDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SingleAssignmentDisposable.swift; path = RxSwift/Disposables/SingleAssignmentDisposable.swift; sourceTree = ""; }; + 1C897A93D54D11502C0795F3D0F8510F /* SkipUntil.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkipUntil.swift; path = RxSwift/Observables/SkipUntil.swift; sourceTree = ""; }; + 24917B863385D1BB04A2303451C9E272 /* OperationQueueScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = OperationQueueScheduler.swift; path = RxSwift/Schedulers/OperationQueueScheduler.swift; sourceTree = ""; }; + 269E63D0B9C1F5552DF3ABA3F5BF88EB /* PrimitiveSequence+Zip+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "PrimitiveSequence+Zip+arity.swift"; path = "RxSwift/Traits/PrimitiveSequence+Zip+arity.swift"; sourceTree = ""; }; + 26CDF11A8572688E0011727ADD962B74 /* Timer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timer.swift; path = RxSwift/Observables/Timer.swift; sourceTree = ""; }; + 287F0ED0B2D6A3F3220B6F4E92A7F350 /* Concat.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Concat.swift; path = RxSwift/Observables/Concat.swift; sourceTree = ""; }; + 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClient-dummy.m"; sourceTree = ""; }; + 2A79D7FF65BAE396D6ACAAA55E3F7181 /* List.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = List.swift; sourceTree = ""; }; + 2AF9D1F5A21CB847E913BF41EC110B1F /* ScheduledItemType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ScheduledItemType.swift; path = RxSwift/Schedulers/Internal/ScheduledItemType.swift; sourceTree = ""; }; + 2FF17440CCD2E1A69791A4AA23325AD5 /* Pods-SwaggerClient-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClient-acknowledgements.markdown"; sourceTree = ""; }; + 30436E554B573E5078213F681DA0061F /* InvocableScheduledItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InvocableScheduledItem.swift; path = RxSwift/Schedulers/Internal/InvocableScheduledItem.swift; sourceTree = ""; }; + 3107FACD612EFAEA66240443DDC4BAED /* Configuration.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Configuration.swift; sourceTree = ""; }; + 31DC6B167D2D13AFD8EAAF1E63021B52 /* RefCountDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RefCountDisposable.swift; path = RxSwift/Disposables/RefCountDisposable.swift; sourceTree = ""; }; + 321FE523C25A0EAF6FF886D6FDE6D24D /* SessionManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionManager.swift; path = Source/SessionManager.swift; sourceTree = ""; }; + 32C44C9A30733440A3D263B43861FBA1 /* DisposeBase.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DisposeBase.swift; path = RxSwift/Disposables/DisposeBase.swift; sourceTree = ""; }; + 33E7362EED7450FC886B01AB15E22681 /* Dematerialize.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Dematerialize.swift; path = RxSwift/Observables/Dematerialize.swift; sourceTree = ""; }; + 36255652C59CEFD4F66EB0B2D5B29273 /* ArrayTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ArrayTest.swift; sourceTree = ""; }; + 365AE864123C488FD72C61ADC9EC624D /* ShareReplay1WhileConnected.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ShareReplay1WhileConnected.swift; path = RxSwift/Observables/ShareReplay1WhileConnected.swift; sourceTree = ""; }; + 36918AB1CF9222600ABF5A21CBEDEAAC /* RxSwift-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxSwift-umbrella.h"; sourceTree = ""; }; + 371A937F09567375756221D7F49C2A8F /* ReadOnlyFirst.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ReadOnlyFirst.swift; sourceTree = ""; }; + 37CEC3599B3E7B7EB3DA8FBA9610E255 /* ToArray.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ToArray.swift; path = RxSwift/Observables/ToArray.swift; sourceTree = ""; }; + 38959EA7078A1CA2DE422B13FE95BB7F /* OuterEnum.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterEnum.swift; sourceTree = ""; }; + 39A2B57F2DAE55FA57D315FDD6953365 /* Variable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Variable.swift; path = RxSwift/Subjects/Variable.swift; sourceTree = ""; }; + 3A07BFAFDAB02F19561FDA4115668F66 /* WithLatestFrom.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = WithLatestFrom.swift; path = RxSwift/Observables/WithLatestFrom.swift; sourceTree = ""; }; + 3AE0D19F7A56CAD4B0A1454D328AF7F2 /* Models.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Models.swift; sourceTree = ""; }; + 3B1C5A8AB9C095DD01A23DB6B7179E5C /* ConcurrentDispatchQueueScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConcurrentDispatchQueueScheduler.swift; path = RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift; sourceTree = ""; }; + 3ECB713449813E363ABB94C83D77F3A9 /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; + 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClient-umbrella.h"; sourceTree = ""; }; + 3F16B43ABD2C8CD4A311AA1AB3B6C02F /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 3F1C7AD0D97D1F541A20DEDFD5AC30AF /* DispatchQueue+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Extensions.swift"; path = "Platform/DispatchQueue+Extensions.swift"; sourceTree = ""; }; + 3F6E2A324F7EF774E148D1D334A98623 /* CodableHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CodableHelper.swift; sourceTree = ""; }; + 4313BF26CA6B25832E158F8FC403D849 /* Catch.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Catch.swift; path = RxSwift/Observables/Catch.swift; sourceTree = ""; }; + 43FC49AA70D3E2A84CAED9C37BE9C4B5 /* Pods-SwaggerClientTests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-frameworks.sh"; sourceTree = ""; }; + 463ABD4055AB6537A2C5B0EDB617C139 /* Cancelable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Cancelable.swift; path = RxSwift/Cancelable.swift; sourceTree = ""; }; + 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PetstoreClient-dummy.m"; sourceTree = ""; }; + 480529C4E288A9BE50C43685CD9BEC40 /* ClassModel.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ClassModel.swift; sourceTree = ""; }; + 48242CA8E564C2C50CFF8E3E77668FB7 /* Platform.Linux.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Platform.Linux.swift; path = Platform/Platform.Linux.swift; sourceTree = ""; }; + 48E60FBF9296448D4A2FEC7E14FBE6DB /* ScheduledDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ScheduledDisposable.swift; path = RxSwift/Disposables/ScheduledDisposable.swift; sourceTree = ""; }; + 4AF8DBA8D803E5226616EC41FA7405ED /* MainScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MainScheduler.swift; path = RxSwift/Schedulers/MainScheduler.swift; sourceTree = ""; }; + 4BE1E4D333C9D950F060195C0BBBF502 /* Cat.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Cat.swift; sourceTree = ""; }; + 4C5338CFA8BEC6D40B446583ED47E4C2 /* Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Extensions.swift; sourceTree = ""; }; + 4EACF73E072E466AF5911B9BB191E174 /* TakeLast.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TakeLast.swift; path = RxSwift/Observables/TakeLast.swift; sourceTree = ""; }; + 4F69F88B1008A9EE1DDF85CBC79677A8 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; + 4FE676DC3C01D76D82723E22A695A308 /* BehaviorSubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BehaviorSubject.swift; path = RxSwift/Subjects/BehaviorSubject.swift; sourceTree = ""; }; + 4FF46ACE1C78929AB44803AE915B394F /* Debug.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Debug.swift; path = RxSwift/Observables/Debug.swift; sourceTree = ""; }; + 5017E276F3AE00F1F45A62F9A35F51C0 /* InfiniteSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InfiniteSequence.swift; path = Platform/DataStructures/InfiniteSequence.swift; sourceTree = ""; }; + 503A5FA54C11AE46D3333E6080D61E9A /* RxSwift.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = RxSwift.modulemap; sourceTree = ""; }; + 510BB12F1D8076F5BA1888E67E121E79 /* BinaryDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BinaryDisposable.swift; path = RxSwift/Disposables/BinaryDisposable.swift; sourceTree = ""; }; + 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; + 5616489D0E6F317C88360E090E031046 /* Category.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Category.swift; sourceTree = ""; }; + 56CC0097103243FBF2702AB35BF7C0A4 /* InvocableType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InvocableType.swift; path = RxSwift/Schedulers/Internal/InvocableType.swift; sourceTree = ""; }; + 596A0129DA8C10F8A3BEECED9EE16F68 /* Buffer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Buffer.swift; path = RxSwift/Observables/Buffer.swift; sourceTree = ""; }; + 59E44229281B70ACA538454D8DB49FC0 /* Multicast.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Multicast.swift; path = RxSwift/Observables/Multicast.swift; sourceTree = ""; }; + 59EA941CFCC415131D36B17780FA7F33 /* RxMutableBox.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxMutableBox.swift; path = RxSwift/RxMutableBox.swift; sourceTree = ""; }; + 5A98136CD6F078204F8B95D995205F04 /* Disposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Disposable.swift; path = RxSwift/Disposable.swift; sourceTree = ""; }; + 5A98B8DAD74FBDB55E3D879266AA14CA /* Queue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Queue.swift; path = Platform/DataStructures/Queue.swift; sourceTree = ""; }; + 5AC613DA00AD0B2ACF145E94AED80E86 /* ConnectableObservable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConnectableObservable.swift; path = RxSwift/Observables/ConnectableObservable.swift; sourceTree = ""; }; + 5B4FF38E4CA2AFB54D788C9F1919BFA8 /* ObservableType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObservableType.swift; path = RxSwift/ObservableType.swift; sourceTree = ""; }; + 5B598E168B47485DC60F9DBBCBEEF5BB /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Alamofire.framework; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 5B5F05AEF12013DFCBEBE433EEBB3C8F /* Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Rx.swift; path = RxSwift/Rx.swift; sourceTree = ""; }; + 5B9186043B7CBCC0AD79F75AFB2A5A23 /* AlamofireImplementations.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AlamofireImplementations.swift; sourceTree = ""; }; + 5D641B399A74F0F9D45B05F8D357C806 /* Bag+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Bag+Rx.swift"; path = "RxSwift/Extensions/Bag+Rx.swift"; sourceTree = ""; }; + 5E047D08FB3120A3AFA0DF05CCC1712A /* RxSwift-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "RxSwift-dummy.m"; sourceTree = ""; }; + 5FA4778A42883943FE99141A948880BE /* Scan.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Scan.swift; path = RxSwift/Observables/Scan.swift; sourceTree = ""; }; + 60544C2EB93D2C784EF3673B4BA12FAD /* SchedulerServices+Emulation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "SchedulerServices+Emulation.swift"; path = "RxSwift/Schedulers/SchedulerServices+Emulation.swift"; sourceTree = ""; }; + 60A9C36627D74537170A05AF2FD4AB9B /* APIs.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIs.swift; sourceTree = ""; }; + 61148633F9614B9AD57C5470C729902C /* TakeWhile.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TakeWhile.swift; path = RxSwift/Observables/TakeWhile.swift; sourceTree = ""; }; + 61FA7A1374F8436149AD148E6CBFB4B8 /* HasOnlyReadOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HasOnlyReadOnly.swift; sourceTree = ""; }; + 62F9DE8CE4FBC650CD1C45E4D55A76AB /* RetryWhen.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RetryWhen.swift; path = RxSwift/Observables/RetryWhen.swift; sourceTree = ""; }; + 63A236E8B385B46BC8C1268A38CCBDE5 /* Deprecated.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Deprecated.swift; path = RxSwift/Deprecated.swift; sourceTree = ""; }; + 64082BE2455C7B840B138508D24C0B0C /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; + 6472AECA91A4E834A9AF15721BC6D569 /* AnonymousObserver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnonymousObserver.swift; path = RxSwift/Observers/AnonymousObserver.swift; sourceTree = ""; }; + 6489C0664BA4C768FBB891CF9DF2CFD1 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; + 64AB42C9C8AA1EFF0761D23E6FEF4776 /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; + 65518CF96489DBA6322987069B264467 /* TakeUntil.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TakeUntil.swift; path = RxSwift/Observables/TakeUntil.swift; sourceTree = ""; }; + 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClientTests-dummy.m"; sourceTree = ""; }; + 6887D641E8100CE8A13FFA165FC59B73 /* Observable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Observable.swift; path = RxSwift/Observable.swift; sourceTree = ""; }; + 6A96069F19C031BE285BF982214ABCB4 /* Create.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Create.swift; path = RxSwift/Observables/Create.swift; sourceTree = ""; }; + 6BE16D6C9576956764F467AFD25183DC /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 6C32D4D3484C860B70069CD1C629F666 /* ScheduledItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ScheduledItem.swift; path = RxSwift/Schedulers/Internal/ScheduledItem.swift; sourceTree = ""; }; + 6CBCC23A46623376CB1616C1C121603D /* Timeout.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeout.swift; path = RxSwift/Observables/Timeout.swift; sourceTree = ""; }; + 6CCE606004614C138E5498F58AA0D8DF /* Producer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Producer.swift; path = RxSwift/Observables/Producer.swift; sourceTree = ""; }; + 6DA0155598FD96A2BBFF3496F7380D93 /* DispatchQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Alamofire.swift"; path = "Source/DispatchQueue+Alamofire.swift"; sourceTree = ""; }; + 6F36EADEC6543EBFEF7DA50ADACD2981 /* Order.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Order.swift; sourceTree = ""; }; + 7011CBC583696921D4186C6121A7F67F /* Skip.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Skip.swift; path = RxSwift/Observables/Skip.swift; sourceTree = ""; }; + 7098927F58CDA88AF2F555BD54050500 /* SessionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDelegate.swift; path = Source/SessionDelegate.swift; sourceTree = ""; }; + 726381CBB76FD8C7554573BCD08F831E /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; + 7269CAD149BFD0BE4D3B1CA43FE6424F /* ReplaySubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ReplaySubject.swift; path = RxSwift/Subjects/ReplaySubject.swift; sourceTree = ""; }; + 72730856B78AF39AB4D248DDA7771A5B /* LockOwnerType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LockOwnerType.swift; path = RxSwift/Concurrency/LockOwnerType.swift; sourceTree = ""; }; + 75DAC3F84E978269F03F6516EE7E9FAE /* DistinctUntilChanged.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DistinctUntilChanged.swift; path = RxSwift/Observables/DistinctUntilChanged.swift; sourceTree = ""; }; + 7728F2E75E01542A06BFA62D24420ADB /* AFError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AFError.swift; path = Source/AFError.swift; sourceTree = ""; }; + 772DB63372E4253C20C516EBF68DD251 /* VirtualTimeConverterType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = VirtualTimeConverterType.swift; path = RxSwift/Schedulers/VirtualTimeConverterType.swift; sourceTree = ""; }; + 7737478C5B309559EBEB826D48D81C26 /* NopDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NopDisposable.swift; path = RxSwift/Disposables/NopDisposable.swift; sourceTree = ""; }; + 77762B0005C750E84813994CE0075E3B /* DisposeBag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DisposeBag.swift; path = RxSwift/Disposables/DisposeBag.swift; sourceTree = ""; }; + 7A9E77B670AC48E19FB2C9FE2BD11E32 /* Reduce.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Reduce.swift; path = RxSwift/Observables/Reduce.swift; sourceTree = ""; }; + 7AC7E0F67AECA3C1CBDBF7BC409CDADC /* GroupedObservable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GroupedObservable.swift; path = RxSwift/GroupedObservable.swift; sourceTree = ""; }; + 7B70F2B6C174F1E6C285A5F774C3C97E /* SynchronizedSubscribeType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SynchronizedSubscribeType.swift; path = RxSwift/Concurrency/SynchronizedSubscribeType.swift; sourceTree = ""; }; + 7C7C61BEED15998D9D7B47AD6F3E069D /* RecursiveLock.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RecursiveLock.swift; path = Platform/RecursiveLock.swift; sourceTree = ""; }; + 7C8E63660D346FD8ED2A97242E74EA09 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 7D9BF77ECD45A0F08FB7892B9597B135 /* PrimitiveSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PrimitiveSequence.swift; path = RxSwift/Traits/PrimitiveSequence.swift; sourceTree = ""; }; + 7E3BEFA00C2C7854A37F845BF40B59F4 /* SkipWhile.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkipWhile.swift; path = RxSwift/Observables/SkipWhile.swift; sourceTree = ""; }; + 7FCDAA2549A70BCA3749CF5FCCF837E9 /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = RxSwift/Observables/Error.swift; sourceTree = ""; }; + 805F15552659D5E233243B40C0C6F028 /* SingleAsync.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SingleAsync.swift; path = RxSwift/Observables/SingleAsync.swift; sourceTree = ""; }; + 80AD53E4312C3B362D3336BDC9D80A80 /* AsyncSubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AsyncSubject.swift; path = RxSwift/Subjects/AsyncSubject.swift; sourceTree = ""; }; + 80C18B1881A0F511B8D6DDA77F355B51 /* Range.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Range.swift; path = RxSwift/Observables/Range.swift; sourceTree = ""; }; + 816735E5125EF6F54113D94CBA10808D /* FormatTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = FormatTest.swift; sourceTree = ""; }; + 821702C06296B57D769A8DCDD13DE971 /* Errors.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Errors.swift; path = RxSwift/Errors.swift; sourceTree = ""; }; + 82B0E05085347AAB90EB2BDF2E0D3F83 /* FakeAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = FakeAPI.swift; sourceTree = ""; }; + 8317D3F53EA1D6DC62811B7F71E22E8E /* SerialDispatchQueueScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SerialDispatchQueueScheduler.swift; path = RxSwift/Schedulers/SerialDispatchQueueScheduler.swift; sourceTree = ""; }; + 83CC571E11B106EB638320B0CBFAE7EC /* Model200Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Model200Response.swift; sourceTree = ""; }; + 83CF28DA7318DA2566376ACECE87D6E3 /* AnonymousInvocable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnonymousInvocable.swift; path = RxSwift/Schedulers/Internal/AnonymousInvocable.swift; sourceTree = ""; }; + 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; + 84A09D760BA2EA13D5BE269086BAD34C /* RxSwift.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = RxSwift.framework; path = RxSwift.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; + 86B5A2A541FCAB86964565123DAF4719 /* CombineLatest+Collection.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "CombineLatest+Collection.swift"; path = "RxSwift/Observables/CombineLatest+Collection.swift"; sourceTree = ""; }; + 870EAFD138EAD59EAC7EE2CE19DE25B4 /* HistoricalSchedulerTimeConverter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HistoricalSchedulerTimeConverter.swift; path = RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift; sourceTree = ""; }; + 880C5FA0EC7B351BE64E748163FA1C31 /* PriorityQueue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PriorityQueue.swift; path = Platform/DataStructures/PriorityQueue.swift; sourceTree = ""; }; + 883F8BF59AD1E1C16492B6CA9A82FB3D /* ImmediateSchedulerType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImmediateSchedulerType.swift; path = RxSwift/ImmediateSchedulerType.swift; sourceTree = ""; }; + 88515C2D0E31A4BB398381850BBA2A54 /* ObserverType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObserverType.swift; path = RxSwift/ObserverType.swift; sourceTree = ""; }; + 8CB7F81ADB00D1823D0166C4402AFCAD /* Name.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Name.swift; sourceTree = ""; }; + 8F94DF516E7B950F928922C1D41C6D4D /* Never.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Never.swift; path = RxSwift/Observables/Never.swift; sourceTree = ""; }; + 91F74F344B9A30862A3CE7AA00DF9505 /* EnumArrays.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = EnumArrays.swift; sourceTree = ""; }; + 939E73AB843F47D6C9EA0D065BAF63FC /* Map.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Map.swift; path = RxSwift/Observables/Map.swift; sourceTree = ""; }; + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 93D2B184ED95D52B41994F4AA9D93A6C /* ObservableConvertibleType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObservableConvertibleType.swift; path = RxSwift/ObservableConvertibleType.swift; sourceTree = ""; }; + 953C28E03A094CB9F3C4E5BB52A3F216 /* User.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = User.swift; sourceTree = ""; }; + 9673B63A000870E60EE3AACD4B6638F2 /* ArrayOfNumberOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ArrayOfNumberOnly.swift; sourceTree = ""; }; + 9675783D8A4B72DF63BAA2050C4E5659 /* Generate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Generate.swift; path = RxSwift/Observables/Generate.swift; sourceTree = ""; }; + 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; + 99787387CBF8F606AB2284B149518528 /* RxSwift-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxSwift-prefix.pch"; sourceTree = ""; }; + 9A49E06FDB29F4420D8D3A423DFF3C20 /* Client.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Client.swift; sourceTree = ""; }; + 9B782CE63F4EDE0F2FE5908E009D66D3 /* ConcurrentMainScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConcurrentMainScheduler.swift; path = RxSwift/Schedulers/ConcurrentMainScheduler.swift; sourceTree = ""; }; + 9B939DC5892884F0418DD9231B1C333B /* DelaySubscription.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DelaySubscription.swift; path = RxSwift/Observables/DelaySubscription.swift; sourceTree = ""; }; + 9BE04EA000FD69A9AF7258C56417D785 /* ObserverBase.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObserverBase.swift; path = RxSwift/Observers/ObserverBase.swift; sourceTree = ""; }; + 9BEFD5C825FC7E42B492A86160C4B4D9 /* CurrentThreadScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CurrentThreadScheduler.swift; path = RxSwift/Schedulers/CurrentThreadScheduler.swift; sourceTree = ""; }; + 9F03D835E561FE785ADB017EC579801D /* Tag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Tag.swift; sourceTree = ""; }; + 9F067CE8E1D793F3477FF78E26651CDB /* GroupBy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GroupBy.swift; path = RxSwift/Observables/GroupBy.swift; sourceTree = ""; }; + 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-umbrella.h"; sourceTree = ""; }; + A222C21465FACA23A74CB83AA9A51FF9 /* AsMaybe.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AsMaybe.swift; path = RxSwift/Observables/AsMaybe.swift; sourceTree = ""; }; + A45D3DB105B4381656B330C1B2B6301E /* Zip.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Zip.swift; path = RxSwift/Observables/Zip.swift; sourceTree = ""; }; + A613FB311411985DD74A85AA342A119D /* SpecialModelName.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = SpecialModelName.swift; sourceTree = ""; }; + A6635256007E4FB66691FA58431C5B23 /* Amb.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Amb.swift; path = RxSwift/Observables/Amb.swift; sourceTree = ""; }; + A962E5C6DA31E53BA6DEFCE4F2BC34B8 /* AddRef.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AddRef.swift; path = RxSwift/Observables/AddRef.swift; sourceTree = ""; }; + AA42FD2B1F921714FC4FEABAFB8D190A /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; + AA9C5856BEAE5090A7D1EB450A10C04F /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + AAA1E6C85A45A787DDD0928D381E3A9A /* OuterBoolean.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterBoolean.swift; sourceTree = ""; }; + AE307308EA13685E2F9959277D7E355A /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + AFDFA640848914890DC3B2555740FF84 /* ConnectableObservableType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConnectableObservableType.swift; path = RxSwift/ConnectableObservableType.swift; sourceTree = ""; }; + B080D68ACAB64CC43222BB3EB4C891E6 /* MapTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MapTest.swift; sourceTree = ""; }; + B1F0B7854DD41D311F76522F61203F7F /* Sequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Sequence.swift; path = RxSwift/Observables/Sequence.swift; sourceTree = ""; }; + B23F66A643FB8A1DEAC31DC3B637ACEB /* Zip+Collection.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Zip+Collection.swift"; path = "RxSwift/Observables/Zip+Collection.swift"; sourceTree = ""; }; + B258A9C347C516AA8D8A3FB2CD665D6D /* SchedulerType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SchedulerType.swift; path = RxSwift/SchedulerType.swift; sourceTree = ""; }; + B34B9F812BB8C50E3EA28F4FB51A1095 /* SynchronizedDisposeType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SynchronizedDisposeType.swift; path = RxSwift/Concurrency/SynchronizedDisposeType.swift; sourceTree = ""; }; + B34E08DA58315FFF5FCCF17FBA995360 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = Alamofire.modulemap; sourceTree = ""; }; + B3A144887C8B13FD888B76AB096B0CA1 /* PetstoreClient-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-prefix.pch"; sourceTree = ""; }; + B4644DAD437464D93509A585F99B235E /* AsSingle.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AsSingle.swift; path = RxSwift/Observables/AsSingle.swift; sourceTree = ""; }; + B4EEA393253D8586EB38190FC649A3FA /* SwitchIfEmpty.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SwitchIfEmpty.swift; path = RxSwift/Observables/SwitchIfEmpty.swift; sourceTree = ""; }; + B5964709E13140A84C6C6822A5E52436 /* OuterString.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterString.swift; sourceTree = ""; }; + B6B8342FF1E17FB5EEB366F22D6E81F4 /* UserAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = UserAPI.swift; sourceTree = ""; }; + B7677FD01A3CD0014041B75BD92F6D97 /* Switch.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Switch.swift; path = RxSwift/Observables/Switch.swift; sourceTree = ""; }; + B77F93192159DCCC6CEF8FC5A0924F9A /* StartWith.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StartWith.swift; path = RxSwift/Observables/StartWith.swift; sourceTree = ""; }; + B80609FF38FDE35E5FE2D38886D2361F /* SubscribeOn.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SubscribeOn.swift; path = RxSwift/Observables/SubscribeOn.swift; sourceTree = ""; }; + BA58F20D8C1234D395CD1165DC3690F3 /* AnyObserver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnyObserver.swift; path = RxSwift/AnyObserver.swift; sourceTree = ""; }; + BB1413438046E9B3E8A94F51358A8205 /* Platform.Darwin.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Platform.Darwin.swift; path = Platform/Platform.Darwin.swift; sourceTree = ""; }; + BBEB0E03EEF6C09C149D4010E27EBCD6 /* Pet.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Pet.swift; sourceTree = ""; }; + BC5B3446AD01BE42D27E9F1B9673C334 /* ObserveOn.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObserveOn.swift; path = RxSwift/Observables/ObserveOn.swift; sourceTree = ""; }; + BCF2D4DFF08D2A18E8C8FE4C4B4633FB /* Pods-SwaggerClient-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-frameworks.sh"; sourceTree = ""; }; + BFBD0B4CB17B692257A69160584B0895 /* Zip+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Zip+arity.swift"; path = "RxSwift/Observables/Zip+arity.swift"; sourceTree = ""; }; + C0141EB6EAA64B81BBA6C558E75FE6A3 /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; + C0528EC401C03A7544A658C38016A893 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; + C071467FD72C9E762BDC54865F1A4193 /* HistoricalScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HistoricalScheduler.swift; path = RxSwift/Schedulers/HistoricalScheduler.swift; sourceTree = ""; }; + C1FCEDB728FD2060B1A8C36A71039328 /* Merge.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Merge.swift; path = RxSwift/Observables/Merge.swift; sourceTree = ""; }; + C2F1C9683D99C60CBEAB9AE235CE6113 /* Dog.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Dog.swift; sourceTree = ""; }; + C30419C2A3E0EC1B15E0D3AF3D91FB15 /* ObservableType+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ObservableType+Extensions.swift"; path = "RxSwift/ObservableType+Extensions.swift"; sourceTree = ""; }; + C367D19B8DD4C0F9954A24DD5A2A6AFB /* SerialDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SerialDisposable.swift; path = RxSwift/Disposables/SerialDisposable.swift; sourceTree = ""; }; + C4B474BD9070828C0F786071EEF46CD0 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_SwaggerClientTests.framework; path = "Pods-SwaggerClientTests.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + C541B03ABB2F0F5E10F027D5E3C9DF4B /* Just.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Just.swift; path = RxSwift/Observables/Just.swift; sourceTree = ""; }; + C83E0FDC2BB7298F1CA6A95272EF6798 /* AnimalFarm.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AnimalFarm.swift; sourceTree = ""; }; + C860BEC2AFE3C3670391CECBA2707574 /* Empty.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Empty.swift; path = RxSwift/Observables/Empty.swift; sourceTree = ""; }; + CA3E73A8C322E8F93F432A4821A988DD /* CombineLatest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CombineLatest.swift; path = RxSwift/Observables/CombineLatest.swift; sourceTree = ""; }; + CB186FED84E02D4539A7335A7D657AEB /* AnonymousDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnonymousDisposable.swift; path = RxSwift/Disposables/AnonymousDisposable.swift; sourceTree = ""; }; + CB3FCE54551234A4F3910C33EB48C016 /* Do.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Do.swift; path = RxSwift/Observables/Do.swift; sourceTree = ""; }; + D14A5F119805F0FCFCC8C1314040D871 /* Delay.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Delay.swift; path = RxSwift/Observables/Delay.swift; sourceTree = ""; }; + D2841E5E2183846280B97F6E660DA26C /* Pods-SwaggerClient-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-resources.sh"; sourceTree = ""; }; + D4151B89B79A8DF7595086BD4A06995F /* EnumClass.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = EnumClass.swift; sourceTree = ""; }; + D497E96ABC5BEF4E26087D1F8D61D35E /* CompositeDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CompositeDisposable.swift; path = RxSwift/Disposables/CompositeDisposable.swift; sourceTree = ""; }; + D5A96975879BDC727B590A6D26389021 /* JSONEncodingHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = JSONEncodingHelper.swift; sourceTree = ""; }; + D5FE55155242FEDEC1B330C78429337F /* Bag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Bag.swift; path = Platform/DataStructures/Bag.swift; sourceTree = ""; }; + D7F67103A7F189F8F3C0CB4A26343EC9 /* Animal.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Animal.swift; sourceTree = ""; }; + D984AFE3BDFDD95C397A0D0F80DFECA6 /* Reactive.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Reactive.swift; path = RxSwift/Reactive.swift; sourceTree = ""; }; + DACA1956515F0B0CED7487724276C51B /* Lock.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Lock.swift; path = RxSwift/Concurrency/Lock.swift; sourceTree = ""; }; + DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PetstoreClient.xcconfig; sourceTree = ""; }; + DAE1A43C13EDE68CF0C6AEA7EA3A2521 /* RecursiveScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RecursiveScheduler.swift; path = RxSwift/Schedulers/RecursiveScheduler.swift; sourceTree = ""; }; + DAE679F6024F9BDC9690AFE107798377 /* Window.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Window.swift; path = RxSwift/Observables/Window.swift; sourceTree = ""; }; + DE164497A94DD3215ED4D1AE0D4703B1 /* Pods-SwaggerClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = "Pods-SwaggerClient.modulemap"; sourceTree = ""; }; + DF7CAA870676F2440AC2CCFC5A522F6C /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; + E0C52E62EB600F7CD3CE9C927980C5FD /* ApiResponse.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ApiResponse.swift; sourceTree = ""; }; + E13906B829CC4C4FB42267C2D107C933 /* StoreAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = StoreAPI.swift; sourceTree = ""; }; + E181A2141028C3EB376581163644E247 /* TaskDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TaskDelegate.swift; path = Source/TaskDelegate.swift; sourceTree = ""; }; + E1E4BCB344D3C100253B24B79421F00A /* Pods-SwaggerClient-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClient-acknowledgements.plist"; sourceTree = ""; }; + E3D1141B63DF38660CD6F3AC588A782B /* PetstoreClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = PetstoreClient.modulemap; sourceTree = ""; }; + E4E6F4A58FE7868CA2177D3AC79AD2FA /* Pods-SwaggerClientTests-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-resources.sh"; sourceTree = ""; }; + E721CFEFA8C057FD4766D5603B283218 /* VirtualTimeScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = VirtualTimeScheduler.swift; path = RxSwift/Schedulers/VirtualTimeScheduler.swift; sourceTree = ""; }; + E7513ADBA4C19938F615442415D28732 /* ShareReplay1.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ShareReplay1.swift; path = RxSwift/Observables/ShareReplay1.swift; sourceTree = ""; }; + E7A01B1A67EE04FE1D9C036932C4C037 /* Filter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Filter.swift; path = RxSwift/Observables/Filter.swift; sourceTree = ""; }; + E841A5E38033B35ED3073E4BBB921518 /* Disposables.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Disposables.swift; path = RxSwift/Disposables/Disposables.swift; sourceTree = ""; }; + E9178D3690ADCB4F8C9057F81C073A45 /* SynchronizedOnType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SynchronizedOnType.swift; path = RxSwift/Concurrency/SynchronizedOnType.swift; sourceTree = ""; }; + E9CBBB398E7A62950FA8BC091CBE0359 /* PetstoreClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = PetstoreClient.framework; path = PetstoreClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + E9F3D725DEDE73039BDB7E383A795037 /* ArrayOfArrayOfNumberOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ArrayOfArrayOfNumberOnly.swift; sourceTree = ""; }; + EA39A7A8DF958888156A2207EF666EB1 /* SynchronizedUnsubscribeType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SynchronizedUnsubscribeType.swift; path = RxSwift/Concurrency/SynchronizedUnsubscribeType.swift; sourceTree = ""; }; + EA4F47C5A2E55E47E45F95C0672F0820 /* AsyncLock.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AsyncLock.swift; path = RxSwift/Concurrency/AsyncLock.swift; sourceTree = ""; }; + EA907F82073836CB66D5D606FB1333D9 /* Using.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Using.swift; path = RxSwift/Observables/Using.swift; sourceTree = ""; }; + EAED6E7C8067874A040C7B3863732D73 /* Repeat.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Repeat.swift; path = RxSwift/Observables/Repeat.swift; sourceTree = ""; }; + EB03103EEECB00DA5C32271413E4E8A3 /* AdditionalPropertiesClass.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AdditionalPropertiesClass.swift; sourceTree = ""; }; + ECB0A2EA86FF43E01E3D3ACE3BD2752B /* Optional.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Optional.swift; path = RxSwift/Observables/Optional.swift; sourceTree = ""; }; + EDC14250FB9B1DCE1112D8F3FB5FCEDA /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + F0D4E00A8974E74325E9E53D456F9AD4 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + F0E53AA6619F07B7C176744B56E96128 /* OuterComposite.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OuterComposite.swift; sourceTree = ""; }; + F104D45199031F05FCEEFA8E947F210E /* String+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "String+Rx.swift"; path = "RxSwift/Extensions/String+Rx.swift"; sourceTree = ""; }; + F119426570E6238D04EAB498E1902F13 /* Deferred.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Deferred.swift; path = RxSwift/Observables/Deferred.swift; sourceTree = ""; }; + F1D34B07FCD98BCADAA8A3B68F1ACF1E /* Materialize.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Materialize.swift; path = RxSwift/Observables/Materialize.swift; sourceTree = ""; }; + F1FCD92EC4EAB245624BBB2DDECF9B2C /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; + F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClientTests-umbrella.h"; sourceTree = ""; }; + F42569FD7843064F8467B7215CC7A9A9 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; + F4668C7356C845C883E13EAB41F34154 /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; + F57EA9DD77194E4F1E5E5E6CB4CDAE4E /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; + F5F0AE167B06634076A6A2605697CE49 /* Timeline.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeline.swift; path = Source/Timeline.swift; sourceTree = ""; }; + F777764A45E0A77BE276ADA473AF453A /* ImmediateScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImmediateScheduler.swift; path = RxSwift/Schedulers/ImmediateScheduler.swift; sourceTree = ""; }; + F7FE769331C0AFEF35319E2F6260F9DF /* Sample.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Sample.swift; path = RxSwift/Observables/Sample.swift; sourceTree = ""; }; + F847CE4C82EA73A82952D85A608F86AB /* DispatchQueueConfiguration.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DispatchQueueConfiguration.swift; path = RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift; sourceTree = ""; }; + F9CD1F74BF087D277406BF9164B9D058 /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; + F9F0644CBB2BCA2DB969F16E2B5D92CE /* Throttle.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Throttle.swift; path = RxSwift/Observables/Throttle.swift; sourceTree = ""; }; + FA0A658092155D1AEAD460DFF753DBEA /* NumberOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = NumberOnly.swift; sourceTree = ""; }; + FA436001918C6F92DC029B7E695520E8 /* PublishSubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PublishSubject.swift; path = RxSwift/Subjects/PublishSubject.swift; sourceTree = ""; }; + FA5DE5258E533171F4B2F41EE6FB6BA8 /* APIHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIHelper.swift; sourceTree = ""; }; + FA9B4E5D66CE4B3D2AB2A934AD6C38CC /* MixedPropertiesAndAdditionalPropertiesClass.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MixedPropertiesAndAdditionalPropertiesClass.swift; sourceTree = ""; }; + FB170EFD14935F121CDE3211DB4C5CA3 /* Pods-SwaggerClientTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClientTests-acknowledgements.markdown"; sourceTree = ""; }; + FB65A0C0C98ACB27CAE43B38C6B4A9FC /* RxSwift.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxSwift.xcconfig; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 4A7651580B2694EFD755E590E1DD812F /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 2A250E5CD76AED19E973BA51D18FCBA9 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 87AF7EC7404199AC8C5D22375A6059BF /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + D32130A2C8AC5B1FF21AF43BCC2B5217 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 8C8E55731D0837311C5F9AEE7078E3F3 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 6BB7B2D7A0C1882973D5C79CE11B5FD0 /* Alamofire.framework in Frameworks */, + BA7354944E9F7AAD4E38332F1FF39A6E /* Foundation.framework in Frameworks */, + 8445D12322A938A0B580CE83C0EC8112 /* RxSwift.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 99195E4207764744AEC07ECCBCD550EB /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + A04BFC558D69E7DBB68023C80A9CFE4E /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + B61347E4B942D85FB700CD798AEC3A6D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + BB0B398A709DABBED7B4B9BAA3601585 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 02E57F930C8EDC9AD0C9932B5CAD1DC8 /* Classes */ = { + isa = PBXGroup; + children = ( + 0A4D3677612A5C349C4E1BCAB8319AE1 /* Swaggers */, + ); + name = Classes; + path = Classes; + sourceTree = ""; + }; + 0A4D3677612A5C349C4E1BCAB8319AE1 /* Swaggers */ = { + isa = PBXGroup; + children = ( + 5B9186043B7CBCC0AD79F75AFB2A5A23 /* AlamofireImplementations.swift */, + FA5DE5258E533171F4B2F41EE6FB6BA8 /* APIHelper.swift */, + 60A9C36627D74537170A05AF2FD4AB9B /* APIs.swift */, + 3F6E2A324F7EF774E148D1D334A98623 /* CodableHelper.swift */, + 3107FACD612EFAEA66240443DDC4BAED /* Configuration.swift */, + 4C5338CFA8BEC6D40B446583ED47E4C2 /* Extensions.swift */, + 034FC37E78F0BAC8EA70F3597100D018 /* JSONEncodableEncoding.swift */, + D5A96975879BDC727B590A6D26389021 /* JSONEncodingHelper.swift */, + 3AE0D19F7A56CAD4B0A1454D328AF7F2 /* Models.swift */, + C072D89366F0AD1F186B30637C168E66 /* APIs */, + 4728A1B259A7002B6D7036C586B6D19D /* Models */, + ); + name = Swaggers; + path = Swaggers; + sourceTree = ""; + }; + 22F52349E1BE90FC6E064DAAC9EA9612 /* Development Pods */ = { + isa = PBXGroup; + children = ( + E9F8459055B900A58FB97600A53E5D1C /* PetstoreClient */, + ); + name = "Development Pods"; + sourceTree = ""; + }; + 2E07FFE8D5239059E139DA4A84322919 /* Support Files */ = { + isa = PBXGroup; + children = ( + 6BE16D6C9576956764F467AFD25183DC /* Info.plist */, + 503A5FA54C11AE46D3333E6080D61E9A /* RxSwift.modulemap */, + FB65A0C0C98ACB27CAE43B38C6B4A9FC /* RxSwift.xcconfig */, + 5E047D08FB3120A3AFA0DF05CCC1712A /* RxSwift-dummy.m */, + 99787387CBF8F606AB2284B149518528 /* RxSwift-prefix.pch */, + 36918AB1CF9222600ABF5A21CBEDEAAC /* RxSwift-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/RxSwift"; + sourceTree = ""; + }; + 3F6894F6346ED0522534B4531C76C476 /* Support Files */ = { + isa = PBXGroup; + children = ( + B34E08DA58315FFF5FCCF17FBA995360 /* Alamofire.modulemap */, + C0141EB6EAA64B81BBA6C558E75FE6A3 /* Alamofire.xcconfig */, + F9CD1F74BF087D277406BF9164B9D058 /* Alamofire-dummy.m */, + 726381CBB76FD8C7554573BCD08F831E /* Alamofire-prefix.pch */, + F42569FD7843064F8467B7215CC7A9A9 /* Alamofire-umbrella.h */, + EDC14250FB9B1DCE1112D8F3FB5FCEDA /* Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/Alamofire"; + sourceTree = ""; + }; + 4728A1B259A7002B6D7036C586B6D19D /* Models */ = { + isa = PBXGroup; + children = ( + EB03103EEECB00DA5C32271413E4E8A3 /* AdditionalPropertiesClass.swift */, + D7F67103A7F189F8F3C0CB4A26343EC9 /* Animal.swift */, + C83E0FDC2BB7298F1CA6A95272EF6798 /* AnimalFarm.swift */, + E0C52E62EB600F7CD3CE9C927980C5FD /* ApiResponse.swift */, + E9F3D725DEDE73039BDB7E383A795037 /* ArrayOfArrayOfNumberOnly.swift */, + 9673B63A000870E60EE3AACD4B6638F2 /* ArrayOfNumberOnly.swift */, + 36255652C59CEFD4F66EB0B2D5B29273 /* ArrayTest.swift */, + 0C997A31F9838A2F145464A1235F5BF4 /* Capitalization.swift */, + 4BE1E4D333C9D950F060195C0BBBF502 /* Cat.swift */, + 5616489D0E6F317C88360E090E031046 /* Category.swift */, + 480529C4E288A9BE50C43685CD9BEC40 /* ClassModel.swift */, + 9A49E06FDB29F4420D8D3A423DFF3C20 /* Client.swift */, + C2F1C9683D99C60CBEAB9AE235CE6113 /* Dog.swift */, + 91F74F344B9A30862A3CE7AA00DF9505 /* EnumArrays.swift */, + D4151B89B79A8DF7595086BD4A06995F /* EnumClass.swift */, + 0480E728A2EC0B202D415F572B00AC0A /* EnumTest.swift */, + 816735E5125EF6F54113D94CBA10808D /* FormatTest.swift */, + 61FA7A1374F8436149AD148E6CBFB4B8 /* HasOnlyReadOnly.swift */, + 2A79D7FF65BAE396D6ACAAA55E3F7181 /* List.swift */, + B080D68ACAB64CC43222BB3EB4C891E6 /* MapTest.swift */, + FA9B4E5D66CE4B3D2AB2A934AD6C38CC /* MixedPropertiesAndAdditionalPropertiesClass.swift */, + 83CC571E11B106EB638320B0CBFAE7EC /* Model200Response.swift */, + 8CB7F81ADB00D1823D0166C4402AFCAD /* Name.swift */, + FA0A658092155D1AEAD460DFF753DBEA /* NumberOnly.swift */, + 6F36EADEC6543EBFEF7DA50ADACD2981 /* Order.swift */, + AAA1E6C85A45A787DDD0928D381E3A9A /* OuterBoolean.swift */, + F0E53AA6619F07B7C176744B56E96128 /* OuterComposite.swift */, + 38959EA7078A1CA2DE422B13FE95BB7F /* OuterEnum.swift */, + 168C646B7D9EDB05BD30540CC92FF275 /* OuterNumber.swift */, + B5964709E13140A84C6C6822A5E52436 /* OuterString.swift */, + BBEB0E03EEF6C09C149D4010E27EBCD6 /* Pet.swift */, + 371A937F09567375756221D7F49C2A8F /* ReadOnlyFirst.swift */, + 0AAD5E7EA7DD4A277DCCEDDF25B5C91E /* Return.swift */, + A613FB311411985DD74A85AA342A119D /* SpecialModelName.swift */, + 9F03D835E561FE785ADB017EC579801D /* Tag.swift */, + 953C28E03A094CB9F3C4E5BB52A3F216 /* User.swift */, + ); + name = Models; + path = Models; + sourceTree = ""; + }; + 69750F9014CEFA9B29584C65B2491D2E /* Frameworks */ = { + isa = PBXGroup; + children = ( + AA9C5856BEAE5090A7D1EB450A10C04F /* Alamofire.framework */, + 19296A8C5E948345E5744A748B1CC720 /* RxSwift.framework */, + B0BAC2B4E5CC03E6A71598C4F4BB9298 /* iOS */, + ); + name = Frameworks; + sourceTree = ""; + }; + 7DB346D0F39D3F0E887471402A8071AB = { + isa = PBXGroup; + children = ( + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, + 22F52349E1BE90FC6E064DAAC9EA9612 /* Development Pods */, + 69750F9014CEFA9B29584C65B2491D2E /* Frameworks */, + B569DEF8BE40A2041ADDA9EB1B3163F0 /* Pods */, + C1398CE2D296EEBAA178C160CA6E6AD6 /* Products */, + C1A60D10CED0E61146591438999C7502 /* Targets Support Files */, + ); + sourceTree = ""; + }; + 88CE2B3F08C34DDB098AD8A5DCC1DF1E /* Pods-SwaggerClient */ = { + isa = PBXGroup; + children = ( + 7C8E63660D346FD8ED2A97242E74EA09 /* Info.plist */, + DE164497A94DD3215ED4D1AE0D4703B1 /* Pods-SwaggerClient.modulemap */, + 2FF17440CCD2E1A69791A4AA23325AD5 /* Pods-SwaggerClient-acknowledgements.markdown */, + E1E4BCB344D3C100253B24B79421F00A /* Pods-SwaggerClient-acknowledgements.plist */, + 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */, + BCF2D4DFF08D2A18E8C8FE4C4B4633FB /* Pods-SwaggerClient-frameworks.sh */, + D2841E5E2183846280B97F6E660DA26C /* Pods-SwaggerClient-resources.sh */, + 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */, + 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */, + 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */, + ); + name = "Pods-SwaggerClient"; + path = "Target Support Files/Pods-SwaggerClient"; + sourceTree = ""; + }; + 8F6D133867EE63820DFB7E83F4C51252 /* Support Files */ = { + isa = PBXGroup; + children = ( + F0D4E00A8974E74325E9E53D456F9AD4 /* Info.plist */, + E3D1141B63DF38660CD6F3AC588A782B /* PetstoreClient.modulemap */, + DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */, + 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */, + B3A144887C8B13FD888B76AB096B0CA1 /* PetstoreClient-prefix.pch */, + 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */, + ); + name = "Support Files"; + path = "SwaggerClientTests/Pods/Target Support Files/PetstoreClient"; + sourceTree = ""; + }; + B0BAC2B4E5CC03E6A71598C4F4BB9298 /* iOS */ = { + isa = PBXGroup; + children = ( + AE307308EA13685E2F9959277D7E355A /* Foundation.framework */, + ); + name = iOS; + sourceTree = ""; + }; + B569DEF8BE40A2041ADDA9EB1B3163F0 /* Pods */ = { + isa = PBXGroup; + children = ( + FF61792A0279354AB25395F889F59979 /* Alamofire */, + E7F23A0F12E60AD47285170493A15C47 /* RxSwift */, + ); + name = Pods; + sourceTree = ""; + }; + C072D89366F0AD1F186B30637C168E66 /* APIs */ = { + isa = PBXGroup; + children = ( + 82B0E05085347AAB90EB2BDF2E0D3F83 /* FakeAPI.swift */, + 18E75181C75944E0ADFCDE449B362260 /* PetAPI.swift */, + E13906B829CC4C4FB42267C2D107C933 /* StoreAPI.swift */, + B6B8342FF1E17FB5EEB366F22D6E81F4 /* UserAPI.swift */, + ); + name = APIs; + path = APIs; + sourceTree = ""; + }; + C1398CE2D296EEBAA178C160CA6E6AD6 /* Products */ = { + isa = PBXGroup; + children = ( + 5B598E168B47485DC60F9DBBCBEEF5BB /* Alamofire.framework */, + E9CBBB398E7A62950FA8BC091CBE0359 /* PetstoreClient.framework */, + 057FC3E5DE19EA8F4DD600557D771032 /* Pods_SwaggerClient.framework */, + C4B474BD9070828C0F786071EEF46CD0 /* Pods_SwaggerClientTests.framework */, + 84A09D760BA2EA13D5BE269086BAD34C /* RxSwift.framework */, + ); + name = Products; + sourceTree = ""; + }; + C1A60D10CED0E61146591438999C7502 /* Targets Support Files */ = { + isa = PBXGroup; + children = ( + 88CE2B3F08C34DDB098AD8A5DCC1DF1E /* Pods-SwaggerClient */, + D6D0CD30E3EAF2ED10AE0CBC07506C5A /* Pods-SwaggerClientTests */, + ); + name = "Targets Support Files"; + sourceTree = ""; + }; + D6D0CD30E3EAF2ED10AE0CBC07506C5A /* Pods-SwaggerClientTests */ = { + isa = PBXGroup; + children = ( + 3F16B43ABD2C8CD4A311AA1AB3B6C02F /* Info.plist */, + 00ACB4396DD1B4E4539E4E81C1D7A14E /* Pods-SwaggerClientTests.modulemap */, + FB170EFD14935F121CDE3211DB4C5CA3 /* Pods-SwaggerClientTests-acknowledgements.markdown */, + 02F28E719AA874BE9213D6CF8CE7E36B /* Pods-SwaggerClientTests-acknowledgements.plist */, + 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */, + 43FC49AA70D3E2A84CAED9C37BE9C4B5 /* Pods-SwaggerClientTests-frameworks.sh */, + E4E6F4A58FE7868CA2177D3AC79AD2FA /* Pods-SwaggerClientTests-resources.sh */, + F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */, + 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */, + 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */, + ); + name = "Pods-SwaggerClientTests"; + path = "Target Support Files/Pods-SwaggerClientTests"; + sourceTree = ""; + }; + E73D9BF152C59F341559DE62A3143721 /* PetstoreClient */ = { + isa = PBXGroup; + children = ( + 02E57F930C8EDC9AD0C9932B5CAD1DC8 /* Classes */, + ); + name = PetstoreClient; + path = PetstoreClient; + sourceTree = ""; + }; + E7F23A0F12E60AD47285170493A15C47 /* RxSwift */ = { + isa = PBXGroup; + children = ( + A962E5C6DA31E53BA6DEFCE4F2BC34B8 /* AddRef.swift */, + A6635256007E4FB66691FA58431C5B23 /* Amb.swift */, + CB186FED84E02D4539A7335A7D657AEB /* AnonymousDisposable.swift */, + 83CF28DA7318DA2566376ACECE87D6E3 /* AnonymousInvocable.swift */, + 6472AECA91A4E834A9AF15721BC6D569 /* AnonymousObserver.swift */, + BA58F20D8C1234D395CD1165DC3690F3 /* AnyObserver.swift */, + A222C21465FACA23A74CB83AA9A51FF9 /* AsMaybe.swift */, + B4644DAD437464D93509A585F99B235E /* AsSingle.swift */, + EA4F47C5A2E55E47E45F95C0672F0820 /* AsyncLock.swift */, + 80AD53E4312C3B362D3336BDC9D80A80 /* AsyncSubject.swift */, + D5FE55155242FEDEC1B330C78429337F /* Bag.swift */, + 5D641B399A74F0F9D45B05F8D357C806 /* Bag+Rx.swift */, + 4FE676DC3C01D76D82723E22A695A308 /* BehaviorSubject.swift */, + 510BB12F1D8076F5BA1888E67E121E79 /* BinaryDisposable.swift */, + 0B6D35FB8DCCEAAD8DC223CD5BC95E99 /* BooleanDisposable.swift */, + 596A0129DA8C10F8A3BEECED9EE16F68 /* Buffer.swift */, + 463ABD4055AB6537A2C5B0EDB617C139 /* Cancelable.swift */, + 4313BF26CA6B25832E158F8FC403D849 /* Catch.swift */, + CA3E73A8C322E8F93F432A4821A988DD /* CombineLatest.swift */, + 0AF6AF4017DB31B86B803FEA577F7A22 /* CombineLatest+arity.swift */, + 86B5A2A541FCAB86964565123DAF4719 /* CombineLatest+Collection.swift */, + D497E96ABC5BEF4E26087D1F8D61D35E /* CompositeDisposable.swift */, + 287F0ED0B2D6A3F3220B6F4E92A7F350 /* Concat.swift */, + 3B1C5A8AB9C095DD01A23DB6B7179E5C /* ConcurrentDispatchQueueScheduler.swift */, + 9B782CE63F4EDE0F2FE5908E009D66D3 /* ConcurrentMainScheduler.swift */, + 5AC613DA00AD0B2ACF145E94AED80E86 /* ConnectableObservable.swift */, + AFDFA640848914890DC3B2555740FF84 /* ConnectableObservableType.swift */, + 6A96069F19C031BE285BF982214ABCB4 /* Create.swift */, + 9BEFD5C825FC7E42B492A86160C4B4D9 /* CurrentThreadScheduler.swift */, + 09CF571E27DC65BF77EFFF62354B5EF0 /* Debounce.swift */, + 4FF46ACE1C78929AB44803AE915B394F /* Debug.swift */, + 14E29B89A0BDB135B2088F4F20D14F46 /* DefaultIfEmpty.swift */, + F119426570E6238D04EAB498E1902F13 /* Deferred.swift */, + D14A5F119805F0FCFCC8C1314040D871 /* Delay.swift */, + 9B939DC5892884F0418DD9231B1C333B /* DelaySubscription.swift */, + 33E7362EED7450FC886B01AB15E22681 /* Dematerialize.swift */, + 63A236E8B385B46BC8C1268A38CCBDE5 /* Deprecated.swift */, + 3F1C7AD0D97D1F541A20DEDFD5AC30AF /* DispatchQueue+Extensions.swift */, + F847CE4C82EA73A82952D85A608F86AB /* DispatchQueueConfiguration.swift */, + 5A98136CD6F078204F8B95D995205F04 /* Disposable.swift */, + E841A5E38033B35ED3073E4BBB921518 /* Disposables.swift */, + 77762B0005C750E84813994CE0075E3B /* DisposeBag.swift */, + 32C44C9A30733440A3D263B43861FBA1 /* DisposeBase.swift */, + 75DAC3F84E978269F03F6516EE7E9FAE /* DistinctUntilChanged.swift */, + CB3FCE54551234A4F3910C33EB48C016 /* Do.swift */, + 0668A90FD8DFEB8D178EE6721979B788 /* ElementAt.swift */, + C860BEC2AFE3C3670391CECBA2707574 /* Empty.swift */, + 7FCDAA2549A70BCA3749CF5FCCF837E9 /* Error.swift */, + 821702C06296B57D769A8DCDD13DE971 /* Errors.swift */, + 0BED5103BCF9D40F85068CF32B24A63E /* Event.swift */, + E7A01B1A67EE04FE1D9C036932C4C037 /* Filter.swift */, + 9675783D8A4B72DF63BAA2050C4E5659 /* Generate.swift */, + 9F067CE8E1D793F3477FF78E26651CDB /* GroupBy.swift */, + 7AC7E0F67AECA3C1CBDBF7BC409CDADC /* GroupedObservable.swift */, + C071467FD72C9E762BDC54865F1A4193 /* HistoricalScheduler.swift */, + 870EAFD138EAD59EAC7EE2CE19DE25B4 /* HistoricalSchedulerTimeConverter.swift */, + F777764A45E0A77BE276ADA473AF453A /* ImmediateScheduler.swift */, + 883F8BF59AD1E1C16492B6CA9A82FB3D /* ImmediateSchedulerType.swift */, + 5017E276F3AE00F1F45A62F9A35F51C0 /* InfiniteSequence.swift */, + 30436E554B573E5078213F681DA0061F /* InvocableScheduledItem.swift */, + 56CC0097103243FBF2702AB35BF7C0A4 /* InvocableType.swift */, + C541B03ABB2F0F5E10F027D5E3C9DF4B /* Just.swift */, + DACA1956515F0B0CED7487724276C51B /* Lock.swift */, + 72730856B78AF39AB4D248DDA7771A5B /* LockOwnerType.swift */, + 4AF8DBA8D803E5226616EC41FA7405ED /* MainScheduler.swift */, + 939E73AB843F47D6C9EA0D065BAF63FC /* Map.swift */, + F1D34B07FCD98BCADAA8A3B68F1ACF1E /* Materialize.swift */, + C1FCEDB728FD2060B1A8C36A71039328 /* Merge.swift */, + 59E44229281B70ACA538454D8DB49FC0 /* Multicast.swift */, + 8F94DF516E7B950F928922C1D41C6D4D /* Never.swift */, + 7737478C5B309559EBEB826D48D81C26 /* NopDisposable.swift */, + 6887D641E8100CE8A13FFA165FC59B73 /* Observable.swift */, + 93D2B184ED95D52B41994F4AA9D93A6C /* ObservableConvertibleType.swift */, + 5B4FF38E4CA2AFB54D788C9F1919BFA8 /* ObservableType.swift */, + C30419C2A3E0EC1B15E0D3AF3D91FB15 /* ObservableType+Extensions.swift */, + BC5B3446AD01BE42D27E9F1B9673C334 /* ObserveOn.swift */, + 9BE04EA000FD69A9AF7258C56417D785 /* ObserverBase.swift */, + 88515C2D0E31A4BB398381850BBA2A54 /* ObserverType.swift */, + 24917B863385D1BB04A2303451C9E272 /* OperationQueueScheduler.swift */, + ECB0A2EA86FF43E01E3D3ACE3BD2752B /* Optional.swift */, + BB1413438046E9B3E8A94F51358A8205 /* Platform.Darwin.swift */, + 48242CA8E564C2C50CFF8E3E77668FB7 /* Platform.Linux.swift */, + 7D9BF77ECD45A0F08FB7892B9597B135 /* PrimitiveSequence.swift */, + 269E63D0B9C1F5552DF3ABA3F5BF88EB /* PrimitiveSequence+Zip+arity.swift */, + 880C5FA0EC7B351BE64E748163FA1C31 /* PriorityQueue.swift */, + 6CCE606004614C138E5498F58AA0D8DF /* Producer.swift */, + FA436001918C6F92DC029B7E695520E8 /* PublishSubject.swift */, + 5A98B8DAD74FBDB55E3D879266AA14CA /* Queue.swift */, + 80C18B1881A0F511B8D6DDA77F355B51 /* Range.swift */, + D984AFE3BDFDD95C397A0D0F80DFECA6 /* Reactive.swift */, + 7C7C61BEED15998D9D7B47AD6F3E069D /* RecursiveLock.swift */, + DAE1A43C13EDE68CF0C6AEA7EA3A2521 /* RecursiveScheduler.swift */, + 7A9E77B670AC48E19FB2C9FE2BD11E32 /* Reduce.swift */, + 31DC6B167D2D13AFD8EAAF1E63021B52 /* RefCountDisposable.swift */, + EAED6E7C8067874A040C7B3863732D73 /* Repeat.swift */, + 7269CAD149BFD0BE4D3B1CA43FE6424F /* ReplaySubject.swift */, + 62F9DE8CE4FBC650CD1C45E4D55A76AB /* RetryWhen.swift */, + 5B5F05AEF12013DFCBEBE433EEBB3C8F /* Rx.swift */, + 59EA941CFCC415131D36B17780FA7F33 /* RxMutableBox.swift */, + F7FE769331C0AFEF35319E2F6260F9DF /* Sample.swift */, + 5FA4778A42883943FE99141A948880BE /* Scan.swift */, + 48E60FBF9296448D4A2FEC7E14FBE6DB /* ScheduledDisposable.swift */, + 6C32D4D3484C860B70069CD1C629F666 /* ScheduledItem.swift */, + 2AF9D1F5A21CB847E913BF41EC110B1F /* ScheduledItemType.swift */, + 60544C2EB93D2C784EF3673B4BA12FAD /* SchedulerServices+Emulation.swift */, + B258A9C347C516AA8D8A3FB2CD665D6D /* SchedulerType.swift */, + B1F0B7854DD41D311F76522F61203F7F /* Sequence.swift */, + 8317D3F53EA1D6DC62811B7F71E22E8E /* SerialDispatchQueueScheduler.swift */, + C367D19B8DD4C0F9954A24DD5A2A6AFB /* SerialDisposable.swift */, + E7513ADBA4C19938F615442415D28732 /* ShareReplay1.swift */, + 365AE864123C488FD72C61ADC9EC624D /* ShareReplay1WhileConnected.swift */, + 1A3D311EA38EC997A02CB05BACC0DD7D /* SingleAssignmentDisposable.swift */, + 805F15552659D5E233243B40C0C6F028 /* SingleAsync.swift */, + 18254952242D69F129DC1ACD4BDF8AF4 /* Sink.swift */, + 7011CBC583696921D4186C6121A7F67F /* Skip.swift */, + 1C897A93D54D11502C0795F3D0F8510F /* SkipUntil.swift */, + 7E3BEFA00C2C7854A37F845BF40B59F4 /* SkipWhile.swift */, + B77F93192159DCCC6CEF8FC5A0924F9A /* StartWith.swift */, + F104D45199031F05FCEEFA8E947F210E /* String+Rx.swift */, + 18328C3FA1839793D455774B0473668C /* SubjectType.swift */, + B80609FF38FDE35E5FE2D38886D2361F /* SubscribeOn.swift */, + 15F7B4D89DB784C462A959824F1E698C /* SubscriptionDisposable.swift */, + B7677FD01A3CD0014041B75BD92F6D97 /* Switch.swift */, + B4EEA393253D8586EB38190FC649A3FA /* SwitchIfEmpty.swift */, + B34B9F812BB8C50E3EA28F4FB51A1095 /* SynchronizedDisposeType.swift */, + E9178D3690ADCB4F8C9057F81C073A45 /* SynchronizedOnType.swift */, + 7B70F2B6C174F1E6C285A5F774C3C97E /* SynchronizedSubscribeType.swift */, + EA39A7A8DF958888156A2207EF666EB1 /* SynchronizedUnsubscribeType.swift */, + 11316F7A1A5EB2E5B756703C0EE77CF6 /* TailRecursiveSink.swift */, + 16B7B7BE1A379F72CFC27449A45EE5AE /* Take.swift */, + 4EACF73E072E466AF5911B9BB191E174 /* TakeLast.swift */, + 65518CF96489DBA6322987069B264467 /* TakeUntil.swift */, + 61148633F9614B9AD57C5470C729902C /* TakeWhile.swift */, + F9F0644CBB2BCA2DB969F16E2B5D92CE /* Throttle.swift */, + 6CBCC23A46623376CB1616C1C121603D /* Timeout.swift */, + 26CDF11A8572688E0011727ADD962B74 /* Timer.swift */, + 37CEC3599B3E7B7EB3DA8FBA9610E255 /* ToArray.swift */, + EA907F82073836CB66D5D606FB1333D9 /* Using.swift */, + 39A2B57F2DAE55FA57D315FDD6953365 /* Variable.swift */, + 772DB63372E4253C20C516EBF68DD251 /* VirtualTimeConverterType.swift */, + E721CFEFA8C057FD4766D5603B283218 /* VirtualTimeScheduler.swift */, + DAE679F6024F9BDC9690AFE107798377 /* Window.swift */, + 3A07BFAFDAB02F19561FDA4115668F66 /* WithLatestFrom.swift */, + A45D3DB105B4381656B330C1B2B6301E /* Zip.swift */, + BFBD0B4CB17B692257A69160584B0895 /* Zip+arity.swift */, + B23F66A643FB8A1DEAC31DC3B637ACEB /* Zip+Collection.swift */, + 2E07FFE8D5239059E139DA4A84322919 /* Support Files */, + ); + name = RxSwift; + path = RxSwift; + sourceTree = ""; + }; + E9F8459055B900A58FB97600A53E5D1C /* PetstoreClient */ = { + isa = PBXGroup; + children = ( + E73D9BF152C59F341559DE62A3143721 /* PetstoreClient */, + 8F6D133867EE63820DFB7E83F4C51252 /* Support Files */, + ); + name = PetstoreClient; + path = ../..; + sourceTree = ""; + }; + FF61792A0279354AB25395F889F59979 /* Alamofire */ = { + isa = PBXGroup; + children = ( + 7728F2E75E01542A06BFA62D24420ADB /* AFError.swift */, + 6489C0664BA4C768FBB891CF9DF2CFD1 /* Alamofire.swift */, + 6DA0155598FD96A2BBFF3496F7380D93 /* DispatchQueue+Alamofire.swift */, + AA42FD2B1F921714FC4FEABAFB8D190A /* MultipartFormData.swift */, + F4668C7356C845C883E13EAB41F34154 /* NetworkReachabilityManager.swift */, + 64082BE2455C7B840B138508D24C0B0C /* Notifications.swift */, + 4F69F88B1008A9EE1DDF85CBC79677A8 /* ParameterEncoding.swift */, + F57EA9DD77194E4F1E5E5E6CB4CDAE4E /* Request.swift */, + DF7CAA870676F2440AC2CCFC5A522F6C /* Response.swift */, + F1FCD92EC4EAB245624BBB2DDECF9B2C /* ResponseSerialization.swift */, + 3ECB713449813E363ABB94C83D77F3A9 /* Result.swift */, + 64AB42C9C8AA1EFF0761D23E6FEF4776 /* ServerTrustPolicy.swift */, + 7098927F58CDA88AF2F555BD54050500 /* SessionDelegate.swift */, + 321FE523C25A0EAF6FF886D6FDE6D24D /* SessionManager.swift */, + E181A2141028C3EB376581163644E247 /* TaskDelegate.swift */, + F5F0AE167B06634076A6A2605697CE49 /* Timeline.swift */, + C0528EC401C03A7544A658C38016A893 /* Validation.swift */, + 3F6894F6346ED0522534B4531C76C476 /* Support Files */, + ); + name = Alamofire; + path = Alamofire; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 1353AC7A6419F876B294A55E5550D1E4 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 31F8B86E3672D0B828B6352C875649C4 /* Pods-SwaggerClientTests-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 411A88E43D5D9D797C82EAD090B6B7C3 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 281AFAEA94C9F83ACC6296BBD7A0D2E4 /* Pods-SwaggerClient-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 8F83F4247FF7A33C0BEB82B35CC248D0 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 9C0BB2AF97FD62807EDEBE69DEF50782 /* PetstoreClient-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9E41EA1B28438EB52F5DF31F4E054588 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + F01BC24737A6EF6A7BE993F32846D421 /* RxSwift-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + B4002B6E97835FDCCAA5963EFE09A3E0 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 1B9EDEDC964E6B08F78920B4F4B9DB84 /* Alamofire-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 136F0A318F13DF38351AC0F2E6934563 /* Pods-SwaggerClient */ = { + isa = PBXNativeTarget; + buildConfigurationList = F74B56615E0AC0F998019998CF3D73B7 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClient" */; + buildPhases = ( + CAA04C85A4D103374E9D4360A031FE9B /* Sources */, + B61347E4B942D85FB700CD798AEC3A6D /* Frameworks */, + 411A88E43D5D9D797C82EAD090B6B7C3 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + AF4FFAE64524D9270D895911B9A3ABB3 /* PBXTargetDependency */, + 9188E15F2308611275AADD534748A210 /* PBXTargetDependency */, + 4DAA97CFDA7F8099D3A7AFC561A555B9 /* PBXTargetDependency */, + ); + name = "Pods-SwaggerClient"; + productName = "Pods-SwaggerClient"; + productReference = 057FC3E5DE19EA8F4DD600557D771032 /* Pods_SwaggerClient.framework */; + productType = "com.apple.product-type.framework"; + }; + 2837E5FF96967EA63E5F7E861959BFC5 /* PetstoreClient */ = { + isa = PBXNativeTarget; + buildConfigurationList = 7F6598701F62B0B1C5B091EE2E3F0DF0 /* Build configuration list for PBXNativeTarget "PetstoreClient" */; + buildPhases = ( + 3A114ED9CC9A08527B63BC0B94371BBE /* Sources */, + 8C8E55731D0837311C5F9AEE7078E3F3 /* Frameworks */, + 8F83F4247FF7A33C0BEB82B35CC248D0 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + 441E977F75EEF0102DB14F8B025276BD /* PBXTargetDependency */, + B2CA96581C57EF58E9BE810E874A6490 /* PBXTargetDependency */, + ); + name = PetstoreClient; + productName = PetstoreClient; + productReference = E9CBBB398E7A62950FA8BC091CBE0359 /* PetstoreClient.framework */; + productType = "com.apple.product-type.framework"; + }; + 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */ = { + isa = PBXNativeTarget; + buildConfigurationList = 419E5D95491847CD79841B971A8A3277 /* Build configuration list for PBXNativeTarget "Alamofire" */; + buildPhases = ( + 32B9974868188C4803318E36329C87FE /* Sources */, + 99195E4207764744AEC07ECCBCD550EB /* Frameworks */, + B4002B6E97835FDCCAA5963EFE09A3E0 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Alamofire; + productName = Alamofire; + productReference = 5B598E168B47485DC60F9DBBCBEEF5BB /* Alamofire.framework */; + productType = "com.apple.product-type.framework"; + }; + E8DEDAB11E7B037AA8A5C5105BF53D42 /* RxSwift */ = { + isa = PBXNativeTarget; + buildConfigurationList = BFE0811465A8E3F52AAAB6D33DD9B27B /* Build configuration list for PBXNativeTarget "RxSwift" */; + buildPhases = ( + 93C16DBB154DC8E9CF39BB034D997D12 /* Sources */, + 4A7651580B2694EFD755E590E1DD812F /* Frameworks */, + 9E41EA1B28438EB52F5DF31F4E054588 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = RxSwift; + productName = RxSwift; + productReference = 84A09D760BA2EA13D5BE269086BAD34C /* RxSwift.framework */; + productType = "com.apple.product-type.framework"; + }; + F3DF8DD6DBDCB07B04D7B1CC8A462562 /* Pods-SwaggerClientTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = B462F7329881FF6565EF44016BE2B959 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClientTests" */; + buildPhases = ( + BDFDEE831A91E115AA482B4E9E9B5CC8 /* Sources */, + 87AF7EC7404199AC8C5D22375A6059BF /* Frameworks */, + 1353AC7A6419F876B294A55E5550D1E4 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "Pods-SwaggerClientTests"; + productName = "Pods-SwaggerClientTests"; + productReference = C4B474BD9070828C0F786071EEF46CD0 /* Pods_SwaggerClientTests.framework */; + productType = "com.apple.product-type.framework"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + D41D8CD98F00B204E9800998ECF8427E /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0730; + LastUpgradeCheck = 0700; + }; + buildConfigurationList = 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = 7DB346D0F39D3F0E887471402A8071AB; + productRefGroup = C1398CE2D296EEBAA178C160CA6E6AD6 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */, + 2837E5FF96967EA63E5F7E861959BFC5 /* PetstoreClient */, + 136F0A318F13DF38351AC0F2E6934563 /* Pods-SwaggerClient */, + F3DF8DD6DBDCB07B04D7B1CC8A462562 /* Pods-SwaggerClientTests */, + E8DEDAB11E7B037AA8A5C5105BF53D42 /* RxSwift */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXSourcesBuildPhase section */ + 32B9974868188C4803318E36329C87FE /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 9ED2BB2981896E0A39EFA365503F58CE /* AFError.swift in Sources */, + A9EEEA7477981DEEBC72432DE9990A4B /* Alamofire-dummy.m in Sources */, + F8B3D3092ED0417E8CDF32033F6122F5 /* Alamofire.swift in Sources */, + 61200D01A1855D7920CEF835C8BE00B0 /* DispatchQueue+Alamofire.swift in Sources */, + B65FCF589DA398C3EFE0128064E510EC /* MultipartFormData.swift in Sources */, + A2A6F71B727312BD45CC7A4AAD7B0AB7 /* NetworkReachabilityManager.swift in Sources */, + EFD264FC408EBF3BA2528E70B08DDD94 /* Notifications.swift in Sources */, + BE5C67A07E289FE1F9BE27335B159997 /* ParameterEncoding.swift in Sources */, + 5387216E723A3C68E851CA15573CDD71 /* Request.swift in Sources */, + CB6D60925223897FFA2662667DF83E8A /* Response.swift in Sources */, + F6BECD98B97CBFEBE2C96F0E9E72A6C0 /* ResponseSerialization.swift in Sources */, + 7D8CC01E8C9EFFF9F4D65406CDE0AB66 /* Result.swift in Sources */, + 62F65AD8DC4F0F9610F4B8B4738EC094 /* ServerTrustPolicy.swift in Sources */, + 7B5FE28C7EA4122B0598738E54DBEBD8 /* SessionDelegate.swift in Sources */, + AE1EF48399533730D0066E04B22CA2D6 /* SessionManager.swift in Sources */, + 3626B94094672CB1C9DEA32B9F9502E1 /* TaskDelegate.swift in Sources */, + 10EB23E9ECC4B33E16933BB1EA560B6A /* Timeline.swift in Sources */, + BBEFE2F9CEB73DC7BD97FFA66A0D9D4F /* Validation.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 3A114ED9CC9A08527B63BC0B94371BBE /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 23BC8C28FAA73E066964C6DF829B08C9 /* AdditionalPropertiesClass.swift in Sources */, + 2C31FD96F208B18BDC8D7486C3AA4A26 /* AlamofireImplementations.swift in Sources */, + 7CE6DC55D9152FB95629A52752FAF5CA /* Animal.swift in Sources */, + FFB5B1F30F30210B83B17FCCF4C0453A /* AnimalFarm.swift in Sources */, + B34E6708A4AC47051C04F75C58D3BEEC /* APIHelper.swift in Sources */, + E956BF8E052B4841F99C3A963BA6C55A /* ApiResponse.swift in Sources */, + B9CA494A4AFDE8C52B3F6D90A4BD1120 /* APIs.swift in Sources */, + 71E5BFD91E5C8AF6ED5D7064321B5127 /* ArrayOfArrayOfNumberOnly.swift in Sources */, + 62909E143F6F7EE50CAFC48DF725EBFB /* ArrayOfNumberOnly.swift in Sources */, + 5D4C6F66F5E087BE67F2887E5E29EF4B /* ArrayTest.swift in Sources */, + 8DAA4A1278B5BC5F7B4D88964444B27F /* Capitalization.swift in Sources */, + 33FE2620347DD810E56795EC10991E11 /* Cat.swift in Sources */, + 31717691AB3E9C1758792C3CF652DC2C /* Category.swift in Sources */, + 8E2709D7B67CFB3F9DD9350B6D10F9E1 /* ClassModel.swift in Sources */, + E0E2C585E6FAE78A091C3E9D68E8C51D /* Client.swift in Sources */, + 6DF49C373380B586ACF445271F522258 /* CodableHelper.swift in Sources */, + 0DCBC9CE464A08CED750039A2076E29A /* Configuration.swift in Sources */, + 46621BFF25A14BE57402CDC543E176C8 /* Dog.swift in Sources */, + 706A9EED70851EF557850C22EBB4A55E /* EnumArrays.swift in Sources */, + D9D7157B8E82FD3EA9527FFB55FDFDA3 /* EnumClass.swift in Sources */, + A33B32B21637691751A537C4D3AC01BB /* EnumTest.swift in Sources */, + FB57C81A917036130717B7633D6C61E9 /* Extensions.swift in Sources */, + 422DCB5DC011F3D4B56E6BDF6076B0B4 /* FakeAPI.swift in Sources */, + 92B4415759ED63F6179B4145A97DDF9D /* FormatTest.swift in Sources */, + 029FC30CF995C77BD2B077C475C5ABF9 /* HasOnlyReadOnly.swift in Sources */, + 60B375EE1E1B3D8B358B6F616A3BDBD5 /* JSONEncodableEncoding.swift in Sources */, + 8B4EEEB1E2148EB4E33F3E4DD168AE6D /* JSONEncodingHelper.swift in Sources */, + 5A6B1C1CBBD3AAC96E1D301C1041C67B /* List.swift in Sources */, + C1231330EA76D9B9229B19C872C75523 /* MapTest.swift in Sources */, + 6232741FBF5E14F1FDCEA83F645E721A /* MixedPropertiesAndAdditionalPropertiesClass.swift in Sources */, + D1EA8B4DFD94E6BB87F5301A73E5E953 /* Model200Response.swift in Sources */, + 366C0CE0948D4FD875334C2F655BA6A0 /* Models.swift in Sources */, + 7184914B9064EDED86A2BAE7D8FD8E73 /* Name.swift in Sources */, + 2A834CD7058DCD3A72B680DB99B76EFC /* NumberOnly.swift in Sources */, + 46408F878C74A244E8A54D1CEF78561F /* Order.swift in Sources */, + AA3D05951A21C1D18FB7CC6CF9B17CD4 /* OuterBoolean.swift in Sources */, + 4A92F049533F11DD39C2CC7EEFFE1C8A /* OuterComposite.swift in Sources */, + 023D1D9D4E093100D847913CFED50A74 /* OuterEnum.swift in Sources */, + E77F71BF5E59D5B613A01CE2402B452C /* OuterNumber.swift in Sources */, + 64C751E7EE440C59D6A0EC77C2E499DE /* OuterString.swift in Sources */, + 4E9624834AEB88088D34D7A1C5963E0A /* Pet.swift in Sources */, + 174EBB2A52F1BB6E943D43A9118E5BA7 /* PetAPI.swift in Sources */, + 5CF5991A8288B434E6E6888DBD1CD2A1 /* PetstoreClient-dummy.m in Sources */, + 858CE0C1137E20D7790A86FA94E3BA93 /* ReadOnlyFirst.swift in Sources */, + F2935C2E2CEEA6C3E8633E0B03EACBD9 /* Return.swift in Sources */, + 8CF9E1445350F8173583A6976731DDBD /* SpecialModelName.swift in Sources */, + 07B475A196F098B24CD1E19A88DC7014 /* StoreAPI.swift in Sources */, + F1AC8927E1A33C651564627140495148 /* Tag.swift in Sources */, + E07F9E8C01F513BFECB85D28AD83778E /* User.swift in Sources */, + 795CC0B664785EBD5F138549E457FB05 /* UserAPI.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 93C16DBB154DC8E9CF39BB034D997D12 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 8E5914B860D1B5199F751A3FEB8DB835 /* AddRef.swift in Sources */, + 14AF37170805FEEA7FC1663CB1741E56 /* Amb.swift in Sources */, + F07B9F771FFEDE12F88006F49C22A6E0 /* AnonymousDisposable.swift in Sources */, + 251956FE94EBA2E766BE0F99847DBB37 /* AnonymousInvocable.swift in Sources */, + A6531EC821090A82EED5E99C1A3FAFC8 /* AnonymousObserver.swift in Sources */, + 478E697551223A40A48A7CA4F732B6D2 /* AnyObserver.swift in Sources */, + 48BD9FF08780754C12487CB31F66C283 /* AsMaybe.swift in Sources */, + 05434308230CE260C67F2AA72F668B42 /* AsSingle.swift in Sources */, + 11662A34666A7661D79EF3F66B19C853 /* AsyncLock.swift in Sources */, + 687A75F93305045731FE4788F204FBE7 /* AsyncSubject.swift in Sources */, + 59BA6D9D29F93FBDEB624C0B66F54699 /* Bag+Rx.swift in Sources */, + 7A4BBA7F582C8B323D338CF692448AED /* Bag.swift in Sources */, + 378E8BDB87FEB648A473B1A8C09880BF /* BehaviorSubject.swift in Sources */, + 042CEED27B8AEA495E49959EB3F82053 /* BinaryDisposable.swift in Sources */, + 437FD4F20E6CCA77205C06A80254013D /* BooleanDisposable.swift in Sources */, + 3728D59522E663AAD6C46F46EFECAECE /* Buffer.swift in Sources */, + 2C9B1C3DCBAB56C8F63E4AD23394747D /* Cancelable.swift in Sources */, + 4E611B02357FA35BC9BE3ABF54204720 /* Catch.swift in Sources */, + 75C53DB402B577C8F2B84FF52B215273 /* CombineLatest+arity.swift in Sources */, + 8B381A672F67EFD4E28AE41DC6C09E32 /* CombineLatest+Collection.swift in Sources */, + C85636A520F6B62A5705106396CC8555 /* CombineLatest.swift in Sources */, + 173B6F93D4DE52781164BBC0E28FA6C0 /* CompositeDisposable.swift in Sources */, + 566F127E9A2C44E602ED79003C26FAC4 /* Concat.swift in Sources */, + E5A9844D1E1181CC100901AEBFEF2594 /* ConcurrentDispatchQueueScheduler.swift in Sources */, + 6B8F33F8AF88B6B9F7E71D3A51CBBF26 /* ConcurrentMainScheduler.swift in Sources */, + EB82DDF3CDA1C8F4119D65ADD824E229 /* ConnectableObservable.swift in Sources */, + 87710B0BE6B1D35BA1089D3D26A3C6B3 /* ConnectableObservableType.swift in Sources */, + E198B4DBA859E20C62670BFA81AD4C3F /* Create.swift in Sources */, + 996C2CA8DEF676FCF156B247CB261E4D /* CurrentThreadScheduler.swift in Sources */, + 752C27C236935788BAE0385B31EB337B /* Debounce.swift in Sources */, + 881A524A3B984BD661474E613677A8B1 /* Debug.swift in Sources */, + AE284464AE544C8F6F0DB932E5CDAAE8 /* DefaultIfEmpty.swift in Sources */, + 718FD78BC2B5CE5D26FBDF35777FD50B /* Deferred.swift in Sources */, + 0F5E293AFDB33339261060E5346578A9 /* Delay.swift in Sources */, + C6EADDBBCB153E895C983C06EF6DD3AC /* DelaySubscription.swift in Sources */, + 8947B195C3745586358032D1A4F6C611 /* Dematerialize.swift in Sources */, + C2F1E72D8D37218AEAD0AF8CDF7CDA2A /* Deprecated.swift in Sources */, + E585F8E6C1C60A0D07836B3B59B265B1 /* DispatchQueue+Extensions.swift in Sources */, + C0075D24F6A3B955E7494EF1E489F88C /* DispatchQueueConfiguration.swift in Sources */, + 2126C1E263B2EF2007442FB3953670CF /* Disposable.swift in Sources */, + E25F732E580028B0199F4066D13C597B /* Disposables.swift in Sources */, + 1F514669DD8305A932C9686E90653160 /* DisposeBag.swift in Sources */, + 26D4DB444B51A5F8B5B5379F031179E4 /* DisposeBase.swift in Sources */, + 08C5AAFAA82B2B16870A85DC53AA9D54 /* DistinctUntilChanged.swift in Sources */, + 36FDD0A47378AADCA2D2FF11F07FE629 /* Do.swift in Sources */, + 7F22F2B8DA555C92027C84C14865D117 /* ElementAt.swift in Sources */, + 3AD79904F10FAA988080A99CA3DEA1B0 /* Empty.swift in Sources */, + 0E95E2B4EE376617EED90402D22E2064 /* Error.swift in Sources */, + AFB1EB0005188DEE754ABF4C4BB5A8C7 /* Errors.swift in Sources */, + EA673361DD150A38520EF307EB17AD9E /* Event.swift in Sources */, + E9F1BECE5C764114F317E3B6B9162667 /* Filter.swift in Sources */, + A7345084BD26040CDC406F5B8ACEB439 /* Generate.swift in Sources */, + CEA2A8A4E36095510E15298612F32C58 /* GroupBy.swift in Sources */, + AF641042D53C43BF8757FBD3CA8E6B5D /* GroupedObservable.swift in Sources */, + B74BE992119AE1BAC8380B2A62A85A96 /* HistoricalScheduler.swift in Sources */, + F31D497BACB658228637EB913918F952 /* HistoricalSchedulerTimeConverter.swift in Sources */, + E3452A69A219F48484893674A8F8B333 /* ImmediateScheduler.swift in Sources */, + 82EC83088D42C7AF036EAC90CA0EC4DD /* ImmediateSchedulerType.swift in Sources */, + C6BC225ADD9B69CED61B8BFBD4C2D24D /* InfiniteSequence.swift in Sources */, + 9E592E40FE434896241A81819DA417D9 /* InvocableScheduledItem.swift in Sources */, + 204293B54491328EBFCC506EF2F2331F /* InvocableType.swift in Sources */, + FAD42007C7BC77A262FDA9F5265C3312 /* Just.swift in Sources */, + 5F5FD5BBB0BE079D6225327B54D77856 /* Lock.swift in Sources */, + 674961F2E1587E146A678DE0E7F7799E /* LockOwnerType.swift in Sources */, + A873E42860058F41BC2A86A30D800A82 /* MainScheduler.swift in Sources */, + 33DF7CD52F1810D369E0B6246D9F4026 /* Map.swift in Sources */, + 66E79497A285F244010125A8CCCC8DA6 /* Materialize.swift in Sources */, + 699728DB0F1DD4724A6194D6E3AFE5F9 /* Merge.swift in Sources */, + 7FA7CE127D4B0DAFCACA8258B1AFB1EB /* Multicast.swift in Sources */, + B9F0D01FEDAF7011F7A4417A43AA0A10 /* Never.swift in Sources */, + 3B39CFE8304874684649508E1C5B6AF7 /* NopDisposable.swift in Sources */, + ADD1CB76F8658ECE9A0FF6BD51908BF3 /* Observable.swift in Sources */, + D556076DDC550682BEECCEB3C37FADF9 /* ObservableConvertibleType.swift in Sources */, + 80EAFB32C911390136DF02D78D43A43A /* ObservableType+Extensions.swift in Sources */, + FA1D1261DB26D216DD6B78418D024A31 /* ObservableType.swift in Sources */, + FBADAA44CA33F062B9A0CB84A7558262 /* ObserveOn.swift in Sources */, + 8F93A485E427E9174C5B226C0745C50C /* ObserverBase.swift in Sources */, + 0A1B1515BE0679E0C397005946DBACE6 /* ObserverType.swift in Sources */, + 7CCEA4D230FCC455D4D9C04122F11AEE /* OperationQueueScheduler.swift in Sources */, + 5808F5D7BD8F0F5C53B085E23EDE442E /* Optional.swift in Sources */, + 6B2A09D0E78C6A727C1A7F81E6D2A78D /* Platform.Darwin.swift in Sources */, + 738FC6F9A5AF6977170AA24621FE9A89 /* Platform.Linux.swift in Sources */, + F5C0376459DD63893B9F91FDC8BCF807 /* PrimitiveSequence+Zip+arity.swift in Sources */, + B31F79F9A3C2824A2993493E4B915E0D /* PrimitiveSequence.swift in Sources */, + 3B6185DBF9E4D927E1EFA16AC5ECC64F /* PriorityQueue.swift in Sources */, + 9385E37D5298476BEE58892CDB2AB911 /* Producer.swift in Sources */, + 769CA2CEA89938507051682F58F5B739 /* PublishSubject.swift in Sources */, + 7EC367969459A4C9954F68892920C636 /* Queue.swift in Sources */, + 5CF06AC8C33500191521DED85C42E0E7 /* Range.swift in Sources */, + 63CD1B23614A22D49CE538603A922FB8 /* Reactive.swift in Sources */, + FCE497B5706C8900534EE96E790F1205 /* RecursiveLock.swift in Sources */, + 82CAF4682477DBE59734FF1341227663 /* RecursiveScheduler.swift in Sources */, + DD5F8EB279A6341B3CDEC6B36A057001 /* Reduce.swift in Sources */, + 2B07B6C2E7F071930AD113DED4E6340D /* RefCountDisposable.swift in Sources */, + 1DE613D9E922FB6ED5CD5200912B2629 /* Repeat.swift in Sources */, + 3D533E2D5A41DE864A2EBEA7E1FC6EAD /* ReplaySubject.swift in Sources */, + 0161E77CE771A20E652637576C11288A /* RetryWhen.swift in Sources */, + 3A70221A6F02D3DB6265483E3FCDAA5D /* Rx.swift in Sources */, + F8C505130735B376CBDA87289A56095E /* RxMutableBox.swift in Sources */, + 2822F49595AEE69D96D94D5793B3373E /* RxSwift-dummy.m in Sources */, + A27F8BAE0E571A46B89423DE8A14289F /* Sample.swift in Sources */, + EF95B008F0A8E62D9B326C0269E06D76 /* Scan.swift in Sources */, + 78512A64DF32CABEC36D10DF56D86A19 /* ScheduledDisposable.swift in Sources */, + 2AB4A4574BC8CB64F49E0B68F8ED61F6 /* ScheduledItem.swift in Sources */, + B6EDAB8C1E6B1AB3BFE4EE7EBC9C49BE /* ScheduledItemType.swift in Sources */, + D07EC53425E587F6C78DC216196706D3 /* SchedulerServices+Emulation.swift in Sources */, + 246646DA752E6C3A9DB8FC582BF21DEC /* SchedulerType.swift in Sources */, + FC2E633740DE8FBE2A334BC7BDCA06C2 /* Sequence.swift in Sources */, + 08EB4C1011B17FDF370CF8B8DCFB6C26 /* SerialDispatchQueueScheduler.swift in Sources */, + 3F75EA6E43704FDCB74DE2FBE7B26B98 /* SerialDisposable.swift in Sources */, + 9BE98C6A25F0A3D58447D017E329A74C /* ShareReplay1.swift in Sources */, + 00C95B00E274459CAEA6FBBC3E3DFA3F /* ShareReplay1WhileConnected.swift in Sources */, + C05CC775CDC72B19F39193D0A7963FD5 /* SingleAssignmentDisposable.swift in Sources */, + BCA27068F62DF3C4AF7F922A5800DAD0 /* SingleAsync.swift in Sources */, + C476C0D3C68492238174642EC1FBB8D0 /* Sink.swift in Sources */, + 092E09A292EACB3789AB861CC905C9B1 /* Skip.swift in Sources */, + 3BF121D4A9FBEAA1ACCCB784D882FC28 /* SkipUntil.swift in Sources */, + 7FE94EEF4752F45F7D9F66D9524A179C /* SkipWhile.swift in Sources */, + 0C929D0417407AC779147DB0484DAD54 /* StartWith.swift in Sources */, + D0A0CFCF09F7868220437333F425BDCC /* String+Rx.swift in Sources */, + 41CE2A41E4001649958EE2C8BD18BCBA /* SubjectType.swift in Sources */, + DCF2A0BC50F66AC329586306A6D31155 /* SubscribeOn.swift in Sources */, + 1178860EDD15DEB3E6A410AF8259253B /* SubscriptionDisposable.swift in Sources */, + 63FA3285013BD933ACE21B6E63FD8FEA /* Switch.swift in Sources */, + 0F1EC6F732F2A572C50396C8AC80B09C /* SwitchIfEmpty.swift in Sources */, + 8CA70260592E5581330996FFCFE46244 /* SynchronizedDisposeType.swift in Sources */, + 0AAEA1A171BF1E732F383B4BCA84EA57 /* SynchronizedOnType.swift in Sources */, + 3C5C260B32509F399FB6A66A420AFA61 /* SynchronizedSubscribeType.swift in Sources */, + 7D76060250DB268942EB8DC75DBF6D91 /* SynchronizedUnsubscribeType.swift in Sources */, + DA66B65753E93CE2577AD8B0F1840E2C /* TailRecursiveSink.swift in Sources */, + 876D748B0125657E576848AFCA30320E /* Take.swift in Sources */, + 500D3B6DEBB40B757375AC8AFA9337CF /* TakeLast.swift in Sources */, + 63D0E36AD412A2FD9CDF7F88E0057B40 /* TakeUntil.swift in Sources */, + A0970A71F45E91480EF6CA6C704ACFA9 /* TakeWhile.swift in Sources */, + 4360C9F8B14834B74EF2EE4FC112977D /* Throttle.swift in Sources */, + 52BFD5DED3C1390E8AF35944507BDA41 /* Timeout.swift in Sources */, + 5F1AE969EB429C504C3D7902AE733270 /* Timer.swift in Sources */, + C7DB82C5CF6A8F3191DD1B6CAFFB025D /* ToArray.swift in Sources */, + 1426B771241B8FEF628AC5AF5812CC3E /* Using.swift in Sources */, + 76D17ABECF45D1B4D734F13084330870 /* Variable.swift in Sources */, + BDA28FE86F9E0530B7C6B93C5BE6A3B0 /* VirtualTimeConverterType.swift in Sources */, + 1D6086B9EB58E46FA66BF6BCC4B77CD5 /* VirtualTimeScheduler.swift in Sources */, + 277A7BF574628ECBA24B448004302D2A /* Window.swift in Sources */, + 99C8FFABABC2F8EEA3E7DEEA53CFD05F /* WithLatestFrom.swift in Sources */, + DF2FB5F62117CCC04A595C338B089C69 /* Zip+arity.swift in Sources */, + F8C14BA4A8CF63EF1C1495175402EE0F /* Zip+Collection.swift in Sources */, + D76C36F4419B1029715732B8F79B5358 /* Zip.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + BDFDEE831A91E115AA482B4E9E9B5CC8 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 897985FA042CD12B825C3032898FAB26 /* Pods-SwaggerClientTests-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + CAA04C85A4D103374E9D4360A031FE9B /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 91BCA631F516CB40742B0D2B1A211246 /* Pods-SwaggerClient-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 441E977F75EEF0102DB14F8B025276BD /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */; + targetProxy = F4CD590A32AA7D5C2F5D6400E4547B0C /* PBXContainerItemProxy */; + }; + 4DAA97CFDA7F8099D3A7AFC561A555B9 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxSwift; + target = E8DEDAB11E7B037AA8A5C5105BF53D42 /* RxSwift */; + targetProxy = A50F0C9B9BA00FA72637B7EE5F05D32C /* PBXContainerItemProxy */; + }; + 9188E15F2308611275AADD534748A210 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = PetstoreClient; + target = 2837E5FF96967EA63E5F7E861959BFC5 /* PetstoreClient */; + targetProxy = 2B4A36E763D78D2BA39A638AF167D81A /* PBXContainerItemProxy */; + }; + AF4FFAE64524D9270D895911B9A3ABB3 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */; + targetProxy = 0B2AA791B256C6F1530511EEF7AB4A24 /* PBXContainerItemProxy */; + }; + B2CA96581C57EF58E9BE810E874A6490 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxSwift; + target = E8DEDAB11E7B037AA8A5C5105BF53D42 /* RxSwift */; + targetProxy = 2DCB98A99AD653C10CE969703079F4AA /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 049FD88A00F46088D2BFCDD93106C4B8 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = FB65A0C0C98ACB27CAE43B38C6B4A9FC /* RxSwift.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/RxSwift/RxSwift-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/RxSwift/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/RxSwift/RxSwift.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = RxSwift; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 0A29B6F510198AF64EFD762EF6FA97A5 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = C0141EB6EAA64B81BBA6C558E75FE6A3 /* Alamofire.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 13E96A645A77DAD1FD4F541F18F5DDBF /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGNING_REQUIRED = NO; + COPY_PHASE_STRIP = NO; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_DEBUG=1", + "DEBUG=1", + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; + ONLY_ACTIVE_ARCH = YES; + PROVISIONING_PROFILE_SPECIFIER = NO_SIGNING/; + STRIP_INSTALLED_PRODUCT = NO; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Debug; + }; + 1B844800D176F3A29FC5285315BC3DAA /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = FB65A0C0C98ACB27CAE43B38C6B4A9FC /* RxSwift.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/RxSwift/RxSwift-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/RxSwift/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/RxSwift/RxSwift.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = RxSwift; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 7DF398BA95C03133FA075421DCE0F3A2 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClientTests/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClientTests; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 862AF3139CD84E18D34FAF2F43CD0DA6 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGNING_REQUIRED = NO; + COPY_PHASE_STRIP = YES; + ENABLE_NS_ASSERTIONS = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_RELEASE=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; + PROVISIONING_PROFILE_SPECIFIER = NO_SIGNING/; + STRIP_INSTALLED_PRODUCT = NO; + SYMROOT = "${SRCROOT}/../build"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + B41B509A79F2C30E68C522FD2127E988 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/PetstoreClient/PetstoreClient-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/PetstoreClient/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/PetstoreClient/PetstoreClient.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = PetstoreClient; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + C45D0F76749207E7E5705591412F9A28 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClientTests/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClientTests; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + C5CA9151745B15E40168EB5564219ADA /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClient/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClient; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + D563BB09E639A64A9DF67D4CD17FC213 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/PetstoreClient/PetstoreClient-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/PetstoreClient/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/PetstoreClient/PetstoreClient.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = PetstoreClient; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + DA5584B68BA62D0430D7F179D8B4EA21 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClient/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClient; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + F383079BFBF927813EA3613CFB679FDE /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = C0141EB6EAA64B81BBA6C558E75FE6A3 /* Alamofire.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 13E96A645A77DAD1FD4F541F18F5DDBF /* Debug */, + 862AF3139CD84E18D34FAF2F43CD0DA6 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 419E5D95491847CD79841B971A8A3277 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + F383079BFBF927813EA3613CFB679FDE /* Debug */, + 0A29B6F510198AF64EFD762EF6FA97A5 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 7F6598701F62B0B1C5B091EE2E3F0DF0 /* Build configuration list for PBXNativeTarget "PetstoreClient" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + D563BB09E639A64A9DF67D4CD17FC213 /* Debug */, + B41B509A79F2C30E68C522FD2127E988 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + B462F7329881FF6565EF44016BE2B959 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClientTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 7DF398BA95C03133FA075421DCE0F3A2 /* Debug */, + C45D0F76749207E7E5705591412F9A28 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + BFE0811465A8E3F52AAAB6D33DD9B27B /* Build configuration list for PBXNativeTarget "RxSwift" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 049FD88A00F46088D2BFCDD93106C4B8 /* Debug */, + 1B844800D176F3A29FC5285315BC3DAA /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + F74B56615E0AC0F998019998CF3D73B7 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClient" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + C5CA9151745B15E40168EB5564219ADA /* Debug */, + DA5584B68BA62D0430D7F179D8B4EA21 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = D41D8CD98F00B204E9800998ECF8427E /* Project object */; +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/LICENSE.md b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/LICENSE.md new file mode 100644 index 0000000000..d6765d9c9b --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/LICENSE.md @@ -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. \ No newline at end of file diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/Platform/DataStructures/Bag.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/Platform/DataStructures/Bag.swift new file mode 100644 index 0000000000..897cdadf58 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/Platform/DataStructures/Bag.swift @@ -0,0 +1,187 @@ +// +// Bag.swift +// Platform +// +// Created by Krunoslav Zaher on 2/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Swift + +let arrayDictionaryMaxSize = 30 + +struct BagKey { + /** + Unique identifier for object added to `Bag`. + + It's underlying type is UInt64. If we assume there in an idealized CPU that works at 4GHz, + it would take ~150 years of continuous running time for it to overflow. + */ + fileprivate let rawValue: UInt64 +} + +/** +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. +*/ +struct Bag : CustomDebugStringConvertible { + /// Type of identifier for inserted elements. + typealias KeyType = BagKey + + typealias Entry = (key: BagKey, value: T) + + fileprivate var _nextKey: BagKey = BagKey(rawValue: 0) + + // data + + // first fill inline variables + var _key0: BagKey? = nil + var _value0: T? = nil + + // then fill "array dictionary" + var _pairs = ContiguousArray() + + // last is sparse dictionary + var _dictionary: [BagKey : T]? = nil + + var _onlyFastPath = true + + /// Creates new empty `Bag`. + init() { + } + + /** + Inserts `value` into bag. + + - parameter element: Element to insert. + - returns: Key that can be used to remove element from bag. + */ + mutating func insert(_ element: T) -> BagKey { + let key = _nextKey + + _nextKey = BagKey(rawValue: _nextKey.rawValue &+ 1) + + if _key0 == nil { + _key0 = key + _value0 = element + return key + } + + _onlyFastPath = false + + 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. + var count: Int { + let dictionaryCount: Int = _dictionary?.count ?? 0 + return (_value0 != nil ? 1 : 0) + _pairs.count + dictionaryCount + } + + /// Removes all elements from bag and clears capacity. + mutating func removeAll() { + _key0 = nil + _value0 = nil + + _pairs.removeAll(keepingCapacity: false) + _dictionary?.removeAll(keepingCapacity: 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. + */ + mutating func removeKey(_ key: BagKey) -> T? { + if _key0 == key { + _key0 = nil + let value = _value0! + _value0 = nil + return value + } + + if let existingObject = _dictionary?.removeValue(forKey: key) { + return existingObject + } + + for i in 0 ..< _pairs.count { + if _pairs[i].key == key { + let value = _pairs[i].value + _pairs.remove(at: i) + return value + } + } + + return nil + } +} + +extension Bag { + /// A textual representation of `self`, suitable for debugging. + var debugDescription : String { + return "\(self.count) elements in Bag" + } +} + +extension Bag { + /// Enumerates elements inside the bag. + /// + /// - parameter action: Enumeration closure. + func forEach(_ action: (T) -> Void) { + if _onlyFastPath { + if let value0 = _value0 { + action(value0) + } + return + } + + let value0 = _value0 + let dictionary = _dictionary + + if let value0 = value0 { + action(value0) + } + + for i in 0 ..< _pairs.count { + action(_pairs[i].value) + } + + if dictionary?.count ?? 0 > 0 { + for element in dictionary!.values { + action(element) + } + } + } +} + +extension BagKey: Hashable { + var hashValue: Int { + return rawValue.hashValue + } +} + +func ==(lhs: BagKey, rhs: BagKey) -> Bool { + return lhs.rawValue == rhs.rawValue +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift new file mode 100644 index 0000000000..5a573a0de1 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift @@ -0,0 +1,26 @@ +// +// InfiniteSequence.swift +// Platform +// +// Created by Krunoslav Zaher on 6/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Sequence that repeats `repeatedValue` infinite number of times. +struct InfiniteSequence : Sequence { + typealias Element = E + typealias Iterator = AnyIterator + + private let _repeatedValue: E + + init(repeatedValue: E) { + _repeatedValue = repeatedValue + } + + func makeIterator() -> Iterator { + let repeatedValue = _repeatedValue + return AnyIterator { + return repeatedValue + } + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift new file mode 100644 index 0000000000..fae70a0539 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift @@ -0,0 +1,112 @@ +// +// PriorityQueue.swift +// Platform +// +// Created by Krunoslav Zaher on 12/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +struct PriorityQueue { + private let _hasHigherPriority: (Element, Element) -> Bool + private let _isEqual: (Element, Element) -> Bool + + fileprivate var _elements = [Element]() + + init(hasHigherPriority: @escaping (Element, Element) -> Bool, isEqual: @escaping (Element, Element) -> Bool) { + _hasHigherPriority = hasHigherPriority + _isEqual = isEqual + } + + 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 _isEqual(_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 + guard _hasHigherPriority(_elements[unbalancedIndex], _elements[parentIndex]) else { break } + + swap(&_elements[unbalancedIndex], &_elements[parentIndex]) + unbalancedIndex = parentIndex + } + } + + private mutating func bubbleToLowerPriority(_ initialUnbalancedIndex: Int) { + precondition(initialUnbalancedIndex >= 0) + precondition(initialUnbalancedIndex < _elements.count) + + var unbalancedIndex = initialUnbalancedIndex + while true { + 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 + } + + guard highestPriorityIndex != unbalancedIndex else { break } + + swap(&_elements[highestPriorityIndex], &_elements[unbalancedIndex]) + unbalancedIndex = highestPriorityIndex + } + } +} + +extension PriorityQueue : CustomDebugStringConvertible { + var debugDescription: String { + return _elements.debugDescription + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/Platform/DataStructures/Queue.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/Platform/DataStructures/Queue.swift new file mode 100644 index 0000000000..d05726c7b9 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/Platform/DataStructures/Queue.swift @@ -0,0 +1,152 @@ +// +// Queue.swift +// Platform +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** +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). +*/ +struct Queue: Sequence { + /// Type of generator. + typealias Generator = AnyIterator + + private let _resizeFactor = 2 + + private var _storage: ContiguousArray + private var _count = 0 + private var _pushNextIndex = 0 + private let _initialCapacity: Int + + /** + Creates new queue. + + - parameter capacity: Capacity of newly created queue. + */ + init(capacity: Int) { + _initialCapacity = capacity + + _storage = ContiguousArray(repeating: nil, count: capacity) + } + + private var dequeueIndex: Int { + let index = _pushNextIndex - count + return index < 0 ? index + _storage.count : index + } + + /// - returns: Is queue empty. + var isEmpty: Bool { + return count == 0 + } + + /// - returns: Number of elements inside queue. + var count: Int { + return _count + } + + /// - returns: Element in front of a list of elements to `dequeue`. + func peek() -> T { + precondition(count > 0) + + return _storage[dequeueIndex]! + } + + mutating private func resizeTo(_ size: Int) { + var newStorage = ContiguousArray(repeating: nil, count: size) + + let count = _count + + let dequeueIndex = self.dequeueIndex + let spaceToEndOfQueue = _storage.count - dequeueIndex + + // first batch is from dequeue index to end of array + let countElementsInFirstBatch = Swift.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. + mutating func enqueue(_ element: T) { + if count == _storage.count { + resizeTo(Swift.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. + 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. + func makeIterator() -> AnyIterator { + var i = dequeueIndex + var count = _count + + return AnyIterator { + if count == 0 { + return nil + } + + defer { + count -= 1 + i += 1 + } + + if i >= self._storage.count { + i -= self._storage.count + } + + return self._storage[i] + } + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift new file mode 100644 index 0000000000..552314a169 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift @@ -0,0 +1,21 @@ +// +// DispatchQueue+Extensions.swift +// Platform +// +// Created by Krunoslav Zaher on 10/22/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Dispatch + +extension DispatchQueue { + private static var token: DispatchSpecificKey<()> = { + let key = DispatchSpecificKey<()>() + DispatchQueue.main.setSpecific(key: key, value: ()) + return key + }() + + static var isMain: Bool { + return DispatchQueue.getSpecific(key: token) != nil + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/Platform/Platform.Darwin.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/Platform/Platform.Darwin.swift new file mode 100644 index 0000000000..d9e744fe72 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/Platform/Platform.Darwin.swift @@ -0,0 +1,66 @@ +// +// Platform.Darwin.swift +// Platform +// +// Created by Krunoslav Zaher on 12/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) + + import Darwin + import class Foundation.Thread + import func Foundation.OSAtomicCompareAndSwap32Barrier + import func Foundation.OSAtomicIncrement32Barrier + import func Foundation.OSAtomicDecrement32Barrier + import protocol Foundation.NSCopying + + typealias AtomicInt = Int32 + + fileprivate func castToUInt32Pointer(_ pointer: UnsafeMutablePointer) -> UnsafeMutablePointer { + let raw = UnsafeMutableRawPointer(pointer) + return raw.assumingMemoryBound(to: UInt32.self) + } + + let AtomicCompareAndSwap = OSAtomicCompareAndSwap32Barrier + let AtomicIncrement = OSAtomicIncrement32Barrier + let AtomicDecrement = OSAtomicDecrement32Barrier + func AtomicOr(_ mask: UInt32, _ theValue : UnsafeMutablePointer) -> Int32 { + return OSAtomicOr32OrigBarrier(mask, castToUInt32Pointer(theValue)) + } + func AtomicFlagSet(_ mask: UInt32, _ theValue : UnsafeMutablePointer) -> Bool { + // just used to create a barrier + OSAtomicXor32OrigBarrier(0, castToUInt32Pointer(theValue)) + return (theValue.pointee & Int32(mask)) != 0 + } + + extension Thread { + + static func setThreadLocalStorageValue(_ value: T?, forKey key: NSCopying + ) { + let currentThread = Thread.current + let threadDictionary = currentThread.threadDictionary + + if let newValue = value { + threadDictionary[key] = newValue + } + else { + threadDictionary[key] = nil + } + + } + static func getThreadLocalStorageValueForKey(_ key: NSCopying) -> T? { + let currentThread = Thread.current + let threadDictionary = currentThread.threadDictionary + + return threadDictionary[key] as? T + } + } + + extension AtomicInt { + func valueSnapshot() -> Int32 { + return self + } + } + +#endif diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/Platform/Platform.Linux.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/Platform/Platform.Linux.swift new file mode 100644 index 0000000000..5cd07e2c04 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/Platform/Platform.Linux.swift @@ -0,0 +1,105 @@ +// +// Platform.Linux.swift +// Platform +// +// Created by Krunoslav Zaher on 12/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(Linux) + + import XCTest + import Glibc + import SwiftShims + import class Foundation.Thread + + final class AtomicInt { + typealias IntegerLiteralType = Int + fileprivate var value: Int32 = 0 + fileprivate var _lock = RecursiveLock() + + func lock() { + _lock.lock() + } + func unlock() { + _lock.unlock() + } + + func valueSnapshot() -> Int32 { + return value + } + } + + extension AtomicInt: ExpressibleByIntegerLiteral { + convenience init(integerLiteral value: Int) { + self.init() + self.value = Int32(value) + } + } + + func >(lhs: AtomicInt, rhs: Int32) -> Bool { + return lhs.value > rhs + } + func ==(lhs: AtomicInt, rhs: Int32) -> Bool { + return lhs.value == rhs + } + + func AtomicFlagSet(_ mask: UInt32, _ atomic: inout AtomicInt) -> Bool { + atomic.lock(); defer { atomic.unlock() } + return (atomic.value & Int32(mask)) != 0 + } + + func AtomicOr(_ mask: UInt32, _ atomic: inout AtomicInt) -> Int32 { + atomic.lock(); defer { atomic.unlock() } + let value = atomic.value + atomic.value |= Int32(mask) + return value + } + + func AtomicIncrement(_ atomic: inout AtomicInt) -> Int32 { + atomic.lock(); defer { atomic.unlock() } + atomic.value += 1 + return atomic.value + } + + func AtomicDecrement(_ atomic: inout AtomicInt) -> Int32 { + atomic.lock(); defer { atomic.unlock() } + atomic.value -= 1 + return atomic.value + } + + func AtomicCompareAndSwap(_ l: Int32, _ r: Int32, _ atomic: inout AtomicInt) -> Bool { + atomic.lock(); defer { atomic.unlock() } + if atomic.value == l { + atomic.value = r + return true + } + + return false + } + + extension Thread { + + static func setThreadLocalStorageValue(_ value: T?, forKey key: String) { + let currentThread = Thread.current + var threadDictionary = currentThread.threadDictionary + + if let newValue = value { + threadDictionary[key] = newValue + } + else { + threadDictionary[key] = nil + } + + currentThread.threadDictionary = threadDictionary + } + + static func getThreadLocalStorageValueForKey(_ key: String) -> T? { + let currentThread = Thread.current + let threadDictionary = currentThread.threadDictionary + + return threadDictionary[key] as? T + } + } + +#endif diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/Platform/RecursiveLock.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/Platform/RecursiveLock.swift new file mode 100644 index 0000000000..c03471d502 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/Platform/RecursiveLock.swift @@ -0,0 +1,34 @@ +// +// RecursiveLock.swift +// Platform +// +// Created by Krunoslav Zaher on 12/18/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import class Foundation.NSRecursiveLock + +#if TRACE_RESOURCES + class RecursiveLock: NSRecursiveLock { + override init() { + _ = Resources.incrementTotal() + super.init() + } + + override func lock() { + super.lock() + _ = Resources.incrementTotal() + } + + override func unlock() { + super.unlock() + _ = Resources.decrementTotal() + } + + deinit { + _ = Resources.decrementTotal() + } + } +#else + typealias RecursiveLock = NSRecursiveLock +#endif diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/README.md b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/README.md new file mode 100644 index 0000000000..463aefa8ea --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/README.md @@ -0,0 +1,207 @@ +Miss Electric Eel 2016 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%20macOS%20%7C%20tvOS%20%7C%20watchOS%20%7C%20Linux-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) [![Swift Package Manager compatible](https://img.shields.io/badge/Swift%20Package%20Manager-compatible-brightgreen.svg)](https://github.com/apple/swift-package-manager) + +## About Rx + +**:warning: This readme describes RxSwift 3.0 version that requires Swift 3.0.** + +**:warning: If you are looking for Swift 2.3 compatible version, please take a look at RxSwift ~> 2.0 versions and [swift-2.3](https://github.com/ReactiveX/RxSwift/tree/rxswift-2.0) branch.** + +Rx is a [generic abstraction of computation](https://youtu.be/looJcaeboBY) expressed through `Observable` 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/macOS 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) +* [traits](Documentation/Traits.md) - what are `Single`, `Completable`, `Maybe`, `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) + +###### ... install + +* Integrate RxSwift/RxCocoa with my app. [Installation Guide](#installation) + +###### ... 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.
[![Slack channel](http://rxswift-slack.herokuapp.com/badge.svg)](http://rxswift-slack.herokuapp.com/) [Join Slack Channel](http://rxswift-slack.herokuapp.com) +* Report a problem using the library. [Open an Issue With Bug Template](.github/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 + + + + + + + + + + + + + + + + + + + +
Here's an exampleIn Action
Define search for GitHub repositories ...
+let searchResults = searchBar.rx.text.orEmpty
+    .throttle(0.3, scheduler: MainScheduler.instance)
+    .distinctUntilChanged()
+    .flatMapLatest { query -> Observable<[Repository]> in
+        if query.isEmpty {
+            return .just([])
+        }
+        return searchGitHub(query)
+            .catchErrorJustReturn([])
+    }
+    .observeOn(MainScheduler.instance)
... then bind the results to your tableview
+searchResults
+    .bind(to: tableView.rx.items(cellIdentifier: "Cell")) {
+        (index, repository: Repository, cell) in
+        cell.textLabel?.text = repository.name
+        cell.detailTextLabel?.text = repository.url
+    }
+    .disposed(by: disposeBag)
+ + +## Requirements + +* Xcode 8.0 +* Swift 3.0 + +## 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) + +**Tested with `pod --version`: `1.1.1`** + +```ruby +# Podfile +use_frameworks! + +target 'YOUR_TARGET_NAME' do + pod 'RxSwift', '~> 3.0' + pod 'RxCocoa', '~> 3.0' +end + +# RxTests and RxBlocking make the most sense in the context of unit/integration tests +target 'YOUR_TESTING_TARGET' do + pod 'RxBlocking', '~> 3.0' + pod 'RxTest', '~> 3.0' +end +``` + +Replace `YOUR_TARGET_NAME` and then, in the `Podfile` directory, type: + +```bash +$ pod install +``` + +### [Carthage](https://github.com/Carthage/Carthage) + +**Tested with `carthage version`: `0.18.1`** + +Add this to `Cartfile` + +``` +github "ReactiveX/RxSwift" ~> 3.0 +``` + +```bash +$ carthage update +``` + +### [Swift Package Manager](https://github.com/apple/swift-package-manager) + +**Tested with `swift build --version`: `3.0.0 (swiftpm-19)`** + +Create a `Package.swift` file. + +```swift +import PackageDescription + +let package = Package( + name: "RxTestProject", + targets: [], + dependencies: [ + .Package(url: "https://github.com/ReactiveX/RxSwift.git", majorVersion: 3) + ] +) +``` + +```bash +$ swift build +``` + +### Manually using git submodules + +* Add RxSwift as a submodule + +```bash +$ 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/) diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/AnyObserver.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/AnyObserver.swift new file mode 100644 index 0000000000..dd4f9c4086 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/AnyObserver.swift @@ -0,0 +1,72 @@ +// +// AnyObserver.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// 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 : ObserverType { + /// The type of elements in sequence that observer can observe. + public typealias E = Element + + /// Anonymous event handler type. + public typealias EventHandler = (Event) -> Void + + private let observer: EventHandler + + /// Construct an instance whose `on(event)` calls `eventHandler(event)` + /// + /// - parameter eventHandler: Event handler that observes sequences events. + public init(eventHandler: @escaping EventHandler) { + self.observer = eventHandler + } + + /// Construct an instance whose `on(event)` calls `observer.on(event)` + /// + /// - parameter observer: Observer that receives sequence events. + public init(_ observer: O) where O.E == Element { + self.observer = observer.on + } + + /// Send `event` to this observer. + /// + /// - parameter event: Event instance. + public func on(_ event: Event) { + return self.observer(event) + } + + /// Erases type of observer and returns canonical observer. + /// + /// - returns: type erased observer. + public func asObserver() -> AnyObserver { + return self + } +} + +extension AnyObserver { + /// Collection of `AnyObserver`s + typealias s = Bag<(Event) -> ()> +} + +extension ObserverType { + /// Erases type of observer and returns canonical observer. + /// + /// - returns: type erased observer. + public func asObserver() -> AnyObserver { + return AnyObserver(self) + } + + /// Transforms observer of type R to type E using custom transform method. + /// Each event sent to result observer is transformed and sent to `self`. + /// + /// - returns: observer that transforms events. + public func mapObserver(_ transform: @escaping (R) throws -> E) -> AnyObserver { + return AnyObserver { e in + self.on(e.map(transform)) + } + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Cancelable.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Cancelable.swift new file mode 100644 index 0000000000..1fa7a67726 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Cancelable.swift @@ -0,0 +1,13 @@ +// +// Cancelable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents disposable resource with state tracking. +public protocol Cancelable : Disposable { + /// Was resource disposed. + var isDisposed: Bool { get } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift new file mode 100644 index 0000000000..259707818a --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift @@ -0,0 +1,102 @@ +// +// AsyncLock.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** +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. +*/ +final class AsyncLock + : Disposable + , Lock + , SynchronizedDisposeType { + typealias Action = () -> Void + + var _lock = SpinLock() + + private var _queue: Queue = 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 + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/Lock.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/Lock.swift new file mode 100644 index 0000000000..52afc1cb87 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/Lock.swift @@ -0,0 +1,36 @@ +// +// Lock.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/31/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol Lock { + func lock() + func unlock() +} + +// https://lists.swift.org/pipermail/swift-dev/Week-of-Mon-20151214/000321.html +typealias SpinLock = RecursiveLock + +extension RecursiveLock : Lock { + @inline(__always) + final func performLocked(_ action: () -> Void) { + lock(); defer { unlock() } + action() + } + + @inline(__always) + final func calculateLocked(_ action: () -> T) -> T { + lock(); defer { unlock() } + return action() + } + + @inline(__always) + final func calculateLockedOrFail(_ action: () throws -> T) throws -> T { + lock(); defer { unlock() } + let result = try action() + return result + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift new file mode 100644 index 0000000000..eca8d8e120 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift @@ -0,0 +1,21 @@ +// +// LockOwnerType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol LockOwnerType : class, Lock { + var _lock: RecursiveLock { get } +} + +extension LockOwnerType { + func lock() { + _lock.lock() + } + + func unlock() { + _lock.unlock() + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift new file mode 100644 index 0000000000..af9548f6ed --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift @@ -0,0 +1,18 @@ +// +// SynchronizedDisposeType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol SynchronizedDisposeType : class, Disposable, Lock { + func _synchronized_dispose() +} + +extension SynchronizedDisposeType { + func synchronizedDispose() { + lock(); defer { unlock() } + _synchronized_dispose() + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift new file mode 100644 index 0000000000..8dfc556841 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift @@ -0,0 +1,18 @@ +// +// SynchronizedOnType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol SynchronizedOnType : class, ObserverType, Lock { + func _synchronized_on(_ event: Event) +} + +extension SynchronizedOnType { + func synchronizedOn(_ event: Event) { + lock(); defer { unlock() } + _synchronized_on(event) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedSubscribeType.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedSubscribeType.swift new file mode 100644 index 0000000000..e6f1d73e92 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedSubscribeType.swift @@ -0,0 +1,18 @@ +// +// SynchronizedSubscribeType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol SynchronizedSubscribeType : class, ObservableType, Lock { + func _synchronized_subscribe(_ observer: O) -> Disposable where O.E == E +} + +extension SynchronizedSubscribeType { + func synchronizedSubscribe(_ observer: O) -> Disposable where O.E == E { + lock(); defer { unlock() } + return _synchronized_subscribe(observer) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift new file mode 100644 index 0000000000..bb1aa7e47d --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift @@ -0,0 +1,13 @@ +// +// SynchronizedUnsubscribeType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol SynchronizedUnsubscribeType : class { + associatedtype DisposeKey + + func synchronizedUnsubscribe(_ disposeKey: DisposeKey) +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ConnectableObservableType.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ConnectableObservableType.swift new file mode 100644 index 0000000000..52bf93c568 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ConnectableObservableType.swift @@ -0,0 +1,19 @@ +// +// ConnectableObservableType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** +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 +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Deprecated.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Deprecated.swift new file mode 100644 index 0000000000..8ebfb0a66b --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Deprecated.swift @@ -0,0 +1,49 @@ +// +// Deprecated.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/5/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +extension Observable { + /** + Converts a optional to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter optional: Optional element in the resulting observable sequence. + - returns: An observable sequence containing the wrapped value or not from given optional. + */ + @available(*, deprecated, message: "Implicit conversions from any type to optional type are allowed and that is causing issues with `from` operator overloading.", renamed: "from(optional:)") + public static func from(_ optional: E?) -> Observable { + return Observable.from(optional: optional) + } + + /** + Converts a optional to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter optional: Optional element in the resulting observable sequence. + - parameter: Scheduler to send the optional element on. + - returns: An observable sequence containing the wrapped value or not from given optional. + */ + @available(*, deprecated, message: "Implicit conversions from any type to optional type are allowed and that is causing issues with `from` operator overloading.", renamed: "from(optional:scheduler:)") + public static func from(_ optional: E?, scheduler: ImmediateSchedulerType) -> Observable { + return Observable.from(optional: optional, scheduler: scheduler) + } +} + +extension Disposable { + /// Deprecated in favor of `disposed(by:)` + /// + /// **@available(\*, deprecated, message="use disposed(by:) instead")** + /// + /// Adds `self` to `bag`. + /// + /// - parameter bag: `DisposeBag` to add `self` to. + public func addDisposableTo(_ bag: DisposeBag) { + disposed(by: bag) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposable.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposable.swift new file mode 100644 index 0000000000..0ff067cf5c --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposable.swift @@ -0,0 +1,13 @@ +// +// Disposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Respresents a disposable resource. +public protocol Disposable { + /// Dispose resource. + func dispose() +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift new file mode 100644 index 0000000000..e54532b973 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift @@ -0,0 +1,61 @@ +// +// AnonymousDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents an Action-based disposable. +/// +/// When dispose method is called, disposal action will be dereferenced. +fileprivate final class AnonymousDisposable : DisposeBase, Cancelable { + public typealias DisposeAction = () -> Void + + private var _isDisposed: AtomicInt = 0 + private var _disposeAction: DisposeAction? + + /// - returns: Was resource disposed. + public var isDisposed: Bool { + return _isDisposed == 1 + } + + /// Constructs a new disposable with the given action used for disposal. + /// + /// - parameter disposeAction: Disposal action which will be run upon calling `dispose`. + fileprivate init(_ disposeAction: @escaping DisposeAction) { + _disposeAction = disposeAction + super.init() + } + + // Non-deprecated version of the constructor, used by `Disposables.create(with:)` + fileprivate init(disposeAction: @escaping 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. + fileprivate func dispose() { + if AtomicCompareAndSwap(0, 1, &_isDisposed) { + assert(_isDisposed == 1) + + if let action = _disposeAction { + _disposeAction = nil + action() + } + } + } +} + +extension Disposables { + + /// Constructs a new disposable with the given action used for disposal. + /// + /// - parameter dispose: Disposal action which will be run upon calling `dispose`. + public static func create(with dispose: @escaping () -> ()) -> Cancelable { + return AnonymousDisposable(disposeAction: dispose) + } + +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift new file mode 100644 index 0000000000..8a518f00ea --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift @@ -0,0 +1,53 @@ +// +// BinaryDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents two disposable resources that are disposed together. +private final class BinaryDisposable : DisposeBase, Cancelable { + + private var _isDisposed: AtomicInt = 0 + + // state + private var _disposable1: Disposable? + private var _disposable2: Disposable? + + /// - returns: Was resource disposed. + var isDisposed: Bool { + return _isDisposed > 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. + func dispose() { + if AtomicCompareAndSwap(0, 1, &_isDisposed) { + _disposable1?.dispose() + _disposable2?.dispose() + _disposable1 = nil + _disposable2 = nil + } + } +} + +extension Disposables { + + /// Creates a disposable with the given disposables. + public static func create(_ disposable1: Disposable, _ disposable2: Disposable) -> Cancelable { + return BinaryDisposable(disposable1, disposable2) + } + +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift new file mode 100644 index 0000000000..efae55e410 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift @@ -0,0 +1,33 @@ +// +// BooleanDisposable.swift +// RxSwift +// +// Created by Junior B. on 10/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a disposable resource that can be checked for disposal status. +public final class BooleanDisposable : Cancelable { + + internal static let BooleanDisposableTrue = BooleanDisposable(isDisposed: true) + private var _isDisposed = false + + /// Initializes a new instance of the `BooleanDisposable` class + public init() { + } + + /// Initializes a new instance of the `BooleanDisposable` class with given value + public init(isDisposed: Bool) { + self._isDisposed = isDisposed + } + + /// - returns: Was resource disposed. + public var isDisposed: Bool { + return _isDisposed + } + + /// Sets the status to disposed, which can be observer through the `isDisposed` property. + public func dispose() { + _isDisposed = true + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift new file mode 100644 index 0000000000..b057817238 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift @@ -0,0 +1,151 @@ +// +// CompositeDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/20/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a group of disposable resources that are disposed together. +public final class CompositeDisposable : DisposeBase, Cancelable { + /// Key used to remove disposable from composite disposable + public struct DisposeKey { + fileprivate let key: BagKey + fileprivate init(key: BagKey) { + self.key = key + } + } + + private var _lock = SpinLock() + + // state + private var _disposables: Bag? = Bag() + + public var isDisposed: 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. + let _ = _disposables!.insert(disposable1) + let _ = _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. + let _ = _disposables!.insert(disposable1) + let _ = _disposables!.insert(disposable2) + let _ = _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. + let _ = _disposables!.insert(disposable1) + let _ = _disposables!.insert(disposable2) + let _ = _disposables!.insert(disposable3) + let _ = _disposables!.insert(disposable4) + + for disposable in disposables { + let _ = _disposables!.insert(disposable) + } + } + + /// Initializes a new instance of composite disposable with the specified number of disposables. + public init(disposables: [Disposable]) { + for disposable in disposables { + let _ = _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 insert(_ disposable: Disposable) -> DisposeKey? { + let key = _insert(disposable) + + if key == nil { + disposable.dispose() + } + + return key + } + + private func _insert(_ disposable: Disposable) -> DisposeKey? { + _lock.lock(); defer { _lock.unlock() } + + let bagKey = _disposables?.insert(disposable) + return bagKey.map(DisposeKey.init) + } + + /// - 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 remove(for disposeKey: DisposeKey) { + _remove(for: disposeKey)?.dispose() + } + + private func _remove(for disposeKey: DisposeKey) -> Disposable? { + _lock.lock(); defer { _lock.unlock() } + return _disposables?.removeKey(disposeKey.key) + } + + /// Disposes all disposables in the group and removes them from the group. + public func dispose() { + if let disposables = _dispose() { + disposeAll(in: disposables) + } + } + + private func _dispose() -> Bag? { + _lock.lock(); defer { _lock.unlock() } + + let disposeBag = _disposables + _disposables = nil + + return disposeBag + } +} + +extension Disposables { + + /// Creates a disposable with the given disposables. + public static func create(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable) -> Cancelable { + return CompositeDisposable(disposable1, disposable2, disposable3) + } + + /// Creates a disposable with the given disposables. + public static func create(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable, _ disposables: Disposable ...) -> Cancelable { + var disposables = disposables + disposables.append(disposable1) + disposables.append(disposable2) + disposables.append(disposable3) + return CompositeDisposable(disposables: disposables) + } + + /// Creates a disposable with the given disposables. + public static func create(_ disposables: [Disposable]) -> Cancelable { + switch disposables.count { + case 2: + return Disposables.create(disposables[0], disposables[1]) + default: + return CompositeDisposable(disposables: disposables) + } + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/Disposables.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/Disposables.swift new file mode 100644 index 0000000000..8cd6e28c3c --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/Disposables.swift @@ -0,0 +1,13 @@ +// +// Disposables.swift +// RxSwift +// +// Created by Mohsen Ramezanpoor on 01/08/2016. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +/// A collection of utility methods for common disposable operations. +public struct Disposables { + private init() {} +} + diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift new file mode 100644 index 0000000000..d5e3b02987 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift @@ -0,0 +1,84 @@ +// +// DisposeBag.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension Disposable { + /// Adds `self` to `bag` + /// + /// - parameter bag: `DisposeBag` to add `self` to. + public func disposed(by bag: DisposeBag) { + bag.insert(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 final class DisposeBag: DisposeBase { + + private var _lock = SpinLock() + + // state + private var _disposables = [Disposable]() + private var _isDisposed = 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 insert(_ disposable: Disposable) { + _insert(disposable)?.dispose() + } + + private func _insert(_ disposable: Disposable) -> Disposable? { + _lock.lock(); defer { _lock.unlock() } + if _isDisposed { + 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(keepingCapacity: false) + _isDisposed = true + + return disposables + } + + deinit { + dispose() + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift new file mode 100644 index 0000000000..8c6a44f0b8 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift @@ -0,0 +1,22 @@ +// +// DisposeBase.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/4/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Base class for all disposables. +public class DisposeBase { + init() { +#if TRACE_RESOURCES + let _ = Resources.incrementTotal() +#endif + } + + deinit { +#if TRACE_RESOURCES + let _ = Resources.decrementTotal() +#endif + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift new file mode 100644 index 0000000000..149f866434 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift @@ -0,0 +1,32 @@ +// +// NopDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a disposable that does nothing on disposal. +/// +/// Nop = No Operation +fileprivate struct NopDisposable : Disposable { + + fileprivate static let noOp: Disposable = NopDisposable() + + fileprivate init() { + + } + + /// Does nothing. + public func dispose() { + } +} + +extension Disposables { + /** + Creates a disposable that does nothing on disposal. + */ + static public func create() -> Disposable { + return NopDisposable.noOp + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift new file mode 100644 index 0000000000..a21662ab46 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift @@ -0,0 +1,117 @@ +// +// RefCountDisposable.swift +// RxSwift +// +// Created by Junior B. on 10/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. +public final 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 isDisposed: 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 { + let _ = try incrementChecked(&_count) + } catch (_) { + rxFatalError("RefCountDisposable increment failed") + } + + return RefCountInnerDisposable(self) + } else { + return Disposables.create() + } + } + } + + /// Disposes the underlying disposable only when all dependent disposables have been disposed. + public func dispose() { + let oldDisposable: Disposable? = _lock.calculateLocked { + if let oldDisposable = _disposable, !_primaryDisposed + { + _primaryDisposed = true + + if (_count == 0) + { + _disposable = nil + return oldDisposable + } + } + + return nil + } + + if let disposable = oldDisposable { + disposable.dispose() + } + } + + fileprivate func release() { + let oldDisposable: Disposable? = _lock.calculateLocked { + if let oldDisposable = _disposable { + do { + let _ = 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 _isDisposed: AtomicInt = 0 + + init(_ parent: RefCountDisposable) + { + _parent = parent + super.init() + } + + internal func dispose() + { + if AtomicCompareAndSwap(0, 1, &_isDisposed) { + _parent.release() + } + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift new file mode 100644 index 0000000000..92c220df20 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift @@ -0,0 +1,50 @@ +// +// ScheduledDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +private let disposeScheduledDisposable: (ScheduledDisposable) -> Disposable = { sd in + sd.disposeInner() + return Disposables.create() +} + +/// Represents a disposable resource whose disposal invocation will be scheduled on the specified scheduler. +public final class ScheduledDisposable : Cancelable { + public let scheduler: ImmediateSchedulerType + + private var _isDisposed: AtomicInt = 0 + + // state + private var _disposable: Disposable? + + /// - returns: Was resource disposed. + public var isDisposed: Bool { + return _isDisposed == 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() { + let _ = scheduler.schedule(self, action: disposeScheduledDisposable) + } + + func disposeInner() { + if AtomicCompareAndSwap(0, 1, &_isDisposed) { + _disposable!.dispose() + _disposable = nil + } + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift new file mode 100644 index 0000000000..4f34bdbe0c --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift @@ -0,0 +1,75 @@ +// +// SerialDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// 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 final class SerialDisposable : DisposeBase, Cancelable { + private var _lock = SpinLock() + + // state + private var _current = nil as Disposable? + private var _isDisposed = false + + /// - returns: Was resource disposed. + public var isDisposed: Bool { + return _isDisposed + } + + /// 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 _isDisposed { + 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 _isDisposed { + return nil + } + else { + _isDisposed = true + let current = _current + _current = nil + return current + } + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift new file mode 100644 index 0000000000..e8ef67dc12 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift @@ -0,0 +1,76 @@ +// +// SingleAssignmentDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** +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 final class SingleAssignmentDisposable : DisposeBase, Cancelable { + + fileprivate enum DisposeState: UInt32 { + case disposed = 1 + case disposableSet = 2 + } + + // Jeej, swift API consistency rules + fileprivate enum DisposeStateInt32: Int32 { + case disposed = 1 + case disposableSet = 2 + } + + // state + private var _state: AtomicInt = 0 + private var _disposable = nil as Disposable? + + /// - returns: A value that indicates whether the object is disposed. + public var isDisposed: Bool { + return AtomicFlagSet(DisposeState.disposed.rawValue, &_state) + } + + /// 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 func setDisposable(_ disposable: Disposable) { + _disposable = disposable + + let previousState = AtomicOr(DisposeState.disposableSet.rawValue, &_state) + + if (previousState & DisposeStateInt32.disposableSet.rawValue) != 0 { + rxFatalError("oldState.disposable != nil") + } + + if (previousState & DisposeStateInt32.disposed.rawValue) != 0 { + disposable.dispose() + _disposable = nil + } + } + + /// Disposes the underlying disposable. + public func dispose() { + let previousState = AtomicOr(DisposeState.disposed.rawValue, &_state) + + if (previousState & DisposeStateInt32.disposed.rawValue) != 0 { + return + } + + if (previousState & DisposeStateInt32.disposableSet.rawValue) != 0 { + guard let disposable = _disposable else { + rxFatalError("Disposable not set") + } + disposable.dispose() + _disposable = nil + } + } + +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift new file mode 100644 index 0000000000..3ae138a8b3 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift @@ -0,0 +1,21 @@ +// +// SubscriptionDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +struct SubscriptionDisposable : 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) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Errors.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Errors.swift new file mode 100644 index 0000000000..a00a3dea4e --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Errors.swift @@ -0,0 +1,52 @@ +// +// Errors.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +let RxErrorDomain = "RxErrorDomain" +let RxCompositeFailures = "RxCompositeFailures" + +/// Generic Rx error codes. +public enum RxError + : Swift.Error + , 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 +} + +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." + } + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Event.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Event.swift new file mode 100644 index 0000000000..377877b614 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Event.swift @@ -0,0 +1,106 @@ +// +// Event.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a sequence event. +/// +/// Sequence grammar: +/// **next\* (error | completed)** +public enum Event { + /// Next element is produced. + case next(Element) + + /// Sequence terminated with an error. + case error(Swift.Error) + + /// 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 { + /// Is `completed` or `error` event. + public var isStopEvent: Bool { + switch self { + case .next: return false + case .error, .completed: return true + } + } + + /// If `next` event, returns element value. + public var element: Element? { + if case .next(let value) = self { + return value + } + return nil + } + + /// If `error` event, returns error. + public var error: Swift.Error? { + if case .error(let error) = self { + return error + } + return nil + } + + /// If `completed` event, returns true. + public var isCompleted: Bool { + if case .completed = self { + return true + } + return false + } +} + +extension Event { + /// Maps sequence elements using transform. If error happens during the transform .error + /// will be returned as value + public func map(_ transform: (Element) throws -> Result) -> Event { + do { + switch self { + case let .next(element): + return .next(try transform(element)) + case let .error(error): + return .error(error) + case .completed: + return .completed + } + } + catch let e { + return .error(e) + } + } +} + +/// A type that can be converted to `Event`. +public protocol EventConvertible { + /// Type of element in event + associatedtype ElementType + + /// Event representation of this instance + var event: Event { get } +} + +extension Event : EventConvertible { + /// Event representation of this instance + public var event: Event { + return self + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift new file mode 100644 index 0000000000..895333cdeb --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift @@ -0,0 +1,62 @@ +// +// Bag+Rx.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/19/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + + +// MARK: forEach + +@inline(__always) +func dispatch(_ bag: Bag<(Event) -> ()>, _ event: Event) { + if bag._onlyFastPath { + bag._value0?(event) + return + } + + let value0 = bag._value0 + let dictionary = bag._dictionary + + if let value0 = value0 { + value0(event) + } + + let pairs = bag._pairs + for i in 0 ..< pairs.count { + pairs[i].value(event) + } + + if let dictionary = dictionary { + for element in dictionary.values { + element(event) + } + } +} + +/// Dispatches `dispose` to all disposables contained inside bag. +func disposeAll(in bag: Bag) { + if bag._onlyFastPath { + bag._value0?.dispose() + return + } + + let value0 = bag._value0 + let dictionary = bag._dictionary + + if let value0 = value0 { + value0.dispose() + } + + let pairs = bag._pairs + for i in 0 ..< pairs.count { + pairs[i].value.dispose() + } + + if let dictionary = dictionary { + for element in dictionary.values { + element.dispose() + } + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift new file mode 100644 index 0000000000..42ef636ca6 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift @@ -0,0 +1,22 @@ +// +// String+Rx.swift +// RxSwift +// +// Created by Krunoslav Zaher on 12/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +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 = self.index(before: index) + if self[index] == character { + return index + } + } + + return nil + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/GroupedObservable.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/GroupedObservable.swift new file mode 100644 index 0000000000..d87e0bad02 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/GroupedObservable.swift @@ -0,0 +1,37 @@ +// +// GroupedObservable.swift +// RxSwift +// +// Created by Tomi Koskinen on 01/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents an observable sequence of elements that have a common key. +public struct GroupedObservable : ObservableType { + public typealias E = Element + + /// Gets the common key. + public let key: Key + + private let source: Observable + + /// Initializes grouped observable sequence with key and source observable sequence. + /// + /// - parameter key: Grouped observable sequence key + /// - parameter source: Observable sequence that represents sequence of elements for the key + /// - returns: Grouped observable sequence of elements for the specific key + public init(key: Key, source: Observable) { + self.key = key + self.source = source + } + + /// Subscribes `observer` to receive events for this sequence. + public func subscribe(_ observer: O) -> Disposable where O.E == E { + return self.source.subscribe(observer) + } + + /// Converts `self` to `Observable` sequence. + public func asObservable() -> Observable { + return source + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift new file mode 100644 index 0000000000..0c5418f50d --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift @@ -0,0 +1,36 @@ +// +// ImmediateSchedulerType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/31/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// 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(_ state: StateType, action: @escaping (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, action: @escaping (_ state: State, _ recurse: (State) -> ()) -> ()) -> Disposable { + let recursiveScheduler = RecursiveImmediateScheduler(action: action, scheduler: self) + + recursiveScheduler.schedule(state) + + return Disposables.create(with: recursiveScheduler.dispose) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observable.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observable.swift new file mode 100644 index 0000000000..f0c55af714 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observable.swift @@ -0,0 +1,44 @@ +// +// Observable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// A type-erased `ObservableType`. +/// +/// It represents a push style sequence. +public class Observable : ObservableType { + /// Type of elements in sequence. + public typealias E = Element + + init() { +#if TRACE_RESOURCES + let _ = Resources.incrementTotal() +#endif + } + + public func subscribe(_ observer: O) -> Disposable where O.E == E { + rxAbstractMethod() + } + + public func asObservable() -> Observable { + return self + } + + deinit { +#if TRACE_RESOURCES + let _ = Resources.decrementTotal() +#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(_ transform: @escaping (Element) throws -> R) -> Observable { + return _map(source: self, transform: transform) + } +} + diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift new file mode 100644 index 0000000000..72cfb1ac3f --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift @@ -0,0 +1,18 @@ +// +// ObservableConvertibleType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Type that can be converted to observable sequence (`Observer`). +public protocol ObservableConvertibleType { + /// Type of elements in sequence. + associatedtype E + + /// Converts `self` to `Observable` sequence. + /// + /// - returns: Observable sequence that represents `self`. + func asObservable() -> Observable +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift new file mode 100644 index 0000000000..1603d39a67 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift @@ -0,0 +1,117 @@ +// +// ObservableType+Extensions.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +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. + */ + public func subscribe(_ on: @escaping (Event) -> Void) + -> Disposable { + let observer = AnonymousObserver { e in + on(e) + } + return self.subscribeSafe(observer) + } + + #if DEBUG + /** + 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. + */ + public func subscribe(file: String = #file, line: UInt = #line, function: String = #function, onNext: ((E) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil) + -> Disposable { + + let disposable: Disposable + + if let disposed = onDisposed { + disposable = Disposables.create(with: disposed) + } + else { + disposable = Disposables.create() + } + + let observer = AnonymousObserver { e in + switch e { + case .next(let value): + onNext?(value) + case .error(let e): + if let onError = onError { + onError(e) + } + else { + print("Received unhandled error: \(file):\(line):\(function) -> \(e)") + } + disposable.dispose() + case .completed: + onCompleted?() + disposable.dispose() + } + } + return Disposables.create( + self.subscribeSafe(observer), + disposable + ) + } + #else + /** + 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. + */ + public func subscribe(onNext: ((E) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil) + -> Disposable { + + let disposable: Disposable + + if let disposed = onDisposed { + disposable = Disposables.create(with: disposed) + } + else { + disposable = Disposables.create() + } + + let observer = AnonymousObserver { e in + switch e { + case .next(let value): + onNext?(value) + case .error(let e): + onError?(e) + disposable.dispose() + case .completed: + onCompleted?() + disposable.dispose() + } + } + return Disposables.create( + self.subscribeSafe(observer), + disposable + ) + } + #endif +} + +extension ObservableType { + /// All internal subscribe calls go through this method. + fileprivate func subscribeSafe(_ observer: O) -> Disposable where O.E == E { + return self.asObservable().subscribe(observer) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObservableType.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObservableType.swift new file mode 100644 index 0000000000..6331dc877a --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObservableType.swift @@ -0,0 +1,50 @@ +// +// ObservableType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// 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. + */ + func subscribe(_ observer: O) -> Disposable where O.E == E +} + +extension ObservableType { + + /// Default implementation of converting `ObservableType` to `Observable`. + public func asObservable() -> Observable { + // temporary workaround + //return Observable.create(subscribe: self.subscribe) + return Observable.create { o in + return self.subscribe(o) + } + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/AddRef.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/AddRef.swift new file mode 100644 index 0000000000..b782c13f49 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/AddRef.swift @@ -0,0 +1,45 @@ +// +// AddRef.swift +// RxSwift +// +// Created by Junior B. on 30/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +final class AddRefSink : Sink, ObserverType { + typealias Element = O.E + + override init(observer: O, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(_): + forwardOn(event) + case .completed, .error(_): + forwardOn(event) + dispose() + } + } +} + +final class AddRef : Producer { + typealias EventHandler = (Event) throws -> Void + + private let _source: Observable + private let _refCount: RefCountDisposable + + init(source: Observable, refCount: RefCountDisposable) { + _source = source + _refCount = refCount + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let releaseDisposable = _refCount.retain() + let sink = AddRefSink(observer: observer, cancel: cancel) + let subscription = Disposables.create(releaseDisposable, _source.subscribe(sink)) + + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Amb.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Amb.swift new file mode 100644 index 0000000000..69d39ba88a --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Amb.swift @@ -0,0 +1,157 @@ +// +// Amb.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension Observable { + /** + Propagates the observable sequence that reacts first. + + - seealso: [amb operator on reactivex.io](http://reactivex.io/documentation/operators/amb.html) + + - returns: An observable sequence that surfaces any of the given sequences, whichever reacted first. + */ + public static func amb(_ sequence: S) -> Observable + where S.Iterator.Element == Observable { + return sequence.reduce(Observable.never()) { a, o in + return a.amb(o.asObservable()) + } + } +} + +extension ObservableType { + + /** + Propagates the observable sequence that reacts first. + + - seealso: [amb operator on reactivex.io](http://reactivex.io/documentation/operators/amb.html) + + - parameter right: Second observable sequence. + - returns: An observable sequence that surfaces either of the given sequences, whichever reacted first. + */ + public func amb + (_ right: O2) + -> Observable where O2.E == E { + return Amb(left: asObservable(), right: right.asObservable()) + } +} + +fileprivate enum AmbState { + case neither + case left + case right +} + +final fileprivate class AmbObserver : ObserverType { + typealias Element = O.E + typealias Parent = AmbSink + typealias This = AmbObserver + typealias Sink = (This, Event) -> Void + + fileprivate let _parent: Parent + fileprivate var _sink: Sink + fileprivate var _cancel: Disposable + + init(parent: Parent, cancel: Disposable, sink: @escaping Sink) { +#if TRACE_RESOURCES + let _ = Resources.incrementTotal() +#endif + + _parent = parent + _sink = sink + _cancel = cancel + } + + func on(_ event: Event) { + _sink(self, event) + if event.isStopEvent { + _cancel.dispose() + } + } + + deinit { +#if TRACE_RESOURCES + let _ = Resources.decrementTotal() +#endif + } +} + +final fileprivate class AmbSink : Sink { + typealias ElementType = O.E + typealias Parent = Amb + typealias AmbObserverType = AmbObserver + + private let _parent: Parent + + private let _lock = RecursiveLock() + // state + private var _choice = AmbState.neither + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let disposeAll = Disposables.create(subscription1, subscription2) + + let forwardEvent = { (o: AmbObserverType, event: Event) -> Void in + self.forwardOn(event) + if event.isStopEvent { + self.dispose() + } + } + + let decide = { (o: AmbObserverType, event: Event, 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.setDisposable(_parent._left.subscribe(sink1)) + subscription2.setDisposable(_parent._right.subscribe(sink2)) + + return disposeAll + } +} + +final fileprivate class Amb: Producer { + fileprivate let _left: Observable + fileprivate let _right: Observable + + init(left: Observable, right: Observable) { + _left = left + _right = right + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = AmbSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift new file mode 100644 index 0000000000..36fa685fa8 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift @@ -0,0 +1,49 @@ +// +// AsMaybe.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +fileprivate final class AsMaybeSink : Sink, ObserverType { + typealias ElementType = O.E + typealias E = ElementType + + private var _element: Event? = nil + + func on(_ event: Event) { + switch event { + case .next: + if _element != nil { + forwardOn(.error(RxError.moreThanOneElement)) + dispose() + } + + _element = event + case .error: + forwardOn(event) + dispose() + case .completed: + if let element = _element { + forwardOn(element) + } + forwardOn(.completed) + dispose() + } + } +} + +final class AsMaybe: Producer { + fileprivate let _source: Observable + + init(source: Observable) { + _source = source + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = AsMaybeSink(observer: observer, cancel: cancel) + let subscription = _source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/AsSingle.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/AsSingle.swift new file mode 100644 index 0000000000..080aa8e1a1 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/AsSingle.swift @@ -0,0 +1,52 @@ +// +// AsSingle.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +fileprivate final class AsSingleSink : Sink, ObserverType { + typealias ElementType = O.E + typealias E = ElementType + + private var _element: Event? = nil + + func on(_ event: Event) { + switch event { + case .next: + if _element != nil { + forwardOn(.error(RxError.moreThanOneElement)) + dispose() + } + + _element = event + case .error: + forwardOn(event) + dispose() + case .completed: + if let element = _element { + forwardOn(element) + forwardOn(.completed) + } + else { + forwardOn(.error(RxError.noElements)) + } + dispose() + } + } +} + +final class AsSingle: Producer { + fileprivate let _source: Observable + + init(source: Observable) { + _source = source + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = AsSingleSink(observer: observer, cancel: cancel) + let subscription = _source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Buffer.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Buffer.swift new file mode 100644 index 0000000000..b8c33ae818 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Buffer.swift @@ -0,0 +1,139 @@ +// +// Buffer.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Projects each element of an observable sequence into a buffer that's sent out when either it's full or a given amount of time has elapsed, using the specified scheduler to run timers. + + A useful real-world analogy of this overload is the behavior of a ferry leaving the dock when all seats are taken, or at the scheduled time of departure, whichever event occurs first. + + - seealso: [buffer operator on reactivex.io](http://reactivex.io/documentation/operators/buffer.html) + + - parameter timeSpan: Maximum time length of a buffer. + - parameter count: Maximum element count of a buffer. + - parameter scheduler: Scheduler to run buffering timers on. + - returns: An observable sequence of buffers. + */ + public func buffer(timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) + -> Observable<[E]> { + return BufferTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler) + } +} + +final fileprivate class BufferTimeCount : Producer<[Element]> { + + fileprivate let _timeSpan: RxTimeInterval + fileprivate let _count: Int + fileprivate let _scheduler: SchedulerType + fileprivate let _source: Observable + + init(source: Observable, timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) { + _source = source + _timeSpan = timeSpan + _count = count + _scheduler = scheduler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == [Element] { + let sink = BufferTimeCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final fileprivate class BufferTimeCountSink + : Sink + , LockOwnerType + , ObserverType + , SynchronizedOnType where O.E == [Element] { + typealias Parent = BufferTimeCount + typealias E = Element + + private let _parent: Parent + + let _lock = RecursiveLock() + + // state + private let _timerD = SerialDisposable() + private var _buffer = [Element]() + private var _windowID = 0 + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + createTimer(_windowID) + return Disposables.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) { + synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + 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.isDisposed { + return + } + + if _windowID != windowID { + return + } + + let nextTimer = SingleAssignmentDisposable() + + _timerD.disposable = nextTimer + + let disposable = _parent._scheduler.scheduleRelative(windowID, dueTime: _parent._timeSpan) { previousWindowID in + self._lock.performLocked { + if previousWindowID != self._windowID { + return + } + + self.startNewWindowAndSendCurrentOne() + } + + return Disposables.create() + } + + nextTimer.setDisposable(disposable) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Catch.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Catch.swift new file mode 100644 index 0000000000..0c534fbed1 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Catch.swift @@ -0,0 +1,235 @@ +// +// Catch.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Continues an observable sequence that is terminated by an error with the observable sequence produced by the handler. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - parameter handler: Error handler function, producing another observable sequence. + - returns: An observable sequence containing the source sequence's elements, followed by the elements produced by the handler's resulting observable sequence in case an error occurred. + */ + public func catchError(_ handler: @escaping (Swift.Error) throws -> Observable) + -> Observable { + return Catch(source: asObservable(), handler: handler) + } + + /** + Continues an observable sequence that is terminated by an error with a single element. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - parameter element: Last element in an observable sequence in case error occurs. + - returns: An observable sequence containing the source sequence's elements, followed by the `element` in case an error occurred. + */ + public func catchErrorJustReturn(_ element: E) + -> Observable { + return Catch(source: asObservable(), handler: { _ in Observable.just(element) }) + } + +} + +extension Observable { + /** + Continues an observable sequence that is terminated by an error with the next observable sequence. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - returns: An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. + */ + public static func catchError(_ sequence: S) -> Observable + where S.Iterator.Element == Observable { + return CatchSequence(sources: sequence) + } +} + +extension ObservableType { + + /** + Repeats the source observable sequence until it successfully terminates. + + **This could potentially create an infinite sequence.** + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - returns: Observable sequence to repeat until it successfully terminates. + */ + public func retry() -> Observable { + return CatchSequence(sources: InfiniteSequence(repeatedValue: self.asObservable())) + } + + /** + Repeats the source observable sequence the specified number of times in case of an error or until it successfully terminates. + + If you encounter an error and want it to retry once, then you must use `retry(2)` + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter maxAttemptCount: Maximum number of times to repeat the sequence. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + public func retry(_ maxAttemptCount: Int) + -> Observable { + return CatchSequence(sources: repeatElement(self.asObservable(), count: maxAttemptCount)) + } +} + +// catch with callback + +final fileprivate class CatchSinkProxy : ObserverType { + typealias E = O.E + typealias Parent = CatchSink + + private let _parent: Parent + + init(parent: Parent) { + _parent = parent + } + + func on(_ event: Event) { + _parent.forwardOn(event) + + switch event { + case .next: + break + case .error, .completed: + _parent.dispose() + } + } +} + +final fileprivate class CatchSink : Sink, ObserverType { + typealias E = O.E + typealias Parent = Catch + + private let _parent: Parent + private let _subscription = SerialDisposable() + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let d1 = SingleAssignmentDisposable() + _subscription.disposable = d1 + d1.setDisposable(_parent._source.subscribe(self)) + + return _subscription + } + + func on(_ event: Event) { + 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() + } + } + } +} + +final fileprivate class Catch : Producer { + typealias Handler = (Swift.Error) throws -> Observable + + fileprivate let _source: Observable + fileprivate let _handler: Handler + + init(source: Observable, handler: @escaping Handler) { + _source = source + _handler = handler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = CatchSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +// catch enumerable + +final fileprivate class CatchSequenceSink + : TailRecursiveSink + , ObserverType where S.Iterator.Element : ObservableConvertibleType, S.Iterator.Element.E == O.E { + typealias Element = O.E + typealias Parent = CatchSequence + + private var _lastError: Swift.Error? + + override init(observer: O, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next: + forwardOn(event) + case .error(let error): + _lastError = error + schedule(.moveNext) + case .completed: + forwardOn(event) + dispose() + } + } + + override func subscribeToNext(_ source: Observable) -> 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) -> SequenceGenerator? { + if let onError = observable as? CatchSequence { + return (onError.sources.makeIterator(), nil) + } + else { + return nil + } + } +} + +final fileprivate class CatchSequence : Producer where S.Iterator.Element : ObservableConvertibleType { + typealias Element = S.Iterator.Element.E + + let sources: S + + init(sources: S) { + self.sources = sources + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = CatchSequenceSink(observer: observer, cancel: cancel) + let subscription = sink.run((self.sources.makeIterator(), nil)) + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift new file mode 100644 index 0000000000..9f713f6f78 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift @@ -0,0 +1,157 @@ +// +// CombineLatest+Collection.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +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. + */ + public static func combineLatest(_ collection: C, _ resultSelector: @escaping ([C.Iterator.Element.E]) throws -> Element) -> Observable + where C.Iterator.Element: ObservableType { + return CombineLatestCollectionType(sources: collection, resultSelector: resultSelector) + } + + /** + Merges the specified observable sequences into one observable sequence whenever any of the observable sequences produces an element. + + - seealso: [combinelatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest(_ collection: C) -> Observable<[Element]> + where C.Iterator.Element: ObservableType, C.Iterator.Element.E == Element { + return CombineLatestCollectionType(sources: collection, resultSelector: { $0 }) + } +} + +final fileprivate class CombineLatestCollectionTypeSink + : Sink where C.Iterator.Element : ObservableConvertibleType { + typealias R = O.E + typealias Parent = CombineLatestCollectionType + typealias SourceElement = C.Iterator.Element.E + + let _parent: Parent + + let _lock = RecursiveLock() + + // state + var _numberOfValues = 0 + var _values: [SourceElement?] + var _isDone: [Bool] + var _numberOfDone = 0 + var _subscriptions: [SingleAssignmentDisposable] + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + _values = [SourceElement?](repeating: nil, count: parent._count) + _isDone = [Bool](repeating: false, count: parent._count) + _subscriptions = Array() + _subscriptions.reserveCapacity(parent._count) + + for _ in 0 ..< parent._count { + _subscriptions.append(SingleAssignmentDisposable()) + } + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event, 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 { + let index = j + let source = i.asObservable() + let disposable = source.subscribe(AnyObserver { event in + self.on(event, atIndex: index) + }) + + _subscriptions[j].setDisposable(disposable) + + j += 1 + } + + if _parent._sources.isEmpty { + self.forwardOn(.completed) + } + + return Disposables.create(_subscriptions) + } +} + +final fileprivate class CombineLatestCollectionType : Producer where C.Iterator.Element : ObservableConvertibleType { + typealias ResultSelector = ([C.Iterator.Element.E]) throws -> R + + let _sources: C + let _resultSelector: ResultSelector + let _count: Int + + init(sources: C, resultSelector: @escaping ResultSelector) { + _sources = sources + _resultSelector = resultSelector + _count = Int(self._sources.count.toIntMax()) + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = CombineLatestCollectionTypeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift new file mode 100644 index 0000000000..aac43a703e --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift @@ -0,0 +1,843 @@ +// 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. +// + + + +// 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. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, resultSelector: @escaping (O1.E, O2.E) throws -> E) + -> Observable { + return CombineLatest2( + source1: source1.asObservable(), source2: source2.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where E == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2) + -> Observable<(O1.E, O2.E)> { + return CombineLatest2( + source1: source1.asObservable(), source2: source2.asObservable(), + resultSelector: { ($0, $1) } + ) + } +} + +final class CombineLatestSink2_ : CombineLatestSink { + typealias R = O.E + typealias Parent = CombineLatest2 + + let _parent: Parent + + var _latestElement1: E1! = nil + var _latestElement2: E2! = nil + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(arity: 2, observer: observer, cancel: cancel) + } + + 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.setDisposable(_parent._source1.subscribe(observer1)) + subscription2.setDisposable(_parent._source2.subscribe(observer2)) + + return Disposables.create([ + subscription1, + subscription2 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_latestElement1, _latestElement2) + } +} + +final class CombineLatest2 : Producer { + typealias ResultSelector = (E1, E2) throws -> R + + let _source1: Observable + let _source2: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, resultSelector: @escaping ResultSelector) { + _source1 = source1 + _source2 = source2 + + _resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = CombineLatestSink2_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 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. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, resultSelector: @escaping (O1.E, O2.E, O3.E) throws -> E) + -> Observable { + return CombineLatest3( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where E == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3) + -> Observable<(O1.E, O2.E, O3.E)> { + return CombineLatest3( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), + resultSelector: { ($0, $1, $2) } + ) + } +} + +final class CombineLatestSink3_ : CombineLatestSink { + typealias R = O.E + typealias Parent = CombineLatest3 + + let _parent: Parent + + var _latestElement1: E1! = nil + var _latestElement2: E2! = nil + var _latestElement3: E3! = nil + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(arity: 3, observer: observer, cancel: cancel) + } + + 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.setDisposable(_parent._source1.subscribe(observer1)) + subscription2.setDisposable(_parent._source2.subscribe(observer2)) + subscription3.setDisposable(_parent._source3.subscribe(observer3)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_latestElement1, _latestElement2, _latestElement3) + } +} + +final class CombineLatest3 : Producer { + typealias ResultSelector = (E1, E2, E3) throws -> R + + let _source1: Observable + let _source2: Observable + let _source3: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, resultSelector: @escaping ResultSelector) { + _source1 = source1 + _source2 = source2 + _source3 = source3 + + _resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = CombineLatestSink3_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 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. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, resultSelector: @escaping (O1.E, O2.E, O3.E, O4.E) throws -> E) + -> Observable { + return CombineLatest4( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where E == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4) + -> Observable<(O1.E, O2.E, O3.E, O4.E)> { + return CombineLatest4( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), + resultSelector: { ($0, $1, $2, $3) } + ) + } +} + +final class CombineLatestSink4_ : CombineLatestSink { + typealias R = O.E + typealias Parent = CombineLatest4 + + let _parent: Parent + + var _latestElement1: E1! = nil + var _latestElement2: E2! = nil + var _latestElement3: E3! = nil + var _latestElement4: E4! = nil + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(arity: 4, observer: observer, cancel: cancel) + } + + 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.setDisposable(_parent._source1.subscribe(observer1)) + subscription2.setDisposable(_parent._source2.subscribe(observer2)) + subscription3.setDisposable(_parent._source3.subscribe(observer3)) + subscription4.setDisposable(_parent._source4.subscribe(observer4)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_latestElement1, _latestElement2, _latestElement3, _latestElement4) + } +} + +final class CombineLatest4 : Producer { + typealias ResultSelector = (E1, E2, E3, E4) throws -> R + + let _source1: Observable + let _source2: Observable + let _source3: Observable + let _source4: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, resultSelector: @escaping ResultSelector) { + _source1 = source1 + _source2 = source2 + _source3 = source3 + _source4 = source4 + + _resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = CombineLatestSink4_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 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. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, resultSelector: @escaping (O1.E, O2.E, O3.E, O4.E, O5.E) throws -> E) + -> Observable { + return CombineLatest5( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where E == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5) + -> Observable<(O1.E, O2.E, O3.E, O4.E, O5.E)> { + return CombineLatest5( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4) } + ) + } +} + +final class CombineLatestSink5_ : CombineLatestSink { + typealias R = O.E + typealias Parent = CombineLatest5 + + 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, cancel: Cancelable) { + _parent = parent + super.init(arity: 5, observer: observer, cancel: cancel) + } + + 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.setDisposable(_parent._source1.subscribe(observer1)) + subscription2.setDisposable(_parent._source2.subscribe(observer2)) + subscription3.setDisposable(_parent._source3.subscribe(observer3)) + subscription4.setDisposable(_parent._source4.subscribe(observer4)) + subscription5.setDisposable(_parent._source5.subscribe(observer5)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_latestElement1, _latestElement2, _latestElement3, _latestElement4, _latestElement5) + } +} + +final class CombineLatest5 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5) throws -> R + + let _source1: Observable + let _source2: Observable + let _source3: Observable + let _source4: Observable + let _source5: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, resultSelector: @escaping ResultSelector) { + _source1 = source1 + _source2 = source2 + _source3 = source3 + _source4 = source4 + _source5 = source5 + + _resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = CombineLatestSink5_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 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. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, resultSelector: @escaping (O1.E, O2.E, O3.E, O4.E, O5.E, O6.E) throws -> E) + -> Observable { + return CombineLatest6( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where E == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6) + -> Observable<(O1.E, O2.E, O3.E, O4.E, O5.E, O6.E)> { + return CombineLatest6( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5) } + ) + } +} + +final class CombineLatestSink6_ : CombineLatestSink { + typealias R = O.E + typealias Parent = CombineLatest6 + + 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, cancel: Cancelable) { + _parent = parent + super.init(arity: 6, observer: observer, cancel: cancel) + } + + 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.setDisposable(_parent._source1.subscribe(observer1)) + subscription2.setDisposable(_parent._source2.subscribe(observer2)) + subscription3.setDisposable(_parent._source3.subscribe(observer3)) + subscription4.setDisposable(_parent._source4.subscribe(observer4)) + subscription5.setDisposable(_parent._source5.subscribe(observer5)) + subscription6.setDisposable(_parent._source6.subscribe(observer6)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_latestElement1, _latestElement2, _latestElement3, _latestElement4, _latestElement5, _latestElement6) + } +} + +final class CombineLatest6 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6) throws -> R + + let _source1: Observable + let _source2: Observable + let _source3: Observable + let _source4: Observable + let _source5: Observable + let _source6: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, resultSelector: @escaping ResultSelector) { + _source1 = source1 + _source2 = source2 + _source3 = source3 + _source4 = source4 + _source5 = source5 + _source6 = source6 + + _resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = CombineLatestSink6_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 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. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, resultSelector: @escaping (O1.E, O2.E, O3.E, O4.E, O5.E, O6.E, O7.E) throws -> E) + -> Observable { + 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 + ) + } +} + +extension ObservableType where E == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7) + -> Observable<(O1.E, O2.E, O3.E, O4.E, O5.E, O6.E, O7.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: { ($0, $1, $2, $3, $4, $5, $6) } + ) + } +} + +final class CombineLatestSink7_ : CombineLatestSink { + typealias R = O.E + typealias Parent = CombineLatest7 + + 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, cancel: Cancelable) { + _parent = parent + super.init(arity: 7, observer: observer, cancel: cancel) + } + + 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.setDisposable(_parent._source1.subscribe(observer1)) + subscription2.setDisposable(_parent._source2.subscribe(observer2)) + subscription3.setDisposable(_parent._source3.subscribe(observer3)) + subscription4.setDisposable(_parent._source4.subscribe(observer4)) + subscription5.setDisposable(_parent._source5.subscribe(observer5)) + subscription6.setDisposable(_parent._source6.subscribe(observer6)) + subscription7.setDisposable(_parent._source7.subscribe(observer7)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_latestElement1, _latestElement2, _latestElement3, _latestElement4, _latestElement5, _latestElement6, _latestElement7) + } +} + +final class CombineLatest7 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7) throws -> R + + let _source1: Observable + let _source2: Observable + let _source3: Observable + let _source4: Observable + let _source5: Observable + let _source6: Observable + let _source7: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, resultSelector: @escaping ResultSelector) { + _source1 = source1 + _source2 = source2 + _source3 = source3 + _source4 = source4 + _source5 = source5 + _source6 = source6 + _source7 = source7 + + _resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = CombineLatestSink7_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 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. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8, resultSelector: @escaping (O1.E, O2.E, O3.E, O4.E, O5.E, O6.E, O7.E, O8.E) throws -> E) + -> Observable { + 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 + ) + } +} + +extension ObservableType where E == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8) + -> Observable<(O1.E, O2.E, O3.E, O4.E, O5.E, O6.E, O7.E, O8.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: { ($0, $1, $2, $3, $4, $5, $6, $7) } + ) + } +} + +final class CombineLatestSink8_ : CombineLatestSink { + typealias R = O.E + typealias Parent = CombineLatest8 + + 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, cancel: Cancelable) { + _parent = parent + super.init(arity: 8, observer: observer, cancel: cancel) + } + + 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.setDisposable(_parent._source1.subscribe(observer1)) + subscription2.setDisposable(_parent._source2.subscribe(observer2)) + subscription3.setDisposable(_parent._source3.subscribe(observer3)) + subscription4.setDisposable(_parent._source4.subscribe(observer4)) + subscription5.setDisposable(_parent._source5.subscribe(observer5)) + subscription6.setDisposable(_parent._source6.subscribe(observer6)) + subscription7.setDisposable(_parent._source7.subscribe(observer7)) + subscription8.setDisposable(_parent._source8.subscribe(observer8)) + + return Disposables.create([ + 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) + } +} + +final class CombineLatest8 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7, E8) throws -> R + + let _source1: Observable + let _source2: Observable + let _source3: Observable + let _source4: Observable + let _source5: Observable + let _source6: Observable + let _source7: Observable + let _source8: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, source8: Observable, resultSelector: @escaping ResultSelector) { + _source1 = source1 + _source2 = source2 + _source3 = source3 + _source4 = source4 + _source5 = source5 + _source6 = source6 + _source7 = source7 + _source8 = source8 + + _resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = CombineLatestSink8_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift new file mode 100644 index 0000000000..8c03e8c38c --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift @@ -0,0 +1,132 @@ +// +// CombineLatest.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol CombineLatestProtocol : class { + func next(_ index: Int) + func fail(_ error: Swift.Error) + func done(_ index: Int) +} + +class CombineLatestSink + : Sink + , CombineLatestProtocol { + typealias Element = O.E + + let _lock = RecursiveLock() + + 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, cancel: Cancelable) { + _arity = arity + _hasValue = [Bool](repeating: false, count: arity) + _isDone = [Bool](repeating: false, count: arity) + + super.init(observer: observer, cancel: cancel) + } + + func getResult() throws -> Element { + rxAbstractMethod() + } + + 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: Swift.Error) { + forwardOn(.error(error)) + dispose() + } + + func done(_ index: Int) { + if _isDone[index] { + return + } + + _isDone[index] = true + _numberOfDone += 1 + + if _numberOfDone == _arity { + forwardOn(.completed) + dispose() + } + } +} + +final class CombineLatestObserver + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = ElementType + typealias ValueSetter = (Element) -> Void + + private let _parent: CombineLatestProtocol + + let _lock: RecursiveLock + private let _index: Int + private let _this: Disposable + private let _setLatestValue: ValueSetter + + init(lock: RecursiveLock, parent: CombineLatestProtocol, index: Int, setLatestValue: @escaping ValueSetter, this: Disposable) { + _lock = lock + _parent = parent + _index = index + _this = this + _setLatestValue = setLatestValue + } + + func on(_ event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + 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) + } + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Concat.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Concat.swift new file mode 100644 index 0000000000..87dbadf9a5 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Concat.swift @@ -0,0 +1,130 @@ +// +// Concat.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Concatenates the second observable sequence to `self` upon successful termination of `self`. + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - parameter second: Second observable sequence. + - returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence. + */ + public func concat(_ second: O) -> Observable where O.E == E { + return Observable.concat([self.asObservable(), second.asObservable()]) + } +} + +extension Observable { + /** + Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully. + + This operator has tail recursive optimizations that will prevent stack overflow. + + Optimizations will be performed in cases equivalent to following: + + [1, [2, [3, .....].concat()].concat].concat() + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each given sequence, in sequential order. + */ + public static func concat(_ sequence: S) -> Observable + where S.Iterator.Element == Observable { + return Concat(sources: sequence, count: nil) + } + + /** + Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully. + + This operator has tail recursive optimizations that will prevent stack overflow. + + Optimizations will be performed in cases equivalent to following: + + [1, [2, [3, .....].concat()].concat].concat() + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each given sequence, in sequential order. + */ + public static func concat(_ collection: S) -> Observable + where S.Iterator.Element == Observable { + return Concat(sources: collection, count: collection.count.toIntMax()) + } + + /** + Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully. + + This operator has tail recursive optimizations that will prevent stack overflow. + + Optimizations will be performed in cases equivalent to following: + + [1, [2, [3, .....].concat()].concat].concat() + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each given sequence, in sequential order. + */ + public static func concat(_ sources: Observable ...) -> Observable { + return Concat(sources: sources, count: sources.count.toIntMax()) + } +} + +final fileprivate class ConcatSink + : TailRecursiveSink + , ObserverType where S.Iterator.Element : ObservableConvertibleType, S.Iterator.Element.E == O.E { + typealias Element = O.E + + override init(observer: O, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event){ + switch event { + case .next: + forwardOn(event) + case .error: + forwardOn(event) + dispose() + case .completed: + schedule(.moveNext) + } + } + + override func subscribeToNext(_ source: Observable) -> Disposable { + return source.subscribe(self) + } + + override func extract(_ observable: Observable) -> SequenceGenerator? { + if let source = observable as? Concat { + return (source._sources.makeIterator(), source._count) + } + else { + return nil + } + } +} + +final fileprivate class Concat : Producer where S.Iterator.Element : ObservableConvertibleType { + typealias Element = S.Iterator.Element.E + + fileprivate let _sources: S + fileprivate let _count: IntMax? + + init(sources: S, count: IntMax?) { + _sources = sources + _count = count + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = ConcatSink(observer: observer, cancel: cancel) + let subscription = sink.run((_sources.makeIterator(), _count)) + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/ConnectableObservable.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/ConnectableObservable.swift new file mode 100644 index 0000000000..7755799cd8 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/ConnectableObservable.swift @@ -0,0 +1,129 @@ +// +// ConnectableObservable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + + +extension ObservableType { + + /** + Multicasts the source sequence notifications through the specified subject to the resulting connectable observable. + + Upon connection of the connectable observable, the subject is subscribed to the source exactly one, and messages are forwarded to the observers registered with the connectable observable. + + For specializations with fixed subject types, see `publish` and `replay`. + + - seealso: [multicast operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) + + - parameter subject: Subject to push source elements into. + - returns: A connectable observable sequence that upon connection causes the source sequence to push results into the specified subject. + */ + public func multicast(_ subject: S) + -> ConnectableObservable where S.SubjectObserverType.E == E { + return ConnectableObservableAdapter(source: self.asObservable(), subject: subject) + } +} + +/** + Represents an observable wrapper that can be connected and disconnected from its underlying observable sequence. +*/ +public class ConnectableObservable + : Observable + , 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 { + rxAbstractMethod() + } +} + +final class Connection : ObserverType, Disposable { + typealias E = S.SubjectObserverType.E + + private var _lock: RecursiveLock + // state + private var _parent: ConnectableObservableAdapter? + private var _subscription : Disposable? + private var _subjectObserver: S.SubjectObserverType + + private var _disposed: Bool = false + + init(parent: ConnectableObservableAdapter, subjectObserver: S.SubjectObserverType, lock: RecursiveLock, subscription: Disposable) { + _parent = parent + _subscription = subscription + _lock = lock + _subjectObserver = subjectObserver + } + + func on(_ event: Event) { + if _disposed { + return + } + _subjectObserver.on(event) + if event.isStopEvent { + self.dispose() + } + } + + func dispose() { + _lock.lock(); defer { _lock.unlock() } // { + _disposed = true + guard let parent = _parent else { + return + } + + if parent._connection === self { + parent._connection = nil + } + _parent = nil + + _subscription?.dispose() + _subscription = nil + // } + } +} + +final class ConnectableObservableAdapter + : ConnectableObservable { + typealias ConnectionType = Connection + + fileprivate let _subject: S + fileprivate let _source: Observable + + fileprivate let _lock = RecursiveLock() + + // state + fileprivate var _connection: ConnectionType? + + init(source: Observable, subject: S) { + _source = source + _subject = subject + _connection = nil + } + + override func connect() -> Disposable { + return _lock.calculateLocked { + if let connection = _connection { + return connection + } + + let singleAssignmentDisposable = SingleAssignmentDisposable() + let connection = Connection(parent: self, subjectObserver: _subject.asObserver(), lock: _lock, subscription: singleAssignmentDisposable) + _connection = connection + let subscription = _source.subscribe(connection) + singleAssignmentDisposable.setDisposable(subscription) + return connection + } + } + + override func subscribe(_ observer: O) -> Disposable where O.E == S.E { + return _subject.subscribe(observer) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Create.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Create.swift new file mode 100644 index 0000000000..1dc66efdcf --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Create.swift @@ -0,0 +1,83 @@ +// +// Create.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension Observable { + // MARK: create + + /** + Creates an observable sequence from a specified subscribe method implementation. + + - seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html) + + - parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method. + - returns: The observable sequence with the specified implementation for the `subscribe` method. + */ + public static func create(_ subscribe: @escaping (AnyObserver) -> Disposable) -> Observable { + return AnonymousObservable(subscribe) + } +} + +final fileprivate class AnonymousObservableSink : Sink, ObserverType { + typealias E = O.E + typealias Parent = AnonymousObservable + + // state + private var _isStopped: AtomicInt = 0 + + #if DEBUG + fileprivate var _numberOfConcurrentCalls: AtomicInt = 0 + #endif + + override init(observer: O, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + #if DEBUG + if AtomicIncrement(&_numberOfConcurrentCalls) > 1 { + rxFatalError("Warning: Recursive call or synchronization error!") + } + + defer { + _ = AtomicDecrement(&_numberOfConcurrentCalls) + } + #endif + 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)) + } +} + +final fileprivate class AnonymousObservable : Producer { + typealias SubscribeHandler = (AnyObserver) -> Disposable + + let _subscribeHandler: SubscribeHandler + + init(_ subscribeHandler: @escaping SubscribeHandler) { + _subscribeHandler = subscribeHandler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = AnonymousObservableSink(observer: observer, cancel: cancel) + let subscription = sink.run(self) + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Debounce.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Debounce.swift new file mode 100644 index 0000000000..866427a0d4 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Debounce.swift @@ -0,0 +1,119 @@ +// +// Debounce.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/11/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers. + + - seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html) + + - parameter dueTime: Throttling duration for each element. + - parameter scheduler: Scheduler to run the throttle timers on. + - returns: The throttled sequence. + */ + public func debounce(_ dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Debounce(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler) + } +} + +final fileprivate class DebounceSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = O.E + typealias ParentType = Debounce + + private let _parent: ParentType + + let _lock = RecursiveLock() + + // state + private var _id = 0 as UInt64 + private var _value: Element? = nil + + let cancellable = SerialDisposable() + + init(parent: ParentType, observer: O, cancel: Cancelable) { + _parent = parent + + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription = _parent._source.subscribe(self) + + return Disposables.create(subscription, cancellable) + } + + func on(_ event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + switch event { + case .next(let element): + _id = _id &+ 1 + let currentId = _id + _value = element + + + let scheduler = _parent._scheduler + let dueTime = _parent._dueTime + + let d = SingleAssignmentDisposable() + self.cancellable.disposable = d + d.setDisposable(scheduler.scheduleRelative(currentId, dueTime: dueTime, action: self.propagate)) + case .error: + _value = nil + forwardOn(event) + dispose() + case .completed: + if let value = _value { + _value = nil + forwardOn(.next(value)) + } + forwardOn(.completed) + dispose() + } + } + + func propagate(_ currentId: UInt64) -> Disposable { + _lock.lock(); defer { _lock.unlock() } // { + let originalValue = _value + + if let value = originalValue, _id == currentId { + _value = nil + forwardOn(.next(value)) + } + // } + return Disposables.create() + } +} + +final fileprivate class Debounce : Producer { + + fileprivate let _source: Observable + fileprivate let _dueTime: RxTimeInterval + fileprivate let _scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, scheduler: SchedulerType) { + _source = source + _dueTime = dueTime + _scheduler = scheduler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = DebounceSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } + +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Debug.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Debug.swift new file mode 100644 index 0000000000..1b7d26236d --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Debug.swift @@ -0,0 +1,103 @@ +// +// Debug.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import struct Foundation.Date +import class Foundation.DateFormatter + +extension ObservableType { + + /** + Prints received events for all observers on standard output. + + - seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html) + + - parameter identifier: Identifier that is printed together with event description to standard output. + - parameter trimOutput: Should output be trimmed to max 40 characters. + - returns: An observable sequence whose events are printed to standard output. + */ + public func debug(_ identifier: String? = nil, trimOutput: Bool = false, file: String = #file, line: UInt = #line, function: String = #function) + -> Observable { + return Debug(source: self, identifier: identifier, trimOutput: trimOutput, file: file, line: line, function: function) + } +} + +fileprivate let dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" + +fileprivate func logEvent(_ identifier: String, dateFormat: DateFormatter, content: String) { + print("\(dateFormat.string(from: Date())): \(identifier) -> \(content)") +} + +final fileprivate class DebugSink : Sink, ObserverType where O.E == Source.E { + typealias Element = O.E + typealias Parent = Debug + + private let _parent: Parent + private let _timestampFormatter = DateFormatter() + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + _timestampFormatter.dateFormat = dateFormat + + logEvent(_parent._identifier, dateFormat: _timestampFormatter, content: "subscribed") + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + let maxEventTextLength = 40 + let eventText = "\(event)" + + let eventNormalized = (eventText.characters.count > maxEventTextLength) && _parent._trimOutput + ? String(eventText.characters.prefix(maxEventTextLength / 2)) + "..." + String(eventText.characters.suffix(maxEventTextLength / 2)) + : eventText + + logEvent(_parent._identifier, dateFormat: _timestampFormatter, content: "Event \(eventNormalized)") + + forwardOn(event) + if event.isStopEvent { + dispose() + } + } + + override func dispose() { + if !self.disposed { + logEvent(_parent._identifier, dateFormat: _timestampFormatter, content: "isDisposed") + } + super.dispose() + } +} + +final fileprivate class Debug : Producer { + fileprivate let _identifier: String + fileprivate let _trimOutput: Bool + fileprivate let _source: Source + + init(source: Source, identifier: String?, trimOutput: Bool, file: String, line: UInt, function: String) { + _trimOutput = trimOutput + if let identifier = identifier { + _identifier = identifier + } + else { + let trimmedFile: String + if let lastIndex = file.lastIndexOf("/") { + trimmedFile = file[file.index(after: lastIndex) ..< file.endIndex] + } + else { + trimmedFile = file + } + _identifier = "\(trimmedFile):\(line) (\(function))" + } + _source = source + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Source.E { + let sink = DebugSink(parent: self, observer: observer, cancel: cancel) + let subscription = _source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift new file mode 100644 index 0000000000..696361fdd3 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift @@ -0,0 +1,66 @@ +// +// DefaultIfEmpty.swift +// RxSwift +// +// Created by sergdort on 23/12/2016. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Emits elements from the source observable sequence, or a default element if the source observable sequence is empty. + + - seealso: [DefaultIfEmpty operator on reactivex.io](http://reactivex.io/documentation/operators/defaultifempty.html) + + - parameter default: Default element to be sent if the source does not emit any elements + - returns: An observable sequence which emits default element end completes in case the original sequence is empty + */ + public func ifEmpty(default: E) -> Observable { + return DefaultIfEmpty(source: self.asObservable(), default: `default`) + } +} + +final fileprivate class DefaultIfEmptySink: Sink, ObserverType { + typealias E = O.E + private let _default: E + private var _isEmpty = true + + init(default: E, observer: O, cancel: Cancelable) { + _default = `default` + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(_): + _isEmpty = false + forwardOn(event) + case .error(_): + forwardOn(event) + dispose() + case .completed: + if _isEmpty { + forwardOn(.next(_default)) + } + forwardOn(.completed) + dispose() + } + } +} + +final fileprivate class DefaultIfEmpty: Producer { + private let _source: Observable + private let _default: SourceType + + init(source: Observable, `default`: SourceType) { + _source = source + _default = `default` + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == SourceType { + let sink = DefaultIfEmptySink(default: _default, observer: observer, cancel: cancel) + let subscription = _source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Deferred.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Deferred.swift new file mode 100644 index 0000000000..6a0b24433a --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Deferred.swift @@ -0,0 +1,74 @@ +// +// Deferred.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension Observable { + /** + Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + + - seealso: [defer operator on reactivex.io](http://reactivex.io/documentation/operators/defer.html) + + - parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence. + - returns: An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + public static func deferred(_ observableFactory: @escaping () throws -> Observable) + -> Observable { + return Deferred(observableFactory: observableFactory) + } +} + +final fileprivate class DeferredSink : Sink, ObserverType where S.E == O.E { + typealias E = O.E + + private let _observableFactory: () throws -> S + + init(observableFactory: @escaping () throws -> S, observer: O, cancel: Cancelable) { + _observableFactory = observableFactory + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + do { + let result = try _observableFactory() + return result.subscribe(self) + } + catch let e { + forwardOn(.error(e)) + dispose() + return Disposables.create() + } + } + + func on(_ event: Event) { + forwardOn(event) + + switch event { + case .next: + break + case .error: + dispose() + case .completed: + dispose() + } + } +} + +final fileprivate class Deferred : Producer { + typealias Factory = () throws -> S + + private let _observableFactory : Factory + + init(observableFactory: @escaping Factory) { + _observableFactory = observableFactory + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == S.E { + let sink = DeferredSink(observableFactory: _observableFactory, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Delay.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Delay.swift new file mode 100644 index 0000000000..6972b845f0 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Delay.swift @@ -0,0 +1,181 @@ +// +// Delay.swift +// RxSwift +// +// Created by tarunon on 2016/02/09. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import struct Foundation.Date + +extension ObservableType { + + /** + Returns an observable sequence by the source observable sequence shifted forward in time by a specified delay. Error events from the source observable sequence are not delayed. + + - seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html) + + - parameter dueTime: Relative time shift of the source by. + - parameter scheduler: Scheduler to run the subscription delay timer on. + - returns: the source Observable shifted in time by the specified delay. + */ + public func delay(_ dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Delay(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler) + } +} + +final fileprivate class DelaySink + : Sink + , ObserverType { + typealias E = O.E + typealias Source = Observable + typealias DisposeKey = Bag.KeyType + + private let _lock = RecursiveLock() + + private let _dueTime: RxTimeInterval + private let _scheduler: SchedulerType + + private let _sourceSubscription = SingleAssignmentDisposable() + private let _cancelable = SerialDisposable() + + // is scheduled some action + private var _active = false + // is "run loop" on different scheduler running + private var _running = false + private var _errorEvent: Event? = nil + + // state + private var _queue = Queue<(eventTime: RxTime, event: Event)>(capacity: 0) + private var _disposed = false + + init(observer: O, dueTime: RxTimeInterval, scheduler: SchedulerType, cancel: Cancelable) { + _dueTime = dueTime + _scheduler = scheduler + super.init(observer: observer, cancel: cancel) + } + + // All of these complications in this method are caused by the fact that + // error should be propagated immediatelly. Error can bepotentially received on different + // scheduler so this process needs to be synchronized somehow. + // + // Another complication is that scheduler is potentially concurrent so internal queue is used. + func drainQueue(state: (), scheduler: AnyRecursiveScheduler<()>) { + + _lock.lock() // { + let hasFailed = _errorEvent != nil + if !hasFailed { + _running = true + } + _lock.unlock() // } + + if hasFailed { + return + } + + var ranAtLeastOnce = false + + while true { + _lock.lock() // { + let errorEvent = _errorEvent + + let eventToForwardImmediatelly = ranAtLeastOnce ? nil : _queue.dequeue()?.event + let nextEventToScheduleOriginalTime: Date? = ranAtLeastOnce && !_queue.isEmpty ? _queue.peek().eventTime : nil + + if let _ = errorEvent { + } + else { + if let _ = eventToForwardImmediatelly { + } + else if let _ = nextEventToScheduleOriginalTime { + _running = false + } + else { + _running = false + _active = false + } + } + _lock.unlock() // { + + if let errorEvent = errorEvent { + self.forwardOn(errorEvent) + self.dispose() + return + } + else { + if let eventToForwardImmediatelly = eventToForwardImmediatelly { + ranAtLeastOnce = true + self.forwardOn(eventToForwardImmediatelly) + if case .completed = eventToForwardImmediatelly { + self.dispose() + return + } + } + else if let nextEventToScheduleOriginalTime = nextEventToScheduleOriginalTime { + let elapsedTime = _scheduler.now.timeIntervalSince(nextEventToScheduleOriginalTime) + let interval = _dueTime - elapsedTime + let normalizedInterval = interval < 0.0 ? 0.0 : interval + scheduler.schedule((), dueTime: normalizedInterval) + return + } + else { + return + } + } + } + } + + func on(_ event: Event) { + if event.isStopEvent { + _sourceSubscription.dispose() + } + + switch event { + case .error(_): + _lock.lock() // { + let shouldSendImmediatelly = !_running + _queue = Queue(capacity: 0) + _errorEvent = event + _lock.unlock() // } + + if shouldSendImmediatelly { + forwardOn(event) + dispose() + } + default: + _lock.lock() // { + let shouldSchedule = !_active + _active = true + _queue.enqueue((_scheduler.now, event)) + _lock.unlock() // } + + if shouldSchedule { + _cancelable.disposable = _scheduler.scheduleRecursive((), dueTime: _dueTime, action: self.drainQueue) + } + } + } + + func run(source: Observable) -> Disposable { + _sourceSubscription.setDisposable(source.subscribe(self)) + return Disposables.create(_sourceSubscription, _cancelable) + } +} + +final fileprivate class Delay: Producer { + private let _source: Observable + private let _dueTime: RxTimeInterval + private let _scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, scheduler: SchedulerType) { + _source = source + _dueTime = dueTime + _scheduler = scheduler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = DelaySink(observer: observer, dueTime: _dueTime, scheduler: _scheduler, cancel: cancel) + let subscription = sink.run(source: _source) + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift new file mode 100644 index 0000000000..9225a196c7 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift @@ -0,0 +1,66 @@ +// +// DelaySubscription.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers. + + - seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html) + + - parameter dueTime: Relative time shift of the subscription. + - parameter scheduler: Scheduler to run the subscription delay timer on. + - returns: Time-shifted sequence. + */ + public func delaySubscription(_ dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return DelaySubscription(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler) + } +} + +final fileprivate class DelaySubscriptionSink + : Sink, ObserverType { + typealias E = O.E + typealias Parent = DelaySubscription + + private let _parent: Parent + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + forwardOn(event) + if event.isStopEvent { + dispose() + } + } + +} + +final fileprivate class DelaySubscription: Producer { + private let _source: Observable + private let _dueTime: RxTimeInterval + private let _scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, scheduler: SchedulerType) { + _source = source + _dueTime = dueTime + _scheduler = scheduler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = DelaySubscriptionSink(parent: self, observer: observer, cancel: cancel) + let subscription = _scheduler.scheduleRelative((), dueTime: _dueTime) { _ in + return self._source.subscribe(sink) + } + + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift new file mode 100644 index 0000000000..d142249a96 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift @@ -0,0 +1,51 @@ +// +// Dematerialize.swift +// RxSwift +// +// Created by Jamie Pinkham on 3/13/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType where E: EventConvertible { + /** + Convert any previously materialized Observable into it's original form. + - seealso: [materialize operator on reactivex.io](http://reactivex.io/documentation/operators/materialize-dematerialize.html) + - returns: The dematerialized observable sequence. + */ + public func dematerialize() -> Observable { + return Dematerialize(source: self.asObservable()) + } + +} + +fileprivate final class DematerializeSink: Sink, ObserverType where O.E == Element.ElementType { + fileprivate func on(_ event: Event) { + switch event { + case .next(let element): + forwardOn(element.event) + if element.event.isStopEvent { + dispose() + } + case .completed: + forwardOn(.completed) + dispose() + case .error(let error): + forwardOn(.error(error)) + dispose() + } + } +} + +final fileprivate class Dematerialize: Producer { + private let _source: Observable + + init(source: Observable) { + _source = source + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element.ElementType { + let sink = DematerializeSink(observer: observer, cancel: cancel) + let subscription = _source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift new file mode 100644 index 0000000000..f72f52014d --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift @@ -0,0 +1,125 @@ +// +// DistinctUntilChanged.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType where E: Equatable { + + /** + Returns an observable sequence that contains only distinct contiguous elements according to equality operator. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence. + */ + public func distinctUntilChanged() + -> Observable { + return self.distinctUntilChanged({ $0 }, comparer: { ($0 == $1) }) + } +} + +extension ObservableType { + /** + Returns an observable sequence that contains only distinct contiguous elements according to the `keySelector`. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - parameter keySelector: A function to compute the comparison key for each element. + - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. + */ + public func distinctUntilChanged(_ keySelector: @escaping (E) throws -> K) + -> Observable { + return self.distinctUntilChanged(keySelector, comparer: { $0 == $1 }) + } + + /** + Returns an observable sequence that contains only distinct contiguous elements according to the `comparer`. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - parameter comparer: Equality comparer for computed key values. + - returns: An observable sequence only containing the distinct contiguous elements, based on `comparer`, from the source sequence. + */ + public func distinctUntilChanged(_ comparer: @escaping (E, E) throws -> Bool) + -> Observable { + return self.distinctUntilChanged({ $0 }, comparer: comparer) + } + + /** + Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - parameter keySelector: A function to compute the comparison key for each element. + - parameter comparer: Equality comparer for computed key values. + - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value and the comparer, from the source sequence. + */ + public func distinctUntilChanged(_ keySelector: @escaping (E) throws -> K, comparer: @escaping (K, K) throws -> Bool) + -> Observable { + return DistinctUntilChanged(source: self.asObservable(), selector: keySelector, comparer: comparer) + } +} + +final fileprivate class DistinctUntilChangedSink: Sink, ObserverType { + typealias E = O.E + + private let _parent: DistinctUntilChanged + private var _currentKey: Key? = nil + + init(parent: DistinctUntilChanged, observer: O, cancel: Cancelable) { + _parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + 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() + } + } +} + +final fileprivate class DistinctUntilChanged: Producer { + typealias KeySelector = (Element) throws -> Key + typealias EqualityComparer = (Key, Key) throws -> Bool + + fileprivate let _source: Observable + fileprivate let _selector: KeySelector + fileprivate let _comparer: EqualityComparer + + init(source: Observable, selector: @escaping KeySelector, comparer: @escaping EqualityComparer) { + _source = source + _selector = selector + _comparer = comparer + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = DistinctUntilChangedSink(parent: self, observer: observer, cancel: cancel) + let subscription = _source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Do.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Do.swift new file mode 100644 index 0000000000..4ee8841918 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Do.swift @@ -0,0 +1,93 @@ +// +// Do.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence. + + - seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html) + + - 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 onSubscribe: Action to invoke before subscribing to source observable sequence. + - parameter onSubscribed: Action to invoke after subscribing to source observable sequence. + - parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed. + - returns: The source sequence with the side-effecting behavior applied. + */ + public func `do`(onNext: ((E) throws -> Void)? = nil, onError: ((Swift.Error) throws -> Void)? = nil, onCompleted: (() throws -> Void)? = nil, onSubscribe: (() -> ())? = nil, onSubscribed: (() -> ())? = nil, onDispose: (() -> ())? = nil) + -> Observable { + return Do(source: self.asObservable(), eventHandler: { e in + switch e { + case .next(let element): + try onNext?(element) + case .error(let e): + try onError?(e) + case .completed: + try onCompleted?() + } + }, onSubscribe: onSubscribe, onSubscribed: onSubscribed, onDispose: onDispose) + } +} + +final fileprivate class DoSink : Sink, ObserverType { + typealias Element = O.E + typealias Parent = Do + + private let _parent: Parent + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + do { + try _parent._eventHandler(event) + forwardOn(event) + if event.isStopEvent { + dispose() + } + } + catch let error { + forwardOn(.error(error)) + dispose() + } + } +} + +final fileprivate class Do : Producer { + typealias EventHandler = (Event) throws -> Void + + fileprivate let _source: Observable + fileprivate let _eventHandler: EventHandler + fileprivate let _onSubscribe: (() -> ())? + fileprivate let _onSubscribed: (() -> ())? + fileprivate let _onDispose: (() -> ())? + + init(source: Observable, eventHandler: @escaping EventHandler, onSubscribe: (() -> ())?, onSubscribed: (() -> ())?, onDispose: (() -> ())?) { + _source = source + _eventHandler = eventHandler + _onSubscribe = onSubscribe + _onSubscribed = onSubscribed + _onDispose = onDispose + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + _onSubscribe?() + let sink = DoSink(parent: self, observer: observer, cancel: cancel) + let subscription = _source.subscribe(sink) + _onSubscribed?() + let onDispose = _onDispose + let allSubscriptions = Disposables.create { + subscription.dispose() + onDispose?() + } + return (sink: sink, subscription: allSubscriptions) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/ElementAt.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/ElementAt.swift new file mode 100644 index 0000000000..500a0442e4 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/ElementAt.swift @@ -0,0 +1,93 @@ +// +// ElementAt.swift +// RxSwift +// +// Created by Junior B. on 21/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Returns a sequence emitting only element _n_ emitted by an Observable + + - seealso: [elementAt operator on reactivex.io](http://reactivex.io/documentation/operators/elementat.html) + + - parameter index: The index of the required element (starting from 0). + - returns: An observable sequence that emits the desired element as its own sole emission. + */ + public func elementAt(_ index: Int) + -> Observable { + return ElementAt(source: asObservable(), index: index, throwOnEmpty: true) + } +} + +final fileprivate class ElementAtSink : Sink, ObserverType { + typealias SourceType = O.E + typealias Parent = ElementAt + + let _parent: Parent + var _i: Int + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + _i = parent._index + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(_): + + if (_i == 0) { + forwardOn(event) + forwardOn(.completed) + self.dispose() + } + + do { + let _ = 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() + } + } +} + +final fileprivate class ElementAt : Producer { + + let _source: Observable + let _throwOnEmpty: Bool + let _index: Int + + init(source: Observable, 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(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == SourceType { + let sink = ElementAtSink(parent: self, observer: observer, cancel: cancel) + let subscription = _source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Empty.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Empty.swift new file mode 100644 index 0000000000..1511a94687 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Empty.swift @@ -0,0 +1,27 @@ +// +// Empty.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension Observable { + /** + Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message. + + - seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) + + - returns: An observable sequence with no elements. + */ + public static func empty() -> Observable { + return EmptyProducer() + } +} + +final fileprivate class EmptyProducer : Producer { + override func subscribe(_ observer: O) -> Disposable where O.E == Element { + observer.on(.completed) + return Disposables.create() + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Error.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Error.swift new file mode 100644 index 0000000000..c76068f020 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Error.swift @@ -0,0 +1,33 @@ +// +// Error.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension Observable { + /** + Returns an observable sequence that terminates with an `error`. + + - seealso: [throw operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) + + - returns: The observable sequence that terminates with specified error. + */ + public static func error(_ error: Swift.Error) -> Observable { + return ErrorProducer(error: error) + } +} + +final fileprivate class ErrorProducer : Producer { + private let _error: Swift.Error + + init(error: Swift.Error) { + _error = error + } + + override func subscribe(_ observer: O) -> Disposable where O.E == Element { + observer.on(.error(_error)) + return Disposables.create() + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Filter.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Filter.swift new file mode 100644 index 0000000000..8cf8c0d55c --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Filter.swift @@ -0,0 +1,89 @@ +// +// Filter.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Filters the elements of an observable sequence based on a predicate. + + - seealso: [filter operator on reactivex.io](http://reactivex.io/documentation/operators/filter.html) + + - parameter predicate: A function to test each source element for a condition. + - returns: An observable sequence that contains elements from the input sequence that satisfy the condition. + */ + public func filter(_ predicate: @escaping (E) throws -> Bool) + -> Observable { + return Filter(source: asObservable(), predicate: predicate) + } +} + +extension ObservableType { + + /** + Skips elements and completes (or errors) when the receiver completes (or errors). Equivalent to filter that always returns false. + + - seealso: [ignoreElements operator on reactivex.io](http://reactivex.io/documentation/operators/ignoreelements.html) + + - returns: An observable sequence that skips all elements of the source sequence. + */ + public func ignoreElements() + -> Observable { + return filter { _ -> Bool in + return false + } + } +} + +final fileprivate class FilterSink: Sink, ObserverType { + typealias Predicate = (Element) throws -> Bool + typealias Element = O.E + + private let _predicate: Predicate + + init(predicate: @escaping Predicate, observer: O, cancel: Cancelable) { + _predicate = predicate + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + do { + let satisfies = try _predicate(value) + if satisfies { + forwardOn(.next(value)) + } + } + catch let e { + forwardOn(.error(e)) + dispose() + } + case .completed, .error: + forwardOn(event) + dispose() + } + } +} + +final fileprivate class Filter : Producer { + typealias Predicate = (Element) throws -> Bool + + private let _source: Observable + private let _predicate: Predicate + + init(source: Observable, predicate: @escaping Predicate) { + _source = source + _predicate = predicate + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = FilterSink(predicate: _predicate, observer: observer, cancel: cancel) + let subscription = _source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Generate.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Generate.swift new file mode 100644 index 0000000000..db5b648826 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Generate.swift @@ -0,0 +1,87 @@ +// +// Generate.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension Observable { + /** + Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler + to run the loop send out observer messages. + + - seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html) + + - parameter initialState: Initial state. + - parameter condition: Condition to terminate generation (upon returning `false`). + - parameter iterate: Iteration step function. + - parameter scheduler: Scheduler on which to run the generator loop. + - returns: The generated sequence. + */ + public static func generate(initialState: E, condition: @escaping (E) throws -> Bool, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance, iterate: @escaping (E) throws -> E) -> Observable { + return Generate(initialState: initialState, condition: condition, iterate: iterate, resultSelector: { $0 }, scheduler: scheduler) + } +} + +final fileprivate class GenerateSink : Sink { + typealias Parent = Generate + + private let _parent: Parent + + private var _state: S + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + _state = parent._initialState + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return _parent._scheduler.scheduleRecursive(true) { (isFirst, recurse) -> Void in + do { + if !isFirst { + self._state = try self._parent._iterate(self._state) + } + + if try self._parent._condition(self._state) { + let result = try self._parent._resultSelector(self._state) + self.forwardOn(.next(result)) + + recurse(false) + } + else { + self.forwardOn(.completed) + self.dispose() + } + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + } + } +} + +final fileprivate class Generate : Producer { + fileprivate let _initialState: S + fileprivate let _condition: (S) throws -> Bool + fileprivate let _iterate: (S) throws -> S + fileprivate let _resultSelector: (S) throws -> E + fileprivate let _scheduler: ImmediateSchedulerType + + init(initialState: S, condition: @escaping (S) throws -> Bool, iterate: @escaping (S) throws -> S, resultSelector: @escaping (S) throws -> E, scheduler: ImmediateSchedulerType) { + _initialState = initialState + _condition = condition + _iterate = iterate + _resultSelector = resultSelector + _scheduler = scheduler + super.init() + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { + let sink = GenerateSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/GroupBy.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/GroupBy.swift new file mode 100644 index 0000000000..a8a0e78afd --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/GroupBy.swift @@ -0,0 +1,134 @@ +// +// GroupBy.swift +// RxSwift +// +// Created by Tomi Koskinen on 01/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /* + Groups the elements of an observable sequence according to a specified key selector function. + + - seealso: [groupBy operator on reactivex.io](http://reactivex.io/documentation/operators/groupby.html) + + - parameter keySelector: A function to extract the key for each element. + - returns: A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. + */ + public func groupBy(keySelector: @escaping (E) throws -> K) + -> Observable> { + return GroupBy(source: self.asObservable(), selector: keySelector) + } +} + +final fileprivate class GroupedObservableImpl : Observable { + private var _subject: PublishSubject + private var _refCount: RefCountDisposable + + init(key: Key, subject: PublishSubject, refCount: RefCountDisposable) { + _subject = subject + _refCount = refCount + } + + override public func subscribe(_ observer: O) -> Disposable where O.E == E { + let release = _refCount.retain() + let subscription = _subject.subscribe(observer) + return Disposables.create(release, subscription) + } +} + + +final fileprivate class GroupBySink + : Sink + , ObserverType where O.E == GroupedObservable { + typealias E = Element + typealias ResultType = O.E + typealias Parent = GroupBy + + private let _parent: Parent + private let _subscription = SingleAssignmentDisposable() + private var _refCountDisposable: RefCountDisposable! + private var _groupedSubjectTable: [Key: PublishSubject] + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + _groupedSubjectTable = [Key: PublishSubject]() + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + _refCountDisposable = RefCountDisposable(disposable: _subscription) + + _subscription.setDisposable(_parent._source.subscribe(self)) + + return _refCountDisposable + } + + private func onGroupEvent(key: Key, value: Element) { + if let writer = _groupedSubjectTable[key] { + writer.on(.next(value)) + } else { + let writer = PublishSubject() + _groupedSubjectTable[key] = writer + + let group = GroupedObservable( + key: key, + source: GroupedObservableImpl(key: key, subject: writer, refCount: _refCountDisposable) + ) + + forwardOn(.next(group)) + writer.on(.next(value)) + } + } + + final func on(_ event: Event) { + switch event { + case let .next(value): + do { + let groupKey = try _parent._selector(value) + onGroupEvent(key: groupKey, value: value) + } + catch let e { + error(e) + return + } + case let .error(e): + error(e) + case .completed: + forwardOnGroups(event: .completed) + forwardOn(.completed) + _subscription.dispose() + dispose() + } + } + + final func error(_ error: Swift.Error) { + forwardOnGroups(event: .error(error)) + forwardOn(.error(error)) + _subscription.dispose() + dispose() + } + + final func forwardOnGroups(event: Event) { + for writer in _groupedSubjectTable.values { + writer.on(event) + } + } +} + +final fileprivate class GroupBy: Producer> { + typealias KeySelector = (Element) throws -> Key + + fileprivate let _source: Observable + fileprivate let _selector: KeySelector + + init(source: Observable, selector: @escaping KeySelector) { + _source = source + _selector = selector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == GroupedObservable { + let sink = GroupBySink(parent: self, observer: observer, cancel: cancel) + return (sink: sink, subscription: sink.run()) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Just.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Just.swift new file mode 100644 index 0000000000..3beb04b917 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Just.swift @@ -0,0 +1,87 @@ +// +// Just.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension Observable { + /** + Returns an observable sequence that contains a single element. + + - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) + + - parameter element: Single element in the resulting observable sequence. + - returns: An observable sequence containing the single specified element. + */ + public static func just(_ element: E) -> Observable { + return Just(element: element) + } + + /** + Returns an observable sequence that contains a single element. + + - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) + + - parameter element: Single element in the resulting observable sequence. + - parameter: Scheduler to send the single element on. + - returns: An observable sequence containing the single specified element. + */ + public static func just(_ element: E, scheduler: ImmediateSchedulerType) -> Observable { + return JustScheduled(element: element, scheduler: scheduler) + } +} + +final fileprivate class JustScheduledSink : Sink { + typealias Parent = JustScheduled + + private let _parent: Parent + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let scheduler = _parent._scheduler + return scheduler.schedule(_parent._element) { element in + self.forwardOn(.next(element)) + return scheduler.schedule(()) { _ in + self.forwardOn(.completed) + self.dispose() + return Disposables.create() + } + } + } +} + +final fileprivate class JustScheduled : Producer { + fileprivate let _scheduler: ImmediateSchedulerType + fileprivate let _element: Element + + init(element: Element, scheduler: ImmediateSchedulerType) { + _scheduler = scheduler + _element = element + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { + let sink = JustScheduledSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final fileprivate class Just : Producer { + private let _element: Element + + init(element: Element) { + _element = element + } + + override func subscribe(_ observer: O) -> Disposable where O.E == Element { + observer.on(.next(_element)) + observer.on(.completed) + return Disposables.create() + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Map.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Map.swift new file mode 100644 index 0000000000..d743c26cdf --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Map.swift @@ -0,0 +1,177 @@ +// +// Map.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Projects each element of an observable sequence into a new form. + + - seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html) + + - parameter transform: A transform function to apply to each source element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source. + + */ + public func map(_ transform: @escaping (E) throws -> R) + -> Observable { + return self.asObservable().composeMap(transform) + } + + /** + Projects each element of an observable sequence into a new form by incorporating the element's index. + + - seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html) + + - parameter selector: A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source. + */ + public func mapWithIndex(_ selector: @escaping (E, Int) throws -> R) + -> Observable { + return MapWithIndex(source: asObservable(), selector: selector) + } +} + +final fileprivate class MapSink : Sink, ObserverType { + typealias Transform = (SourceType) throws -> ResultType + + typealias ResultType = O.E + typealias Element = SourceType + + private let _transform: Transform + + init(transform: @escaping Transform, observer: O, cancel: Cancelable) { + _transform = transform + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let element): + do { + let mappedElement = try _transform(element) + forwardOn(.next(mappedElement)) + } + catch let e { + forwardOn(.error(e)) + dispose() + } + case .error(let error): + forwardOn(.error(error)) + dispose() + case .completed: + forwardOn(.completed) + dispose() + } + } +} + +final fileprivate class MapWithIndexSink : Sink, ObserverType { + typealias Selector = (SourceType, Int) throws -> ResultType + + typealias ResultType = O.E + typealias Element = SourceType + typealias Parent = MapWithIndex + + private let _selector: Selector + + private var _index = 0 + + init(selector: @escaping Selector, observer: O, cancel: Cancelable) { + _selector = selector + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let element): + do { + let mappedElement = try _selector(element, try incrementChecked(&_index)) + forwardOn(.next(mappedElement)) + } + catch let e { + forwardOn(.error(e)) + dispose() + } + case .error(let error): + forwardOn(.error(error)) + dispose() + case .completed: + forwardOn(.completed) + dispose() + } + } +} + +final fileprivate class MapWithIndex : Producer { + typealias Selector = (SourceType, Int) throws -> ResultType + + private let _source: Observable + + private let _selector: Selector + + init(source: Observable, selector: @escaping Selector) { + _source = source + _selector = selector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == ResultType { + let sink = MapWithIndexSink(selector: _selector, observer: observer, cancel: cancel) + let subscription = _source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} + +#if TRACE_RESOURCES + fileprivate var _numberOfMapOperators: AtomicInt = 0 + extension Resources { + public static var numberOfMapOperators: Int32 { + return _numberOfMapOperators.valueSnapshot() + } + } +#endif + +internal func _map(source: Observable, transform: @escaping (Element) throws -> R) -> Observable { + return Map(source: source, transform: transform) +} + +final fileprivate class Map: Producer { + typealias Transform = (SourceType) throws -> ResultType + + private let _source: Observable + + private let _transform: Transform + + init(source: Observable, transform: @escaping Transform) { + _source = source + _transform = transform + +#if TRACE_RESOURCES + let _ = AtomicIncrement(&_numberOfMapOperators) +#endif + } + + override func composeMap(_ selector: @escaping (ResultType) throws -> R) -> Observable { + let originalSelector = _transform + return Map(source: _source, transform: { (s: SourceType) throws -> R in + let r: ResultType = try originalSelector(s) + return try selector(r) + }) + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == ResultType { + let sink = MapSink(transform: _transform, observer: observer, cancel: cancel) + let subscription = _source.subscribe(sink) + return (sink: sink, subscription: subscription) + } + + #if TRACE_RESOURCES + deinit { + let _ = AtomicDecrement(&_numberOfMapOperators) + } + #endif +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Materialize.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Materialize.swift new file mode 100644 index 0000000000..cf19b6da9b --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Materialize.swift @@ -0,0 +1,44 @@ +// +// Materialize.swift +// RxSwift +// +// Created by sergdort on 08/03/2017. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Convert any Observable into an Observable of its events. + - seealso: [materialize operator on reactivex.io](http://reactivex.io/documentation/operators/materialize-dematerialize.html) + - returns: An observable sequence that wraps events in an Event. The returned Observable never errors, but it does complete after observing all of the events of the underlying Observable. + */ + public func materialize() -> Observable> { + return Materialize(source: self.asObservable()) + } +} + +fileprivate final class MaterializeSink: Sink, ObserverType where O.E == Event { + + func on(_ event: Event) { + forwardOn(.next(event)) + if event.isStopEvent { + forwardOn(.completed) + dispose() + } + } +} + +final fileprivate class Materialize: Producer> { + private let _source: Observable + + init(source: Observable) { + _source = source + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { + let sink = MaterializeSink(observer: observer, cancel: cancel) + let subscription = _source.subscribe(sink) + + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Merge.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Merge.swift new file mode 100644 index 0000000000..91996860de --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Merge.swift @@ -0,0 +1,561 @@ +// +// Merge.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + + - seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to each element. + - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence. + */ + public func flatMap(_ selector: @escaping (E) throws -> O) + -> Observable { + return FlatMap(source: asObservable(), selector: selector) + } + + /** + Projects each element of an observable sequence to an observable sequence by incorporating the element's index and merges the resulting observable sequences into one observable sequence. + + - seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to each element; the second parameter of the function represents the index of the source element. + - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence. + */ + public func flatMapWithIndex(_ selector: @escaping (E, Int) throws -> O) + -> Observable { + return FlatMapWithIndex(source: asObservable(), selector: selector) + } +} + +extension ObservableType { + + /** + Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + If element is received while there is some projected observable sequence being merged it will simply be ignored. + + - seealso: [flatMapFirst operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to element that was observed while no observable is executing in parallel. + - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence that was received while no other sequence was being calculated. + */ + public func flatMapFirst(_ selector: @escaping (E) throws -> O) + -> Observable { + return FlatMapFirst(source: asObservable(), selector: selector) + } +} + +extension ObservableType where E : ObservableConvertibleType { + + /** + Merges elements from all observable sequences in the given enumerable sequence into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public func merge() -> Observable { + return Merge(source: asObservable()) + } + + /** + Merges elements from all inner observable sequences into a single observable sequence, limiting the number of concurrent subscriptions to inner sequences. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter maxConcurrent: Maximum number of inner observable sequences being subscribed to concurrently. + - returns: The observable sequence that merges the elements of the inner sequences. + */ + public func merge(maxConcurrent: Int) + -> Observable { + return MergeLimited(source: asObservable(), maxConcurrent: maxConcurrent) + } +} + +extension ObservableType where E : ObservableConvertibleType { + + /** + Concatenates all inner observable sequences, as long as the previous observable sequence terminated successfully. + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each observed inner sequence, in sequential order. + */ + public func concat() -> Observable { + return merge(maxConcurrent: 1) + } +} + +extension Observable { + /** + Merges elements from all observable sequences from collection into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter sources: Collection of observable sequences to merge. + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public static func merge(_ sources: C) -> Observable where C.Iterator.Element == Observable { + return MergeArray(sources: Array(sources)) + } + + /** + Merges elements from all observable sequences from array into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter sources: Array of observable sequences to merge. + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public static func merge(_ sources: [Observable]) -> Observable { + return MergeArray(sources: sources) + } + + /** + Merges elements from all observable sequences into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter sources: Collection of observable sequences to merge. + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public static func merge(_ sources: Observable...) -> Observable { + return MergeArray(sources: sources) + } +} + +fileprivate final class MergeLimitedSinkIter + : ObserverType + , LockOwnerType + , SynchronizedOnType where S.E == O.E { + typealias E = O.E + typealias DisposeKey = CompositeDisposable.DisposeKey + typealias Parent = MergeLimitedSink + + private let _parent: Parent + private let _disposeKey: DisposeKey + + var _lock: RecursiveLock { + return _parent._lock + } + + init(parent: Parent, disposeKey: DisposeKey) { + _parent = parent + _disposeKey = disposeKey + } + + func on(_ event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + switch event { + case .next: + _parent.forwardOn(event) + case .error: + _parent.forwardOn(event) + _parent.dispose() + case .completed: + _parent._group.remove(for: _disposeKey) + if let next = _parent._queue.dequeue() { + _parent.subscribe(next, group: _parent._group) + } + else { + _parent._activeCount = _parent._activeCount - 1 + + if _parent._stopped && _parent._activeCount == 0 { + _parent.forwardOn(.completed) + _parent.dispose() + } + } + } + } +} + +fileprivate final class MergeLimitedSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType where S.E == O.E { + typealias E = S + typealias QueueType = Queue + + let _maxConcurrent: Int + + let _lock = RecursiveLock() + + // state + var _stopped = false + var _activeCount = 0 + var _queue = QueueType(capacity: 2) + + let _sourceSubscription = SingleAssignmentDisposable() + let _group = CompositeDisposable() + + init(maxConcurrent: Int, observer: O, cancel: Cancelable) { + _maxConcurrent = maxConcurrent + + let _ = _group.insert(_sourceSubscription) + super.init(observer: observer, cancel: cancel) + } + + func run(_ source: Observable) -> Disposable { + let _ = _group.insert(_sourceSubscription) + + let disposable = source.subscribe(self) + _sourceSubscription.setDisposable(disposable) + return _group + } + + func subscribe(_ innerSource: E, group: CompositeDisposable) { + let subscription = SingleAssignmentDisposable() + + let key = group.insert(subscription) + + if let key = key { + let observer = MergeLimitedSinkIter(parent: self, disposeKey: key) + + let disposable = innerSource.asObservable().subscribe(observer) + subscription.setDisposable(disposable) + } + } + + func on(_ event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + switch event { + case .next(let value): + let subscribe: Bool + if _activeCount < _maxConcurrent { + _activeCount += 1 + subscribe = true + } + else { + _queue.enqueue(value) + subscribe = false + } + + if subscribe { + self.subscribe(value, group: _group) + } + case .error(let error): + forwardOn(.error(error)) + dispose() + case .completed: + if _activeCount == 0 { + forwardOn(.completed) + dispose() + } + else { + _sourceSubscription.dispose() + } + + _stopped = true + } + } +} + +final fileprivate class MergeLimited : Producer { + private let _source: Observable + private let _maxConcurrent: Int + + init(source: Observable, maxConcurrent: Int) { + _source = source + _maxConcurrent = maxConcurrent + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == S.E { + let sink = MergeLimitedSink(maxConcurrent: _maxConcurrent, observer: observer, cancel: cancel) + let subscription = sink.run(_source) + return (sink: sink, subscription: subscription) + } +} + +// MARK: Merge + +fileprivate final class MergeBasicSink : MergeSink where O.E == S.E { + override init(observer: O, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + override func performMap(_ element: S) throws -> S { + return element + } +} + +// MARK: flatMap + +fileprivate final class FlatMapSink : MergeSink where O.E == S.E { + typealias Selector = (SourceType) throws -> S + + private let _selector: Selector + + init(selector: @escaping Selector, observer: O, cancel: Cancelable) { + _selector = selector + super.init(observer: observer, cancel: cancel) + } + + override func performMap(_ element: SourceType) throws -> S { + return try _selector(element) + } +} + +fileprivate final class FlatMapWithIndexSink : MergeSink where O.E == S.E { + typealias Selector = (SourceType, Int) throws -> S + + private var _index = 0 + private let _selector: Selector + + init(selector: @escaping Selector, observer: O, cancel: Cancelable) { + _selector = selector + super.init(observer: observer, cancel: cancel) + } + + override func performMap(_ element: SourceType) throws -> S { + return try _selector(element, try incrementChecked(&_index)) + } +} + +// MARK: FlatMapFirst + +fileprivate final class FlatMapFirstSink : MergeSink where O.E == S.E { + typealias Selector = (SourceType) throws -> S + + private let _selector: Selector + + override var subscribeNext: Bool { + return _activeCount == 0 + } + + init(selector: @escaping Selector, observer: O, cancel: Cancelable) { + _selector = selector + super.init(observer: observer, cancel: cancel) + } + + override func performMap(_ element: SourceType) throws -> S { + return try _selector(element) + } +} + +fileprivate final class MergeSinkIter : ObserverType where O.E == S.E { + typealias Parent = MergeSink + typealias DisposeKey = CompositeDisposable.DisposeKey + typealias E = O.E + + private let _parent: Parent + private let _disposeKey: DisposeKey + + init(parent: Parent, disposeKey: DisposeKey) { + _parent = parent + _disposeKey = disposeKey + } + + func on(_ event: Event) { + _parent._lock.lock(); defer { _parent._lock.unlock() } // lock { + switch event { + case .next(let value): + _parent.forwardOn(.next(value)) + case .error(let error): + _parent.forwardOn(.error(error)) + _parent.dispose() + case .completed: + _parent._group.remove(for: _disposeKey) + _parent._activeCount -= 1 + _parent.checkCompleted() + } + // } + } +} + + +fileprivate class MergeSink + : Sink + , ObserverType where O.E == S.E { + typealias ResultType = O.E + typealias Element = SourceType + + let _lock = RecursiveLock() + + var subscribeNext: Bool { + return true + } + + // state + let _group = CompositeDisposable() + let _sourceSubscription = SingleAssignmentDisposable() + + var _activeCount = 0 + var _stopped = false + + override init(observer: O, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func performMap(_ element: SourceType) throws -> S { + rxAbstractMethod() + } + + func on(_ event: Event) { + _lock.lock(); defer { _lock.unlock() } // lock { + switch event { + case .next(let element): + if !subscribeNext { + return + } + do { + let value = try performMap(element) + subscribeInner(value.asObservable()) + } + catch let e { + forwardOn(.error(e)) + dispose() + } + case .error(let error): + forwardOn(.error(error)) + dispose() + case .completed: + _stopped = true + _sourceSubscription.dispose() + checkCompleted() + } + //} + } + + func subscribeInner(_ source: Observable) { + let iterDisposable = SingleAssignmentDisposable() + if let disposeKey = _group.insert(iterDisposable) { + _activeCount += 1 + let iter = MergeSinkIter(parent: self, disposeKey: disposeKey) + let subscription = source.subscribe(iter) + iterDisposable.setDisposable(subscription) + } + } + + func run(_ sources: [SourceType]) -> Disposable { + let _ = _group.insert(_sourceSubscription) + + for source in sources { + self.on(.next(source)) + } + + _stopped = true + + checkCompleted() + + return _group + } + + @inline(__always) + func checkCompleted() { + if _stopped && _activeCount == 0 { + self.forwardOn(.completed) + self.dispose() + } + } + + func run(_ source: Observable) -> Disposable { + let _ = _group.insert(_sourceSubscription) + + let subscription = source.subscribe(self) + _sourceSubscription.setDisposable(subscription) + + return _group + } +} + +// MARK: Producers + +final fileprivate class FlatMap: Producer { + typealias Selector = (SourceType) throws -> S + + private let _source: Observable + + private let _selector: Selector + + init(source: Observable, selector: @escaping Selector) { + _source = source + _selector = selector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == S.E { + let sink = FlatMapSink(selector: _selector, observer: observer, cancel: cancel) + let subscription = sink.run(_source) + return (sink: sink, subscription: subscription) + } +} + +final fileprivate class FlatMapWithIndex: Producer { + typealias Selector = (SourceType, Int) throws -> S + + private let _source: Observable + + private let _selector: Selector + + init(source: Observable, selector: @escaping Selector) { + _source = source + _selector = selector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == S.E { + let sink = FlatMapWithIndexSink(selector: _selector, observer: observer, cancel: cancel) + let subscription = sink.run(_source) + return (sink: sink, subscription: subscription) + } + +} + +final fileprivate class FlatMapFirst: Producer { + typealias Selector = (SourceType) throws -> S + + private let _source: Observable + + private let _selector: Selector + + init(source: Observable, selector: @escaping Selector) { + _source = source + _selector = selector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == S.E { + let sink = FlatMapFirstSink(selector: _selector, observer: observer, cancel: cancel) + let subscription = sink.run(_source) + return (sink: sink, subscription: subscription) + } +} + +final fileprivate class Merge : Producer { + private let _source: Observable + + init(source: Observable) { + _source = source + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == S.E { + let sink = MergeBasicSink(observer: observer, cancel: cancel) + let subscription = sink.run(_source) + return (sink: sink, subscription: subscription) + } +} + +final fileprivate class MergeArray : Producer { + private let _sources: [Observable] + + init(sources: [Observable]) { + _sources = sources + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { + let sink = MergeBasicSink, O>(observer: observer, cancel: cancel) + let subscription = sink.run(_sources) + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Multicast.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Multicast.swift new file mode 100644 index 0000000000..279291c4b8 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Multicast.swift @@ -0,0 +1,251 @@ +// +// Multicast.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. + + Each subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's invocation. + + For specializations with fixed subject types, see `publish` and `replay`. + + - seealso: [multicast operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) + + - parameter subjectSelector: Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. + - parameter selector: Selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. + - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. + */ + public func multicast(_ subjectSelector: @escaping () throws -> S, selector: @escaping (Observable) throws -> Observable) + -> Observable where S.SubjectObserverType.E == E { + return Multicast( + source: self.asObservable(), + subjectSelector: subjectSelector, + selector: selector + ) + } +} + +extension ObservableType { + + /** + Returns a connectable observable sequence that shares a single subscription to the underlying sequence. + + This operator is a specialization of `multicast` using a `PublishSubject`. + + - seealso: [publish operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) + + - returns: A connectable observable sequence that shares a single subscription to the underlying sequence. + */ + public func publish() -> ConnectableObservable { + return self.multicast(PublishSubject()) + } +} + +extension ObservableType { + + /** + Returns a connectable observable sequence that shares a single subscription to the underlying sequence replaying bufferSize elements. + + This operator is a specialization of `multicast` using a `ReplaySubject`. + + - seealso: [replay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) + + - parameter bufferSize: Maximum element count of the replay buffer. + - returns: A connectable observable sequence that shares a single subscription to the underlying sequence. + */ + public func replay(_ bufferSize: Int) + -> ConnectableObservable { + return self.multicast(ReplaySubject.create(bufferSize: bufferSize)) + } + + /** + Returns a connectable observable sequence that shares a single subscription to the underlying sequence replaying all elements. + + This operator is a specialization of `multicast` using a `ReplaySubject`. + + - seealso: [replay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) + + - returns: A connectable observable sequence that shares a single subscription to the underlying sequence. + */ + public func replayAll() + -> ConnectableObservable { + return self.multicast(ReplaySubject.createUnbounded()) + } +} + +extension ConnectableObservableType { + + /** + Returns an observable sequence that stays connected to the source as long as there is at least one subscription to the observable sequence. + + - seealso: [refCount operator on reactivex.io](http://reactivex.io/documentation/operators/refCount.html) + + - returns: An observable sequence that stays connected to the source as long as there is at least one subscription to the observable sequence. + */ + public func refCount() -> Observable { + return RefCount(source: self) + } +} + +extension ObservableType { + + /** + Returns an observable sequence that shares a single subscription to the underlying sequence. + + This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. + + - seealso: [share operator on reactivex.io](http://reactivex.io/documentation/operators/refcount.html) + + - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. + */ + public func share() -> Observable { + return self.publish().refCount() + } +} + +final fileprivate class RefCountSink + : Sink + , ObserverType where CO.E == O.E { + typealias Element = O.E + typealias Parent = RefCount + + private let _parent: Parent + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription = _parent._source.subscribe(self) + + _parent._lock.lock(); defer { _parent._lock.unlock() } // { + if _parent._count == 0 { + _parent._count = 1 + _parent._connectableSubscription = _parent._source.connect() + } + else { + _parent._count = _parent._count + 1 + } + // } + + return Disposables.create { + subscription.dispose() + self._parent._lock.lock(); defer { self._parent._lock.unlock() } // { + if self._parent._count == 1 { + self._parent._count = 0 + guard let connectableSubscription = self._parent._connectableSubscription else { + return + } + + connectableSubscription.dispose() + self._parent._connectableSubscription = nil + } + else if self._parent._count > 1 { + self._parent._count = self._parent._count - 1 + } + else { + rxFatalError("Something went wrong with RefCount disposing mechanism") + } + // } + } + } + + func on(_ event: Event) { + switch event { + case .next: + forwardOn(event) + case .error, .completed: + forwardOn(event) + dispose() + } + } +} + +final fileprivate class RefCount: Producer { + fileprivate let _lock = RecursiveLock() + + // state + fileprivate var _count = 0 + fileprivate var _connectableSubscription = nil as Disposable? + + fileprivate let _source: CO + + init(source: CO) { + _source = source + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == CO.E { + let sink = RefCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final fileprivate class MulticastSink: Sink, ObserverType { + typealias Element = O.E + typealias ResultType = Element + typealias MutlicastType = Multicast + + private let _parent: MutlicastType + + init(parent: MutlicastType, observer: O, cancel: Cancelable) { + _parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + do { + let subject = try _parent._subjectSelector() + let connectable = ConnectableObservableAdapter(source: _parent._source, subject: subject) + + let observable = try _parent._selector(connectable) + + let subscription = observable.subscribe(self) + let connection = connectable.connect() + + return Disposables.create(subscription, connection) + } + catch let e { + forwardOn(.error(e)) + dispose() + return Disposables.create() + } + } + + func on(_ event: Event) { + forwardOn(event) + switch event { + case .next: break + case .error, .completed: + dispose() + } + } +} + +final fileprivate class Multicast: Producer { + typealias SubjectSelectorType = () throws -> S + typealias SelectorType = (Observable) throws -> Observable + + fileprivate let _source: Observable + fileprivate let _subjectSelector: SubjectSelectorType + fileprivate let _selector: SelectorType + + init(source: Observable, subjectSelector: @escaping SubjectSelectorType, selector: @escaping SelectorType) { + _source = source + _subjectSelector = subjectSelector + _selector = selector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = MulticastSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Never.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Never.swift new file mode 100644 index 0000000000..4cb9b87ba5 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Never.swift @@ -0,0 +1,27 @@ +// +// Never.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension Observable { + + /** + Returns a non-terminating observable sequence, which can be used to denote an infinite duration. + + - seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) + + - returns: An observable sequence whose observers will never get called. + */ + public static func never() -> Observable { + return NeverProducer() + } +} + +final fileprivate class NeverProducer : Producer { + override func subscribe(_ observer: O) -> Disposable where O.E == Element { + return Disposables.create() + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift new file mode 100644 index 0000000000..fd8ce3375b --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift @@ -0,0 +1,229 @@ +// +// ObserveOn.swift +// RxSwift +// +// Created by Krunoslav Zaher on 7/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Wraps the source sequence in order to run its observer callbacks on the specified scheduler. + + This only invokes observer callbacks on a `scheduler`. In case the subscription and/or unsubscription + actions have side-effects that require to be run on a scheduler, use `subscribeOn`. + + - seealso: [observeOn operator on reactivex.io](http://reactivex.io/documentation/operators/observeon.html) + + - parameter scheduler: Scheduler to notify observers on. + - returns: The source sequence whose observations happen on the specified scheduler. + */ + public func observeOn(_ scheduler: ImmediateSchedulerType) + -> Observable { + if let scheduler = scheduler as? SerialDispatchQueueScheduler { + return ObserveOnSerialDispatchQueue(source: self.asObservable(), scheduler: scheduler) + } + else { + return ObserveOn(source: self.asObservable(), scheduler: scheduler) + } + } +} + +final fileprivate class ObserveOn : Producer { + let scheduler: ImmediateSchedulerType + let source: Observable + + init(source: Observable, scheduler: ImmediateSchedulerType) { + self.scheduler = scheduler + self.source = source + +#if TRACE_RESOURCES + let _ = Resources.incrementTotal() +#endif + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { + let sink = ObserveOnSink(scheduler: scheduler, observer: observer, cancel: cancel) + let subscription = source.subscribe(sink) + return (sink: sink, subscription: subscription) + } + +#if TRACE_RESOURCES + deinit { + let _ = Resources.decrementTotal() + } +#endif +} + +enum ObserveOnState : Int32 { + // pump is not running + case stopped = 0 + // pump is running + case running = 1 +} + +final fileprivate class ObserveOnSink : ObserverBase { + typealias E = O.E + + let _scheduler: ImmediateSchedulerType + + var _lock = SpinLock() + let _observer: O + + // state + var _state = ObserveOnState.stopped + var _queue = Queue>(capacity: 10) + + let _scheduleDisposable = SerialDisposable() + let _cancel: Cancelable + + init(scheduler: ImmediateSchedulerType, observer: O, cancel: Cancelable) { + _scheduler = scheduler + _observer = observer + _cancel = cancel + } + + override func onCore(_ event: Event) { + let shouldStart = _lock.calculateLocked { () -> Bool in + self._queue.enqueue(event) + + switch self._state { + case .stopped: + self._state = .running + return true + case .running: + return false + } + } + + if shouldStart { + _scheduleDisposable.disposable = self._scheduler.scheduleRecursive((), action: self.run) + } + } + + func run(_ state: Void, recurse: (Void) -> Void) { + let (nextEvent, observer) = self._lock.calculateLocked { () -> (Event?, O) in + if self._queue.count > 0 { + return (self._queue.dequeue(), self._observer) + } + else { + self._state = .stopped + return (nil, self._observer) + } + } + + if let nextEvent = nextEvent, !_cancel.isDisposed { + observer.on(nextEvent) + if nextEvent.isStopEvent { + dispose() + } + } + else { + return + } + + let shouldContinue = _shouldContinue_synchronized() + + if shouldContinue { + recurse() + } + } + + func _shouldContinue_synchronized() -> Bool { + _lock.lock(); defer { _lock.unlock() } // { + if self._queue.count > 0 { + return true + } + else { + self._state = .stopped + return false + } + // } + } + + override func dispose() { + super.dispose() + + _cancel.dispose() + _scheduleDisposable.dispose() + } +} + +#if TRACE_RESOURCES + fileprivate var _numberOfSerialDispatchQueueObservables: AtomicInt = 0 + extension Resources { + /** + Counts number of `SerialDispatchQueueObservables`. + + Purposed for unit tests. + */ + public static var numberOfSerialDispatchQueueObservables: Int32 { + return _numberOfSerialDispatchQueueObservables.valueSnapshot() + } + } +#endif + +final fileprivate class ObserveOnSerialDispatchQueueSink : ObserverBase { + let scheduler: SerialDispatchQueueScheduler + let observer: O + + let cancel: Cancelable + + var cachedScheduleLambda: ((ObserveOnSerialDispatchQueueSink, Event) -> Disposable)! + + init(scheduler: SerialDispatchQueueScheduler, observer: O, cancel: Cancelable) { + self.scheduler = scheduler + self.observer = observer + self.cancel = cancel + super.init() + + cachedScheduleLambda = { sink, event in + sink.observer.on(event) + + if event.isStopEvent { + sink.dispose() + } + + return Disposables.create() + } + } + + override func onCore(_ event: Event) { + let _ = self.scheduler.schedule((self, event), action: cachedScheduleLambda) + } + + override func dispose() { + super.dispose() + + cancel.dispose() + } +} + +final fileprivate class ObserveOnSerialDispatchQueue : Producer { + let scheduler: SerialDispatchQueueScheduler + let source: Observable + + init(source: Observable, scheduler: SerialDispatchQueueScheduler) { + self.scheduler = scheduler + self.source = source + + #if TRACE_RESOURCES + let _ = Resources.incrementTotal() + let _ = AtomicIncrement(&_numberOfSerialDispatchQueueObservables) + #endif + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { + let sink = ObserveOnSerialDispatchQueueSink(scheduler: scheduler, observer: observer, cancel: cancel) + let subscription = source.subscribe(sink) + return (sink: sink, subscription: subscription) + } + + #if TRACE_RESOURCES + deinit { + let _ = Resources.decrementTotal() + let _ = AtomicDecrement(&_numberOfSerialDispatchQueueObservables) + } + #endif +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Optional.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Optional.swift new file mode 100644 index 0000000000..fa74c04be5 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Optional.swift @@ -0,0 +1,95 @@ +// +// Optional.swift +// RxSwift +// +// Created by tarunon on 2016/12/13. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +extension Observable { + /** + Converts a optional to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter optional: Optional element in the resulting observable sequence. + - returns: An observable sequence containing the wrapped value or not from given optional. + */ + public static func from(optional: E?) -> Observable { + return ObservableOptional(optional: optional) + } + + /** + Converts a optional to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter optional: Optional element in the resulting observable sequence. + - parameter: Scheduler to send the optional element on. + - returns: An observable sequence containing the wrapped value or not from given optional. + */ + public static func from(optional: E?, scheduler: ImmediateSchedulerType) -> Observable { + return ObservableOptionalScheduled(optional: optional, scheduler: scheduler) + } +} + +final fileprivate class ObservableOptionalScheduledSink : Sink { + typealias E = O.E + typealias Parent = ObservableOptionalScheduled + + private let _parent: Parent + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return _parent._scheduler.schedule(_parent._optional) { (optional: E?) -> Disposable in + if let next = optional { + self.forwardOn(.next(next)) + return self._parent._scheduler.schedule(()) { _ in + self.forwardOn(.completed) + self.dispose() + return Disposables.create() + } + } else { + self.forwardOn(.completed) + self.dispose() + return Disposables.create() + } + } + } +} + +final fileprivate class ObservableOptionalScheduled : Producer { + fileprivate let _optional: E? + fileprivate let _scheduler: ImmediateSchedulerType + + init(optional: E?, scheduler: ImmediateSchedulerType) { + _optional = optional + _scheduler = scheduler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { + let sink = ObservableOptionalScheduledSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final fileprivate class ObservableOptional: Producer { + private let _optional: E? + + init(optional: E?) { + _optional = optional + } + + override func subscribe(_ observer: O) -> Disposable where O.E == E { + if let element = _optional { + observer.on(.next(element)) + } + observer.on(.completed) + return Disposables.create() + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Producer.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Producer.swift new file mode 100644 index 0000000000..996b0110dc --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Producer.swift @@ -0,0 +1,98 @@ +// +// Producer.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/20/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +class Producer : Observable { + override init() { + super.init() + } + + override func subscribe(_ observer: O) -> Disposable where O.E == Element { + if !CurrentThreadScheduler.isScheduleRequired { + // The returned disposable needs to release all references once it was disposed. + let disposer = SinkDisposer() + let sinkAndSubscription = run(observer, cancel: disposer) + disposer.setSinkAndSubscription(sink: sinkAndSubscription.sink, subscription: sinkAndSubscription.subscription) + + return disposer + } + else { + return CurrentThreadScheduler.instance.schedule(()) { _ in + let disposer = SinkDisposer() + let sinkAndSubscription = self.run(observer, cancel: disposer) + disposer.setSinkAndSubscription(sink: sinkAndSubscription.sink, subscription: sinkAndSubscription.subscription) + + return disposer + } + } + } + + func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + rxAbstractMethod() + } +} + +fileprivate final class SinkDisposer: Cancelable { + fileprivate enum DisposeState: UInt32 { + case disposed = 1 + case sinkAndSubscriptionSet = 2 + } + + // Jeej, swift API consistency rules + fileprivate enum DisposeStateInt32: Int32 { + case disposed = 1 + case sinkAndSubscriptionSet = 2 + } + + private var _state: AtomicInt = 0 + private var _sink: Disposable? = nil + private var _subscription: Disposable? = nil + + var isDisposed: Bool { + return AtomicFlagSet(DisposeState.disposed.rawValue, &_state) + } + + func setSinkAndSubscription(sink: Disposable, subscription: Disposable) { + _sink = sink + _subscription = subscription + + let previousState = AtomicOr(DisposeState.sinkAndSubscriptionSet.rawValue, &_state) + if (previousState & DisposeStateInt32.sinkAndSubscriptionSet.rawValue) != 0 { + rxFatalError("Sink and subscription were already set") + } + + if (previousState & DisposeStateInt32.disposed.rawValue) != 0 { + sink.dispose() + subscription.dispose() + _sink = nil + _subscription = nil + } + } + + func dispose() { + let previousState = AtomicOr(DisposeState.disposed.rawValue, &_state) + + if (previousState & DisposeStateInt32.disposed.rawValue) != 0 { + return + } + + if (previousState & DisposeStateInt32.sinkAndSubscriptionSet.rawValue) != 0 { + guard let sink = _sink else { + rxFatalError("Sink not set") + } + guard let subscription = _subscription else { + rxFatalError("Subscription not set") + } + + sink.dispose() + subscription.dispose() + + _sink = nil + _subscription = nil + } + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Range.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Range.swift new file mode 100644 index 0000000000..2ebaca2e91 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Range.swift @@ -0,0 +1,73 @@ +// +// Range.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension Observable where Element : SignedInteger { + /** + Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to generate and send out observer messages. + + - seealso: [range operator on reactivex.io](http://reactivex.io/documentation/operators/range.html) + + - parameter start: The value of the first integer in the sequence. + - parameter count: The number of sequential integers to generate. + - parameter scheduler: Scheduler to run the generator loop on. + - returns: An observable sequence that contains a range of sequential integral numbers. + */ + public static func range(start: E, count: E, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + return RangeProducer(start: start, count: count, scheduler: scheduler) + } +} + +final fileprivate class RangeProducer : Producer { + fileprivate let _start: E + fileprivate let _count: E + fileprivate let _scheduler: ImmediateSchedulerType + + init(start: E, count: E, scheduler: ImmediateSchedulerType) { + if count < 0 { + rxFatalError("count can't be negative") + } + + if start &+ (count - 1) < start { + rxFatalError("overflow of count") + } + + _start = start + _count = count + _scheduler = scheduler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { + let sink = RangeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final fileprivate class RangeSink : Sink where O.E: SignedInteger { + typealias Parent = RangeProducer + + private let _parent: Parent + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return _parent._scheduler.scheduleRecursive(0 as O.E) { i, recurse in + if i < self._parent._count { + self.forwardOn(.next(self._parent._start + i)) + recurse(i + 1) + } + else { + self.forwardOn(.completed) + self.dispose() + } + } + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Reduce.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Reduce.swift new file mode 100644 index 0000000000..3e4a7b9de9 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Reduce.swift @@ -0,0 +1,109 @@ +// +// Reduce.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + + +extension ObservableType { + /** + Applies an `accumulator` function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified `seed` value is used as the initial accumulator value. + + For aggregation behavior with incremental intermediate results, see `scan`. + + - seealso: [reduce operator on reactivex.io](http://reactivex.io/documentation/operators/reduce.html) + + - parameter seed: The initial accumulator value. + - parameter accumulator: A accumulator function to be invoked on each element. + - parameter mapResult: A function to transform the final accumulator value into the result value. + - returns: An observable sequence containing a single element with the final accumulator value. + */ + public func reduce(_ seed: A, accumulator: @escaping (A, E) throws -> A, mapResult: @escaping (A) throws -> R) + -> Observable { + return Reduce(source: self.asObservable(), seed: seed, accumulator: accumulator, mapResult: mapResult) + } + + /** + Applies an `accumulator` function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified `seed` value is used as the initial accumulator value. + + For aggregation behavior with incremental intermediate results, see `scan`. + + - seealso: [reduce operator on reactivex.io](http://reactivex.io/documentation/operators/reduce.html) + + - parameter seed: The initial accumulator value. + - parameter accumulator: A accumulator function to be invoked on each element. + - returns: An observable sequence containing a single element with the final accumulator value. + */ + public func reduce(_ seed: A, accumulator: @escaping (A, E) throws -> A) + -> Observable { + return Reduce(source: self.asObservable(), seed: seed, accumulator: accumulator, mapResult: { $0 }) + } +} + +final fileprivate class ReduceSink : Sink, ObserverType { + typealias ResultType = O.E + typealias Parent = Reduce + + private let _parent: Parent + private var _accumulation: AccumulateType + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + _accumulation = parent._seed + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + do { + _accumulation = try _parent._accumulator(_accumulation, value) + } + catch let e { + forwardOn(.error(e)) + dispose() + } + case .error(let e): + forwardOn(.error(e)) + dispose() + case .completed: + do { + let result = try _parent._mapResult(_accumulation) + forwardOn(.next(result)) + forwardOn(.completed) + dispose() + } + catch let e { + forwardOn(.error(e)) + dispose() + } + } + } +} + +final fileprivate class Reduce : Producer { + typealias AccumulatorType = (AccumulateType, SourceType) throws -> AccumulateType + typealias ResultSelectorType = (AccumulateType) throws -> ResultType + + fileprivate let _source: Observable + fileprivate let _seed: AccumulateType + fileprivate let _accumulator: AccumulatorType + fileprivate let _mapResult: ResultSelectorType + + init(source: Observable, seed: AccumulateType, accumulator: @escaping AccumulatorType, mapResult: @escaping ResultSelectorType) { + _source = source + _seed = seed + _accumulator = accumulator + _mapResult = mapResult + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == ResultType { + let sink = ReduceSink(parent: self, observer: observer, cancel: cancel) + let subscription = _source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} + diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Repeat.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Repeat.swift new file mode 100644 index 0000000000..3ed7165bad --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Repeat.swift @@ -0,0 +1,57 @@ +// +// Repeat.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension Observable { + /** + Generates an observable sequence that repeats the given element infinitely, using the specified scheduler to send out observer messages. + + - seealso: [repeat operator on reactivex.io](http://reactivex.io/documentation/operators/repeat.html) + + - parameter element: Element to repeat. + - parameter scheduler: Scheduler to run the producer loop on. + - returns: An observable sequence that repeats the given element infinitely. + */ + public static func repeatElement(_ element: E, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + return RepeatElement(element: element, scheduler: scheduler) + } +} + +final fileprivate class RepeatElement : Producer { + fileprivate let _element: Element + fileprivate let _scheduler: ImmediateSchedulerType + + init(element: Element, scheduler: ImmediateSchedulerType) { + _element = element + _scheduler = scheduler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = RepeatElementSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + + return (sink: sink, subscription: subscription) + } +} + +final fileprivate class RepeatElementSink : Sink { + typealias Parent = RepeatElement + + private let _parent: Parent + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return _parent._scheduler.scheduleRecursive(_parent._element) { e, recurse in + self.forwardOn(.next(e)) + recurse(e) + } + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift new file mode 100644 index 0000000000..268b399a8c --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift @@ -0,0 +1,182 @@ +// +// RetryWhen.swift +// RxSwift +// +// Created by Junior B. on 06/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Repeats the source observable sequence on error when the notifier emits a next value. + If the source observable errors and the notifier completes, it will complete the source sequence. + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete. + */ + public func retryWhen(_ notificationHandler: @escaping (Observable) -> TriggerObservable) + -> Observable { + return RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler) + } + + /** + Repeats the source observable sequence on error when the notifier emits a next value. + If the source observable errors and the notifier completes, it will complete the source sequence. + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete. + */ + public func retryWhen(_ notificationHandler: @escaping (Observable) -> TriggerObservable) + -> Observable { + return RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler) + } +} + +final fileprivate class RetryTriggerSink + : ObserverType where S.Iterator.Element : ObservableType, S.Iterator.Element.E == O.E { + typealias E = TriggerObservable.E + + typealias Parent = RetryWhenSequenceSinkIter + + fileprivate let _parent: Parent + + init(parent: Parent) { + _parent = parent + } + + func on(_ event: Event) { + switch event { + case .next: + _parent._parent._lastError = nil + _parent._parent.schedule(.moveNext) + case .error(let e): + _parent._parent.forwardOn(.error(e)) + _parent._parent.dispose() + case .completed: + _parent._parent.forwardOn(.completed) + _parent._parent.dispose() + } + } +} + +final fileprivate class RetryWhenSequenceSinkIter + : ObserverType + , Disposable where S.Iterator.Element : ObservableType, S.Iterator.Element.E == O.E { + typealias E = O.E + typealias Parent = RetryWhenSequenceSink + + fileprivate let _parent: Parent + fileprivate let _errorHandlerSubscription = SingleAssignmentDisposable() + fileprivate let _subscription: Disposable + + init(parent: Parent, subscription: Disposable) { + _parent = parent + _subscription = subscription + } + + func on(_ event: Event) { + switch event { + case .next: + _parent.forwardOn(event) + case .error(let error): + _parent._lastError = error + + if let failedWith = error as? Error { + // dispose current subscription + _subscription.dispose() + + let errorHandlerSubscription = _parent._notifier.subscribe(RetryTriggerSink(parent: self)) + _errorHandlerSubscription.setDisposable(errorHandlerSubscription) + _parent._errorSubject.on(.next(failedWith)) + } + else { + _parent.forwardOn(.error(error)) + _parent.dispose() + } + case .completed: + _parent.forwardOn(event) + _parent.dispose() + } + } + + final func dispose() { + _subscription.dispose() + _errorHandlerSubscription.dispose() + } +} + +final fileprivate class RetryWhenSequenceSink + : TailRecursiveSink where S.Iterator.Element : ObservableType, S.Iterator.Element.E == O.E { + typealias Element = O.E + typealias Parent = RetryWhenSequence + + let _lock = RecursiveLock() + + fileprivate let _parent: Parent + + fileprivate var _lastError: Swift.Error? + fileprivate let _errorSubject = PublishSubject() + fileprivate let _handler: Observable + fileprivate let _notifier = PublishSubject() + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + _handler = parent._notificationHandler(_errorSubject).asObservable() + super.init(observer: observer, cancel: cancel) + } + + override func done() { + if let lastError = _lastError { + forwardOn(.error(lastError)) + _lastError = nil + } + else { + forwardOn(.completed) + } + + dispose() + } + + override func extract(_ observable: Observable) -> SequenceGenerator? { + // It is important to always return `nil` here because there are sideffects in the `run` method + // that are dependant on particular `retryWhen` operator so single operator stack can't be reused in this + // case. + return nil + } + + override func subscribeToNext(_ source: Observable) -> Disposable { + let subscription = SingleAssignmentDisposable() + let iter = RetryWhenSequenceSinkIter(parent: self, subscription: subscription) + subscription.setDisposable(source.subscribe(iter)) + return iter + } + + override func run(_ sources: SequenceGenerator) -> Disposable { + let triggerSubscription = _handler.subscribe(_notifier.asObserver()) + let superSubscription = super.run(sources) + return Disposables.create(superSubscription, triggerSubscription) + } +} + +final fileprivate class RetryWhenSequence : Producer where S.Iterator.Element : ObservableType { + typealias Element = S.Iterator.Element.E + + fileprivate let _sources: S + fileprivate let _notificationHandler: (Observable) -> TriggerObservable + + init(sources: S, notificationHandler: @escaping (Observable) -> TriggerObservable) { + _sources = sources + _notificationHandler = notificationHandler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = RetryWhenSequenceSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run((self._sources.makeIterator(), nil)) + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Sample.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Sample.swift new file mode 100644 index 0000000000..31f8b625d6 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Sample.swift @@ -0,0 +1,142 @@ +// +// Sample.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Samples the source observable sequence using a sampler observable sequence producing sampling ticks. + + Upon each sampling tick, the latest element (if any) in the source sequence during the last sampling interval is sent to the resulting sequence. + + **In case there were no new elements between sampler ticks, no element is sent to the resulting sequence.** + + - seealso: [sample operator on reactivex.io](http://reactivex.io/documentation/operators/sample.html) + + - parameter sampler: Sampling tick sequence. + - returns: Sampled observable sequence. + */ + public func sample(_ sampler: O) + -> Observable { + return Sample(source: self.asObservable(), sampler: sampler.asObservable()) + } +} + +final fileprivate class SamplerSink + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias E = SampleType + + typealias Parent = SampleSequenceSink + + fileprivate let _parent: Parent + + var _lock: RecursiveLock { + return _parent._lock + } + + init(parent: Parent) { + _parent = parent + } + + func on(_ event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + switch event { + case .next: + if let element = _parent._element { + _parent._element = nil + _parent.forwardOn(.next(element)) + } + + if _parent._atEnd { + _parent.forwardOn(.completed) + _parent.dispose() + } + case .error(let e): + _parent.forwardOn(.error(e)) + _parent.dispose() + case .completed: + if let element = _parent._element { + _parent._element = nil + _parent.forwardOn(.next(element)) + } + if _parent._atEnd { + _parent.forwardOn(.completed) + _parent.dispose() + } + } + } +} + +final fileprivate class SampleSequenceSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = O.E + typealias Parent = Sample + + fileprivate let _parent: Parent + + let _lock = RecursiveLock() + + // state + fileprivate var _element = nil as Element? + fileprivate var _atEnd = false + + fileprivate let _sourceSubscription = SingleAssignmentDisposable() + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + _sourceSubscription.setDisposable(_parent._source.subscribe(self)) + let samplerSubscription = _parent._sampler.subscribe(SamplerSink(parent: self)) + + return Disposables.create(_sourceSubscription, samplerSubscription) + } + + func on(_ event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + switch event { + case .next(let element): + _element = element + case .error: + forwardOn(event) + dispose() + case .completed: + _atEnd = true + _sourceSubscription.dispose() + } + } + +} + +final fileprivate class Sample : Producer { + fileprivate let _source: Observable + fileprivate let _sampler: Observable + + init(source: Observable, sampler: Observable) { + _source = source + _sampler = sampler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = SampleSequenceSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Scan.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Scan.swift new file mode 100644 index 0000000000..e94db11b85 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Scan.swift @@ -0,0 +1,82 @@ +// +// Scan.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value. + + For aggregation behavior with no intermediate results, see `reduce`. + + - seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html) + + - parameter seed: The initial accumulator value. + - parameter accumulator: An accumulator function to be invoked on each element. + - returns: An observable sequence containing the accumulated values. + */ + public func scan(_ seed: A, accumulator: @escaping (A, E) throws -> A) + -> Observable { + return Scan(source: self.asObservable(), seed: seed, accumulator: accumulator) + } +} + +final fileprivate class ScanSink : Sink, ObserverType { + typealias Accumulate = O.E + typealias Parent = Scan + typealias E = ElementType + + fileprivate let _parent: Parent + fileprivate var _accumulate: Accumulate + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + _accumulate = parent._seed + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let element): + do { + _accumulate = try _parent._accumulator(_accumulate, element) + forwardOn(.next(_accumulate)) + } + catch let error { + forwardOn(.error(error)) + dispose() + } + case .error(let error): + forwardOn(.error(error)) + dispose() + case .completed: + forwardOn(.completed) + dispose() + } + } + +} + +final fileprivate class Scan: Producer { + typealias Accumulator = (Accumulate, Element) throws -> Accumulate + + fileprivate let _source: Observable + fileprivate let _seed: Accumulate + fileprivate let _accumulator: Accumulator + + init(source: Observable, seed: Accumulate, accumulator: @escaping Accumulator) { + _source = source + _seed = seed + _accumulator = accumulator + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Accumulate { + let sink = ScanSink(parent: self, observer: observer, cancel: cancel) + let subscription = _source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Sequence.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Sequence.swift new file mode 100644 index 0000000000..1e9afe1c40 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Sequence.swift @@ -0,0 +1,89 @@ +// +// Sequence.swift +// RxSwift +// +// Created by Krunoslav Zaher on 11/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension Observable { + // MARK: of + + /** + This method creates a new Observable instance with a variable number of elements. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter elements: Elements to generate. + - parameter scheduler: Scheduler to send elements on. If `nil`, elements are sent immediatelly on subscription. + - returns: The observable sequence whose elements are pulled from the given arguments. + */ + public static func of(_ elements: E ..., scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + return ObservableSequence(elements: elements, scheduler: scheduler) + } +} + +extension Observable { + /** + Converts an array to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - returns: The observable sequence whose elements are pulled from the given enumerable sequence. + */ + public static func from(_ array: [E], scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + return ObservableSequence(elements: array, scheduler: scheduler) + } + + /** + Converts a sequence to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - returns: The observable sequence whose elements are pulled from the given enumerable sequence. + */ + public static func from(_ sequence: S, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable where S.Iterator.Element == E { + return ObservableSequence(elements: sequence, scheduler: scheduler) + } +} + +final fileprivate class ObservableSequenceSink : Sink where S.Iterator.Element == O.E { + typealias Parent = ObservableSequence + + private let _parent: Parent + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return _parent._scheduler.scheduleRecursive((_parent._elements.makeIterator(), _parent._elements)) { (iterator, recurse) in + var mutableIterator = iterator + if let next = mutableIterator.0.next() { + self.forwardOn(.next(next)) + recurse(mutableIterator) + } + else { + self.forwardOn(.completed) + self.dispose() + } + } + } +} + +final fileprivate class ObservableSequence : Producer { + fileprivate let _elements: S + fileprivate let _scheduler: ImmediateSchedulerType + + init(elements: S, scheduler: ImmediateSchedulerType) { + _elements = elements + _scheduler = scheduler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { + let sink = ObservableSequenceSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/ShareReplay1.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/ShareReplay1.swift new file mode 100644 index 0000000000..5381034200 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/ShareReplay1.swift @@ -0,0 +1,127 @@ +// +// ShareReplay1.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Returns an observable sequence that shares a single subscription to the underlying sequence, and immediately upon subscription replays maximum number of elements in buffer. + + This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. + + - seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) + + - parameter bufferSize: Maximum element count of the replay buffer. + - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. + */ + public func shareReplay(_ bufferSize: Int) + -> Observable { + if bufferSize == 1 { + return ShareReplay1(source: self.asObservable()) + } + else { + return self.replay(bufferSize).refCount() + } + } +} + +// optimized version of share replay for most common case +final fileprivate class ShareReplay1 + : Observable + , ObserverType + , SynchronizedUnsubscribeType { + + typealias Observers = AnyObserver.s + typealias DisposeKey = Observers.KeyType + + private let _source: Observable + + private let _lock = RecursiveLock() + + private var _connection: SingleAssignmentDisposable? + private var _element: Element? + private var _stopped = false + private var _stopEvent = nil as Event? + private var _observers = Observers() + + init(source: Observable) { + self._source = source + } + + override func subscribe(_ observer: O) -> Disposable where O.E == E { + _lock.lock() + let result = _synchronized_subscribe(observer) + _lock.unlock() + return result + } + + func _synchronized_subscribe(_ observer: O) -> Disposable where O.E == E { + if let element = self._element { + observer.on(.next(element)) + } + + if let stopEvent = self._stopEvent { + observer.on(stopEvent) + return Disposables.create() + } + + let initialCount = self._observers.count + + let disposeKey = self._observers.insert(observer.on) + + if initialCount == 0 { + let connection = SingleAssignmentDisposable() + _connection = connection + + connection.setDisposable(self._source.subscribe(self)) + } + + return SubscriptionDisposable(owner: self, key: disposeKey) + } + + func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { + _lock.lock() + _synchronized_unsubscribe(disposeKey) + _lock.unlock() + } + + func _synchronized_unsubscribe(_ disposeKey: DisposeKey) { + // if already unsubscribed, just return + if self._observers.removeKey(disposeKey) == nil { + return + } + + if _observers.count == 0 { + _connection?.dispose() + _connection = nil + } + } + + func on(_ event: Event) { + dispatch(_synchronized_on(event), event) + } + + func _synchronized_on(_ event: Event) -> Observers { + _lock.lock(); defer { _lock.unlock() } + if _stopped { + return Observers() + } + + switch event { + case .next(let element): + _element = element + case .error, .completed: + _stopEvent = event + _stopped = true + _connection?.dispose() + _connection = nil + } + + return _observers + } + +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/ShareReplay1WhileConnected.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/ShareReplay1WhileConnected.swift new file mode 100644 index 0000000000..fc490ec10e --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/ShareReplay1WhileConnected.swift @@ -0,0 +1,175 @@ +// +// ShareReplay1WhileConnected.swift +// RxSwift +// +// Created by Krunoslav Zaher on 12/6/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Returns an observable sequence that shares a single subscription to the underlying sequence, and immediately upon subscription replays latest element in buffer. + + This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. + + Unlike `shareReplay(bufferSize: Int)`, this operator will clear latest element from replay buffer in case number of subscribers drops from one to zero. In case sequence + completes or errors out replay buffer is also cleared. + + - seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) + + - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. + */ + public func shareReplayLatestWhileConnected() + -> Observable { + return ShareReplay1WhileConnected(source: self.asObservable()) + } +} + +fileprivate final class ShareReplay1WhileConnectedConnection + : ObserverType + , SynchronizedUnsubscribeType { + typealias E = Element + typealias Observers = AnyObserver.s + typealias DisposeKey = Observers.KeyType + + typealias Parent = ShareReplay1WhileConnected + private let _parent: Parent + private let _subscription = SingleAssignmentDisposable() + + private let _lock: RecursiveLock + private var _disposed: Bool = false + fileprivate var _observers = Observers() + fileprivate var _element: Element? + + init(parent: Parent, lock: RecursiveLock) { + _parent = parent + _lock = lock + + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + #endif + } + + final func on(_ event: Event) { + _lock.lock() + let observers = _synchronized_on(event) + _lock.unlock() + dispatch(observers, event) + } + + final private func _synchronized_on(_ event: Event) -> Observers { + if _disposed { + return Observers() + } + + switch event { + case .next(let element): + _element = element + return _observers + case .error, .completed: + let observers = _observers + self._synchronized_dispose() + return observers + } + } + + final func connect() { + _subscription.setDisposable(_parent._source.subscribe(self)) + } + + final func _synchronized_subscribe(_ observer: O) -> Disposable where O.E == Element { + _lock.lock(); defer { _lock.unlock() } + if let element = _element { + observer.on(.next(element)) + } + + let disposeKey = _observers.insert(observer.on) + + return SubscriptionDisposable(owner: self, key: disposeKey) + } + + final private func _synchronized_dispose() { + _disposed = true + if _parent._connection === self { + _parent._connection = nil + } + _observers = Observers() + _subscription.dispose() + } + + final func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { + _lock.lock() + _synchronized_unsubscribe(disposeKey) + _lock.unlock() + } + + @inline(__always) + final private func _synchronized_unsubscribe(_ disposeKey: DisposeKey) { + // if already unsubscribed, just return + if self._observers.removeKey(disposeKey) == nil { + return + } + + if _observers.count == 0 { + _synchronized_dispose() + } + } + + #if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } + #endif +} + +// optimized version of share replay for most common case +final fileprivate class ShareReplay1WhileConnected + : Observable { + + fileprivate typealias Connection = ShareReplay1WhileConnectedConnection + + fileprivate let _source: Observable + + fileprivate let _lock = RecursiveLock() + + fileprivate var _connection: Connection? + + init(source: Observable) { + self._source = source + } + + override func subscribe(_ observer: O) -> Disposable where O.E == E { + _lock.lock() + + let connection = _synchronized_subscribe(observer) + let count = connection._observers.count + + let disposable = connection._synchronized_subscribe(observer) + + if count == 0 { + connection.connect() + } + + _lock.unlock() + + return disposable + } + + @inline(__always) + private func _synchronized_subscribe(_ observer: O) -> Connection where O.E == E { + let connection: Connection + + if let existingConnection = _connection { + connection = existingConnection + } + else { + connection = ShareReplay1WhileConnectedConnection( + parent: self, + lock: _lock) + _connection = connection + } + + return connection + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift new file mode 100644 index 0000000000..1419a93fc8 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift @@ -0,0 +1,105 @@ +// +// SingleAsync.swift +// RxSwift +// +// Created by Junior B. on 09/11/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + The single operator is similar to first, but throws a `RxError.noElements` or `RxError.moreThanOneElement` + if the source Observable does not emit exactly one element before successfully completing. + + - seealso: [single operator on reactivex.io](http://reactivex.io/documentation/operators/first.html) + + - returns: An observable sequence that emits a single element or throws an exception if more (or none) of them are emitted. + */ + public func single() + -> Observable { + return SingleAsync(source: asObservable()) + } + + /** + The single operator is similar to first, but throws a `RxError.NoElements` or `RxError.MoreThanOneElement` + if the source Observable does not emit exactly one element before successfully completing. + + - seealso: [single operator on reactivex.io](http://reactivex.io/documentation/operators/first.html) + + - parameter predicate: A function to test each source element for a condition. + - returns: An observable sequence that emits a single element or throws an exception if more (or none) of them are emitted. + */ + public func single(_ predicate: @escaping (E) throws -> Bool) + -> Observable { + return SingleAsync(source: asObservable(), predicate: predicate) + } +} + +fileprivate final class SingleAsyncSink : Sink, ObserverType { + typealias ElementType = O.E + typealias Parent = SingleAsync + typealias E = ElementType + + private let _parent: Parent + private var _seenValue: Bool = false + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + do { + let forward = try _parent._predicate?(value) ?? true + if !forward { + return + } + } + catch let error { + forwardOn(.error(error as Swift.Error)) + dispose() + return + } + + if _seenValue { + forwardOn(.error(RxError.moreThanOneElement)) + dispose() + return + } + + _seenValue = true + forwardOn(.next(value)) + case .error: + forwardOn(event) + dispose() + case .completed: + if (_seenValue) { + forwardOn(.completed) + } else { + forwardOn(.error(RxError.noElements)) + } + dispose() + } + } +} + +final class SingleAsync: Producer { + typealias Predicate = (Element) throws -> Bool + + fileprivate let _source: Observable + fileprivate let _predicate: Predicate? + + init(source: Observable, predicate: Predicate? = nil) { + _source = source + _predicate = predicate + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = SingleAsyncSink(parent: self, observer: observer, cancel: cancel) + let subscription = _source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Sink.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Sink.swift new file mode 100644 index 0000000000..bd65cc932a --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Sink.swift @@ -0,0 +1,81 @@ +// +// Sink.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +class Sink : Disposable { + fileprivate let _observer: O + fileprivate let _cancel: Cancelable + fileprivate var _disposed: Bool + + #if DEBUG + fileprivate var _numberOfConcurrentCalls: AtomicInt = 0 + #endif + + init(observer: O, cancel: Cancelable) { +#if TRACE_RESOURCES + let _ = Resources.incrementTotal() +#endif + _observer = observer + _cancel = cancel + _disposed = false + } + + final func forwardOn(_ event: Event) { + #if DEBUG + if AtomicIncrement(&_numberOfConcurrentCalls) > 1 { + rxFatalError("Warning: Recursive call or synchronization error!") + } + + defer { + _ = AtomicDecrement(&_numberOfConcurrentCalls) + } + #endif + if _disposed { + return + } + _observer.on(event) + } + + final func forwarder() -> SinkForward { + return SinkForward(forward: self) + } + + final var disposed: Bool { + return _disposed + } + + func dispose() { + _disposed = true + _cancel.dispose() + } + + deinit { +#if TRACE_RESOURCES + let _ = Resources.decrementTotal() +#endif + } +} + +final class SinkForward: ObserverType { + typealias E = O.E + + private let _forward: Sink + + init(forward: Sink) { + _forward = forward + } + + final func on(_ event: Event) { + switch event { + case .next: + _forward._observer.on(event) + case .error, .completed: + _forward._observer.on(event) + _forward._cancel.dispose() + } + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Skip.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Skip.swift new file mode 100644 index 0000000000..1226bf89b1 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Skip.swift @@ -0,0 +1,159 @@ +// +// Skip.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + + - seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html) + + - parameter count: The number of elements to skip before returning the remaining elements. + - returns: An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + public func skip(_ count: Int) + -> Observable { + return SkipCount(source: asObservable(), count: count) + } +} + +extension ObservableType { + + /** + Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + + - seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html) + + - parameter duration: Duration for skipping elements from the start of the sequence. + - parameter scheduler: Scheduler to run the timer on. + - returns: An observable sequence with the elements skipped during the specified duration from the start of the source sequence. + */ + public func skip(_ duration: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return SkipTime(source: self.asObservable(), duration: duration, scheduler: scheduler) + } +} + +// count version + +final fileprivate class SkipCountSink : Sink, ObserverType { + typealias Element = O.E + typealias Parent = SkipCount + + let parent: Parent + + var remaining: Int + + init(parent: Parent, observer: O, cancel: Cancelable) { + self.parent = parent + self.remaining = parent.count + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + + if remaining <= 0 { + forwardOn(.next(value)) + } + else { + remaining -= 1 + } + case .error: + forwardOn(event) + self.dispose() + case .completed: + forwardOn(event) + self.dispose() + } + } + +} + +final fileprivate class SkipCount: Producer { + let source: Observable + let count: Int + + init(source: Observable, count: Int) { + self.source = source + self.count = count + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = SkipCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = source.subscribe(sink) + + return (sink: sink, subscription: subscription) + } +} + +// time version + +final fileprivate class SkipTimeSink : Sink, ObserverType where O.E == ElementType { + typealias Parent = SkipTime + typealias Element = ElementType + + let parent: Parent + + // state + var open = false + + init(parent: Parent, observer: O, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + if open { + forwardOn(.next(value)) + } + case .error: + forwardOn(event) + self.dispose() + case .completed: + forwardOn(event) + self.dispose() + } + } + + func tick() { + open = true + } + + func run() -> Disposable { + let disposeTimer = parent.scheduler.scheduleRelative((), dueTime: self.parent.duration) { + self.tick() + return Disposables.create() + } + + let disposeSubscription = parent.source.subscribe(self) + + return Disposables.create(disposeTimer, disposeSubscription) + } +} + +final fileprivate class SkipTime: Producer { + let source: Observable + let duration: RxTimeInterval + let scheduler: SchedulerType + + init(source: Observable, duration: RxTimeInterval, scheduler: SchedulerType) { + self.source = source + self.scheduler = scheduler + self.duration = duration + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = SkipTimeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift new file mode 100644 index 0000000000..f35f1fd8ae --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift @@ -0,0 +1,139 @@ +// +// SkipUntil.swift +// RxSwift +// +// Created by Yury Korolev on 10/3/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Returns the elements from the source observable sequence that are emitted after the other observable sequence produces an element. + + - seealso: [skipUntil operator on reactivex.io](http://reactivex.io/documentation/operators/skipuntil.html) + + - parameter other: Observable sequence that starts propagation of elements of the source sequence. + - returns: An observable sequence containing the elements of the source sequence that are emitted after the other sequence emits an item. + */ + public func skipUntil(_ other: O) + -> Observable { + return SkipUntil(source: asObservable(), other: other.asObservable()) + } +} + +final fileprivate class SkipUntilSinkOther + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Parent = SkipUntilSink + typealias E = Other + + fileprivate let _parent: Parent + + var _lock: RecursiveLock { + return _parent._lock + } + + let _subscription = SingleAssignmentDisposable() + + init(parent: Parent) { + _parent = parent + #if TRACE_RESOURCES + let _ = Resources.incrementTotal() + #endif + } + + func on(_ event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + switch event { + case .next: + _parent._forwardElements = true + _subscription.dispose() + case .error(let e): + _parent.forwardOn(.error(e)) + _parent.dispose() + case .completed: + _subscription.dispose() + } + } + + #if TRACE_RESOURCES + deinit { + let _ = Resources.decrementTotal() + } + #endif + +} + + +final fileprivate class SkipUntilSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias E = O.E + typealias Parent = SkipUntil + + let _lock = RecursiveLock() + fileprivate let _parent: Parent + fileprivate var _forwardElements = false + + fileprivate let _sourceSubscription = SingleAssignmentDisposable() + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + switch event { + case .next: + if _forwardElements { + forwardOn(event) + } + case .error: + forwardOn(event) + self.dispose() + case .completed: + if _forwardElements { + forwardOn(event) + } + self.dispose() + } + } + + func run() -> Disposable { + let sourceSubscription = _parent._source.subscribe(self) + let otherObserver = SkipUntilSinkOther(parent: self) + let otherSubscription = _parent._other.subscribe(otherObserver) + _sourceSubscription.setDisposable(sourceSubscription) + otherObserver._subscription.setDisposable(otherSubscription) + + return Disposables.create(_sourceSubscription, otherObserver._subscription) + } +} + +final fileprivate class SkipUntil: Producer { + + fileprivate let _source: Observable + fileprivate let _other: Observable + + init(source: Observable, other: Observable) { + _source = source + _other = other + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = SkipUntilSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift new file mode 100644 index 0000000000..42bf9bc59a --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift @@ -0,0 +1,143 @@ +// +// SkipWhile.swift +// RxSwift +// +// Created by Yury Korolev on 10/9/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + + - seealso: [skipWhile operator on reactivex.io](http://reactivex.io/documentation/operators/skipwhile.html) + + - parameter predicate: A function to test each element for a condition. + - returns: An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + public func skipWhile(_ predicate: @escaping (E) throws -> Bool) -> Observable { + return SkipWhile(source: asObservable(), predicate: predicate) + } + + /** + Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + The element's index is used in the logic of the predicate function. + + - seealso: [skipWhile operator on reactivex.io](http://reactivex.io/documentation/operators/skipwhile.html) + + - parameter predicate: A function to test each element for a condition; the second parameter of the function represents the index of the source element. + - returns: An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + public func skipWhileWithIndex(_ predicate: @escaping (E, Int) throws -> Bool) -> Observable { + return SkipWhile(source: asObservable(), predicate: predicate) + } +} + +final fileprivate class SkipWhileSink : Sink, ObserverType { + + typealias Element = O.E + typealias Parent = SkipWhile + + fileprivate let _parent: Parent + fileprivate var _running = false + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + if !_running { + do { + _running = try !_parent._predicate(value) + } catch let e { + forwardOn(.error(e)) + dispose() + return + } + } + + if _running { + forwardOn(.next(value)) + } + case .error, .completed: + forwardOn(event) + dispose() + } + } +} + +final fileprivate class SkipWhileSinkWithIndex : Sink, ObserverType { + + typealias Element = O.E + typealias Parent = SkipWhile + + fileprivate let _parent: Parent + fileprivate var _index = 0 + fileprivate var _running = false + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + if !_running { + do { + _running = try !_parent._predicateWithIndex(value, _index) + let _ = try incrementChecked(&_index) + } catch let e { + forwardOn(.error(e)) + dispose() + return + } + } + + if _running { + forwardOn(.next(value)) + } + case .error, .completed: + forwardOn(event) + dispose() + } + } +} + +final fileprivate class SkipWhile: Producer { + typealias Predicate = (Element) throws -> Bool + typealias PredicateWithIndex = (Element, Int) throws -> Bool + + fileprivate let _source: Observable + fileprivate let _predicate: Predicate! + fileprivate let _predicateWithIndex: PredicateWithIndex! + + init(source: Observable, predicate: @escaping Predicate) { + _source = source + _predicate = predicate + _predicateWithIndex = nil + } + + init(source: Observable, predicate: @escaping PredicateWithIndex) { + _source = source + _predicate = nil + _predicateWithIndex = predicate + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + if let _ = _predicate { + let sink = SkipWhileSink(parent: self, observer: observer, cancel: cancel) + let subscription = _source.subscribe(sink) + return (sink: sink, subscription: subscription) + } + else { + let sink = SkipWhileSinkWithIndex(parent: self, observer: observer, cancel: cancel) + let subscription = _source.subscribe(sink) + return (sink: sink, subscription: subscription) + } + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/StartWith.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/StartWith.swift new file mode 100644 index 0000000000..14776f9e65 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/StartWith.swift @@ -0,0 +1,42 @@ +// +// StartWith.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/6/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Prepends a sequence of values to an observable sequence. + + - seealso: [startWith operator on reactivex.io](http://reactivex.io/documentation/operators/startwith.html) + + - parameter elements: Elements to prepend to the specified sequence. + - returns: The source sequence prepended with the specified values. + */ + public func startWith(_ elements: E ...) + -> Observable { + return StartWith(source: self.asObservable(), elements: elements) + } +} + +final fileprivate class StartWith: Producer { + let elements: [Element] + let source: Observable + + init(source: Observable, elements: [Element]) { + self.source = source + self.elements = elements + super.init() + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + for e in elements { + observer.on(.next(e)) + } + + return (sink: Disposables.create(), subscription: source.subscribe(observer)) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift new file mode 100644 index 0000000000..2a33e03e5a --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift @@ -0,0 +1,83 @@ +// +// SubscribeOn.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Wraps the source sequence in order to run its subscription and unsubscription logic on the specified + scheduler. + + This operation is not commonly used. + + This only performs the side-effects of subscription and unsubscription on the specified scheduler. + + In order to invoke observer callbacks on a `scheduler`, use `observeOn`. + + - seealso: [subscribeOn operator on reactivex.io](http://reactivex.io/documentation/operators/subscribeon.html) + + - parameter scheduler: Scheduler to perform subscription and unsubscription actions on. + - returns: The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + public func subscribeOn(_ scheduler: ImmediateSchedulerType) + -> Observable { + return SubscribeOn(source: self, scheduler: scheduler) + } +} + +final fileprivate class SubscribeOnSink : Sink, ObserverType where Ob.E == O.E { + typealias Element = O.E + typealias Parent = SubscribeOn + + let parent: Parent + + init(parent: Parent, observer: O, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + forwardOn(event) + + if event.isStopEvent { + self.dispose() + } + } + + func run() -> Disposable { + let disposeEverything = SerialDisposable() + let cancelSchedule = SingleAssignmentDisposable() + + disposeEverything.disposable = cancelSchedule + + let disposeSchedule = parent.scheduler.schedule(()) { (_) -> Disposable in + let subscription = self.parent.source.subscribe(self) + disposeEverything.disposable = ScheduledDisposable(scheduler: self.parent.scheduler, disposable: subscription) + return Disposables.create() + } + + cancelSchedule.setDisposable(disposeSchedule) + + return disposeEverything + } +} + +final fileprivate class SubscribeOn : Producer { + let source: Ob + let scheduler: ImmediateSchedulerType + + init(source: Ob, scheduler: ImmediateSchedulerType) { + self.source = source + self.scheduler = scheduler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Ob.E { + let sink = SubscribeOnSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Switch.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Switch.swift new file mode 100644 index 0000000000..cc7cf6d1ea --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Switch.swift @@ -0,0 +1,228 @@ +// +// Switch.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Projects each element of an observable sequence into a new sequence of observable sequences and then + transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + + It is a combination of `map` + `switchLatest` operator + + - seealso: [flatMapLatest operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to each element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source producing an + Observable of Observable sequences and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + public func flatMapLatest(_ selector: @escaping (E) throws -> O) + -> Observable { + return FlatMapLatest(source: asObservable(), selector: selector) + } +} + +extension ObservableType where E : ObservableConvertibleType { + + /** + Transforms an observable sequence of observable sequences into an observable sequence + producing values only from the most recent observable sequence. + + Each time a new inner observable sequence is received, unsubscribe from the + previous inner observable sequence. + + - seealso: [switch operator on reactivex.io](http://reactivex.io/documentation/operators/switch.html) + + - returns: The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + public func switchLatest() -> Observable { + return Switch(source: asObservable()) + } +} + +fileprivate class SwitchSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType where S.E == O.E { + typealias E = SourceType + + fileprivate let _subscriptions: SingleAssignmentDisposable = SingleAssignmentDisposable() + fileprivate let _innerSubscription: SerialDisposable = SerialDisposable() + + let _lock = RecursiveLock() + + // state + fileprivate var _stopped = false + fileprivate var _latest = 0 + fileprivate var _hasLatest = false + + override init(observer: O, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func run(_ source: Observable) -> Disposable { + let subscription = source.subscribe(self) + _subscriptions.setDisposable(subscription) + return Disposables.create(_subscriptions, _innerSubscription) + } + + func on(_ event: Event) { + synchronizedOn(event) + } + + func performMap(_ element: SourceType) throws -> S { + rxAbstractMethod() + } + + func _synchronized_on(_ event: Event) { + switch event { + case .next(let element): + do { + let observable = try performMap(element).asObservable() + _hasLatest = true + _latest = _latest &+ 1 + let latest = _latest + + let d = SingleAssignmentDisposable() + _innerSubscription.disposable = d + + let observer = SwitchSinkIter(parent: self, id: latest, _self: d) + let disposable = observable.subscribe(observer) + d.setDisposable(disposable) + } + catch let error { + forwardOn(.error(error)) + dispose() + } + case .error(let error): + forwardOn(.error(error)) + dispose() + case .completed: + _stopped = true + + _subscriptions.dispose() + + if !_hasLatest { + forwardOn(.completed) + dispose() + } + } + } +} + +final fileprivate class SwitchSinkIter + : ObserverType + , LockOwnerType + , SynchronizedOnType where S.E == O.E { + typealias E = S.E + typealias Parent = SwitchSink + + fileprivate let _parent: Parent + fileprivate let _id: Int + fileprivate let _self: Disposable + + var _lock: RecursiveLock { + return _parent._lock + } + + init(parent: Parent, id: Int, _self: Disposable) { + _parent = parent + _id = id + self._self = _self + } + + func on(_ event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + switch event { + case .next: break + case .error, .completed: + _self.dispose() + } + + if _parent._latest != _id { + return + } + + switch event { + case .next: + _parent.forwardOn(event) + case .error: + _parent.forwardOn(event) + _parent.dispose() + case .completed: + _parent._hasLatest = false + if _parent._stopped { + _parent.forwardOn(event) + _parent.dispose() + } + } + } +} + +// MARK: Specializations + +final fileprivate class SwitchIdentitySink : SwitchSink where O.E == S.E { + override init(observer: O, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + override func performMap(_ element: S) throws -> S { + return element + } +} + +final fileprivate class MapSwitchSink : SwitchSink where O.E == S.E { + typealias Selector = (SourceType) throws -> S + + fileprivate let _selector: Selector + + init(selector: @escaping Selector, observer: O, cancel: Cancelable) { + _selector = selector + super.init(observer: observer, cancel: cancel) + } + + override func performMap(_ element: SourceType) throws -> S { + return try _selector(element) + } +} + +// MARK: Producers + +final fileprivate class Switch : Producer { + fileprivate let _source: Observable + + init(source: Observable) { + _source = source + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == S.E { + let sink = SwitchIdentitySink(observer: observer, cancel: cancel) + let subscription = sink.run(_source) + return (sink: sink, subscription: subscription) + } +} + +final fileprivate class FlatMapLatest : Producer { + typealias Selector = (SourceType) throws -> S + + fileprivate let _source: Observable + fileprivate let _selector: Selector + + init(source: Observable, selector: @escaping Selector) { + _source = source + _selector = selector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == S.E { + let sink = MapSwitchSink(selector: _selector, observer: observer, cancel: cancel) + let subscription = sink.run(_source) + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift new file mode 100644 index 0000000000..0b10dc614a --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift @@ -0,0 +1,104 @@ +// +// SwitchIfEmpty.swift +// RxSwift +// +// Created by sergdort on 23/12/2016. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns the elements of the specified sequence or `switchTo` sequence if the sequence is empty. + + - seealso: [DefaultIfEmpty operator on reactivex.io](http://reactivex.io/documentation/operators/defaultifempty.html) + + - parameter switchTo: Observable sequence being returned when source sequence is empty. + - returns: Observable sequence that contains elements from switchTo sequence if source is empty, otherwise returns source sequence elements. + */ + public func ifEmpty(switchTo other: Observable) -> Observable { + return SwitchIfEmpty(source: asObservable(), ifEmpty: other) + } +} + +final fileprivate class SwitchIfEmpty: Producer { + + private let _source: Observable + private let _ifEmpty: Observable + + init(source: Observable, ifEmpty: Observable) { + _source = source + _ifEmpty = ifEmpty + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = SwitchIfEmptySink(ifEmpty: _ifEmpty, + observer: observer, + cancel: cancel) + let subscription = sink.run(_source.asObservable()) + + return (sink: sink, subscription: subscription) + } +} + +final fileprivate class SwitchIfEmptySink: Sink + , ObserverType { + typealias E = O.E + + private let _ifEmpty: Observable + private var _isEmpty = true + private let _ifEmptySubscription = SingleAssignmentDisposable() + + init(ifEmpty: Observable, observer: O, cancel: Cancelable) { + _ifEmpty = ifEmpty + super.init(observer: observer, cancel: cancel) + } + + func run(_ source: Observable) -> Disposable { + let subscription = source.subscribe(self) + return Disposables.create(subscription, _ifEmptySubscription) + } + + func on(_ event: Event) { + switch event { + case .next: + _isEmpty = false + forwardOn(event) + case .error: + forwardOn(event) + dispose() + case .completed: + guard _isEmpty else { + forwardOn(.completed) + dispose() + return + } + let ifEmptySink = SwitchIfEmptySinkIter(parent: self) + _ifEmptySubscription.setDisposable(_ifEmpty.subscribe(ifEmptySink)) + } + } +} + +final fileprivate class SwitchIfEmptySinkIter + : ObserverType { + typealias E = O.E + typealias Parent = SwitchIfEmptySink + + private let _parent: Parent + + init(parent: Parent) { + _parent = parent + } + + func on(_ event: Event) { + switch event { + case .next: + _parent.forwardOn(event) + case .error: + _parent.forwardOn(event) + _parent.dispose() + case .completed: + _parent.forwardOn(event) + _parent.dispose() + } + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Take.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Take.swift new file mode 100644 index 0000000000..a7fbe85205 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Take.swift @@ -0,0 +1,180 @@ +// +// Take.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Returns a specified number of contiguous elements from the start of an observable sequence. + + - seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html) + + - parameter count: The number of elements to return. + - returns: An observable sequence that contains the specified number of elements from the start of the input sequence. + */ + public func take(_ count: Int) + -> Observable { + if count == 0 { + return Observable.empty() + } + else { + return TakeCount(source: asObservable(), count: count) + } + } +} + +extension ObservableType { + + /** + Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + + - seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html) + + - parameter duration: Duration for taking elements from the start of the sequence. + - parameter scheduler: Scheduler to run the timer on. + - returns: An observable sequence with the elements taken during the specified duration from the start of the source sequence. + */ + public func take(_ duration: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return TakeTime(source: self.asObservable(), duration: duration, scheduler: scheduler) + } +} + +// count version + +final fileprivate class TakeCountSink : Sink, ObserverType { + typealias E = O.E + typealias Parent = TakeCount + + private let _parent: Parent + + private var _remaining: Int + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + _remaining = parent._count + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + + if _remaining > 0 { + _remaining -= 1 + + forwardOn(.next(value)) + + if _remaining == 0 { + forwardOn(.completed) + dispose() + } + } + case .error: + forwardOn(event) + dispose() + case .completed: + forwardOn(event) + dispose() + } + } + +} + +final fileprivate class TakeCount: Producer { + fileprivate let _source: Observable + fileprivate let _count: Int + + init(source: Observable, count: Int) { + if count < 0 { + rxFatalError("count can't be negative") + } + _source = source + _count = count + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = TakeCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = _source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} + +// time version + +final fileprivate class TakeTimeSink + : Sink + , LockOwnerType + , ObserverType + , SynchronizedOnType where O.E == ElementType { + typealias Parent = TakeTime + typealias E = ElementType + + fileprivate let _parent: Parent + + let _lock = RecursiveLock() + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + switch event { + case .next(let value): + forwardOn(.next(value)) + case .error: + forwardOn(event) + dispose() + case .completed: + forwardOn(event) + dispose() + } + } + + func tick() { + _lock.lock(); defer { _lock.unlock() } + + forwardOn(.completed) + dispose() + } + + func run() -> Disposable { + let disposeTimer = _parent._scheduler.scheduleRelative((), dueTime: _parent._duration) { + self.tick() + return Disposables.create() + } + + let disposeSubscription = _parent._source.subscribe(self) + + return Disposables.create(disposeTimer, disposeSubscription) + } +} + +final fileprivate class TakeTime : Producer { + typealias TimeInterval = RxTimeInterval + + fileprivate let _source: Observable + fileprivate let _duration: TimeInterval + fileprivate let _scheduler: SchedulerType + + init(source: Observable, duration: TimeInterval, scheduler: SchedulerType) { + _source = source + _scheduler = scheduler + _duration = duration + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = TakeTimeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/TakeLast.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/TakeLast.swift new file mode 100644 index 0000000000..7bf1664bfd --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/TakeLast.swift @@ -0,0 +1,78 @@ +// +// TakeLast.swift +// RxSwift +// +// Created by Tomi Koskinen on 25/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Returns a specified number of contiguous elements from the end of an observable sequence. + + This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. + + - seealso: [takeLast operator on reactivex.io](http://reactivex.io/documentation/operators/takelast.html) + + - parameter count: Number of elements to take from the end of the source sequence. + - returns: An observable sequence containing the specified number of elements from the end of the source sequence. + */ + public func takeLast(_ count: Int) + -> Observable { + return TakeLast(source: asObservable(), count: count) + } +} + +final fileprivate class TakeLastSink : Sink, ObserverType { + typealias E = O.E + typealias Parent = TakeLast + + private let _parent: Parent + + private var _elements: Queue + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + _elements = Queue(capacity: parent._count + 1) + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + _elements.enqueue(value) + if _elements.count > self._parent._count { + let _ = _elements.dequeue() + } + case .error: + forwardOn(event) + dispose() + case .completed: + for e in _elements { + forwardOn(.next(e)) + } + forwardOn(.completed) + dispose() + } + } +} + +final fileprivate class TakeLast: Producer { + fileprivate let _source: Observable + fileprivate let _count: Int + + init(source: Observable, count: Int) { + if count < 0 { + rxFatalError("count can't be negative") + } + _source = source + _count = count + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = TakeLastSink(parent: self, observer: observer, cancel: cancel) + let subscription = _source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/TakeUntil.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/TakeUntil.swift new file mode 100644 index 0000000000..f2e5f98b01 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/TakeUntil.swift @@ -0,0 +1,131 @@ +// +// TakeUntil.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Returns the elements from the source observable sequence until the other observable sequence produces an element. + + - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) + + - parameter other: Observable sequence that terminates propagation of elements of the source sequence. + - returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + public func takeUntil(_ other: O) + -> Observable { + return TakeUntil(source: asObservable(), other: other.asObservable()) + } +} + +final fileprivate class TakeUntilSinkOther + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Parent = TakeUntilSink + typealias E = Other + + fileprivate let _parent: Parent + + var _lock: RecursiveLock { + return _parent._lock + } + + fileprivate let _subscription = SingleAssignmentDisposable() + + init(parent: Parent) { + _parent = parent +#if TRACE_RESOURCES + let _ = Resources.incrementTotal() +#endif + } + + func on(_ event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + switch event { + case .next: + _parent.forwardOn(.completed) + _parent.dispose() + case .error(let e): + _parent.forwardOn(.error(e)) + _parent.dispose() + case .completed: + _subscription.dispose() + } + } + +#if TRACE_RESOURCES + deinit { + let _ = Resources.decrementTotal() + } +#endif +} + +final fileprivate class TakeUntilSink + : Sink + , LockOwnerType + , ObserverType + , SynchronizedOnType { + typealias E = O.E + typealias Parent = TakeUntil + + fileprivate let _parent: Parent + + let _lock = RecursiveLock() + + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + switch event { + case .next: + forwardOn(event) + case .error: + forwardOn(event) + dispose() + case .completed: + forwardOn(event) + dispose() + } + } + + func run() -> Disposable { + let otherObserver = TakeUntilSinkOther(parent: self) + let otherSubscription = _parent._other.subscribe(otherObserver) + otherObserver._subscription.setDisposable(otherSubscription) + let sourceSubscription = _parent._source.subscribe(self) + + return Disposables.create(sourceSubscription, otherObserver._subscription) + } +} + +final fileprivate class TakeUntil: Producer { + + fileprivate let _source: Observable + fileprivate let _other: Observable + + init(source: Observable, other: Observable) { + _source = source + _other = other + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = TakeUntilSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/TakeWhile.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/TakeWhile.swift new file mode 100644 index 0000000000..45521fb41d --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/TakeWhile.swift @@ -0,0 +1,161 @@ +// +// TakeWhile.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Returns elements from an observable sequence as long as a specified condition is true. + + - seealso: [takeWhile operator on reactivex.io](http://reactivex.io/documentation/operators/takewhile.html) + + - parameter predicate: A function to test each element for a condition. + - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. + */ + public func takeWhile(_ predicate: @escaping (E) throws -> Bool) + -> Observable { + return TakeWhile(source: asObservable(), predicate: predicate) + } + + /** + Returns elements from an observable sequence as long as a specified condition is true. + + The element's index is used in the logic of the predicate function. + + - seealso: [takeWhile operator on reactivex.io](http://reactivex.io/documentation/operators/takewhile.html) + + - parameter predicate: A function to test each element for a condition; the second parameter of the function represents the index of the source element. + - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. + */ + public func takeWhileWithIndex(_ predicate: @escaping (E, Int) throws -> Bool) + -> Observable { + return TakeWhile(source: asObservable(), predicate: predicate) + } +} + +final fileprivate class TakeWhileSink + : Sink + , ObserverType { + typealias Element = O.E + typealias Parent = TakeWhile + + fileprivate let _parent: Parent + + fileprivate var _running = true + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + if !_running { + return + } + + do { + _running = try _parent._predicate(value) + } catch let e { + forwardOn(.error(e)) + dispose() + return + } + + if _running { + forwardOn(.next(value)) + } else { + forwardOn(.completed) + dispose() + } + case .error, .completed: + forwardOn(event) + dispose() + } + } + +} + +final fileprivate class TakeWhileSinkWithIndex + : Sink + , ObserverType { + typealias Element = O.E + typealias Parent = TakeWhile + + fileprivate let _parent: Parent + + fileprivate var _running = true + fileprivate var _index = 0 + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + if !_running { + return + } + + do { + _running = try _parent._predicateWithIndex(value, _index) + let _ = try incrementChecked(&_index) + } catch let e { + forwardOn(.error(e)) + dispose() + return + } + + if _running { + forwardOn(.next(value)) + } else { + forwardOn(.completed) + dispose() + } + case .error, .completed: + forwardOn(event) + dispose() + } + } + +} + +final fileprivate class TakeWhile: Producer { + typealias Predicate = (Element) throws -> Bool + typealias PredicateWithIndex = (Element, Int) throws -> Bool + + fileprivate let _source: Observable + fileprivate let _predicate: Predicate! + fileprivate let _predicateWithIndex: PredicateWithIndex! + + init(source: Observable, predicate: @escaping Predicate) { + _source = source + _predicate = predicate + _predicateWithIndex = nil + } + + init(source: Observable, predicate: @escaping PredicateWithIndex) { + _source = source + _predicate = nil + _predicateWithIndex = predicate + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + if let _ = _predicate { + let sink = TakeWhileSink(parent: self, observer: observer, cancel: cancel) + let subscription = _source.subscribe(sink) + return (sink: sink, subscription: subscription) + } else { + let sink = TakeWhileSinkWithIndex(parent: self, observer: observer, cancel: cancel) + let subscription = _source.subscribe(sink) + return (sink: sink, subscription: subscription) + } + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Throttle.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Throttle.swift new file mode 100644 index 0000000000..0c4ca7466f --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Throttle.swift @@ -0,0 +1,163 @@ +// +// Throttle.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/22/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import struct Foundation.Date + +extension ObservableType { + + /** + Returns an Observable that emits the first and the latest item emitted by the source Observable during sequential time windows of a specified duration. + + This operator makes sure that no two elements are emitted in less then dueTime. + + - seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html) + + - parameter dueTime: Throttling duration for each element. + - parameter latest: Should latest element received in a dueTime wide time window since last element emission be emitted. + - parameter scheduler: Scheduler to run the throttle timers on. + - returns: The throttled sequence. + */ + public func throttle(_ dueTime: RxTimeInterval, latest: Bool = true, scheduler: SchedulerType) + -> Observable { + return Throttle(source: self.asObservable(), dueTime: dueTime, latest: latest, scheduler: scheduler) + } +} + +final fileprivate class ThrottleSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = O.E + typealias ParentType = Throttle + + private let _parent: ParentType + + let _lock = RecursiveLock() + + // state + private var _lastUnsentElement: Element? = nil + private var _lastSentTime: Date? = nil + private var _completed: Bool = false + + let cancellable = SerialDisposable() + + init(parent: ParentType, observer: O, cancel: Cancelable) { + _parent = parent + + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription = _parent._source.subscribe(self) + + return Disposables.create(subscription, cancellable) + } + + func on(_ event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + switch event { + case .next(let element): + let now = _parent._scheduler.now + + let timeIntervalSinceLast: RxTimeInterval + + if let lastSendingTime = _lastSentTime { + timeIntervalSinceLast = now.timeIntervalSince(lastSendingTime) + } + else { + timeIntervalSinceLast = _parent._dueTime + } + + let couldSendNow = timeIntervalSinceLast >= _parent._dueTime + + if couldSendNow { + self.sendNow(element: element) + return + } + + if !_parent._latest { + return + } + + let isThereAlreadyInFlightRequest = _lastUnsentElement != nil + + _lastUnsentElement = element + + if isThereAlreadyInFlightRequest { + return + } + + let scheduler = _parent._scheduler + let dueTime = _parent._dueTime + + let d = SingleAssignmentDisposable() + self.cancellable.disposable = d + + d.setDisposable(scheduler.scheduleRelative(0, dueTime: dueTime - timeIntervalSinceLast, action: self.propagate)) + case .error: + _lastUnsentElement = nil + forwardOn(event) + dispose() + case .completed: + if let _ = _lastUnsentElement { + _completed = true + } + else { + forwardOn(.completed) + dispose() + } + } + } + + private func sendNow(element: Element) { + _lastUnsentElement = nil + self.forwardOn(.next(element)) + // in case element processing takes a while, this should give some more room + _lastSentTime = _parent._scheduler.now + } + + func propagate(_: Int) -> Disposable { + _lock.lock(); defer { _lock.unlock() } // { + if let lastUnsentElement = _lastUnsentElement { + sendNow(element: lastUnsentElement) + } + + if _completed { + forwardOn(.completed) + dispose() + } + // } + return Disposables.create() + } +} + +final fileprivate class Throttle : Producer { + + fileprivate let _source: Observable + fileprivate let _dueTime: RxTimeInterval + fileprivate let _latest: Bool + fileprivate let _scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, latest: Bool, scheduler: SchedulerType) { + _source = source + _dueTime = dueTime + _latest = latest + _scheduler = scheduler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = ThrottleSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } + +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Timeout.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Timeout.swift new file mode 100644 index 0000000000..7008de8286 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Timeout.swift @@ -0,0 +1,152 @@ +// +// Timeout.swift +// RxSwift +// +// Created by Tomi Koskinen on 13/11/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Applies a timeout policy for each element in the observable sequence. If the next element isn't received within the specified timeout duration starting from its predecessor, a TimeoutError is propagated to the observer. + + - seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html) + + - parameter dueTime: Maximum duration between values before a timeout occurs. + - parameter scheduler: Scheduler to run the timeout timer on. + - returns: An observable sequence with a `RxError.timeout` in case of a timeout. + */ + public func timeout(_ dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Timeout(source: self.asObservable(), dueTime: dueTime, other: Observable.error(RxError.timeout), scheduler: scheduler) + } + + /** + Applies a timeout policy for each element in the observable sequence, using the specified scheduler to run timeout timers. If the next element isn't received within the specified timeout duration starting from its predecessor, the other observable sequence is used to produce future messages from that point on. + + - seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html) + + - parameter dueTime: Maximum duration between values before a timeout occurs. + - parameter other: Sequence to return in case of a timeout. + - parameter scheduler: Scheduler to run the timeout timer on. + - returns: The source sequence switching to the other sequence in case of a timeout. + */ + public func timeout(_ dueTime: RxTimeInterval, other: O, scheduler: SchedulerType) + -> Observable where E == O.E { + return Timeout(source: self.asObservable(), dueTime: dueTime, other: other.asObservable(), scheduler: scheduler) + } +} + +final fileprivate class TimeoutSink: Sink, LockOwnerType, ObserverType { + typealias E = O.E + typealias Parent = Timeout + + private let _parent: Parent + + let _lock = RecursiveLock() + + private let _timerD = SerialDisposable() + private let _subscription = SerialDisposable() + + private var _id = 0 + private var _switched = false + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let original = SingleAssignmentDisposable() + _subscription.disposable = original + + _createTimeoutTimer() + + original.setDisposable(_parent._source.subscribe(self)) + + return Disposables.create(_subscription, _timerD) + } + + func on(_ event: Event) { + switch event { + case .next: + var onNextWins = false + + _lock.performLocked() { + onNextWins = !self._switched + if onNextWins { + self._id = self._id &+ 1 + } + } + + if onNextWins { + forwardOn(event) + self._createTimeoutTimer() + } + case .error, .completed: + var onEventWins = false + + _lock.performLocked() { + onEventWins = !self._switched + if onEventWins { + self._id = self._id &+ 1 + } + } + + if onEventWins { + forwardOn(event) + self.dispose() + } + } + } + + private func _createTimeoutTimer() { + if _timerD.isDisposed { + return + } + + let nextTimer = SingleAssignmentDisposable() + _timerD.disposable = nextTimer + + let disposeSchedule = _parent._scheduler.scheduleRelative(_id, dueTime: _parent._dueTime) { state in + + var timerWins = false + + self._lock.performLocked() { + self._switched = (state == self._id) + timerWins = self._switched + } + + if timerWins { + self._subscription.disposable = self._parent._other.subscribe(self.forwarder()) + } + + return Disposables.create() + } + + nextTimer.setDisposable(disposeSchedule) + } +} + + +final fileprivate class Timeout : Producer { + + fileprivate let _source: Observable + fileprivate let _dueTime: RxTimeInterval + fileprivate let _other: Observable + fileprivate let _scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, other: Observable, scheduler: SchedulerType) { + _source = source + _dueTime = dueTime + _other = other + _scheduler = scheduler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = TimeoutSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Timer.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Timer.swift new file mode 100644 index 0000000000..f62be1cce8 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Timer.swift @@ -0,0 +1,111 @@ +// +// Timer.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension Observable where Element : SignedInteger { + /** + Returns an observable sequence that produces a value after each period, using the specified scheduler to run timers and to send out observer messages. + + - seealso: [interval operator on reactivex.io](http://reactivex.io/documentation/operators/interval.html) + + - parameter period: Period for producing the values in the resulting sequence. + - parameter scheduler: Scheduler to run the timer on. + - returns: An observable sequence that produces a value after each period. + */ + public static func interval(_ period: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Timer(dueTime: period, + period: period, + scheduler: scheduler + ) + } +} + +extension Observable where Element: SignedInteger { + /** + Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers. + + - seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html) + + - parameter dueTime: Relative time at which to produce the first value. + - parameter period: Period to produce subsequent values. + - parameter scheduler: Scheduler to run timers on. + - returns: An observable sequence that produces a value after due time has elapsed and then each period. + */ + public static func timer(_ dueTime: RxTimeInterval, period: RxTimeInterval? = nil, scheduler: SchedulerType) + -> Observable { + return Timer( + dueTime: dueTime, + period: period, + scheduler: scheduler + ) + } +} + +final fileprivate class TimerSink : Sink where O.E : SignedInteger { + typealias Parent = Timer + + private let _parent: Parent + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return _parent._scheduler.schedulePeriodic(0 as O.E, startAfter: _parent._dueTime, period: _parent._period!) { state in + self.forwardOn(.next(state)) + return state &+ 1 + } + } +} + +final fileprivate class TimerOneOffSink : Sink where O.E : SignedInteger { + typealias Parent = Timer + + private let _parent: Parent + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return _parent._scheduler.scheduleRelative(self, dueTime: _parent._dueTime) { (`self`) -> Disposable in + self.forwardOn(.next(0)) + self.forwardOn(.completed) + self.dispose() + + return Disposables.create() + } + } +} + +final fileprivate class Timer: Producer { + fileprivate let _scheduler: SchedulerType + fileprivate let _dueTime: RxTimeInterval + fileprivate let _period: RxTimeInterval? + + init(dueTime: RxTimeInterval, period: RxTimeInterval?, scheduler: SchedulerType) { + _scheduler = scheduler + _dueTime = dueTime + _period = period + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { + if let _ = _period { + let sink = TimerSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } + else { + let sink = TimerOneOffSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/ToArray.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/ToArray.swift new file mode 100644 index 0000000000..93fcb80e11 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/ToArray.swift @@ -0,0 +1,66 @@ +// +// ToArray.swift +// RxSwift +// +// Created by Junior B. on 20/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + + +extension ObservableType { + + /** + Converts an Observable into another Observable that emits the whole sequence as a single array and then terminates. + + For aggregation behavior see `reduce`. + + - seealso: [toArray operator on reactivex.io](http://reactivex.io/documentation/operators/to.html) + + - returns: An observable sequence containing all the emitted elements as array. + */ + public func toArray() + -> Observable<[E]> { + return ToArray(source: self.asObservable()) + } +} + +final fileprivate class ToArraySink : Sink, ObserverType where O.E == [SourceType] { + typealias Parent = ToArray + + let _parent: Parent + var _list = Array() + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + self._list.append(value) + case .error(let e): + forwardOn(.error(e)) + self.dispose() + case .completed: + forwardOn(.next(_list)) + forwardOn(.completed) + self.dispose() + } + } +} + +final fileprivate class ToArray : Producer<[SourceType]> { + let _source: Observable + + init(source: Observable) { + _source = source + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == [SourceType] { + let sink = ToArraySink(parent: self, observer: observer, cancel: cancel) + let subscription = _source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Using.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Using.swift new file mode 100644 index 0000000000..2f772101d2 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Using.swift @@ -0,0 +1,90 @@ +// +// Using.swift +// RxSwift +// +// Created by Yury Korolev on 10/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension Observable { + /** + Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. + + - seealso: [using operator on reactivex.io](http://reactivex.io/documentation/operators/using.html) + + - parameter resourceFactory: Factory function to obtain a resource object. + - parameter observableFactory: Factory function to obtain an observable sequence that depends on the obtained resource. + - returns: An observable sequence whose lifetime controls the lifetime of the dependent resource object. + */ + public static func using(_ resourceFactory: @escaping () throws -> R, observableFactory: @escaping (R) throws -> Observable) -> Observable { + return Using(resourceFactory: resourceFactory, observableFactory: observableFactory) + } +} + +final fileprivate class UsingSink : Sink, ObserverType { + typealias SourceType = O.E + typealias Parent = Using + + private let _parent: Parent + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + var disposable = Disposables.create() + + do { + let resource = try _parent._resourceFactory() + disposable = resource + let source = try _parent._observableFactory(resource) + + return Disposables.create( + source.subscribe(self), + disposable + ) + } catch let error { + return Disposables.create( + Observable.error(error).subscribe(self), + disposable + ) + } + } + + func on(_ event: Event) { + switch event { + case let .next(value): + forwardOn(.next(value)) + case let .error(error): + forwardOn(.error(error)) + dispose() + case .completed: + forwardOn(.completed) + dispose() + } + } +} + +final fileprivate class Using: Producer { + + typealias E = SourceType + + typealias ResourceFactory = () throws -> ResourceType + typealias ObservableFactory = (ResourceType) throws -> Observable + + fileprivate let _resourceFactory: ResourceFactory + fileprivate let _observableFactory: ObservableFactory + + + init(resourceFactory: @escaping ResourceFactory, observableFactory: @escaping ObservableFactory) { + _resourceFactory = resourceFactory + _observableFactory = observableFactory + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { + let sink = UsingSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Window.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Window.swift new file mode 100644 index 0000000000..c862dfba78 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Window.swift @@ -0,0 +1,170 @@ +// +// Window.swift +// RxSwift +// +// Created by Junior B. on 29/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Projects each element of an observable sequence into a window that is completed when either it’s full or a given amount of time has elapsed. + + - seealso: [window operator on reactivex.io](http://reactivex.io/documentation/operators/window.html) + + - parameter timeSpan: Maximum time length of a window. + - parameter count: Maximum element count of a window. + - parameter scheduler: Scheduler to run windowing timers on. + - returns: An observable sequence of windows (instances of `Observable`). + */ + public func window(timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) + -> Observable> { + return WindowTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler) + } +} + +final fileprivate class WindowTimeCountSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType where O.E == Observable { + typealias Parent = WindowTimeCount + typealias E = Element + + private let _parent: Parent + + let _lock = RecursiveLock() + + private var _subject = PublishSubject() + private var _count = 0 + private var _windowId = 0 + + private let _timerD = SerialDisposable() + private let _refCountDisposable: RefCountDisposable + private let _groupDisposable = CompositeDisposable() + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + + let _ = _groupDisposable.insert(_timerD) + + _refCountDisposable = RefCountDisposable(disposable: _groupDisposable) + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + + forwardOn(.next(AddRef(source: _subject, refCount: _refCountDisposable).asObservable())) + createTimer(_windowId) + + let _ = _groupDisposable.insert(_parent._source.subscribe(self)) + return _refCountDisposable + } + + func startNewWindowAndCompleteCurrentOne() { + _subject.on(.completed) + _subject = PublishSubject() + + forwardOn(.next(AddRef(source: _subject, refCount: _refCountDisposable).asObservable())) + } + + func on(_ event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + var newWindow = false + var newId = 0 + + switch event { + case .next(let element): + _subject.on(.next(element)) + + do { + let _ = try incrementChecked(&_count) + } catch (let e) { + _subject.on(.error(e as Swift.Error)) + dispose() + } + + if (_count == _parent._count) { + newWindow = true + _count = 0 + _windowId += 1 + newId = _windowId + self.startNewWindowAndCompleteCurrentOne() + } + + case .error(let error): + _subject.on(.error(error)) + forwardOn(.error(error)) + dispose() + case .completed: + _subject.on(.completed) + forwardOn(.completed) + dispose() + } + + if newWindow { + createTimer(newId) + } + } + + func createTimer(_ windowId: Int) { + if _timerD.isDisposed { + return + } + + if _windowId != windowId { + return + } + + let nextTimer = SingleAssignmentDisposable() + + _timerD.disposable = nextTimer + + let scheduledRelative = _parent._scheduler.scheduleRelative(windowId, dueTime: _parent._timeSpan) { previousWindowId in + + var newId = 0 + + self._lock.performLocked { + if previousWindowId != self._windowId { + return + } + + self._count = 0 + self._windowId = self._windowId &+ 1 + newId = self._windowId + self.startNewWindowAndCompleteCurrentOne() + } + + self.createTimer(newId) + + return Disposables.create() + } + + nextTimer.setDisposable(scheduledRelative) + } +} + +final fileprivate class WindowTimeCount : Producer> { + + fileprivate let _timeSpan: RxTimeInterval + fileprivate let _count: Int + fileprivate let _scheduler: SchedulerType + fileprivate let _source: Observable + + init(source: Observable, timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) { + _source = source + _timeSpan = timeSpan + _count = count + _scheduler = scheduler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Observable { + let sink = WindowTimeCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift new file mode 100644 index 0000000000..35205e4fdc --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift @@ -0,0 +1,149 @@ +// +// WithLatestFrom.swift +// RxSwift +// +// Created by Yury Korolev on 10/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Merges two observable sequences into one observable sequence by combining each element from self with the latest element from the second source, if any. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter second: Second observable source. + - parameter resultSelector: Function to invoke for each element from the self combined with the latest element from the second source, if any. + - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. + */ + public func withLatestFrom(_ second: SecondO, resultSelector: @escaping (E, SecondO.E) throws -> ResultType) -> Observable { + return WithLatestFrom(first: asObservable(), second: second.asObservable(), resultSelector: resultSelector) + } + + /** + Merges two observable sequences into one observable sequence by using latest element from the second sequence every time when `self` emitts an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter second: Second observable source. + - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. + */ + public func withLatestFrom(_ second: SecondO) -> Observable { + return WithLatestFrom(first: asObservable(), second: second.asObservable(), resultSelector: { $1 }) + } +} + +final fileprivate class WithLatestFromSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias ResultType = O.E + typealias Parent = WithLatestFrom + typealias E = FirstType + + fileprivate let _parent: Parent + + var _lock = RecursiveLock() + fileprivate var _latest: SecondType? + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let sndSubscription = SingleAssignmentDisposable() + let sndO = WithLatestFromSecond(parent: self, disposable: sndSubscription) + + sndSubscription.setDisposable(_parent._second.subscribe(sndO)) + let fstSubscription = _parent._first.subscribe(self) + + return Disposables.create(fstSubscription, sndSubscription) + } + + func on(_ event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + switch event { + case let .next(value): + guard let latest = _latest else { return } + do { + let res = try _parent._resultSelector(value, latest) + + forwardOn(.next(res)) + } catch let e { + forwardOn(.error(e)) + dispose() + } + case .completed: + forwardOn(.completed) + dispose() + case let .error(error): + forwardOn(.error(error)) + dispose() + } + } +} + +final fileprivate class WithLatestFromSecond + : ObserverType + , LockOwnerType + , SynchronizedOnType { + + typealias ResultType = O.E + typealias Parent = WithLatestFromSink + typealias E = SecondType + + private let _parent: Parent + private let _disposable: Disposable + + var _lock: RecursiveLock { + return _parent._lock + } + + init(parent: Parent, disposable: Disposable) { + _parent = parent + _disposable = disposable + } + + func on(_ event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + switch event { + case let .next(value): + _parent._latest = value + case .completed: + _disposable.dispose() + case let .error(error): + _parent.forwardOn(.error(error)) + _parent.dispose() + } + } +} + +final fileprivate class WithLatestFrom: Producer { + typealias ResultSelector = (FirstType, SecondType) throws -> ResultType + + fileprivate let _first: Observable + fileprivate let _second: Observable + fileprivate let _resultSelector: ResultSelector + + init(first: Observable, second: Observable, resultSelector: @escaping ResultSelector) { + _first = first + _second = second + _resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == ResultType { + let sink = WithLatestFromSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift new file mode 100644 index 0000000000..6559491b8c --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift @@ -0,0 +1,169 @@ +// +// Zip+Collection.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip(_ collection: C, _ resultSelector: @escaping ([C.Iterator.Element.E]) throws -> Element) -> Observable + where C.Iterator.Element: ObservableType { + return ZipCollectionType(sources: collection, resultSelector: resultSelector) + } + + /** + Merges the specified observable sequences into one observable sequence whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip(_ collection: C) -> Observable<[Element]> + where C.Iterator.Element: ObservableType, C.Iterator.Element.E == Element { + return ZipCollectionType(sources: collection, resultSelector: { $0 }) + } + +} + +final fileprivate class ZipCollectionTypeSink + : Sink where C.Iterator.Element : ObservableConvertibleType { + typealias R = O.E + typealias Parent = ZipCollectionType + typealias SourceElement = C.Iterator.Element.E + + private let _parent: Parent + + private let _lock = RecursiveLock() + + // state + private var _numberOfValues = 0 + private var _values: [Queue] + private var _isDone: [Bool] + private var _numberOfDone = 0 + private var _subscriptions: [SingleAssignmentDisposable] + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + _values = [Queue](repeating: Queue(capacity: 4), count: parent.count) + _isDone = [Bool](repeating: false, count: parent.count) + _subscriptions = Array() + _subscriptions.reserveCapacity(parent.count) + + for _ in 0 ..< parent.count { + _subscriptions.append(SingleAssignmentDisposable()) + } + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event, atIndex: Int) { + _lock.lock(); defer { _lock.unlock() } // { + switch event { + case .next(let element): + _values[atIndex].enqueue(element) + + if _values[atIndex].count == 1 { + _numberOfValues += 1 + } + + if _numberOfValues < _parent.count { + if _numberOfDone == _parent.count - 1 { + self.forwardOn(.completed) + self.dispose() + } + return + } + + do { + var arguments = [SourceElement]() + arguments.reserveCapacity(_parent.count) + + // recalculate number of values + _numberOfValues = 0 + + for i in 0 ..< _values.count { + arguments.append(_values[i].dequeue()!) + if _values[i].count > 0 { + _numberOfValues += 1 + } + } + + let result = try _parent.resultSelector(arguments) + self.forwardOn(.next(result)) + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + if _isDone[atIndex] { + return + } + + _isDone[atIndex] = true + _numberOfDone += 1 + + if _numberOfDone == _parent.count { + self.forwardOn(.completed) + self.dispose() + } + else { + _subscriptions[atIndex].dispose() + } + } + // } + } + + func run() -> Disposable { + var j = 0 + for i in _parent.sources { + let index = j + let source = i.asObservable() + + let disposable = source.subscribe(AnyObserver { event in + self.on(event, atIndex: index) + }) + _subscriptions[j].setDisposable(disposable) + j += 1 + } + + if _parent.sources.isEmpty { + self.forwardOn(.completed) + } + + return Disposables.create(_subscriptions) + } +} + +final fileprivate class ZipCollectionType : Producer where C.Iterator.Element : ObservableConvertibleType { + typealias ResultSelector = ([C.Iterator.Element.E]) throws -> R + + let sources: C + let resultSelector: ResultSelector + let count: Int + + init(sources: C, resultSelector: @escaping ResultSelector) { + self.sources = sources + self.resultSelector = resultSelector + self.count = Int(self.sources.count.toIntMax()) + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = ZipCollectionTypeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift new file mode 100644 index 0000000000..602b49ef1c --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift @@ -0,0 +1,948 @@ +// This file is autogenerated. Take a look at `Preprocessor` target in RxSwift project +// +// Zip+arity.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + + + +// 2 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, resultSelector: @escaping (O1.E, O2.E) throws -> E) + -> Observable { + return Zip2( + source1: source1.asObservable(), source2: source2.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where E == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2) + -> Observable<(O1.E, O2.E)> { + return Zip2( + source1: source1.asObservable(), source2: source2.asObservable(), + resultSelector: { ($0, $1) } + ) + } +} + +final class ZipSink2_ : ZipSink { + typealias R = O.E + typealias Parent = Zip2 + + let _parent: Parent + + var _values1: Queue = Queue(capacity: 2) + var _values2: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(arity: 2, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch (index) { + case 0: return _values1.count > 0 + case 1: return _values2.count > 0 + + default: + rxFatalError("Unhandled case (Function)") + } + + return false + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: _lock, parent: self, index: 0, setNextValue: { self._values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: _lock, parent: self, index: 1, setNextValue: { self._values2.enqueue($0) }, this: subscription2) + + subscription1.setDisposable(_parent.source1.subscribe(observer1)) + subscription2.setDisposable(_parent.source2.subscribe(observer2)) + + return Disposables.create([ + subscription1, + subscription2 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_values1.dequeue()!, _values2.dequeue()!) + } +} + +final class Zip2 : Producer { + typealias ResultSelector = (E1, E2) throws -> R + + let source1: Observable + let source2: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + + _resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = ZipSink2_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 3 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, resultSelector: @escaping (O1.E, O2.E, O3.E) throws -> E) + -> Observable { + return Zip3( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where E == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3) + -> Observable<(O1.E, O2.E, O3.E)> { + return Zip3( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), + resultSelector: { ($0, $1, $2) } + ) + } +} + +final class ZipSink3_ : ZipSink { + typealias R = O.E + typealias Parent = Zip3 + + let _parent: Parent + + var _values1: Queue = Queue(capacity: 2) + var _values2: Queue = Queue(capacity: 2) + var _values3: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(arity: 3, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch (index) { + case 0: return _values1.count > 0 + case 1: return _values2.count > 0 + case 2: return _values3.count > 0 + + default: + rxFatalError("Unhandled case (Function)") + } + + return false + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: _lock, parent: self, index: 0, setNextValue: { self._values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: _lock, parent: self, index: 1, setNextValue: { self._values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: _lock, parent: self, index: 2, setNextValue: { self._values3.enqueue($0) }, this: subscription3) + + subscription1.setDisposable(_parent.source1.subscribe(observer1)) + subscription2.setDisposable(_parent.source2.subscribe(observer2)) + subscription3.setDisposable(_parent.source3.subscribe(observer3)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_values1.dequeue()!, _values2.dequeue()!, _values3.dequeue()!) + } +} + +final class Zip3 : Producer { + typealias ResultSelector = (E1, E2, E3) throws -> R + + let source1: Observable + let source2: Observable + let source3: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + + _resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = ZipSink3_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 4 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, resultSelector: @escaping (O1.E, O2.E, O3.E, O4.E) throws -> E) + -> Observable { + return Zip4( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where E == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4) + -> Observable<(O1.E, O2.E, O3.E, O4.E)> { + return Zip4( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), + resultSelector: { ($0, $1, $2, $3) } + ) + } +} + +final class ZipSink4_ : ZipSink { + typealias R = O.E + typealias Parent = Zip4 + + let _parent: Parent + + var _values1: Queue = Queue(capacity: 2) + var _values2: Queue = Queue(capacity: 2) + var _values3: Queue = Queue(capacity: 2) + var _values4: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(arity: 4, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch (index) { + case 0: return _values1.count > 0 + case 1: return _values2.count > 0 + case 2: return _values3.count > 0 + case 3: return _values4.count > 0 + + default: + rxFatalError("Unhandled case (Function)") + } + + return false + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: _lock, parent: self, index: 0, setNextValue: { self._values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: _lock, parent: self, index: 1, setNextValue: { self._values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: _lock, parent: self, index: 2, setNextValue: { self._values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: _lock, parent: self, index: 3, setNextValue: { self._values4.enqueue($0) }, this: subscription4) + + subscription1.setDisposable(_parent.source1.subscribe(observer1)) + subscription2.setDisposable(_parent.source2.subscribe(observer2)) + subscription3.setDisposable(_parent.source3.subscribe(observer3)) + subscription4.setDisposable(_parent.source4.subscribe(observer4)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_values1.dequeue()!, _values2.dequeue()!, _values3.dequeue()!, _values4.dequeue()!) + } +} + +final class Zip4 : Producer { + typealias ResultSelector = (E1, E2, E3, E4) throws -> R + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + + _resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = ZipSink4_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 5 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, resultSelector: @escaping (O1.E, O2.E, O3.E, O4.E, O5.E) throws -> E) + -> Observable { + return Zip5( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where E == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5) + -> Observable<(O1.E, O2.E, O3.E, O4.E, O5.E)> { + return Zip5( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4) } + ) + } +} + +final class ZipSink5_ : ZipSink { + typealias R = O.E + typealias Parent = Zip5 + + let _parent: Parent + + var _values1: Queue = Queue(capacity: 2) + var _values2: Queue = Queue(capacity: 2) + var _values3: Queue = Queue(capacity: 2) + var _values4: Queue = Queue(capacity: 2) + var _values5: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(arity: 5, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch (index) { + case 0: return _values1.count > 0 + case 1: return _values2.count > 0 + case 2: return _values3.count > 0 + case 3: return _values4.count > 0 + case 4: return _values5.count > 0 + + default: + rxFatalError("Unhandled case (Function)") + } + + return false + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: _lock, parent: self, index: 0, setNextValue: { self._values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: _lock, parent: self, index: 1, setNextValue: { self._values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: _lock, parent: self, index: 2, setNextValue: { self._values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: _lock, parent: self, index: 3, setNextValue: { self._values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: _lock, parent: self, index: 4, setNextValue: { self._values5.enqueue($0) }, this: subscription5) + + subscription1.setDisposable(_parent.source1.subscribe(observer1)) + subscription2.setDisposable(_parent.source2.subscribe(observer2)) + subscription3.setDisposable(_parent.source3.subscribe(observer3)) + subscription4.setDisposable(_parent.source4.subscribe(observer4)) + subscription5.setDisposable(_parent.source5.subscribe(observer5)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_values1.dequeue()!, _values2.dequeue()!, _values3.dequeue()!, _values4.dequeue()!, _values5.dequeue()!) + } +} + +final class Zip5 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5) throws -> R + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + + _resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = ZipSink5_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 6 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, resultSelector: @escaping (O1.E, O2.E, O3.E, O4.E, O5.E, O6.E) throws -> E) + -> Observable { + return Zip6( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where E == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6) + -> Observable<(O1.E, O2.E, O3.E, O4.E, O5.E, O6.E)> { + return Zip6( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5) } + ) + } +} + +final class ZipSink6_ : ZipSink { + typealias R = O.E + typealias Parent = Zip6 + + let _parent: Parent + + var _values1: Queue = Queue(capacity: 2) + var _values2: Queue = Queue(capacity: 2) + var _values3: Queue = Queue(capacity: 2) + var _values4: Queue = Queue(capacity: 2) + var _values5: Queue = Queue(capacity: 2) + var _values6: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(arity: 6, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch (index) { + case 0: return _values1.count > 0 + case 1: return _values2.count > 0 + case 2: return _values3.count > 0 + case 3: return _values4.count > 0 + case 4: return _values5.count > 0 + case 5: return _values6.count > 0 + + default: + rxFatalError("Unhandled case (Function)") + } + + return false + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: _lock, parent: self, index: 0, setNextValue: { self._values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: _lock, parent: self, index: 1, setNextValue: { self._values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: _lock, parent: self, index: 2, setNextValue: { self._values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: _lock, parent: self, index: 3, setNextValue: { self._values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: _lock, parent: self, index: 4, setNextValue: { self._values5.enqueue($0) }, this: subscription5) + let observer6 = ZipObserver(lock: _lock, parent: self, index: 5, setNextValue: { self._values6.enqueue($0) }, this: subscription6) + + subscription1.setDisposable(_parent.source1.subscribe(observer1)) + subscription2.setDisposable(_parent.source2.subscribe(observer2)) + subscription3.setDisposable(_parent.source3.subscribe(observer3)) + subscription4.setDisposable(_parent.source4.subscribe(observer4)) + subscription5.setDisposable(_parent.source5.subscribe(observer5)) + subscription6.setDisposable(_parent.source6.subscribe(observer6)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_values1.dequeue()!, _values2.dequeue()!, _values3.dequeue()!, _values4.dequeue()!, _values5.dequeue()!, _values6.dequeue()!) + } +} + +final class Zip6 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6) throws -> R + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + + _resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = ZipSink6_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 7 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, resultSelector: @escaping (O1.E, O2.E, O3.E, O4.E, O5.E, O6.E, O7.E) throws -> E) + -> Observable { + return Zip7( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where E == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7) + -> Observable<(O1.E, O2.E, O3.E, O4.E, O5.E, O6.E, O7.E)> { + return Zip7( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5, $6) } + ) + } +} + +final class ZipSink7_ : ZipSink { + typealias R = O.E + typealias Parent = Zip7 + + let _parent: Parent + + var _values1: Queue = Queue(capacity: 2) + var _values2: Queue = Queue(capacity: 2) + var _values3: Queue = Queue(capacity: 2) + var _values4: Queue = Queue(capacity: 2) + var _values5: Queue = Queue(capacity: 2) + var _values6: Queue = Queue(capacity: 2) + var _values7: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(arity: 7, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch (index) { + case 0: return _values1.count > 0 + case 1: return _values2.count > 0 + case 2: return _values3.count > 0 + case 3: return _values4.count > 0 + case 4: return _values5.count > 0 + case 5: return _values6.count > 0 + case 6: return _values7.count > 0 + + default: + rxFatalError("Unhandled case (Function)") + } + + return false + } + + 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 = ZipObserver(lock: _lock, parent: self, index: 0, setNextValue: { self._values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: _lock, parent: self, index: 1, setNextValue: { self._values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: _lock, parent: self, index: 2, setNextValue: { self._values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: _lock, parent: self, index: 3, setNextValue: { self._values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: _lock, parent: self, index: 4, setNextValue: { self._values5.enqueue($0) }, this: subscription5) + let observer6 = ZipObserver(lock: _lock, parent: self, index: 5, setNextValue: { self._values6.enqueue($0) }, this: subscription6) + let observer7 = ZipObserver(lock: _lock, parent: self, index: 6, setNextValue: { self._values7.enqueue($0) }, this: subscription7) + + subscription1.setDisposable(_parent.source1.subscribe(observer1)) + subscription2.setDisposable(_parent.source2.subscribe(observer2)) + subscription3.setDisposable(_parent.source3.subscribe(observer3)) + subscription4.setDisposable(_parent.source4.subscribe(observer4)) + subscription5.setDisposable(_parent.source5.subscribe(observer5)) + subscription6.setDisposable(_parent.source6.subscribe(observer6)) + subscription7.setDisposable(_parent.source7.subscribe(observer7)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_values1.dequeue()!, _values2.dequeue()!, _values3.dequeue()!, _values4.dequeue()!, _values5.dequeue()!, _values6.dequeue()!, _values7.dequeue()!) + } +} + +final class Zip7 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7) throws -> R + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + let source7: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + self.source7 = source7 + + _resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = ZipSink7_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 8 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8, resultSelector: @escaping (O1.E, O2.E, O3.E, O4.E, O5.E, O6.E, O7.E, O8.E) throws -> E) + -> Observable { + return Zip8( + 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 + ) + } +} + +extension ObservableType where E == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8) + -> Observable<(O1.E, O2.E, O3.E, O4.E, O5.E, O6.E, O7.E, O8.E)> { + return Zip8( + 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: { ($0, $1, $2, $3, $4, $5, $6, $7) } + ) + } +} + +final class ZipSink8_ : ZipSink { + typealias R = O.E + typealias Parent = Zip8 + + let _parent: Parent + + var _values1: Queue = Queue(capacity: 2) + var _values2: Queue = Queue(capacity: 2) + var _values3: Queue = Queue(capacity: 2) + var _values4: Queue = Queue(capacity: 2) + var _values5: Queue = Queue(capacity: 2) + var _values6: Queue = Queue(capacity: 2) + var _values7: Queue = Queue(capacity: 2) + var _values8: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: O, cancel: Cancelable) { + _parent = parent + super.init(arity: 8, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch (index) { + case 0: return _values1.count > 0 + case 1: return _values2.count > 0 + case 2: return _values3.count > 0 + case 3: return _values4.count > 0 + case 4: return _values5.count > 0 + case 5: return _values6.count > 0 + case 6: return _values7.count > 0 + case 7: return _values8.count > 0 + + default: + rxFatalError("Unhandled case (Function)") + } + + return false + } + + 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 = ZipObserver(lock: _lock, parent: self, index: 0, setNextValue: { self._values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: _lock, parent: self, index: 1, setNextValue: { self._values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: _lock, parent: self, index: 2, setNextValue: { self._values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: _lock, parent: self, index: 3, setNextValue: { self._values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: _lock, parent: self, index: 4, setNextValue: { self._values5.enqueue($0) }, this: subscription5) + let observer6 = ZipObserver(lock: _lock, parent: self, index: 5, setNextValue: { self._values6.enqueue($0) }, this: subscription6) + let observer7 = ZipObserver(lock: _lock, parent: self, index: 6, setNextValue: { self._values7.enqueue($0) }, this: subscription7) + let observer8 = ZipObserver(lock: _lock, parent: self, index: 7, setNextValue: { self._values8.enqueue($0) }, this: subscription8) + + subscription1.setDisposable(_parent.source1.subscribe(observer1)) + subscription2.setDisposable(_parent.source2.subscribe(observer2)) + subscription3.setDisposable(_parent.source3.subscribe(observer3)) + subscription4.setDisposable(_parent.source4.subscribe(observer4)) + subscription5.setDisposable(_parent.source5.subscribe(observer5)) + subscription6.setDisposable(_parent.source6.subscribe(observer6)) + subscription7.setDisposable(_parent.source7.subscribe(observer7)) + subscription8.setDisposable(_parent.source8.subscribe(observer8)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7, + subscription8 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_values1.dequeue()!, _values2.dequeue()!, _values3.dequeue()!, _values4.dequeue()!, _values5.dequeue()!, _values6.dequeue()!, _values7.dequeue()!, _values8.dequeue()!) + } +} + +final class Zip8 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7, E8) throws -> R + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + let source7: Observable + let source8: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, source8: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + self.source7 = source7 + self.source8 = source8 + + _resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = ZipSink8_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Zip.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Zip.swift new file mode 100644 index 0000000000..a283bf2b23 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Zip.swift @@ -0,0 +1,155 @@ +// +// Zip.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol ZipSinkProtocol : class +{ + func next(_ index: Int) + func fail(_ error: Swift.Error) + func done(_ index: Int) +} + +class ZipSink : Sink, ZipSinkProtocol { + typealias Element = O.E + + let _arity: Int + + let _lock = RecursiveLock() + + // state + private var _isDone: [Bool] + + init(arity: Int, observer: O, cancel: Cancelable) { + _isDone = [Bool](repeating: false, count: arity) + _arity = arity + + super.init(observer: observer, cancel: cancel) + } + + func getResult() throws -> Element { + rxAbstractMethod() + } + + func hasElements(_ index: Int) -> Bool { + rxAbstractMethod() + } + + func next(_ index: Int) { + var hasValueAll = true + + for i in 0 ..< _arity { + if !hasElements(i) { + hasValueAll = false + break + } + } + + if hasValueAll { + do { + let result = try getResult() + self.forwardOn(.next(result)) + } + catch let e { + self.forwardOn(.error(e)) + dispose() + } + } + else { + var allOthersDone = true + + let arity = _isDone.count + for i in 0 ..< arity { + if i != index && !_isDone[i] { + allOthersDone = false + break + } + } + + if allOthersDone { + forwardOn(.completed) + self.dispose() + } + } + } + + func fail(_ error: Swift.Error) { + forwardOn(.error(error)) + dispose() + } + + func done(_ index: Int) { + _isDone[index] = true + + var allDone = true + + for done in _isDone { + if !done { + allDone = false + break + } + } + + if allDone { + forwardOn(.completed) + dispose() + } + } +} + +final class ZipObserver + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias E = ElementType + typealias ValueSetter = (ElementType) -> () + + private var _parent: ZipSinkProtocol? + + let _lock: RecursiveLock + + // state + private let _index: Int + private let _this: Disposable + private let _setNextValue: ValueSetter + + init(lock: RecursiveLock, parent: ZipSinkProtocol, index: Int, setNextValue: @escaping ValueSetter, this: Disposable) { + _lock = lock + _parent = parent + _index = index + _this = this + _setNextValue = setNextValue + } + + func on(_ event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + if let _ = _parent { + switch event { + case .next(_): + break + case .error(_): + _this.dispose() + case .completed: + _this.dispose() + } + } + + if let parent = _parent { + switch event { + case .next(let value): + _setNextValue(value) + parent.next(_index) + case .error(let error): + parent.fail(error) + case .completed: + parent.done(_index) + } + } + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObserverType.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObserverType.swift new file mode 100644 index 0000000000..b024b0fb7a --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObserverType.swift @@ -0,0 +1,40 @@ +// +// ObserverType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Supports push-style iteration over an observable sequence. +public protocol ObserverType { + /// The type of elements in sequence that observer can observe. + associatedtype E + + /// Notify observer about sequence event. + /// + /// - parameter event: Event that occured. + func on(_ event: Event) +} + +/// Convenience API extensions to provide alternate next, error, completed events +extension ObserverType { + + /// Convenience method equivalent to `on(.next(element: E))` + /// + /// - parameter element: Next element to send to observer(s) + public final func onNext(_ element: E) { + on(.next(element)) + } + + /// Convenience method equivalent to `on(.completed)` + public final func onCompleted() { + on(.completed) + } + + /// Convenience method equivalent to `on(.error(Swift.Error))` + /// - parameter error: Swift.Error to send to observer(s) + public final func onError(_ error: Swift.Error) { + on(.error(error)) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift new file mode 100644 index 0000000000..54e83f5485 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift @@ -0,0 +1,32 @@ +// +// AnonymousObserver.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +final class AnonymousObserver : ObserverBase { + typealias Element = ElementType + + typealias EventHandler = (Event) -> Void + + private let _eventHandler : EventHandler + + init(_ eventHandler: @escaping EventHandler) { +#if TRACE_RESOURCES + let _ = Resources.incrementTotal() +#endif + _eventHandler = eventHandler + } + + override func onCore(_ event: Event) { + return _eventHandler(event) + } + +#if TRACE_RESOURCES + deinit { + let _ = Resources.decrementTotal() + } +#endif +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift new file mode 100644 index 0000000000..3811565226 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift @@ -0,0 +1,34 @@ +// +// ObserverBase.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +class ObserverBase : Disposable, ObserverType { + typealias E = ElementType + + private var _isStopped: AtomicInt = 0 + + func on(_ event: Event) { + switch event { + case .next: + if _isStopped == 0 { + onCore(event) + } + case .error, .completed: + if AtomicCompareAndSwap(0, 1, &_isStopped) { + onCore(event) + } + } + } + + func onCore(_ event: Event) { + rxAbstractMethod() + } + + func dispose() { + _ = AtomicCompareAndSwap(0, 1, &_isStopped) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift new file mode 100644 index 0000000000..332e6d2e4f --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift @@ -0,0 +1,150 @@ +// +// TailRecursiveSink.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +enum TailRecursiveSinkCommand { + case moveNext + case dispose +} + +#if DEBUG || TRACE_RESOURCES + public var maxTailRecursiveSinkStackSize = 0 +#endif + +/// This class is usually used with `Generator` version of the operators. +class TailRecursiveSink + : Sink + , InvocableWithValueType where S.Iterator.Element: ObservableConvertibleType, S.Iterator.Element.E == O.E { + typealias Value = TailRecursiveSinkCommand + typealias E = O.E + typealias SequenceGenerator = (generator: S.Iterator, remaining: IntMax?) + + var _generators: [SequenceGenerator] = [] + var _isDisposed = false + var _subscription = SerialDisposable() + + // this is thread safe object + var _gate = AsyncLock>>() + + override init(observer: O, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func run(_ sources: SequenceGenerator) -> Disposable { + _generators.append(sources) + + schedule(.moveNext) + + return _subscription + } + + func invoke(_ command: TailRecursiveSinkCommand) { + switch command { + case .dispose: + disposeCommand() + case .moveNext: + moveNextCommand() + } + } + + // simple implementation for now + func schedule(_ command: TailRecursiveSinkCommand) { + _gate.invoke(InvocableScheduledItem(invocable: self, state: command)) + } + + func done() { + forwardOn(.completed) + dispose() + } + + func extract(_ observable: Observable) -> SequenceGenerator? { + rxAbstractMethod() + } + + // should be done on gate locked + + private func moveNextCommand() { + var next: Observable? = nil + + repeat { + guard let (g, left) = _generators.last else { + break + } + + if _isDisposed { + return + } + + _generators.removeLast() + + var e = g + + guard let nextCandidate = e.next()?.asObservable() else { + continue + } + + // `left` is a hint of how many elements are left in generator. + // In case this is the last element, then there is no need to push + // that generator on stack. + // + // This is an optimization used to make sure in tail recursive case + // there is no memory leak in case this operator is used to generate non terminating + // sequence. + + if let knownOriginalLeft = left { + // `- 1` because generator.next() has just been called + if knownOriginalLeft - 1 >= 1 { + _generators.append((e, knownOriginalLeft - 1)) + } + } + else { + _generators.append((e, nil)) + } + + let nextGenerator = extract(nextCandidate) + + if let nextGenerator = nextGenerator { + _generators.append(nextGenerator) + #if DEBUG || TRACE_RESOURCES + if maxTailRecursiveSinkStackSize < _generators.count { + maxTailRecursiveSinkStackSize = _generators.count + } + #endif + } + else { + next = nextCandidate + } + } while next == nil + + guard let existingNext = next else { + done() + return + } + + let disposable = SingleAssignmentDisposable() + _subscription.disposable = disposable + disposable.setDisposable(subscribeToNext(existingNext)) + } + + func subscribeToNext(_ source: Observable) -> Disposable { + rxAbstractMethod() + } + + func disposeCommand() { + _isDisposed = true + _generators.removeAll(keepingCapacity: false) + } + + override func dispose() { + super.dispose() + + _subscription.dispose() + + schedule(.dispose) + } +} + diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Reactive.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Reactive.swift new file mode 100644 index 0000000000..b87399664f --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Reactive.swift @@ -0,0 +1,74 @@ +// +// Reactive.swift +// RxSwift +// +// Created by Yury Korolev on 5/2/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +/** + Use `Reactive` proxy as customization point for constrained protocol extensions. + + General pattern would be: + + // 1. Extend Reactive protocol with constrain on Base + // Read as: Reactive Extension where Base is a SomeType + extension Reactive where Base: SomeType { + // 2. Put any specific reactive extension for SomeType here + } + + With this approach we can have more specialized methods and properties using + `Base` and not just specialized on common base type. + + */ + +public struct Reactive { + /// Base object to extend. + public let base: Base + + /// Creates extensions with base object. + /// + /// - parameter base: Base object. + public init(_ base: Base) { + self.base = base + } +} + +/// A type that has reactive extensions. +public protocol ReactiveCompatible { + /// Extended type + associatedtype CompatibleType + + /// Reactive extensions. + static var rx: Reactive.Type { get set } + + /// Reactive extensions. + var rx: Reactive { get set } +} + +extension ReactiveCompatible { + /// Reactive extensions. + public static var rx: Reactive.Type { + get { + return Reactive.self + } + set { + // this enables using Reactive to "mutate" base type + } + } + + /// Reactive extensions. + public var rx: Reactive { + get { + return Reactive(self) + } + set { + // this enables using Reactive to "mutate" base object + } + } +} + +import class Foundation.NSObject + +/// Extend NSObject with `rx` proxy. +extension NSObject: ReactiveCompatible { } diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Rx.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Rx.swift new file mode 100644 index 0000000000..93b066e76d --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Rx.swift @@ -0,0 +1,67 @@ +// +// Rx.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if TRACE_RESOURCES + fileprivate var resourceCount: AtomicInt = 0 + + /// Resource utilization information + public struct Resources { + /// Counts internal Rx resource allocations (Observables, Observers, Disposables, etc.). This provides a simple way to detect leaks during development. + public static var total: Int32 { + return resourceCount.valueSnapshot() + } + + /// Increments `Resources.total` resource count. + /// + /// - returns: New resource count + public static func incrementTotal() -> Int32 { + return AtomicIncrement(&resourceCount) + } + + /// Decrements `Resources.total` resource count + /// + /// - returns: New resource count + public static func decrementTotal() -> Int32 { + return AtomicDecrement(&resourceCount) + } + } +#endif + +/// Swift does not implement abstract methods. This method is used as a runtime check to ensure that methods which intended to be abstract (i.e., they should be implemented in subclasses) are not called directly on the superclass. +func rxAbstractMethod(file: StaticString = #file, line: UInt = #line) -> Swift.Never { + rxFatalError("Abstract method", file: file, line: line) +} + +func rxFatalError(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) -> Swift.Never { + // The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours. + fatalError(lastMessage(), file: file, line: line) +} + +func rxFatalErrorInDebug(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) { + #if DEBUG + fatalError(lastMessage(), file: file, line: line) + #else + print("\(file):\(line): \(lastMessage())") + #endif +} + +func incrementChecked(_ i: inout Int) throws -> Int { + if i == Int.max { + throw RxError.overflow + } + defer { i += 1 } + return i +} + +func decrementChecked(_ i: inout Int) throws -> Int { + if i == Int.min { + throw RxError.overflow + } + defer { i -= 1 } + return i +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/RxMutableBox.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/RxMutableBox.swift new file mode 100644 index 0000000000..7f3c333baa --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/RxMutableBox.swift @@ -0,0 +1,27 @@ +// +// RxMutableBox.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/22/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Creates mutable reference wrapper for any type. +final class RxMutableBox : CustomDebugStringConvertible { + /// Wrapped value + var value : T + + /// Creates reference wrapper for `value`. + /// + /// - parameter value: Value to wrap. + init (_ value: T) { + self.value = value + } +} + +extension RxMutableBox { + /// - returns: Box description. + var debugDescription: String { + return "MutatingBox(\(self.value))" + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/SchedulerType.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/SchedulerType.swift new file mode 100644 index 0000000000..bdfcf8b017 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/SchedulerType.swift @@ -0,0 +1,71 @@ +// +// SchedulerType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import struct Foundation.TimeInterval +import struct Foundation.Date + +// Type that represents time interval in the context of RxSwift. +public typealias RxTimeInterval = TimeInterval + +/// Type that represents absolute time in the context of RxSwift. +public typealias RxTime = Date + +/// Represents an object that schedules units of work. +public protocol SchedulerType: ImmediateSchedulerType { + + /// - returns: Current time. + var now : RxTime { + get + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + func scheduleRelative(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + func schedulePeriodic(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable +} + +extension SchedulerType { + + /** + Periodic task will be emulated using recursive scheduling. + + - parameter state: Initial state passed to the action upon the first iteration. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - returns: The disposable object used to cancel the scheduled recurring action (best effort). + */ + public func schedulePeriodic(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + let schedule = SchedulePeriodicRecursive(scheduler: self, startAfter: startAfter, period: period, action: action, state: state) + + return schedule.start() + } + + func scheduleRecursive(_ state: State, dueTime: RxTimeInterval, action: @escaping (State, AnyRecursiveScheduler) -> ()) -> Disposable { + let scheduler = AnyRecursiveScheduler(scheduler: self, action: action) + + scheduler.schedule(state, dueTime: dueTime) + + return Disposables.create(with: scheduler.dispose) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift new file mode 100644 index 0000000000..d7ec3d88e8 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift @@ -0,0 +1,82 @@ +// +// ConcurrentDispatchQueueScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 7/5/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import struct Foundation.Date +import struct Foundation.TimeInterval +import Dispatch + +/// Abstracts the work that needs to be performed on a specific `dispatch_queue_t`. You can also pass a serial dispatch queue, it shouldn't cause any problems. +/// +/// This scheduler is suitable when some work needs to be performed in background. +public class ConcurrentDispatchQueueScheduler: SchedulerType { + public typealias TimeInterval = Foundation.TimeInterval + public typealias Time = Date + + public var now : Date { + return Date() + } + + let configuration: DispatchQueueConfiguration + + /// Constructs new `ConcurrentDispatchQueueScheduler` that wraps `queue`. + /// + /// - parameter queue: Target dispatch queue. + public init(queue: DispatchQueue, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + configuration = DispatchQueueConfiguration(queue: queue, leeway: leeway) + } + + /// Convenience init for scheduler that wraps one of the global concurrent dispatch queues. + /// + /// - parameter qos: Target global dispatch queue, by quality of service class. + @available(iOS 8, OSX 10.10, *) + public convenience init(qos: DispatchQoS, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + self.init(queue: DispatchQueue( + label: "rxswift.queue.\(qos)", + qos: qos, + attributes: [DispatchQueue.Attributes.concurrent], + target: nil), + leeway: leeway + ) + } + + /** + 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). + */ + public final func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + return self.configuration.schedule(state, action: action) + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func scheduleRelative(_ state: StateType, dueTime: Foundation.TimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + return self.configuration.scheduleRelative(state, dueTime: dueTime, action: action) + } + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedulePeriodic(_ state: StateType, startAfter: TimeInterval, period: TimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + return self.configuration.schedulePeriodic(state, startAfter: startAfter, period: period, action: action) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift new file mode 100644 index 0000000000..92028b1787 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift @@ -0,0 +1,88 @@ +// +// ConcurrentMainScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import struct Foundation.Date +import struct Foundation.TimeInterval +import Dispatch + +/** +Abstracts work that needs to be performed on `MainThread`. In case `schedule` methods are called from main thread, it will perform action immediately without scheduling. + +This scheduler is optimized for `subscribeOn` operator. If you want to observe observable sequence elements on main thread using `observeOn` operator, +`MainScheduler` is more suitable for that purpose. +*/ +public final class ConcurrentMainScheduler : SchedulerType { + public typealias TimeInterval = Foundation.TimeInterval + public typealias Time = Date + + private let _mainScheduler: MainScheduler + private let _mainQueue: DispatchQueue + + /// - returns: Current time. + public var now : Date { + return _mainScheduler.now as Date + } + + private init(mainScheduler: MainScheduler) { + _mainQueue = DispatchQueue.main + _mainScheduler = mainScheduler + } + + /// Singleton instance of `ConcurrentMainScheduler` + public static let instance = ConcurrentMainScheduler(mainScheduler: MainScheduler.instance) + + /** + 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). + */ + public func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + if DispatchQueue.isMain { + return action(state) + } + + let cancel = SingleAssignmentDisposable() + + _mainQueue.async { + if cancel.isDisposed { + return + } + + cancel.setDisposable(action(state)) + } + + return cancel + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func scheduleRelative(_ state: StateType, dueTime: Foundation.TimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + return _mainScheduler.scheduleRelative(state, dueTime: dueTime, action: action) + } + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedulePeriodic(_ state: StateType, startAfter: TimeInterval, period: TimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + return _mainScheduler.schedulePeriodic(state, startAfter: startAfter, period: period, action: action) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift new file mode 100644 index 0000000000..cbdb98d91b --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift @@ -0,0 +1,136 @@ +// +// CurrentThreadScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import class Foundation.NSObject +import protocol Foundation.NSCopying +import class Foundation.Thread +import Dispatch + +#if os(Linux) + import struct Foundation.pthread_key_t + import func Foundation.pthread_setspecific + import func Foundation.pthread_getspecific + import func Foundation.pthread_key_create + + fileprivate enum CurrentThreadSchedulerQueueKey { + fileprivate static let instance = "RxSwift.CurrentThreadScheduler.Queue" + } +#else + fileprivate class CurrentThreadSchedulerQueueKey: NSObject, NSCopying { + static let instance = CurrentThreadSchedulerQueueKey() + private override init() { + super.init() + } + + override var hash: Int { + return 0 + } + + public func copy(with zone: NSZone? = nil) -> Any { + return self + } + } +#endif + +/// Represents an object that schedules units of work on the current thread. +/// +/// This is the default scheduler for operators that generate elements. +/// +/// This scheduler is also sometimes called `trampoline scheduler`. +public class CurrentThreadScheduler : ImmediateSchedulerType { + typealias ScheduleQueue = RxMutableBox> + + /// The singleton instance of the current thread scheduler. + public static let instance = CurrentThreadScheduler() + + private static var isScheduleRequiredKey: pthread_key_t = { () -> pthread_key_t in + let key = UnsafeMutablePointer.allocate(capacity: 1) + if pthread_key_create(key, nil) != 0 { + rxFatalError("isScheduleRequired key creation failed") + } + + return key.pointee + }() + + private static var scheduleInProgressSentinel: UnsafeRawPointer = { () -> UnsafeRawPointer in + return UnsafeRawPointer(UnsafeMutablePointer.allocate(capacity: 1)) + }() + + static var queue : ScheduleQueue? { + get { + return Thread.getThreadLocalStorageValueForKey(CurrentThreadSchedulerQueueKey.instance) + } + set { + Thread.setThreadLocalStorageValue(newValue, forKey: CurrentThreadSchedulerQueueKey.instance) + } + } + + /// Gets a value that indicates whether the caller must call a `schedule` method. + public static fileprivate(set) var isScheduleRequired: Bool { + get { + return pthread_getspecific(CurrentThreadScheduler.isScheduleRequiredKey) == nil + } + set(isScheduleRequired) { + if pthread_setspecific(CurrentThreadScheduler.isScheduleRequiredKey, isScheduleRequired ? nil : scheduleInProgressSentinel) != 0 { + rxFatalError("pthread_setspecific failed") + } + } + } + + /** + Schedules an action to be executed as soon as possible on current thread. + + If this method is called on some thread that doesn't have `CurrentThreadScheduler` installed, scheduler will be + automatically installed and uninstalled after all work is performed. + + - 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). + */ + public func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + if CurrentThreadScheduler.isScheduleRequired { + CurrentThreadScheduler.isScheduleRequired = false + + let disposable = action(state) + + defer { + CurrentThreadScheduler.isScheduleRequired = true + CurrentThreadScheduler.queue = nil + } + + guard let queue = CurrentThreadScheduler.queue else { + return disposable + } + + while let latest = queue.value.dequeue() { + if latest.isDisposed { + continue + } + latest.invoke() + } + + return disposable + } + + let existingQueue = CurrentThreadScheduler.queue + + let queue: RxMutableBox> + if let existingQueue = existingQueue { + queue = existingQueue + } + else { + queue = RxMutableBox(Queue(capacity: 1)) + CurrentThreadScheduler.queue = queue + } + + let scheduledItem = ScheduledItem(action: action, state: state) + queue.value.enqueue(scheduledItem) + + return scheduledItem + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift new file mode 100644 index 0000000000..11af238a3b --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift @@ -0,0 +1,22 @@ +// +// HistoricalScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 12/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import struct Foundation.Date + +/// Provides a virtual time scheduler that uses `Date` for absolute time and `NSTimeInterval` for relative time. +public class HistoricalScheduler : VirtualTimeScheduler { + + /** + Creates a new historical scheduler with initial clock value. + + - parameter initialClock: Initial value for virtual clock. + */ + public init(initialClock: RxTime = Date(timeIntervalSince1970: 0)) { + super.init(initialClock: initialClock, converter: HistoricalSchedulerTimeConverter()) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift new file mode 100644 index 0000000000..3602d2d047 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift @@ -0,0 +1,67 @@ +// +// HistoricalSchedulerTimeConverter.swift +// RxSwift +// +// Created by Krunoslav Zaher on 12/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import struct Foundation.Date + +/// Converts historial virtual time into real time. +/// +/// Since historical virtual time is also measured in `Date`, this converter is identity function. +public struct HistoricalSchedulerTimeConverter : VirtualTimeConverterType { + /// Virtual time unit used that represents ticks of virtual clock. + public typealias VirtualTimeUnit = RxTime + + /// Virtual time unit used to represent differences of virtual times. + public typealias VirtualTimeIntervalUnit = RxTimeInterval + + /// Returns identical value of argument passed because historical virtual time is equal to real time, just + /// decoupled from local machine clock. + public func convertFromVirtualTime(_ virtualTime: VirtualTimeUnit) -> RxTime { + return virtualTime + } + + /// Returns identical value of argument passed because historical virtual time is equal to real time, just + /// decoupled from local machine clock. + public func convertToVirtualTime(_ time: RxTime) -> VirtualTimeUnit { + return time + } + + /// Returns identical value of argument passed because historical virtual time is equal to real time, just + /// decoupled from local machine clock. + public func convertFromVirtualTimeInterval(_ virtualTimeInterval: VirtualTimeIntervalUnit) -> RxTimeInterval { + return virtualTimeInterval + } + + /// Returns identical value of argument passed because historical virtual time is equal to real time, just + /// decoupled from local machine clock. + public func convertToVirtualTimeInterval(_ timeInterval: RxTimeInterval) -> VirtualTimeIntervalUnit { + return timeInterval + } + + /** + Offsets `Date` by time interval. + + - parameter time: Time. + - parameter timeInterval: Time interval offset. + - returns: Time offsetted by time interval. + */ + public func offsetVirtualTime(_ time: VirtualTimeUnit, offset: VirtualTimeIntervalUnit) -> VirtualTimeUnit { + return time.addingTimeInterval(offset) + } + + /// Compares two `Date`s. + public func compareVirtualTime(_ lhs: VirtualTimeUnit, _ rhs: VirtualTimeUnit) -> VirtualTimeComparison { + switch lhs.compare(rhs as Date) { + case .orderedAscending: + return .lessThan + case .orderedSame: + return .equal + case .orderedDescending: + return .greaterThan + } + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ImmediateScheduler.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ImmediateScheduler.swift new file mode 100644 index 0000000000..d411dac7ee --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ImmediateScheduler.swift @@ -0,0 +1,35 @@ +// +// ImmediateScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents an object that schedules units of work to run immediately on the current thread. +private final class ImmediateScheduler : ImmediateSchedulerType { + + private let _asyncLock = AsyncLock() + + /** + Schedules an action to be executed immediatelly. + + In case `schedule` is called recursively from inside of `action` callback, scheduled `action` will be enqueued + and executed after current `action`. (`AsyncLock` behavior) + + - 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(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + let disposable = SingleAssignmentDisposable() + _asyncLock.invoke(AnonymousInvocable { + if disposable.isDisposed { + return + } + disposable.setDisposable(action(state)) + }) + + return disposable + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/AnonymousInvocable.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/AnonymousInvocable.swift new file mode 100644 index 0000000000..8d1d965b63 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/AnonymousInvocable.swift @@ -0,0 +1,19 @@ +// +// AnonymousInvocable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 11/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +struct AnonymousInvocable : InvocableType { + private let _action: () -> () + + init(_ action: @escaping () -> ()) { + _action = action + } + + func invoke() { + _action() + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift new file mode 100644 index 0000000000..dc191b1585 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift @@ -0,0 +1,104 @@ +// +// DispatchQueueConfiguration.swift +// RxSwift +// +// Created by Krunoslav Zaher on 7/23/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import struct Foundation.TimeInterval + +struct DispatchQueueConfiguration { + let queue: DispatchQueue + let leeway: DispatchTimeInterval +} + +private func dispatchInterval(_ interval: Foundation.TimeInterval) -> DispatchTimeInterval { + precondition(interval >= 0.0) + // TODO: Replace 1000 with something that actually works + // NSEC_PER_MSEC returns 1000000 + return DispatchTimeInterval.milliseconds(Int(interval * 1000.0)) +} + +extension DispatchQueueConfiguration { + func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + let cancel = SingleAssignmentDisposable() + + queue.async { + if cancel.isDisposed { + return + } + + + cancel.setDisposable(action(state)) + } + + return cancel + } + + func scheduleRelative(_ state: StateType, dueTime: Foundation.TimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + let deadline = DispatchTime.now() + dispatchInterval(dueTime) + + let compositeDisposable = CompositeDisposable() + + let timer = DispatchSource.makeTimerSource(queue: queue) + timer.scheduleOneshot(deadline: deadline) + + // TODO: + // This looks horrible, and yes, it is. + // It looks like Apple has made a conceputal change here, and I'm unsure why. + // Need more info on this. + // It looks like just setting timer to fire and not holding a reference to it + // until deadline causes timer cancellation. + var timerReference: DispatchSourceTimer? = timer + let cancelTimer = Disposables.create { + timerReference?.cancel() + timerReference = nil + } + + timer.setEventHandler(handler: { + if compositeDisposable.isDisposed { + return + } + _ = compositeDisposable.insert(action(state)) + cancelTimer.dispose() + }) + timer.resume() + + _ = compositeDisposable.insert(cancelTimer) + + return compositeDisposable + } + + func schedulePeriodic(_ state: StateType, startAfter: TimeInterval, period: TimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + let initial = DispatchTime.now() + dispatchInterval(startAfter) + + var timerState = state + + let timer = DispatchSource.makeTimerSource(queue: queue) + timer.scheduleRepeating(deadline: initial, interval: dispatchInterval(period), leeway: leeway) + + // TODO: + // This looks horrible, and yes, it is. + // It looks like Apple has made a conceputal change here, and I'm unsure why. + // Need more info on this. + // It looks like just setting timer to fire and not holding a reference to it + // until deadline causes timer cancellation. + var timerReference: DispatchSourceTimer? = timer + let cancelTimer = Disposables.create { + timerReference?.cancel() + timerReference = nil + } + + timer.setEventHandler(handler: { + if cancelTimer.isDisposed { + return + } + timerState = action(timerState) + }) + timer.resume() + + return cancelTimer + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift new file mode 100644 index 0000000000..90445f8d5a --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift @@ -0,0 +1,22 @@ +// +// InvocableScheduledItem.swift +// RxSwift +// +// Created by Krunoslav Zaher on 11/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +struct InvocableScheduledItem : InvocableType { + + let _invocable: I + let _state: I.Value + + init(invocable: I, state: I.Value) { + _invocable = invocable + _state = state + } + + func invoke() { + _invocable.invoke(_state) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift new file mode 100644 index 0000000000..0dba4336a7 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift @@ -0,0 +1,17 @@ +// +// InvocableType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 11/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol InvocableType { + func invoke() +} + +protocol InvocableWithValueType { + associatedtype Value + + func invoke(_ value: Value) +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift new file mode 100644 index 0000000000..454fb34bb7 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift @@ -0,0 +1,35 @@ +// +// ScheduledItem.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +struct ScheduledItem + : ScheduledItemType + , InvocableType { + typealias Action = (T) -> Disposable + + private let _action: Action + private let _state: T + + private let _disposable = SingleAssignmentDisposable() + + var isDisposed: Bool { + return _disposable.isDisposed + } + + init(action: @escaping Action, state: T) { + _action = action + _state = state + } + + func invoke() { + _disposable.setDisposable(_action(_state)) + } + + func dispose() { + _disposable.dispose() + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift new file mode 100644 index 0000000000..d2b16cab70 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift @@ -0,0 +1,13 @@ +// +// ScheduledItemType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 11/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol ScheduledItemType + : Cancelable + , InvocableType { + func invoke() +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift new file mode 100644 index 0000000000..7d2ac2187d --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift @@ -0,0 +1,68 @@ +// +// MainScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch + +/** +Abstracts work that needs to be performed on `DispatchQueue.main`. In case `schedule` methods are called from `DispatchQueue.main`, it will perform action immediately without scheduling. + +This scheduler is usually used to perform UI work. + +Main scheduler is a specialization of `SerialDispatchQueueScheduler`. + +This scheduler is optimized for `observeOn` operator. To ensure observable sequence is subscribed on main thread using `subscribeOn` +operator please use `ConcurrentMainScheduler` because it is more optimized for that purpose. +*/ +public final class MainScheduler : SerialDispatchQueueScheduler { + + private let _mainQueue: DispatchQueue + + var numberEnqueued: AtomicInt = 0 + + /// Initializes new instance of `MainScheduler`. + public init() { + _mainQueue = DispatchQueue.main + super.init(serialQueue: _mainQueue) + } + + /// Singleton instance of `MainScheduler` + public static let instance = MainScheduler() + + /// Singleton instance of `MainScheduler` that always schedules work asynchronously + /// and doesn't perform optimizations for calls scheduled from main queue. + public static let asyncInstance = SerialDispatchQueueScheduler(serialQueue: DispatchQueue.main) + + /// In case this method is called on a background thread it will throw an exception. + public class func ensureExecutingOnScheduler(errorMessage: String? = nil) { + if !DispatchQueue.isMain { + rxFatalError(errorMessage ?? "Executing on backgound thread. Please use `MainScheduler.instance.schedule` to schedule work on main thread.") + } + } + + override func scheduleInternal(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + let currentNumberEnqueued = AtomicIncrement(&numberEnqueued) + + if DispatchQueue.isMain && currentNumberEnqueued == 1 { + let disposable = action(state) + _ = AtomicDecrement(&numberEnqueued) + return disposable + } + + let cancel = SingleAssignmentDisposable() + + _mainQueue.async { + if !cancel.isDisposed { + _ = action(state) + } + + _ = AtomicDecrement(&self.numberEnqueued) + } + + return cancel + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift new file mode 100644 index 0000000000..82d30fbcec --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift @@ -0,0 +1,50 @@ +// +// OperationQueueScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/4/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import class Foundation.OperationQueue +import class Foundation.BlockOperation +import Dispatch + +/// Abstracts the work that needs to be performed on a specific `NSOperationQueue`. +/// +/// This scheduler is suitable for cases when there is some bigger chunk of work that needs to be performed in background and you want to fine tune concurrent processing using `maxConcurrentOperationCount`. +public class OperationQueueScheduler: ImmediateSchedulerType { + public let operationQueue: OperationQueue + + /// Constructs new instance of `OperationQueueScheduler` that performs work on `operationQueue`. + /// + /// - parameter operationQueue: Operation queue targeted to perform work on. + public init(operationQueue: OperationQueue) { + self.operationQueue = operationQueue + } + + /** + 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 schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + let cancel = SingleAssignmentDisposable() + + let operation = BlockOperation { + if cancel.isDisposed { + return + } + + + cancel.setDisposable(action(state)) + } + + self.operationQueue.addOperation(operation) + + return cancel + } + +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift new file mode 100644 index 0000000000..24d19cc677 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift @@ -0,0 +1,226 @@ +// +// RecursiveScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +fileprivate enum ScheduleState { + case initial + case added(CompositeDisposable.DisposeKey) + case done +} + +/// Type erased recursive scheduler. +final class AnyRecursiveScheduler { + + typealias Action = (State, AnyRecursiveScheduler) -> Void + + private let _lock = RecursiveLock() + + // state + private let _group = CompositeDisposable() + + private var _scheduler: SchedulerType + private var _action: Action? + + init(scheduler: SchedulerType, action: @escaping Action) { + _action = action + _scheduler = scheduler + } + + /** + Schedules an action to be executed recursively. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the recursive action. + */ + func schedule(_ state: State, dueTime: RxTimeInterval) { + var scheduleState: ScheduleState = .initial + + let d = _scheduler.scheduleRelative(state, dueTime: dueTime) { (state) -> Disposable in + // best effort + if self._group.isDisposed { + return Disposables.create() + } + + let action = self._lock.calculateLocked { () -> Action? in + switch scheduleState { + case let .added(removeKey): + self._group.remove(for: removeKey) + case .initial: + break + case .done: + break + } + + scheduleState = .done + + return self._action + } + + if let action = action { + action(state, self) + } + + return Disposables.create() + } + + _lock.performLocked { + switch scheduleState { + case .added: + rxFatalError("Invalid state") + break + case .initial: + if let removeKey = _group.insert(d) { + scheduleState = .added(removeKey) + } + else { + scheduleState = .done + } + break + case .done: + break + } + } + } + + /// Schedules an action to be executed recursively. + /// + /// - parameter state: State passed to the action to be executed. + func schedule(_ state: State) { + var scheduleState: ScheduleState = .initial + + let d = _scheduler.schedule(state) { (state) -> Disposable in + // best effort + if self._group.isDisposed { + return Disposables.create() + } + + let action = self._lock.calculateLocked { () -> Action? in + switch scheduleState { + case let .added(removeKey): + self._group.remove(for: removeKey) + case .initial: + break + case .done: + break + } + + scheduleState = .done + + return self._action + } + + if let action = action { + action(state, self) + } + + return Disposables.create() + } + + _lock.performLocked { + switch scheduleState { + case .added: + rxFatalError("Invalid state") + break + case .initial: + if let removeKey = _group.insert(d) { + scheduleState = .added(removeKey) + } + else { + scheduleState = .done + } + break + case .done: + break + } + } + } + + func dispose() { + _lock.performLocked { + _action = nil + } + _group.dispose() + } +} + +/// Type erased recursive scheduler. +final class RecursiveImmediateScheduler { + typealias Action = (_ state: State, _ recurse: (State) -> Void) -> Void + + private var _lock = SpinLock() + private let _group = CompositeDisposable() + + private var _action: Action? + private let _scheduler: ImmediateSchedulerType + + init(action: @escaping Action, scheduler: ImmediateSchedulerType) { + _action = action + _scheduler = scheduler + } + + // immediate scheduling + + /// Schedules an action to be executed recursively. + /// + /// - parameter state: State passed to the action to be executed. + func schedule(_ state: State) { + var scheduleState: ScheduleState = .initial + + let d = _scheduler.schedule(state) { (state) -> Disposable in + // best effort + if self._group.isDisposed { + return Disposables.create() + } + + let action = self._lock.calculateLocked { () -> Action? in + switch scheduleState { + case let .added(removeKey): + self._group.remove(for: removeKey) + case .initial: + break + case .done: + break + } + + scheduleState = .done + + return self._action + } + + if let action = action { + action(state, self.schedule) + } + + return Disposables.create() + } + + _lock.performLocked { + switch scheduleState { + case .added: + rxFatalError("Invalid state") + break + case .initial: + if let removeKey = _group.insert(d) { + scheduleState = .added(removeKey) + } + else { + scheduleState = .done + } + break + case .done: + break + } + } + } + + func dispose() { + _lock.performLocked { + _action = nil + } + _group.dispose() + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift new file mode 100644 index 0000000000..1d224775be --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift @@ -0,0 +1,61 @@ +// +// SchedulerServices+Emulation.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/6/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +enum SchedulePeriodicRecursiveCommand { + case tick + case dispatchStart +} + +final class SchedulePeriodicRecursive { + typealias RecursiveAction = (State) -> State + typealias RecursiveScheduler = AnyRecursiveScheduler + + private let _scheduler: SchedulerType + private let _startAfter: RxTimeInterval + private let _period: RxTimeInterval + private let _action: RecursiveAction + + private var _state: State + private var _pendingTickCount: AtomicInt = 0 + + init(scheduler: SchedulerType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping RecursiveAction, state: State) { + _scheduler = scheduler + _startAfter = startAfter + _period = period + _action = action + _state = state + } + + func start() -> Disposable { + return _scheduler.scheduleRecursive(SchedulePeriodicRecursiveCommand.tick, dueTime: _startAfter, action: self.tick) + } + + func tick(_ command: SchedulePeriodicRecursiveCommand, scheduler: RecursiveScheduler) -> Void { + // Tries to emulate periodic scheduling as best as possible. + // The problem that could arise is if handling periodic ticks take too long, or + // tick interval is short. + switch command { + case .tick: + scheduler.schedule(.tick, dueTime: _period) + + // The idea is that if on tick there wasn't any item enqueued, schedule to perform work immediatelly. + // Else work will be scheduled after previous enqueued work completes. + if AtomicIncrement(&_pendingTickCount) == 1 { + self.tick(.dispatchStart, scheduler: scheduler) + } + + case .dispatchStart: + _state = _action(_state) + // Start work and schedule check is this last batch of work + if AtomicDecrement(&_pendingTickCount) > 0 { + // This gives priority to scheduler emulation, it's not perfect, but helps + scheduler.schedule(SchedulePeriodicRecursiveCommand.dispatchStart) + } + } + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift new file mode 100644 index 0000000000..a163406cb9 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift @@ -0,0 +1,123 @@ +// +// SerialDispatchQueueScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import struct Foundation.TimeInterval +import struct Foundation.Date +import Dispatch + +/** +Abstracts the work that needs to be performed on a specific `dispatch_queue_t`. It will make sure +that even if concurrent dispatch queue is passed, it's transformed into a serial one. + +It is extremely important that this scheduler is serial, because +certain operator perform optimizations that rely on that property. + +Because there is no way of detecting is passed dispatch queue serial or +concurrent, for every queue that is being passed, worst case (concurrent) +will be assumed, and internal serial proxy dispatch queue will be created. + +This scheduler can also be used with internal serial queue alone. + +In case some customization need to be made on it before usage, +internal serial queue can be customized using `serialQueueConfiguration` +callback. +*/ +public class SerialDispatchQueueScheduler : SchedulerType { + public typealias TimeInterval = Foundation.TimeInterval + public typealias Time = Date + + /// - returns: Current time. + public var now : Date { + return Date() + } + + let configuration: DispatchQueueConfiguration + + init(serialQueue: DispatchQueue, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + configuration = DispatchQueueConfiguration(queue: serialQueue, leeway: leeway) + } + + /** + Constructs new `SerialDispatchQueueScheduler` with internal serial queue named `internalSerialQueueName`. + + Additional dispatch queue properties can be set after dispatch queue is created using `serialQueueConfiguration`. + + - parameter internalSerialQueueName: Name of internal serial dispatch queue. + - parameter serialQueueConfiguration: Additional configuration of internal serial dispatch queue. + */ + public convenience init(internalSerialQueueName: String, serialQueueConfiguration: ((DispatchQueue) -> Void)? = nil, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + let queue = DispatchQueue(label: internalSerialQueueName, attributes: []) + serialQueueConfiguration?(queue) + self.init(serialQueue: queue, leeway: leeway) + } + + /** + Constructs new `SerialDispatchQueueScheduler` named `internalSerialQueueName` that wraps `queue`. + + - parameter queue: Possibly concurrent dispatch queue used to perform work. + - parameter internalSerialQueueName: Name of internal serial dispatch queue proxy. + */ + public convenience init(queue: DispatchQueue, internalSerialQueueName: String, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + // Swift 3.0 IUO + let serialQueue = DispatchQueue(label: internalSerialQueueName, + attributes: [], + target: queue) + self.init(serialQueue: serialQueue, leeway: leeway) + } + + /** + Constructs new `SerialDispatchQueueScheduler` that wraps on of the global concurrent dispatch queues. + + - parameter qos: Identifier for global dispatch queue with specified quality of service class. + - parameter internalSerialQueueName: Custom name for internal serial dispatch queue proxy. + */ + @available(iOS 8, OSX 10.10, *) + public convenience init(qos: DispatchQoS, internalSerialQueueName: String = "rx.global_dispatch_queue.serial", leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + self.init(queue: DispatchQueue.global(qos: qos.qosClass), internalSerialQueueName: internalSerialQueueName, leeway: leeway) + } + + /** + 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). + */ + public final func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + return self.scheduleInternal(state, action: action) + } + + func scheduleInternal(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + return self.configuration.schedule(state, action: action) + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func scheduleRelative(_ state: StateType, dueTime: Foundation.TimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + return self.configuration.scheduleRelative(state, dueTime: dueTime, action: action) + } + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedulePeriodic(_ state: StateType, startAfter: TimeInterval, period: TimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + return self.configuration.schedulePeriodic(state, startAfter: startAfter, period: period, action: action) + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift new file mode 100644 index 0000000000..b207836ef7 --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift @@ -0,0 +1,95 @@ +// +// VirtualTimeConverterType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 12/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Parametrization for virtual time used by `VirtualTimeScheduler`s. +public protocol VirtualTimeConverterType { + /// Virtual time unit used that represents ticks of virtual clock. + associatedtype VirtualTimeUnit + + /// Virtual time unit used to represent differences of virtual times. + associatedtype VirtualTimeIntervalUnit + + /** + Converts virtual time to real time. + + - parameter virtualTime: Virtual time to convert to `Date`. + - returns: `Date` corresponding to virtual time. + */ + func convertFromVirtualTime(_ virtualTime: VirtualTimeUnit) -> RxTime + + /** + Converts real time to virtual time. + + - parameter time: `Date` to convert to virtual time. + - returns: Virtual time corresponding to `Date`. + */ + func convertToVirtualTime(_ time: RxTime) -> VirtualTimeUnit + + /** + Converts from virtual time interval to `NSTimeInterval`. + + - parameter virtualTimeInterval: Virtual time interval to convert to `NSTimeInterval`. + - returns: `NSTimeInterval` corresponding to virtual time interval. + */ + func convertFromVirtualTimeInterval(_ virtualTimeInterval: VirtualTimeIntervalUnit) -> RxTimeInterval + + /** + Converts from virtual time interval to `NSTimeInterval`. + + - parameter timeInterval: `NSTimeInterval` to convert to virtual time interval. + - returns: Virtual time interval corresponding to time interval. + */ + func convertToVirtualTimeInterval(_ timeInterval: RxTimeInterval) -> VirtualTimeIntervalUnit + + /** + Offsets virtual time by virtual time interval. + + - parameter time: Virtual time. + - parameter offset: Virtual time interval. + - returns: Time corresponding to time offsetted by virtual time interval. + */ + func offsetVirtualTime(_ time: VirtualTimeUnit, offset: VirtualTimeIntervalUnit) -> VirtualTimeUnit + + /** + This is aditional abstraction because `Date` is unfortunately not comparable. + Extending `Date` with `Comparable` would be too risky because of possible collisions with other libraries. + */ + func compareVirtualTime(_ lhs: VirtualTimeUnit, _ rhs: VirtualTimeUnit) -> VirtualTimeComparison +} + +/** + Virtual time comparison result. + + This is aditional abstraction because `Date` is unfortunately not comparable. + Extending `Date` with `Comparable` would be too risky because of possible collisions with other libraries. +*/ +public enum VirtualTimeComparison { + /// lhs < rhs. + case lessThan + /// lhs == rhs. + case equal + /// lhs > rhs. + case greaterThan +} + +extension VirtualTimeComparison { + /// lhs < rhs. + var lessThen: Bool { + return self == .lessThan + } + + /// lhs > rhs + var greaterThan: Bool { + return self == .greaterThan + } + + /// lhs == rhs + var equal: Bool { + return self == .equal + } +} diff --git a/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift new file mode 100644 index 0000000000..0e650c602a --- /dev/null +++ b/samples/client/petstore/swift4/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift @@ -0,0 +1,269 @@ +// +// VirtualTimeScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Base class for virtual time schedulers using a priority queue for scheduled items. +open class VirtualTimeScheduler + : SchedulerType { + + public typealias VirtualTime = Converter.VirtualTimeUnit + public typealias VirtualTimeInterval = Converter.VirtualTimeIntervalUnit + + private var _running : Bool + + private var _clock: VirtualTime + + fileprivate var _schedulerQueue : PriorityQueue> + private var _converter: Converter + + private var _nextId = 0 + + /// - returns: Current time. + public var now: RxTime { + return _converter.convertFromVirtualTime(clock) + } + + /// - returns: Scheduler's absolute time clock value. + public var clock: VirtualTime { + return _clock + } + + /// Creates a new virtual time scheduler. + /// + /// - parameter initialClock: Initial value for the clock. + public init(initialClock: VirtualTime, converter: Converter) { + _clock = initialClock + _running = false + _converter = converter + _schedulerQueue = PriorityQueue(hasHigherPriority: { + switch converter.compareVirtualTime($0.time, $1.time) { + case .lessThan: + return true + case .equal: + return $0.id < $1.id + case .greaterThan: + return false + } + }, isEqual: { $0 === $1 }) + #if TRACE_RESOURCES + let _ = Resources.incrementTotal() + #endif + } + + /** + 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). + */ + public func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + return self.scheduleRelative(state, dueTime: 0.0) { a in + return action(a) + } + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleRelative(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + let time = self.now.addingTimeInterval(dueTime) + let absoluteTime = _converter.convertToVirtualTime(time) + let adjustedTime = self.adjustScheduledTime(absoluteTime) + return scheduleAbsoluteVirtual(state, time: adjustedTime, action: action) + } + + /** + Schedules an action to be executed after relative time has passed. + + - parameter state: State passed to the action to be executed. + - parameter time: Absolute time when to execute the action. If this is less or equal then `now`, `now + 1` will be used. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleRelativeVirtual(_ state: StateType, dueTime: VirtualTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + let time = _converter.offsetVirtualTime(self.clock, offset: dueTime) + return scheduleAbsoluteVirtual(state, time: time, action: action) + } + + /** + Schedules an action to be executed at absolute virtual time. + + - parameter state: State passed to the action to be executed. + - parameter time: Absolute time when to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleAbsoluteVirtual(_ state: StateType, time: Converter.VirtualTimeUnit, action: @escaping (StateType) -> Disposable) -> Disposable { + MainScheduler.ensureExecutingOnScheduler() + + let compositeDisposable = CompositeDisposable() + + let item = VirtualSchedulerItem(action: { + let dispose = action(state) + return dispose + }, time: time, id: _nextId) + + _nextId += 1 + + _schedulerQueue.enqueue(item) + + _ = compositeDisposable.insert(item) + + return compositeDisposable + } + + /// Adjusts time of scheduling before adding item to schedule queue. + open func adjustScheduledTime(_ time: Converter.VirtualTimeUnit) -> Converter.VirtualTimeUnit { + return time + } + + /// Starts the virtual time scheduler. + public func start() { + MainScheduler.ensureExecutingOnScheduler() + + if _running { + return + } + + _running = true + repeat { + guard let next = findNext() else { + break + } + + if _converter.compareVirtualTime(next.time, self.clock).greaterThan { + _clock = next.time + } + + next.invoke() + _schedulerQueue.remove(next) + } while _running + + _running = false + } + + func findNext() -> VirtualSchedulerItem? { + while let front = _schedulerQueue.peek() { + if front.isDisposed { + _schedulerQueue.remove(front) + continue + } + + return front + } + + return nil + } + + /// Advances the scheduler's clock to the specified time, running all work till that point. + /// + /// - parameter virtualTime: Absolute time to advance the scheduler's clock to. + public func advanceTo(_ virtualTime: VirtualTime) { + MainScheduler.ensureExecutingOnScheduler() + + if _running { + fatalError("Scheduler is already running") + } + + _running = true + repeat { + guard let next = findNext() else { + break + } + + if _converter.compareVirtualTime(next.time, virtualTime).greaterThan { + break + } + + if _converter.compareVirtualTime(next.time, self.clock).greaterThan { + _clock = next.time + } + + next.invoke() + _schedulerQueue.remove(next) + } while _running + + _clock = virtualTime + _running = false + } + + /// Advances the scheduler's clock by the specified relative time. + public func sleep(_ virtualInterval: VirtualTimeInterval) { + MainScheduler.ensureExecutingOnScheduler() + + let sleepTo = _converter.offsetVirtualTime(clock, offset: virtualInterval) + if _converter.compareVirtualTime(sleepTo, clock).lessThen { + fatalError("Can't sleep to past.") + } + + _clock = sleepTo + } + + /// Stops the virtual time scheduler. + public func stop() { + MainScheduler.ensureExecutingOnScheduler() + + _running = false + } + + #if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } + #endif +} + +// MARK: description + +extension VirtualTimeScheduler: CustomDebugStringConvertible { + /// A textual representation of `self`, suitable for debugging. + public var debugDescription: String { + return self._schedulerQueue.debugDescription + } +} + +final class VirtualSchedulerItem